forked from Blogger-Peer-Review/quotebacks
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoptions.js
More file actions
684 lines (522 loc) · 19.8 KB
/
options.js
File metadata and controls
684 lines (522 loc) · 19.8 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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
var alldata;
var allKeys;
var alljson = [];
var sorted = [];
document.addEventListener("DOMContentLoaded", function(){
chrome.storage.local.get(null, function(items) {
allKeys = Object.keys(items);
//only run all the code if there are items in the DB
if(allKeys.length != 0){
alldata = items;
console.log(alldata);
embedquoteback();
//create sorted array by last_updated
for (var item in items) {
//for quotes with no last_mod
//i.e. beta users
if(!items[item].last_update){
items[item].last_update = "1546347661"
}
sorted.push([item, items[item].last_update]);
}
sorted.sort(function(a,b){
return a[1] - b[1]
})
sorted.reverse();
for( var i in sorted){
alljson.push(items[sorted[i][0]]);
const article_fragment = document.getElementById('articleItem');
const article_instance = document.importNode(article_fragment.content, true);
// Add relevant content to the template
var domain = extractHostname(items[sorted[i][0]].url);
article_instance.querySelector('.title').innerHTML = items[sorted[i][0]].title;
article_instance.querySelector('.mini-favicon').src = "https://s2.googleusercontent.com/s2/favicons?domain_url="+domain+"&size=64";
article_instance.querySelector('.url').innerHTML = domain;
article_instance.querySelector('.article').setAttribute("data-id",items[sorted[i][0]].url);
// Append the instance ot the DOM
document.getElementById('article-scrollContainer').appendChild(article_instance);
}
alljson = JSON.stringify(alljson);
alljson = JSON.parse(alljson);
var pagehash = $(location).attr('hash').replace("#","");
if($(location).attr('hash')){
if(allKeys.includes(pagehash)){ // error handling for some mishandled hash value
displayquotes(pagehash)
}else{
displayquotes(sorted[0][0]);
};
}else{
displayquotes(sorted[0][0]);
}
window.addEventListener('hashchange', function() {
var hashval = $(location).attr('hash').replace("#","");
if(allKeys.includes(hashval)){ // check hash is a valid entry in data
displayquotes(hashval)
};
}, false);
$( ".article" ).click(function() {
var url = $(this).attr('data-id');
displayquotes(url);
});
$('#rightpanel').on('click',"#copy", function() {
var quote = $(this).closest(".quote-container").find("#quoteback-component");
var text = decodeURIComponent(quote.attr("text"));
var htmlfragment = document.createRange().createContextualFragment(text);
var cleaned = htmlfragment.textContent;
copyToClipboard(cleaned);
var el = $(this);
el.html("Copied!");
setTimeout(function() {
el.html("Copy Text");
}, 1000);
});
$('#rightpanel').on('click',"#embedLink", function() {
var quote = $(this).closest(".quote-container").find("#quoteback-component");
var title = $(".selected").find(".title").text();
var url = $(".selected").attr("data-id");
var text = quote.attr("text");
// if we want to use text instead of html inside the blockquote we should use this:
// https://ourcodeworld.com/articles/read/376/how-to-strip-html-from-a-string-extract-only-text-content-in-javascript
// however we'd then need to move to storing the html string in an attribute in the web component
//var stripedHtml = decodeURIComponent(text).replace(/<[^>]+>/g, '');
var author = quote.attr("author");
var embed = `
<blockquote class="quoteback" data-title="${title}" data-author="${author}" cite="${url}">
${decodeURIComponent(text)}
<footer>${author}<cite><a href="${url}">${url}</a></cite></footer>
</blockquote><script note="" src="https://cdn.jsdelivr.net/gh/Blogger-Peer-Review/quotebacks@1/quoteback.js"></script>`;
copyToClipboard(embed);
let el = $(this);
el.html("Copied!");
setTimeout(function() {
el.html("<> Embed");
}, 1000);
});
// use html2screenshot to generate canvas, copy img to clipboard
$('#rightpanel').on('click',"#copyimg", function() {
var el = $(this);
quote = el.closest(".quoteblock");
quote = quote[0].querySelector("quoteback-component");
console.log(quote);
var newDiv = document.createElement("div");
newDiv.id = "copyimage";
newDiv.innerHTML = quote.shadowRoot.innerHTML;
//position div offscreen to prevent flicker
document.getElementById("panel-scrollContainer").style.height = "3000px";
newDiv.style.bottom = "-999px";
newDiv.style.position = "absolute";
newDiv.style.width = "500px";
newDiv.style.padding = "5px 5px 5px 5px";
newDiv.querySelector(".quoteback-container").style.margin = "0px 0px 0px 0px";
document.getElementById("panel-scrollContainer").appendChild(newDiv);
//stop the "go to text" element rendering in the image
document.getElementById("copyimage").querySelector(".quoteback-backlink").setAttribute("data-html2canvas-ignore", "true");
// use faviconkit for screenshots for CORS
var url = document.getElementById("copyimage").querySelector(".quoteback-arrow").href;
var hostname = (new URL(url)).hostname;
document.getElementById("copyimage").querySelector(".mini-favicon").src = "https://api.faviconkit.com/"+hostname;
var title = document.getElementById("copyimage").querySelector(".quoteback-title");
if(title.innerHTML.length > 65){ // html2canvas doesn't support text-overflow:ellipses
title.innerHTML = title.innerHTML.substring(0,60);
title.innerHTML = title.innerHTML + "...";
}
html2canvas(document.getElementById("copyimage"), {
useCORS: true,
onclone: function(document) {
}
}).then((canvas) => {
canvas.toBlob(function(blob) {
saveAs(canvas.toDataURL(), url+'.png');
var item = new ClipboardItem({ "image/png": blob });
navigator.clipboard.write([item]).then(
function() {
console.log("Copied to clipboard successfully!");
var element = document.getElementById("copyimage");
element.parentNode.removeChild(element);
document.getElementById("panel-scrollContainer").style.height = "initial";
el.html("Copied!");
setTimeout(function() {
el.html("Copy Image");
}, 1000);
},
function(error) {
console.error("unable to write to clipboard. Error:");
console.log(error);
}
);
});
}).catch(function (error) {
console.log('oops, something went wrong!', error);
});
});
// used in html2canvas
function saveAs(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
link.href = uri;
link.download = filename;
//Firefox requires the link to be in the body
document.body.appendChild(link);
//simulate click
link.click();
//remove the link when done
document.body.removeChild(link);
} else {
window.open(uri);
}
}
// convert quote to markdown using turndown.js
$('#rightpanel').on('click',"#copymd", function() {
var el = $(this);
quote = el.closest(".quoteblock");
quote = quote[0].querySelector("quoteback-component");
var html = `<blockquote>${quote.text}</blockquote>
Source: <a href="${quote.url}">${quote.title}</a> by ${quote.author}`;
const turndownService = new TurndownService();
const markdown = turndownService.turndown(html);
copyToClipboard(markdown);
el.html("Copied!");
setTimeout(function() {
el.html("Copy Markdown");
}, 1000);
});
// Delete QUOTE
$('#rightpanel').on('click',"#delete", function() {
var r = confirm("Are you sure you want to delete this quote?");
if (r == true) {
var url = $(".selected").attr("data-id");
var quoteblock = $(this).closest('.quoteblock');
var index = $(".quoteblock").index(quoteblock);
var quotes = alldata[url]["quotes"];
var removed = quotes.splice(index,1);
alldata[url]["quotes"] = quotes;
if(quotes.length == 0){ //if no quotes left then delete whole item from alldata
chrome.storage.local.remove(url, function (){
console.log("deleted "+url);
location.reload();
});
}else{
chrome.storage.local.set(alldata, function(){
console.log("saving data");
displayquotes(url);
});
}
} else {
}
});
// DELETE ARTICLE
$('#titlebar').on('click',"#titlebar-delete", function(){
var r = confirm("Are you sure you want to delete this entire article?")
if (r == true) {
var url = $(".selected").attr("data-id");
chrome.storage.local.remove(url, function(){ // delete entire item from alldata
location.reload();
});
}else{
}
});
// on title/author -> trigger autosave
$( "#rightpanel" ).on("focus" , "#titlebar-author", function() {
var el = $(this);
var url = $(".selected").attr("data-id");
var object = alldata[url];
AutoSaveTitle.start(object, el ,url);
$("#titlebar-author").keypress(function(e){ // prevent return in title
if(e.which == 13){
$("#titlebar-author").blur();
}
return e.which != 13;
});
});
$( "#rightpanel" ).on("focusout" , "#titlebar-author", function() {
AutoSaveTitle.stop();
});
$( "#rightpanel" ).on("focus" , "#titlebar-title", function() {
var el = $(this);
var url = $(".selected").attr("data-id");
var object = alldata[url];
AutoSaveTitle.start(object, el ,url);
$("#titlebar-title").keypress(function(e){ // prevent return in title
if(e.which == 13){
$("#titlebar-title").blur();
}
return e.which != 13;
});
});
$( "#rightpanel" ).on("focusout" , "#titlebar-title", function() {
AutoSaveTitle.stop();
});
// on focus comment box -> trigger autosave
$( "#rightpanel" ).on("focus" , ".comment", function() {
var url = $(".selected").attr("data-id");
var object = alldata[url];
console.log($(this).text());
if($(this).text() == "Add comment"){
$(this).text("");
};
$(this).css("color","#464A4D")
var el = $(this);
AutoSave.start(object, el , $(this).index(".comment"),url);
});
// on focusout comment box -> stop autosave
$( "#rightpanel" ).on("focusout" , ".comment", function() {
AutoSave.stop();
});
};
});
});
document.addEventListener("DOMContentLoaded", function(){
// Import function
document.getElementById("importQuotes").onclick = function(){
document.getElementById('fileid').click();
};
document.getElementById('fileid').onchange = function(evt) {
try {
let files = evt.target.files;
if (!files.length) {
alert('No file selected!');
return;
}
let file = files[0];
let reader = new FileReader();
const self = this;
var importobject = {};
reader.onload = (event) => {
var importitems = JSON.parse(event.target.result);
//console.log('FILE CONTENT', event.target.result);
chrome.storage.local.set(importitems, function() {
console.log("import done!");
location.reload();
});
//console.log(importitems);
};
reader.readAsText(file);
} catch (err) {
console.error(err);
}
}
// CLEAR STORAGE
document.getElementById("clearStorage").onclick = function(){
var r = confirm("Are you sure you want to delete all citations?!");
if (r == true) {
chrome.storage.local.clear();
location.reload();
} else {
}
};
// Export function
document.getElementById("exportQuotes").onclick = function(){
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(alldata, null, 2));
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
var a = document.createElement("a");
a.setAttribute("href", dataStr );
a.setAttribute("download", curr_date + "-" + curr_month + "-" + curr_year +"-quoteback.json");
a.click();
};
});
function displayquotes(url){
if(alldata[url]){
document.getElementById('panel-scrollContainer').innerHTML = "";
window.location.hash = url;
const fragment = document.getElementById('quote');
var offset = $(".article[data-id='"+url+"']").offset();
if(offset){
$("#article-scrollContainer").scrollTop(offset.top);
}
alldata[url].quotes.forEach(item => {
var date = new Date(item.date);
var dd = String(date.getDate()).padStart(2, '0');
var mm = String(date.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = date.getFullYear();
date = mm + '/' + dd + '/' + yyyy;
var datefield = date;
var quotetemplate = `
<div class="quoteblock">
<div class="meta">
<div class="date">Created ${datefield}</div>
<div class="linkback"><a target="_blank" href="${url}#:~:text=${encodeURIComponent(item.text)}">View Original</a></div>
</div>
<div class="quote-container">
<quoteback-component id="quoteback-component" url="${url}" text="${encodeURIComponent(item.text)}" author="${alldata[url].author}" title="${alldata[url].title}" favicon="https://s2.googleusercontent.com/s2/favicons?domain_url=${url}&size=64">
</quoteback-component>
<div class="quote-controls">
<button id="embedLink" class="options-control-button"><> Embed</button>
<button id="copyimg" class="options-control-button">Copy Image</button>
<button id="copy" class="options-control-button">Copy Text</button>
<button id="copymd" class="options-control-button">Copy Markdown</button>
<button id="delete" class="options-control-button">Delete</button>
</div>
</div>
<div class="comment" contenteditable="true" ${item.comment ? "style='color:#464A4D'" : ""}}>${item.comment ? item.comment : "Add Comment"}</div>
</div>
`;
embedquoteback();
// Append the instance ot the DOM
document.getElementById('panel-scrollContainer').insertAdjacentHTML("beforeend", quotetemplate);
$( ".article" ).each(function() {
$( this ).removeClass( "selected" );
});
$(".article[data-id='"+url+"']").addClass( "selected" );
// Update the Title Bar
var titlebar = document.getElementById('titlebar');
titlebar.querySelector("#titlebar-author").innerHTML = alldata[url].author;
titlebar.querySelector("#titlebar-title").innerHTML = alldata[url].title;
});
}
};
// COPY TO CLIPBOARD
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};
function extractHostname(url) {
var hostname;
//find & remove protocol (http, ftp, etc.) and get hostname
if (url.indexOf("//") > -1) {
hostname = url.split('/')[2];
}
else {
hostname = url.split('/')[0];
}
return hostname
};
// HOVER TO SHOW CONTROLS
$(document).on('mouseenter mouseleave', '.quoteblock', function(e) {
if (e.type == "mouseenter"){
$(this).find('.quote-controls').addClass('showcontrols');
}else{
$(this).find('.quote-controls').removeClass('showcontrols');
}
});
// AUTOSAVE FUNCTION
var AutoSave = (function(){
var timer = null;
function save(object, el, index, url){
console.log("running save");
console.log(el);
alldata[url]["quotes"][index]["comment"] = el.text();
chrome.storage.local.set(alldata, function(){
console.log("autosaved");
});
};
function restore(){ //don't think I actually need this restore function...?
var page = document.location.href;
var saved = "";
chrome.storage.local.get([page], function(result) {
saved = result[page]["quotes"][0]["comment"];
});
var editor = getEditor();
if (saved && editor){
editor.value = saved;
}
}
return {
start: function(object, el, index, url){
if (timer != null){
clearInterval(timer);
timer = null;
}
timer = setInterval(function(){
save(object, el, index, url)
}, 500);
},
stop: function(){
if (timer){
clearInterval(timer);
timer = null;
}
}
}
}());
// AUTOSAVE Meta Title / Author FUNCTION
var AutoSaveTitle = (function(){
var timer = null;
function save(object, el, url){
console.log("running autosavetitle");
console.log(el);
var author = document.getElementById("titlebar-author").textContent;
var title = document.getElementById("titlebar-title").textContent;
alldata[url]["author"] = author;
alldata[url]["title"] = title;
chrome.storage.local.set(alldata, function(){
var quoteelems = document.getElementsByTagName("quoteback-component");
for(var i = 0; i < quoteelems.length; i++){
quoteelems[i].author = author;
quoteelems[i].title = title;
}
console.log("autosaved");
});
};
return {
start: function(object, el, url){
if (timer != null){
clearInterval(timer);
timer = null;
}
timer = setInterval(function(){
save(object, el, url)
}, 500);
},
stop: function(){
if (timer){
clearInterval(timer);
timer = null;
}
}
}
}());
document.addEventListener("DOMContentLoaded", function(){
$(".comment").resizable();
});
document.addEventListener("DOMContentLoaded", function(){
var articleOptions = document.getElementById("titlebar-options");
var dropdown = document.getElementById("titlebar-dropdown");
var addMenu = function addDropDownMenu() {
dropdown.classList.add("on");
};
var removeMenu = function removeDropDownMenu() {
dropdown.classList.remove("on");
};
articleOptions.addEventListener("mouseover", addMenu);
articleOptions.addEventListener("mouseout", removeMenu);
});
document.addEventListener("DOMContentLoaded", function(){
var globalOptions = document.getElementById("global-options-button");
var dropdown = document.getElementById("global-options");
var addMenu = function addDropDownMenu() {
dropdown.classList.add("on");
};
var removeMenu = function removeDropDownMenu() {
dropdown.classList.remove("on");
};
// Add mouse over event to show menu
globalOptions.addEventListener("mouseover", addMenu);
// Add mouse out event to remove menu
globalOptions.addEventListener("mouseout", removeMenu);
});
// $("#leftnav").resizable({
// // only use the eastern handle
// handles: 'e',
// // restrict the width range
// minWidth: 120,
// maxWidth: 450,
// // resize handler updates the content panel width
// resize: function(event, ui){
// var currentWidth = ui.size.width;
// // this accounts for padding in the panels +
// // borders, you could calculate this using jQuery
// var padding = 12;
// // this accounts for some lag in the ui.size value, if you take this away
// // you'll get some instable behaviour
// $(this).width(currentWidth);
// // set the content panel width
// $("#rightpanel").width(containerWidth - currentWidth - padding);
// }
// });