forked from Aplokjoy/Chrome-Notepad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
executable file
·250 lines (227 loc) · 8.28 KB
/
background.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
// todo add google analytics
const NEW = "NEW";
var BOOKMARK_NAME = "CuteNotepad";
var TRASH_BOOKMARK_NAME = "trashedNotes";
var SUBSTRING_END_INDEX = 15;
const RECENTLY_UPDATED_COUNT = 4;
var Model = {
bookmarkData: {}
};
var ContextMenuBuilder = function () {
var ContextMenuBuilderInstance;
// active notes
var notes = [];
function setUpContextMenus() {
chrome.contextMenus.removeAll();
chrome.contextMenus.create({
id: NEW,
title: "Create into a new note",
contexts:["selection"]
});
for (var i = 0; i < notes.length; i++) {
if (i > RECENTLY_UPDATED_COUNT) break;
chrome.contextMenus.create({
id: notes[i].id,
title: "Add to " + notes[i].title,
contexts:["selection"]
});
}
chrome.contextMenus.onClicked.addListener(updateNote);
}
function updateNote(itemData) {
if (itemData.menuItemId === NEW) {
createNewNote(itemData)
} else {
var note = notes.filter(function(note) {
return note.id === itemData.menuItemId;
});
if (note.length === 1) {
var content = note[0].url.replace("data:text/plain;charset=UTF-8,", "");
content = decodeURIComponent(content) + getNewContent(itemData);
chrome.bookmarks.update(note[0].id, {
title: getTitleFromContent(content),
url: "data:text/plain;charset=UTF-8," + encodePercentSymbol(content)
}, updatedNote => {
// todo track context menu used to add to existing view
const index = notes.findIndex(note => note.id === updatedNote.id);
notes.splice(index, 1);
notes.unshift(updatedNote);
setUpContextMenus();
});
} else {
// very unlikely todo log
}
}
}
function getTitleFromContent(content) {
var d = document.createElement('div');
d.innerHTML = content;
return d.textContent.trim().substring(0, SUBSTRING_END_INDEX) || "New Note";
}
function encodePercentSymbol(str) {
return str.replace(/%/g, "%25");
}
/**
* when we select 'add to a new note' in contextmenu
* @param itemData
*/
function createNewNote(itemData) {
var newContent = getNewContent(itemData);
chrome.bookmarks.create({
parentId: Model.bookmarkData.id,
title: getTitleFromContent(itemData.selectionText),
url: "data:text/plain;charset=UTF-8," + encodePercentSymbol(newContent)
}, function(bookmarkNode) { // new note
// todo track context menu used to add to new view
notes.unshift(bookmarkNode);
setUpContextMenus();
});
}
function getSource(itemData) {
return itemData.pageUrl ? itemData.pageUrl : itemData.frameUrl;
}
function getNewContent(itemData) {
return "<div>" + itemData.selectionText + "</div>";
}
function build(activeNotes) {
notes = activeNotes;
setUpContextMenus();
}
const obj = {
buildWith: build
};
if (!ContextMenuBuilderInstance) {
ContextMenuBuilderInstance = obj
}
return ContextMenuBuilderInstance;
}();
/**
* Genesis
*/
chrome.runtime.onInstalled.addListener(function(details) {
if (!details.previousVersion) {
localStorage.setItem("isNewInstallation", "true"); // registered here and google event triggered in view as there is no access to Utils here
} else {
localStorage.setItem("isNewInstallation", "false");
}
launchNotes();
});
function launchNotes() {
return new Promise(resolve => {
loadLocalData();
chrome.bookmarks.search(BOOKMARK_NAME, function(bookmarkTreeNodes) {
// bookmarkTreeNodes sample "[{"dateAdded":1580827736483,"dateGroupModified":1589585176156,"id":"512","index":1,"parentId":"2","title":"CuteNotepad"}]"
if (bookmarkTreeNodes.length === 0) {
// fresh
bootstrapNotes(launchTrash);
} else {
Model.bookmarkData = bookmarkTreeNodes[0];
launchTrash();
chrome.bookmarks.getSubTree(Model.bookmarkData.id, function(bookmarkTreeNodes) {
var activeNotes = [];
bookmarkTreeNodes[0].children.forEach((item) => {
//No children means they are active notes.
if (!item.children) {
item.deleted = item.deleted ? item.deleted : false;
activeNotes.push(item);
}
});
var orderMap = localStorage['orderMap'] &&
(typeof localStorage['orderMap'] === "string") &&
JSON.parse(localStorage['orderMap']) || {};
activeNotes.sort((a, b) => {
//Means no children - if children then it means it is a trash notes folder
if (!(a.children || b.children)) {
if (orderMap[a.id] && orderMap[b.id]) {
return orderMap[a.id].displayOrder - orderMap[b.id].displayOrder;
} else {
return 1;
}
}
});
ContextMenuBuilder.buildWith(activeNotes);
resolve();
});
}
});
}, reject => {
// unlikely todo
});
}
function bootstrapNotes(cb) {
chrome.bookmarks.create({ "title": BOOKMARK_NAME }, function(bookmarkTreeNode) {
Model.bookmarkData = bookmarkTreeNode;
ContextMenuBuilder.buildWith([]);
cb && cb();
});
}
function launchTrash() {
chrome.bookmarks.search(TRASH_BOOKMARK_NAME, function(trashTreeNodes) {
if (trashTreeNodes.length === 0) {
bootstrapTrash();
} else {
Model.trashedFolderData = trashTreeNodes[0];
}
});
}
function bootstrapTrash() {
chrome.bookmarks.create({ "title": TRASH_BOOKMARK_NAME, parentId: Model.bookmarkData.id }, function(trashTreeNode) {
Model.trashedFolderData = trashTreeNode;
});
}
function loadLocalData() {
if (localStorage['data']) {
try {
Model.data = JSON.parse(localStorage['data']);
Model.selectedNoteId = Model.data.selectedNoteId;
Model.collapsed = Model.data.collapsed;
} catch (ex) {
Model.data = null;
}
}
// Initialize this.data
if (!Model.data) {
Model.data = {
'content': '',
'selection': {
'start': 0,
'end': 9
},
'scroll': {
'left': 0,
'top': 0
},
'size': {
'width': 100,
'height': 80
},
'options': {
'sync': true
}
}
}
if (!Model.data.options) {
Model.data.options = {
'sync': true
}
}
}
function loadConfig(cb) {
chrome.storage.sync.get({
fontSize: "14px",
fontFamily: "default",
size: 300
}, function (item) {
cb(item);
});
}
function getCoronaMessage() {
var messages = [{message: "Coronavirus: Do not leave your home", emoji: "🏡"},
{message: "Coronavirus: Regularly and thoroughly clean your hands", emoji: "👐"},
{message: "Coronavirus: Stay at least 3 feet away from others", emoji: "⇠⇢"},
{message: "Coronavirus: Work from home if you can ", emoji: "💻"},
{message: "Coronavirus: If unwell isolate yourself from family", emoji: "😷"},
{message: "Coronavirus: Cover coughs and sneezes", emoji: "💦"}
];
return messages[Math.floor(Math.random() * Math.floor(messages.length))];
}