-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbooklet.js
289 lines (268 loc) · 11.8 KB
/
booklet.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
const LISTENER_OPTS = {
once: true,
passive: true,
},
STORE = 'coupons',
DB_VERSION = 1,
WWW_PREFIX = 'www.',
DOUBLE_DIGIT = 2,
ONE = 1,
NONE = 0;
//TODO context menu item that pre-fills add form with selection and current URL
//TODO option to define URL aliases
//TODO support coupon websites and pre-fill more info from that (content script)
//TODO support being loaded in a sidebar and communicating with a potential popup
function waitForRequest(request) {
return new Promise((resolve, reject) => {
request.addEventListener("success", resolve, LISTENER_OPTS);
request.addEventListener("error", reject, LISTENER_OPTS);
});
}
function ignoreWWW(host) {
if(host.startsWith(WWW_PREFIX)) {
return host.slice(WWW_PREFIX.length);
}
return host;
}
function getHost(url) {
return (new URL(url)).hostname;
}
Promise.all([
new Promise((resolve, reject) => {
try {
const request = globalThis.indexedDB.open(STORE, DB_VERSION);
resolve(waitForRequest(request));
}
catch(error) {
reject(error);
// can't open DB
}
}),
new Promise((resolve) => {
document.addEventListener("DOMContentLoaded", resolve, LISTENER_OPTS);
}),
])
.then(([ { target: { result: database } } ]) => {
const now = new Date();
document.querySelector("#expiryDate").min = `${now.getFullYear()}-${(now.getMonth() + ONE).toString().padStart(DOUBLE_DIGIT, '0')}-${now.getDate().toString()
.padStart(DOUBLE_DIGIT, '0')}`;
function showAdd() {
document.querySelector("#addcoupon").hidden = false;
document.querySelector("ul").hidden = true;
document.querySelector("header").hidden = true;
document.querySelector("#add").hidden = true;
document.querySelector("#add").disabled = true;
}
function removeCoupon(id) {
const transaction = database.transaction(STORE, 'readwrite'),
store = transaction.objectStore(STORE),
request = store.delete(id);
waitForRequest(request)
.then(loadCoupons) //eslint-disable-line no-use-before-define
.catch(console.error);
}
async function buildList(coupons, list) {
const [ currentTab ] = await browser.tabs.query({
active: true,
currentWindow: true,
}),
currentHost = ignoreWWW(getHost(currentTab.url));
let addedSome = false,
itemCount = 0;
for(const host in coupons) {
if(coupons.hasOwnProperty(host)) {
addedSome = true;
const hostItem = document.createElement("li"),
hostDetails = document.createElement("details");
if(currentHost == ignoreWWW(host)) {
hostItem.classList.add('current');
itemCount += coupons[host].length;
hostDetails.open = true;
}
const hostSummary = document.createElement("summary"),
mainTitle = document.createElement("span");
mainTitle.classList.add('space');
mainTitle.textContent = host;
hostSummary.append(mainTitle);
// This is a button and not a link because a link would open in a new window instead of a tab
// and the button styles would havee to be manually ported to it.
const open = document.createElement("button");
open.classList.add('browser-style');
open.textContent = 'visit';
open.title = browser.i18n.getMessage("open");
open.addEventListener("click", (event) => {
event.preventDefault();
// Yes, we assume HTTPS here, but you shouldn't be shopping on HTTP sites to start with...
browser.tabs.create({
url: `https://${host}`,
})
.then(() => {
window.close();
})
.catch(console.error);
}, {
passive: false,
once: true,
});
hostSummary.append(open);
hostDetails.append(hostSummary);
const couponCodes = document.createElement("ul");
for(const code of coupons[host]) {
const codeItem = document.createElement("li"),
codeTitle = document.createElement("span");
codeTitle.classList.add('space');
codeTitle.classList.add('code');
codeTitle.textContent = code.coupon;
codeItem.append(codeTitle);
const buttonGroup = document.createElement("span");
if(code.expires > new Date(NONE)) {
codeItem.title = browser.i18n.getMessage("valid", code.expires.toLocaleDateString());
buttonGroup.append(document.createTextNode('⏰'));
}
if(code.notes) {
if(codeItem.title) {
codeItem.title += ' - ';
}
codeItem.title += code.notes;
buttonGroup.append(document.createTextNode('🗒️'));
}
buttonGroup.classList.add('button-group');
const copy = document.createElement("button");
copy.textContent = "copy";
copy.title = browser.i18n.getMessage("copy");
copy.classList.add('browser-style');
copy.classList.add('default');
copy.addEventListener("click", () => {
navigator.clipboard.writeText(code.coupon);
//TODO tell the user that it was copied
}, { passive: true });
const remove = document.createElement("button");
remove.textContent = '×';
remove.title = browser.i18n.getMessage("delete");
remove.classList.add('browser-style');
remove.addEventListener("click", () => {
removeCoupon(code.id);
}, { passive: true });
buttonGroup.append(remove);
buttonGroup.append(copy);
codeItem.append(buttonGroup);
couponCodes.append(codeItem);
}
hostDetails.append(couponCodes);
hostItem.append(hostDetails);
list.append(hostItem);
}
}
if(!addedSome) {
const empty = document.createElement("li");
empty.textContent = browser.i18n.getMessage("empty");
empty.classList.add("empty");
list.append(empty);
}
browser.browserAction.setBadgeText({
text: itemCount > NONE ? itemCount.toString() : "",
tabId: currentTab.id,
});
}
function loadCoupons() {
const list = document.querySelector("main > ul");
while(list.firstElementChild) {
list.firstElementChild.remove();
}
const transaction = database.transaction(STORE),
store = transaction.objectStore(STORE),
request = store.openCursor(),
coupons = {};
request.addEventListener("success", (event) => {
const cursor = event.target.result;
if(cursor) {
const { value } = cursor;
let hostToUse = value.host;
if(coupons.hasOwnProperty(ignoreWWW(value.host))) {
hostToUse = ignoreWWW(value.host);
}
else if(!coupons.hasOwnProperty(hostToUse)) {
const withWWW = WWW_PREFIX + ignoreWWW(value.host);
if(coupons.hasOwnProperty(withWWW)) {
coupons[hostToUse] = coupons[withWWW];
delete coupons[withWWW];
}
else {
coupons[hostToUse] = [];
}
}
coupons[hostToUse].push(value);
cursor.continue();
}
else {
buildList(coupons, list).catch(console.error);
}
});
request.addEventListener("error", (event) => {
//TODO handle erros
console.error(event);
});
}
function hideAdd() {
document.querySelector("#addcoupon").hidden = true;
document.querySelector("ul").hidden = false;
document.querySelector("header").hidden = false;
document.querySelector("#add").hidden = false;
document.querySelector("#add").disabled = false;
document.querySelector("form").reset();
loadCoupons();
}
function addCoupon(event) {
event.preventDefault();
const coupon = {
coupon: document.querySelector("#code").value,
host: getHost(document.querySelector("#website").value),
notes: document.querySelector("#notes").value,
},
expiry = document.querySelector("#expiryDate");
if(expiry.value) {
coupon.expires = expiry.valueAsDate;
}
else {
coupon.expires = new Date(NONE);
}
const transaction = database.transaction(STORE, 'readwrite'),
store = transaction.objectStore(STORE),
request = store.add(coupon);
waitForRequest(request)
.then(hideAdd)
.catch(console.error);
}
// init
document.querySelector("#add").addEventListener("click", showAdd, { passive: true });
document.querySelector("form").addEventListener("submit", addCoupon, { passive: false });
document.querySelector("#back").addEventListener("click", hideAdd, { passive: true });
document.querySelector("#useCurrent").addEventListener("click", () => {
browser.tabs.query({
active: true,
currentWindow: true,
})
.then((tabs) => {
if(tabs.length) {
const [ firstTab ] = tabs;
document.querySelector("#website").value = firstTab.url;
}
})
.catch(console.error);
}, { passive: true });
document.documentElement.addEventListener("toggle", (event) => {
if(event.target.open) {
const details = document.querySelectorAll("details");
for(const detail of details) {
if(!detail.isEqualNode(event.target) && detail.open) {
detail.open = false;
}
}
}
}, {
passive: true,
capture: true,
});
loadCoupons();
})
.catch(console.error);