Repository navigation
Expand file tree
/
Copy pathnewtab.js
More file actions
443 lines (392 loc) · 17.8 KB
/
Copy pathnewtab.js
File metadata and controls
443 lines (392 loc) · 17.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
; (() => {
// FIXME: Should use uuid instead of index as key for storage
/** DB
* {
* version: <number>,
* mode: <string>
* list: [{
* content: <string>
* time: <number>
* }]
* }
**/
const newtab_script = () => {
const THEMES = {
night: "night",
day: "day"
}
const $body = document.querySelector('body')
const $textarea = document.querySelector('#note-content')
const $list = document.querySelector('#list')
const $mode_switcher = document.querySelector('#mode-switcher')
const $setting_gear = document.querySelector('#setting-icon')
const $credits_button = document.querySelector("#addon-author")
const $status = document.querySelector('#status')
const $create_entry = document.querySelector('#create_entry')
const $undo_deletion = document.querySelector("#undo_deletion")
const $list_indicator = document.querySelector('#list-indicator')
let currentNoteId = 0
let data = null
//deleted notes are kept in storage (the latest 20), so undo still works after closing the tab
const TRASH_SIZE = 20
let hide_timeout = null
//paste text in plaintext, still allow pasting images
$textarea.addEventListener("paste", function (event) {
if (event.clipboardData.getData("text/plain") !== "") {
event.preventDefault();
document.execCommand("inserttext", false, event.clipboardData.getData("text/plain"));
}
})
//click links with ctrl+click
$textarea.addEventListener("click", function (event) {
if (data.clickablelinks && event.ctrlKey) {
var link = clickedword()
try {
url = new URL(link);
window.open(url)
} catch (_) {
console.log(link + " is an invalid link.")
}
}
})
//to-do checkboxes: "[ ] " at the start of a line becomes ☐, and clicking ☐ or ☑ toggles it
const UNCHECKED = '☐', CHECKED = '☑'
//a text node starts a line when nothing inline comes before it in the same block
const _startsLine = node => {
const prev = node.previousSibling
return !prev || prev.nodeName === 'BR' || /^(DIV|P|LI)$/.test(prev.nodeName)
}
$textarea.addEventListener('input', event => {
if (event.inputType !== 'insertText' || event.data !== ' ') { return }
const selection = document.getSelection()
const node = selection.anchorNode
if (!node || node.nodeType !== Node.TEXT_NODE) { return }
const offset = selection.anchorOffset
const before = node.textContent.slice(0, offset)
//browsers insert a no-break space when typing a space at the end of a line
const match = before.match(/(^|\n)\[[ ]?\][ ]$/)
if (!match || (match.index === 0 && !match[1] && !_startsLine(node))) { return }
const start = match.index + match[1].length
//a no-break space, since a plain trailing space would collapse
node.textContent = before.slice(0, start) + UNCHECKED + '\u00a0' + node.textContent.slice(offset)
selection.collapse(node, start + 2)
})
$textarea.addEventListener('click', event => {
//find the character under the pointer (caretPositionFromPoint in Firefox, caretRangeFromPoint in Chromium)
const position = document.caretPositionFromPoint
? document.caretPositionFromPoint(event.clientX, event.clientY)
: document.caretRangeFromPoint(event.clientX, event.clientY)
if (!position) { return }
const node = position.offsetNode || position.startContainer
const offset = position.offset ?? position.startOffset
if (!node || node.nodeType !== Node.TEXT_NODE) { return }
const text = node.textContent
//the caret lands before or after the box depending on which half was clicked
const index = [offset, offset - 1].find(i => text[i] === UNCHECKED || text[i] === CHECKED)
if (index === undefined) { return }
//only toggle when the pointer is on the box itself, not in the margin next to it
const range = document.createRange()
range.setStart(node, index)
range.setEnd(node, index + 1)
const box = range.getBoundingClientRect()
if (event.clientX < box.left || event.clientX > box.right || event.clientY < box.top || event.clientY > box.bottom) { return }
node.textContent = text.slice(0, index) + (text[index] === UNCHECKED ? CHECKED : UNCHECKED) + text.slice(index + 1)
document.getSelection().collapse(node, index + 1)
$textarea.dispatchEvent(new Event('input'))
})
function clickedword() {
var sel = document.getSelection();
sel.modify("extend", "backward", "paragraphboundary");
var pos = sel.toString().length;
if (sel.anchorNode != undefined) sel.collapseToEnd();
var fullstr = sel.focusNode.textContent
return fullstr.substring(fullstr.lastIndexOf(' ', pos) + 1, fullstr.indexOf(' ', pos) >= pos ? fullstr.indexOf(' ', pos) : fullstr.length)
}
const _emptyNote = () => {
const emptyNote = Object.create(null)
emptyNote.content = ''
emptyNote.time = (new Date()).getTime()
return emptyNote
}
//plain-text title: the first letters and digits of the note in any script, with tags and entities removed
const _noteTitle = content => {
const text = content.replace(/<[^>]*>/g, ' ').slice(0, 200)
//DOMParser decodes entities like without loading images or running scripts
const decoded = new DOMParser().parseFromString(text, 'text/html').body.textContent
return decoded.replace(/\s+/g, ' ').replace(/[^\p{L}\p{N} ]/gu, '').trim().substr(0, 10)
}
const _render = (rendernote) => {
$body.style.backgroundColor = "#ffffff"
const _renderList = list => {
const _makeTitleString = content => _noteTitle(content) || '<span class="empty-string">(EMPTY)</span>'
const $ul = document.querySelector('ul')
$ul.innerHTML = list.sort((a, b) => b.time - a.time).map((item, index) => {
let title = _makeTitleString(item.content)
let className = index === currentNoteId ? 'current' : ''
return `<li class="${className}" data-id="${index}"><span>${title}<div class='del'>+</div><div class='dnld'><img class="dnldimg" src="./dnld.png" alt="Download"></div></span></li>`
}).join('')
if (data.trash.length > 0) {
$undo_deletion.style.display = "block"
} else {
$undo_deletion.style.display = "none"
}
$ul.querySelectorAll('li').forEach(function ($li, index) {
$li.addEventListener('click', function (event) {
//console.log($textarea.innerText || $textarea.textContent)
if (event.target.classList.contains('del')) {
const currentNote = list[index]
if (currentNote.content !== '') {
const noteTitle = _noteTitle(currentNote.content) || '(EMPTY)'
const deleteConfirmString = `Do you want to delete note: ${noteTitle}?`
if (!confirm(deleteConfirmString)) { return }
}
//this code is responsible for deleting notes
//if after deleting this note, the list of notes will be empty:
if (index === 0 && data.list.length === 1) {
data.trash = [...data.trash, data.list[index]].slice(-TRASH_SIZE)
data.list = [_emptyNote()]
}
//if after deleting this note, the list of notes is not empty:
else {
data.trash = [...data.trash, data.list[index]].slice(-TRASH_SIZE)
data.list = data.list.filter((note, i) => i !== index)
if (currentNoteId >= data.list.length) {
currentNoteId = data.list.length - 1
}
}
browser.storage.local.set({ list: data.list, trash: data.trash })
_render(true)
return
}
else if (event.target.classList.contains('dnld') || event.target.classList.contains('dnldimg')) {
currentNoteId = index
_render(true)
const noteTitle = _noteTitle(list[index].content) || 'note'
//const dbutton = $li.querySelector('.dnld');
//console.log(dbutton);
var userInput = $textarea.innerText;
var blob = new Blob([userInput], { type: "text/plain;charset=utf-8" });
let newLink = document.createElement("a");
newLink.download = `${noteTitle}.txt`;
if (window.webkitURL != null) {
newLink.href = window.webkitURL.createObjectURL(blob);
}
else {
newLink.href = window.URL.createObjectURL(blob);
newLink.style.display = "none";
document.body.appendChild(newLink);
}
newLink.click();
return
}
if (currentNoteId === index) { return }
currentNoteId = index
_render(true)
})
})
}
const _renderNote = note => {
$textarea.innerHTML = note.content || ''
$textarea.focus()
}
_renderList(data.list)
if (rendernote) {
_renderNote(data.list[currentNoteId])
}
}
const _enableAnimation = () => {
setTimeout(() => {
document.querySelector('style').innerHTML += `
#create_entry, #note-content, #mode-switcher,
#addon-author, #list, #list li > span, #list .current:before {
transition-duration: .2s;
}
`
}, 300)
}
const _noteEventHandler = () => {
// auto saving and indicator; "input" also covers mouse paste, drag and drop, and undo from the menu
let write_timeout
$textarea.addEventListener('input', () => {
//if note didnt change
if (data.list[currentNoteId].content === $textarea.innerHTML) { return }
$status.classList.remove('hide')
$status.textContent = 'Saving...'
clearTimeout(hide_timeout)
clearTimeout(write_timeout)
write_timeout = setTimeout(_saveNote, 250)
})
$textarea.focus()
}
const _saveNote = async () => {
const edited = data.list[currentNoteId]
const note = { content: $textarea.innerHTML, time: (new Date()).getTime() }
//merge into the latest stored list, so notes saved meanwhile by another Tab Notes page are kept
const { list = [] } = await browser.storage.local.get('list')
const index = list.findIndex(n => n.time === edited.time)
//if another page changed or deleted this note meanwhile, keep both versions
if (index >= 0) { list[index] = note } else { list.unshift(note) }
data.list = list.sort((a, b) => b.time - a.time)
currentNoteId = 0
await browser.storage.local.set({ list: data.list })
$status.textContent = 'Saved.'
clearTimeout(hide_timeout)
_render(false)
hide_timeout = setTimeout(() => $status.classList.add('hide'), 3000)
}
//another Tab Notes page (a tab or the toolbar popup) saved, so show its changes here
const _storageChangeHandler = () => {
const signature = list => list.map(note => `${note.time}:${note.content.length}`).join()
browser.storage.onChanged.addListener((changes, area) => {
if (area !== 'local') { return }
if (changes.trash) {
data.trash = changes.trash.newValue || []
if (!changes.list) { _render(false) }
}
if (!changes.list || !changes.list.newValue) { return }
const list = changes.list.newValue
//this page's own save
if (signature(list) === signature(data.list)) { return }
const current = data.list[currentNoteId]
const unsaved = Boolean(current) && $textarea.innerHTML !== current.content
//keep the note being typed even if the other page changed or deleted it; the next save adds it back
if (unsaved && !list.some(note => note.time === current.time)) { list.push(current) }
//sort before looking up the index, since rendering sorts the list too
data.list = list.sort((a, b) => b.time - a.time)
currentNoteId = current ? Math.max(data.list.findIndex(note => note.time === current.time), 0) : 0
//leave the editor alone while typing; otherwise show the latest content
_render(!unsaved)
})
}
const _createButtonEventHandler = () => {
$create_entry.addEventListener('click', () => {
currentNoteId = 0
data.list = [_emptyNote(), ...data.list]
browser.storage.local.set({ list: data.list })
_render(true)
})
}
const _undoButtonEventHandler = () => {
$undo_deletion.addEventListener('click', () => {
if (data.trash.length > 0) {
data.list = [...data.list, data.trash[data.trash.length - 1]]
data.trash = data.trash.slice(0, -1)
browser.storage.local.set({ list: data.list, trash: data.trash })
_render(true)
} else {
alert("Nothing to undo.")
}
})
}
const _renderTheme = () => {
//font and font size stay unset until chosen in settings, so fall back to the stylesheet instead of "undefined"
$textarea.style.fontFamily = data.font || ''
$textarea.style.fontSize = data.fontsize ? data.fontsize + "px" : ''
$textarea.style.lineHeight = data.fontsize ? data.fontsize * 1.5 + "px" : ''
if (window.utils.isDark(data)) {
$body.classList.add('dark')
$textarea.classList.add('dark')
$list.classList.add('dark')
$setting_gear.classList.add('dark')
}
else {
$body.classList.remove('dark')
$textarea.classList.remove('dark')
$list.classList.remove('dark')
$setting_gear.classList.remove('dark')
}
$mode_switcher.hidden = !data.darktoggleonnotes
$credits_button.hidden = !data.showcredits
$list_indicator.checked = Boolean(data.listopen)
}
const _themeSwitchHandler = () => {
$mode_switcher.addEventListener('click', event => {
//choosing a theme by hand stops following the system
data.mode = window.utils.isDark(data) ? THEMES.day : THEMES.night
data.followsystem = false
browser.storage.local.set({ mode: data.mode, followsystem: data.followsystem })
_renderTheme()
})
window.utils.systemDarkMode.addEventListener('change', _renderTheme)
}
//remember whether the note list was left open
const _listToggleHandler = () => {
$list_indicator.addEventListener('change', () => {
data.listopen = $list_indicator.checked
browser.storage.local.set({ listopen: data.listopen })
})
}
const _settingHandler = () => {
$setting_gear.addEventListener('click', event => {
window.open('settings.html')
})
}
const _multiTabHandler = () => {
const loadLatestData = async updateTabInfo => {
let currentTabInfo = await browser.tabs.getCurrent()
if (typeof updateTabInfo === 'object') { // tab switch
if (currentTabInfo.id !== updateTabInfo.tabId || currentTabInfo.windowId !== updateTabInfo.windowId) { return }
}
else { // window
if (currentTabInfo.windowId !== updateTabInfo) { return }
}
data = await window.utils.loadPreference()
_render(true)
_renderTheme()
}
browser.tabs.onActivated.addListener(loadLatestData)
// XXX: Window event causing double click issue, should temporarily comment it when default open sidebar...
browser.windows.onFocusChanged.addListener(loadLatestData)
}
const _initEventHandler = () => {
_noteEventHandler()
_storageChangeHandler()
_createButtonEventHandler()
_undoButtonEventHandler()
_themeSwitchHandler()
_listToggleHandler()
_settingHandler()
_multiTabHandler()
}
const _renderAnnoucement = async () => {
const syncRes = await browser.storage.sync.get()
if (!syncRes.list && !syncRes.mode) { return } // not use the version using storage.sync
// annoucement
const $annoucement_container = document.querySelector('.annoucement-container')
$annoucement_container.innerHTML = `
<div id='annoucement'>
Due to <a href='https://blog.mozilla.org/addons/2020/07/09/changes-to-storage-sync-in-firefox-79/' target='_blank'>Firefox WebExtension Storage API update</a>,
the sync function between Firefox is not work anymore...
<div class='btn'>So sad, I get it.</div>
</div>
`
const $migrate_btn = $annoucement_container.querySelector('.btn')
const migrateBtnOnClick = async () => {
$migrate_btn.removeEventListener('click', migrateBtnOnClick)
const before = await browser.storage.sync.get()
const clearRes = await browser.storage.sync.clear()
const after = await browser.storage.sync.get()
$annoucement_container.remove()
}
$migrate_btn.addEventListener('click', migrateBtnOnClick)
}
const init = async () => {
data = await window.utils.loadPreference()
//GitHub sync was removed in 4.0.4, so drop the token and sync state it left behind
browser.storage.local.remove(['map', 'gistid', 'offline'])
//render instantly so screen doesn't stay white
_render(true)
_renderAnnoucement()
_render(true)
_renderTheme()
_initEventHandler()
_enableAnimation()
}
return {
init: init
}
}
window.addEventListener('load', () => {
newtab_script().init()
})
})()