-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontentScript.js
309 lines (271 loc) · 10.7 KB
/
contentScript.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
function search_topics(e) {
var val = $(e.srcElement).val();
console.log("Pre-Scrubbed:" + val);
val = val.replace(/[^א-תa-zA-Z0-9\s\w\.\']+/g, ' ');
console.log("Post-Scrubbed: " + val);
if (val.length < 3) {
$("#sef-results").empty();
filter_references(null);
} else {
filter_references(val);
$.get("//www.sefaria.org.il/api/name/" + val)
.done(function (data) {
if (data.completion_objects) {
var result = data.completion_objects.filter(function (val) { return val.type == 'ref' });
var safeValue=$("<div>").text(val).html();
var html = "<li><A id='sef-feeling-lucky' style='color:red;' class='_sefaria_link' data-link=\"//sefaria.org.il/" + escape(val) + "\">" + safeValue + "</a></li>";
result.forEach(function (x) {
html += "<li><A class='_sefaria_link' data-link=\"//sefaria.org.il/" + escape(x.key) + "\">" + x.title + "</a></li>";
});
console.log(html);
}
$("#sef-results").html(html);
});
}
}
function filter_references(text){
$("li.sef-category-item").toggleClass("sef-filtered",false);
if(text==null) return;
$("li.sef-category-item").filter(function(){
var link=$(this).find("a").first();
var textMatch= link.text()
.toLowerCase()
.replace(/['\'\"']+/g, '')
.replace(/[^א-תa-zA-Z0-9\s\w\.\']+/g, ' ')
.indexOf(text.toLowerCase())==-1;
var refMatch=link.data('ref').toLowerCase()
.replace(/['\'\"']+/g, '')
.replace(/[^א-תa-zA-Z0-9\s\w\.\']+/g, ' ')
.indexOf(text.toLowerCase())==-1;
return textMatch && refMatch;
}).toggleClass("sef-filtered",true);
}
function sefariaFeelingLucky() {
$("#sef-feeling-lucky").click();
setTimeout(clearSefariaSearch, 1500);
}
function clearSefariaSearch() {
$("#sef-search-box").val("");
$("#sef-results").empty();
filter_references(null);
}
var sefaria_current = null;
function sefariaLinkClicked(e) {
e.stopPropagation();
var url = $(e.target).data('link');
load_sefaria(url);
$("#sef-sidebar-ext ol li").toggleClass('active', false);
$(e.target).parent().toggleClass('active', true);
}
function escapeQuotes(str){
return str.replace(/([\"\'\\])/g,"\\$1");
}
function load_sefaria(url, force) {
var same = (sefaria_current === url);
if (!same || force) {
sefaria_current = url;
if (force) url += ((url.indexOf("?") > -1) ? "&" : "?") + "r=" + new Date().getTime();
$(".loading-mask").show();
$("#sef-sidebar-ext-iframe").hide();
$('#sef-sidebar-ext-iframe').attr('src', url);
}
$('#sef-sidebar-ext-modal-viewer').toggleClass('visible', true);
}
var pages = [];
function removeSidebar() {
pages=[];
$("#sefaria-extension-output").remove();
}
var categories = [];
async function getLinks(txt, mode) {
console.log("//www.sefaria.org.il/api/links/" + txt);
// Check if I'm getting both sides or just one side
if (mode && mode == DOUBLE) {
console.log("Getting both sides of the page");
if (/.*([א-ת]+)$/.test(txt)) {
pages.push({ page: txt + " א", title: "עמוד א", id: "sef-side-a" });
pages.push({ page: txt + " ב", title: "עמוד ב", id: "sef-side-b" });
} else if (/.*([0-9]+)$/.test(txt)) {
pages.push({ page: txt + "a", title: "עמוד א", id: "sef-side-a" });
pages.push({ page: txt + "b", title: "עמוד ב", id: "sef-side-b" });
}
console.log("INITIAL LINK TEXT: " + txt)
} else {
pages.push({ page: txt, id: "sef-side-a" });
}
pages.map((frame) => {
frame.open = true;
frame.page = frame.page.trim();
});
console.log("PAGES: " + JSON.stringify(pages));
categories = [];
var categoryCounts = {};
// playing with async/await - for some reason this likes not being in a callback
for (var i = 0; i < pages.length; ++i) {
console.log("Loading for "+pages[i]);
pages[i].data = await getData(pages[i].page);;
console.log("Loaded Data for "+pages[i]);
pages[i].data.forEach(d => { if (!categoryCounts[d.category]) categoryCounts[d.category] = 1; else categoryCounts[d.category]++; });
}
categories = Object.keys(categoryCounts).sort();
var totalCount=0;
Object.keys(categoryCounts).forEach(function(key){ totalCount+=categoryCounts[key]; });
console.log("Frames: " + pages.length);
var html = "<span id='sefaria-extension-output'><div id='sef-sidebar-ext-btn2'></div><div id='sef-sidebar-ext' ><div class='logowrap'><div id='sef-sidebar-ext-btn'></div></div>";
html += "<div id='sef-search'><input type='text' id='sef-search-box' style='width:95%' placeholder='Search Sefaria'/><ol id='sef-results'></ol></div>";
html += "<div id='sef-categories'>";
html += "<a class='sef-cat-hdr' data-category='all' id='sef-cat-all'>ALL("+totalCount+")</a> ";
categories.forEach(cat => {
html += "<a class='sef-cat-hdr ' data-category='" + cat + "' id='sef-cat-" + cat + "'>" + cat + " (" + categoryCounts[cat] + ")</a> ";
});
html += "</div>";
$.each(pages, function (i, frame) {
html += "<ol id='" + frame.id + "'><li style='color:red;font-weight:bold'><span class='sef-folder' id='sef-closed-" + frame.id + "'>📁</span><span class='sef-folder' id='sef-opened-" + frame.id + "'>📂</span><a class='_sefaria-link sef-category-main' data-link='//www.sefaria.org.il/" + frame.page + "?lang=he&with=all&lang2=he'>" + frame.page + "</a></li>";
var data = frame.data;
$.each(data, function (i, item) {
console.log(item.ref);
console.log(item.sourceHeRef);
console.log("//www.sefaria.org.il/" + escapeQuotes(item.ref));
html += "<li class='sef-category-item' data-category='" + item.category + "'><a class='_sefaria-link' data-ref='"+escapeQuotes(item.ref)+"' data-link='//www.sefaria.org.il/" + escapeQuotes(item.ref) + "?lang=he&lang2=he'>" + item.sourceHeRef + "</a></li>";
});
html += "</ol>";
});
html += "</div>";
html += "<div id='sef-sidebar-ext-modal-viewer'><div class='modalbar'><a id='modal-sidebar-new-win'>New Window</a> | <a id='modal-sidebar-reload'>Reload</a> | <a id='modal-sidebar-toggle'>Close</a></div><iframe id='sef-sidebar-ext-iframe' src='about:blank'></iframe><div class='loading-mask'>Loading Page...</div></div>";
html += "</span>";
$("body").append(html);
$(document).ready(function () {
$("#sef-search-box").on("input", search_topics);
$("#sef-search-box").on("keyup", function (e) {
if (e.which == 27) clearSefariaSearch();
if (e.which == 13) sefariaFeelingLucky();
});
$(".sef-cat-hdr").click(function () {
toggleCategory($(this).data("category"));
});
// hide all but halakha
$.each(categories, function (i, cat) {
toggleCategory(cat, false);
});
toggleCategory("Halakhah", true);
$.each(pages, function (i, page) {
var id = page.id;
// initial toggle
togglePage(id, true);
// subscribe to header bar
$("#" + id + " li:nth-of-type(1)").click(function () {
togglePage(id);
});
});
$("#sef-results").on('click', 'a', sefariaLinkClicked);
$("#sef-sidebar-ext-iframe").on("load", function () {
$(".loading-mask").hide();
$("#sef-sidebar-ext-iframe").show();
});
$('#sef-sidebar-ext-btn2').on('click', function () {
$('#sef-sidebar-ext').toggleClass('visible', true);
});
$('#sef-sidebar-ext-btn').on('click', function () {
$('#sef-sidebar-ext').toggleClass('visible', false);
$('#sef-sidebar-ext-modal-viewer').toggleClass('visible', false);
$(".loading-mask").hide();
});
$('#modal-sidebar-toggle,.modalbar').on('click', function () {
$('#sef-sidebar-ext-modal-viewer').toggleClass('visible', false);
});
$('#modal-sidebar-new-win').on('click', function () {
$('#sef-sidebar-ext-modal-viewer').toggleClass('visible', false);
window.open($("#sef-sidebar-ext-iframe").attr("src"));
});
$('#modal-sidebar-reload').on('click', function (e) {
e.stopPropagation();
load_sefaria(sefaria_current, true);
});
$('._sefaria-link').on('click', sefariaLinkClicked);
});
}
var activeCategories = [];
function toggleCategory(cat, state) {
if (state == null) {
if (activeCategories.indexOf(cat) > -1) {
state = false;
}
else state = true;
}
var idx = activeCategories.indexOf(cat);
if (state) {
if (idx == -1) activeCategories.push(cat);
} else {
if (idx > -1) delete activeCategories[idx];
}
if(cat=='all'){
$.each(categories, function (i, cat) {
toggleCategory(cat, state);
});
return;
}
console.log("Toggle Cat" + cat + "/" + state);
$(".sef-cat-hdr[data-category=\"" + cat + "\"]").toggleClass("sef-cat-hdr-active", state);
$(".sef-category-item[data-category=\"" + cat + "\"]").toggleClass("sef-cat-hidden", !state);
}
function setupExtension(url) {
removeSidebar();
var ref = getSefariaReference(url);
if (ref != null) {
console.log("Discovered reference: " + ref.site + " on " + ref.reference);
cleanUpReference(ref);
refreshExtension(ref.reference, ref.mode);
} else {
console.log("No referenceable Sefaria Content on this page.");
}
}
function cleanUpReference(ref){
// Would be nice if sefaria was more tolerant of alt spellings and case inesensitive 2word names
var alt_terms={
"sukah":"sukkah",
"yevamos":"yevamot",
"kesuvos":"ketubot",
"nidah":"niddah",
"makos":"makkot",
"horayos":"horayot",
"menachos":"menachot",
"chulin":"chullin",
"erchin":"arakhin",
"kerisus":"keritot"
}
var reference=ref.reference;
Object.keys(alt_terms).map(k=>{reference=reference.replace(k,alt_terms[k]);});
reference=reference.replace(/\b\w/g, function(c) {
return c.toUpperCase();
});
console.log("Cleaned up reference: "+reference);
ref.reference=reference;
}
function refreshExtension (reference,mode){
removeSidebar();
getLinks(reference, mode);
}
function togglePage(id, state) {
var myPage = pages.find(x => x.id === id);
if (state != null) myPage.open = state;
else myPage.open = !myPage.open;
$("#sef-closed-" + id).toggleClass("sef-hidden", myPage.open);
$("#sef-opened-" + id).toggleClass("sef-hidden", !myPage.open);
$("#" + id + " li:nth-of-type(n+2)").toggleClass("sef-hidden", !myPage.open);
}
function getData(txt) {
console.log("GetData "+txt);
return new Promise((resolve, reject) => {
var apiTarget="//www.sefaria.org.il/api/links/" + txt;
console.log("API Target: "+apiTarget);
$.get(apiTarget).done(function (data) {
data.map(item => { item.section = item.anchorRef.substring(0, item.anchorRef.indexOf(":")); })
console.log("GetData "+txt+"-->"+data.length);
data = data.filter(function (x) {
return true;//x.type == "ein mishpat / ner mitsvah";
});
resolve(data);
});
});
}
setupExtension(location.href);