-
Notifications
You must be signed in to change notification settings - Fork 0
/
newCardModal.js
109 lines (95 loc) · 2.61 KB
/
newCardModal.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
$(document).ready(function () {
let pageUrl;
let numberOfCards;
$("#newCardBtn").attr("disabled", true);
// creating new card
chrome.storage.sync.get(["message"], function (result) {
if (result) {
// for question
if (result.message.itemId === "cardFront") {
$("#question").val(sanitizeString(result.message.text));
}
// for answer
else if (result.message.itemId === "cardBack") {
$("#answer").val(sanitizeString(result.message.text));
}
pageUrl = result.message.pageUrl;
}
});
function checkStatus() {
var q = $("#question").val();
var ans = $("#answer").val();
if (q != "" && ans != "" && numberOfCards <= 10) {
$("#newCardBtn").attr("disabled", false);
$("#newCardBtn").removeClass("cardOff");
} else {
$("#newCardBtn").attr("disabled", true);
$("#newCardBtn").addClass("cardOff");
}
}
$(document).on("input", "textarea", checkStatus);
$("#cancelBtn").click(removeModal);
// cancel cardModal
function removeModal() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
action: "REMOVE_CARD",
});
});
}
// handle card creation
$("#newCardBtn").click(function () {
getFromStorage(function (cards) {
const question = sanitizeString($("#question").val());
const answer = sanitizeString($("#answer").val());
const card = {
id: getID(),
question,
answer,
pageUrl,
};
cards.push(card);
saveToStorage(cards);
resetTextarea();
removeModal();
});
});
// local storage
function getFromStorage(callback) {
chrome.storage.sync.get(["cards"], function (result) {
if (result && result.cards) {
callback(result.cards);
} else callback([]);
});
}
function saveToStorage(cards, cb) {
chrome.storage.sync.set({ cards }, function () {
console.log("card added");
});
}
// sanitizing input
function sanitizeString(str) {
str = str.replace(/[^a-z0-9 \.,_-]/gim, "");
return str.trim();
}
// generate unique id
function getID() {
console.log(Math.random().toString(36));
return "_" + Math.random().toString(36).substr(2, 9);
}
function onLoad() {
resetTextarea();
getFromStorage(function (cards) {
numberOfCards = cards.length;
});
}
function resetTextarea() {
$("#question").val("");
$("#answer").val("");
}
onLoad();
// just for testing -- will remove later
// getFromStorage(function (cards) {
// console.log(cards);
// });
});