-
Notifications
You must be signed in to change notification settings - Fork 0
/
note.js
94 lines (78 loc) · 3 KB
/
note.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
(function () {
'use strict';
// https://stackoverflow.com/a/9310752/2289640
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
function makeQuery(text) {
return '^' + escapeRegExp(text) + '$';
}
function setNote(notesStorage, tabUrl, noteText) {
var nowDate = (new Date()).getTime(),
page,
pageIdx = notesStorage.find("url", makeQuery(tabUrl));
if (pageIdx !== -1) {
page = notesStorage.getRecordByIndex(pageIdx);
page.udate = nowDate;
page.note = noteText;
notesStorage.updateRecord(page);
return false; // При обновлении возвращаем FALSE.
} else {
page = notesStorage.createRecord({
url: tabUrl,
note: noteText,
cdate: nowDate,
udate: nowDate
});
return true; // При создании возвращаем TRUE.
}
}
function getNote(notesStorage, tabUrl) {
var nowDate = (new Date()).getTime(),
page,
pageIdx = notesStorage.find("url", makeQuery(tabUrl));
if (pageIdx !== -1) {
page = notesStorage.getRecordByIndex(pageIdx);
return page;
} else {
return {
url: tabUrl,
note: "",
cdate: nowDate,
udate: nowDate
};
}
}
function notesChangedCallback() {
// Do nothing.
}
function save(notesStorage, noteText) {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (setNote(notesStorage, tabs[0].url, noteText)) {
chrome.pageAction.setIcon({ path: "icons.iconarchive.com/icons/fatcow/farm-fresh/16/note-edit-icon.png", tabId: tabs[0].id });
}
});
}
document.addEventListener('DOMContentLoaded', function () {
var port = chrome.runtime.connect(), // https://stackoverflow.com/q/39730493
notesStorage = new WebStore(localStorage, 'note', notesChangedCallback),
notes = notesStorage.getAllRecords(),
noteTextArea = document.getElementById("noteTextArea");
noteTextArea.addEventListener("keyup", function () {
var noteText = this.value;
save(notesStorage, noteText);
});
noteTextArea.addEventListener("paste", function () {
var noteText = this.value;
save(notesStorage, noteText);
});
noteTextArea.addEventListener("cut", function () {
var noteText = this.value;
save(notesStorage, noteText);
});
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
var page = getNote(notesStorage, tabs[0].url);
noteTextArea.value = page.note;
});
});
}());