-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.js
372 lines (323 loc) · 13.9 KB
/
content.js
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
// Initialize current color for highlighting
let currentColor = 'yellow';
// Add a listener for mouseup events to handle text selection
document.addEventListener('mouseup', function() {
let selection = window.getSelection();
if (selection.toString()) {
let range = selection.getRangeAt(0);
let parent = range.commonAncestorContainer.nodeType === Node.TEXT_NODE
? range.commonAncestorContainer.parentNode
: range.commonAncestorContainer;
let { startOffset, endOffset } = getRelativeOffsets(range, parent);
// Log calculated offsets
console.log('Calculated offsets:', { startOffset, endOffset });
let span = document.createElement('span');
span.className = `highlight highlight-${currentColor}`;
span.setAttribute('data-color', currentColor); // Store the current color in the span
range.surroundContents(span);
// Show note input popup
showNoteInputPopup(span, selection.toString(), startOffset, endOffset, parent);
// Add click event listener to show note popup immediately
span.addEventListener('click', function() {
let note = span.getAttribute('data-note') || '';
showNoteInputPopup(span, span.textContent, startOffset, endOffset, parent, note); // Use span.textContent for the original text
});
// Clear the current selection
selection.removeAllRanges();
}
});
function showNoteInputPopup(span, text, startOffset, endOffset, parent, existingNote = '') {
let popup = document.createElement('div');
popup.className = 'note-popup';
popup.innerHTML = `
<textarea placeholder="Enter your note here">${existingNote}</textarea>
<button class="save-button">Save</button>
<button class="cancel-button">Cancel</button>
<button class="remove-highlight-button">Remove Highlight</button>
`;
document.body.appendChild(popup);
popup.style.top = `${span.getBoundingClientRect().top + window.scrollY}px`;
popup.style.left = `${span.getBoundingClientRect().left + window.scrollX}px`;
const saveNote = () => {
let note = popup.querySelector('textarea').value;
let color = span.getAttribute('data-color');
saveHighlight(text, startOffset, endOffset, parent, color, note);
span.setAttribute('data-note', note);
document.body.removeChild(popup);
};
popup.querySelector('.save-button').addEventListener('click', saveNote);
popup.querySelector('.cancel-button').addEventListener('click', function() {
if (!existingNote) {
saveHighlight(text, startOffset, endOffset, parent, span.getAttribute('data-color'), '');
}
document.body.removeChild(popup);
});
popup.querySelector('.remove-highlight-button').addEventListener('click', function() {
removeHighlight(span, startOffset, endOffset, parent);
document.body.removeChild(popup);
});
}
// Function to get relative offsets within the parent node's text content
function getRelativeOffsets(range, parent) {
let textNodes = getTextNodes(parent);
let startOffset = 0, endOffset = 0, charCount = 0;
textNodes.forEach(node => {
if (node === range.startContainer) {
startOffset = charCount + range.startOffset;
}
if (node === range.endContainer) {
endOffset = charCount + range.endOffset;
}
charCount += node.textContent.length;
});
return { startOffset, endOffset };
}
// Function to save highlights in Chrome's local storage
function saveHighlight(text, startOffset, endOffset, parent, color, note) {
const url = window.location.href;
const newHighlight = {
text,
startOffset,
endOffset,
parentXPath: getXPath(parent),
color,
note
};
// Log the highlight parameters
console.log('Highlight to save:', newHighlight);
// Get the current highlights data from local storage
chrome.storage.local.get('highlights', function(result) {
const highlightsData = result.highlights || {};
highlightsData[url] = highlightsData[url] || [];
// Check if this highlight already exists and update it if necessary
let highlightIndex = highlightsData[url].findIndex(h => h.startOffset === startOffset && h.endOffset === endOffset && h.parentXPath === newHighlight.parentXPath);
if (highlightIndex > -1) {
highlightsData[url][highlightIndex] = newHighlight;
} else {
highlightsData[url].push(newHighlight);
}
// Save the updated highlights back to local storage
chrome.storage.local.set({ highlights: highlightsData }, function() {
console.log('Highlights saved:', highlightsData);
});
});
}
// Function to remove a specific highlight from Chrome's local storage and the DOM
function removeHighlight(span, startOffset, endOffset, parent) {
const url = window.location.href;
chrome.storage.local.get('highlights', function(result) {
const highlightsData = result.highlights || {};
highlightsData[url] = highlightsData[url] || [];
// Find and remove the highlight
highlightsData[url] = highlightsData[url].filter(h => !(h.startOffset === startOffset && h.endOffset === endOffset && h.parentXPath === getXPath(parent)));
// Save the updated highlights back to local storage
chrome.storage.local.set({ highlights: highlightsData }, function() {
console.log('Highlight removed:', highlightsData);
});
// Remove the highlight from the DOM
let parentElement = span.parentNode;
while (span.firstChild) {
parentElement.insertBefore(span.firstChild, span);
}
parentElement.removeChild(span);
parentElement.normalize();
});
}
// Function to load highlights from Chrome's local storage
function loadHighlights() {
const url = window.location.href;
console.log('Loading highlights for:', url);
chrome.storage.local.get('highlights', function(result) {
console.log('Stored highlights:', result);
if (result.highlights && result.highlights[url]) {
clearHighlights();
result.highlights[url].forEach(highlight => {
console.log('Highlight to load:', highlight);
let parent = getNodeByXPath(highlight.parentXPath);
console.log('Parent node:', parent);
if (parent) {
applyHighlight(parent, highlight.startOffset, highlight.endOffset, highlight.color, highlight.note);
}
});
}
});
}
// Function to apply highlight using text offsets
function applyHighlight(parent, startOffset, endOffset, color, note) {
let range = document.createRange();
let textNodes = getTextNodes(parent);
let charCount = 0, startNode = null, endNode = null, startOffsetInNode, endOffsetInNode;
textNodes.forEach(node => {
let nodeLength = node.textContent.length;
if (charCount <= startOffset && charCount + nodeLength > startOffset) {
startNode = node;
startOffsetInNode = startOffset - charCount;
}
if (charCount <= endOffset && charCount + nodeLength > endOffset) {
endNode = node;
endOffsetInNode = endOffset - charCount;
}
charCount += nodeLength;
});
if (startNode && endNode) {
range.setStart(startNode, startOffsetInNode);
range.setEnd(endNode, endOffsetInNode);
let span = document.createElement('span');
span.className = `highlight highlight-${color}`;
span.setAttribute('data-note', note);
span.setAttribute('data-color', color);
range.surroundContents(span);
console.log('Highlight applied:', { range, color, note });
// Add click event listener to show note popup
span.addEventListener('click', function() {
let currentText = span.textContent; // Get the current highlighted text
showNoteInputPopup(span, currentText, startOffset, endOffset, parent, note);
});
} else {
console.error('Error: Unable to find text node or apply highlight', {
startOffset,
endOffset,
charCount,
parent
});
}
}
// Function to get all text nodes within a parent node
function getTextNodes(node) {
let textNodes = [];
if (node.nodeType === Node.TEXT_NODE) {
textNodes.push(node);
} else {
node.childNodes.forEach(child => {
textNodes.push(...getTextNodes(child));
});
}
return textNodes;
}
// Function to generate XPath for an element
function getXPath(element) {
if (element.id !== '') { // If the element has an ID, use it
return 'id("' + element.id + '")';
}
if (element === document.body) { // If the element is the body, return /html/body
return '/html/body';
}
let ix = 0;
let siblings = element.parentNode.childNodes;
for (let i = 0; i < siblings.length; i++) {
let sibling = siblings[i];
if (sibling === element) {
return getXPath(element.parentNode) + '/' + element.tagName.toLowerCase() + '[' + (ix + 1) + ']';
}
if (sibling.nodeType === 1 && sibling.tagName === element.tagName) {
ix++;
}
}
}
// Function to get node by XPath
function getNodeByXPath(xpath) {
let result = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return result.singleNodeValue;
}
// Function to clear existing highlights
function clearHighlights() {
document.querySelectorAll('.highlight').forEach(span => {
let parent = span.parentNode;
while (span.firstChild) {
parent.insertBefore(span.firstChild, span);
}
parent.removeChild(span);
parent.normalize();
});
}
// Function to apply highlight filter
function applyHighlightFilter(colors) {
clearHighlights();
const url = window.location.href;
chrome.storage.local.get('highlights', function(result) {
if (result.highlights && result.highlights[url]) {
result.highlights[url].forEach(highlight => {
if (colors.includes(highlight.color)) {
let parent = getNodeByXPath(highlight.parentXPath);
if (parent) {
applyHighlight(parent, highlight.startOffset, highlight.endOffset, highlight.color, highlight.note);
}
}
});
}
});
}
// Function to clear highlight filter and show all highlights
function clearHighlightFilter() {
clearHighlights();
loadHighlights();
}
// Function to export highlights to PDF using jsPDF
function exportHighlightsToPDF() {
const url = window.location.href;
chrome.storage.local.get('highlights', function(result) {
if (result.highlights && result.highlights[url]) {
const highlights = result.highlights[url];
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
const pageWidth = doc.internal.pageSize.getWidth();
const pageHeight = doc.internal.pageSize.getHeight();
const margin = 10;
const maxWidth = pageWidth - 2 * margin; // Set max width for text
doc.text(`URL: ${url}`, margin, 10);
let yPosition = 20;
highlights.forEach((highlight, index) => {
// Add the highlight text
let textLines = doc.splitTextToSize(`Highlight ${index + 1}: ${highlight.text}`, maxWidth);
doc.text(textLines, margin, yPosition);
yPosition += textLines.length * 7; // Adjust y position for text height with smaller line height
// Add the note, if any
if (highlight.note) {
let noteLines = doc.splitTextToSize(`Note: ${highlight.note}`, maxWidth);
doc.text(noteLines, margin, yPosition);
yPosition += noteLines.length * 7; // Adjust y position for note height with smaller line height
}
// Add some space between entries
yPosition += 5;
// Check if we need to add a new page
if (yPosition + 10 > pageHeight) {
doc.addPage();
yPosition = 10; // Reset y position for new page
}
});
doc.save('highlights.pdf');
}
});
}
// Load highlights when the page loads
loadHighlights();
// Listen for messages from the popup to clear highlights, change color, apply filter, clear filter, and export to PDF
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === 'clearHighlights') {
clearHighlights();
const url = window.location.href;
chrome.storage.local.get('highlights', function(result) {
const highlightsData = result.highlights || {};
highlightsData[url] = [];
chrome.storage.local.set({ highlights: highlightsData }, function() {
console.log('Highlights cleared:', highlightsData);
});
});
sendResponse({ status: 'highlights_cleared' });
} else if (request.action === 'changeColor') {
currentColor = request.color;
chrome.storage.local.set({ currentColor: request.color }, function() {
console.log('Color changed to:', currentColor);
});
sendResponse({ status: 'color_changed', color: currentColor });
} else if (request.action === 'applyFilter') {
applyHighlightFilter(request.colors);
sendResponse({ status: 'filter_applied', colors: request.colors });
} else if (request.action === 'clearFilter') {
clearHighlightFilter();
sendResponse({ status: 'filter_cleared' });
} else if (request.action === 'exportToPDF') {
exportHighlightsToPDF();
sendResponse({ status: 'export_to_pdf' });
}
});