Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
300 lines (244 loc) · 10.4 KB
/
Copy pathindex.js
File metadata and controls
300 lines (244 loc) · 10.4 KB
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
// This is the main script
// Fix issue for parcel/babel, for async await thing for old browser, or only support new browsers with async await functionality
// https://flaviocopes.com/parcel-regeneratorruntime-not-defined/
// import 'regenerator-runtime/runtime'
// Fix issue for parcel jquery script
// https://github.com/parcel-bundler/parcel/issues/333#issuecomment-504552272
// https://www.npmjs.com/package/jquery
// import $ from 'jquery'
// import Cookies from 'js-cookie'
import './commoncode.js'
const defaultEdition = 'eng-mustafakhattabg'
let editionsJSON
// Lock to wait for translations to show
let lock = false
// call this only once
async function oneTimeFunc() {
document.querySelector('#mycontainer').insertAdjacentHTML('afterbegin', window.searchBar);
// Editions JSON from quran api
[editionsJSON] = await window.getJSON(['editions'])
// Create the dropdown
await createDropdown()
// first set edition, then chapter, then verse
setInitEditions()
setInitChapter()
// show the translations on cookie/link selected values
await window.showTranslations()
setInitVerse()
// Add searchable select
$('select').select2({
theme: 'bootstrap4',
});
let hashValue = getHashTextFragment()
if(hashValue)
location = hashValue
await new Promise(r => setTimeout(r, 2000));
addEventListener('hashchange', async (event) => {
let [newURLChapter, newURLVerse ]= new URL(event.newURL).hash.substring(1).split(':')
let [oldURLChapter, oldURLVerse ]= new URL(event.oldURL).hash.substring(1).split(':')
if(newURLChapter && newURLChapter!=oldURLChapter){
window.currentVerse = newURLVerse
$('#chapter option[value="' + newURLChapter + '"]').prop('selected', true)
$('#chapter').trigger('change');
lock = true
while(lock){
await new Promise(r => setTimeout(r, 500));
}
if(newURLVerse){
$('#verse option[value="' + new URL(event.newURL).hash + '"]').prop('selected', true)
$('#verse').trigger('change');
}
}
if(newURLChapter==oldURLChapter && newURLVerse && newURLVerse!= oldURLVerse){
$('#verse option[value="' + new URL(event.newURL).hash + '"]').prop('selected', true)
$('#verse').trigger('change');
}
});
}
function setInitEditions() {
// Set by url
const currenturl = new window.URL(window.location)
const urlparams = currenturl.searchParams
if (urlparams.get('editions') !== null) {
urlparams.get('editions').split(',').map(e => $('#translationdropdown option[value="' + e + '"]').prop('selected', true))
return
}
// Set editions by cookie
const editionCookie = Cookies.get('editions')
if (editionCookie !== undefined) {
JSON.parse(editionCookie).map(e => $('#translationdropdown option[value="' + e + '"]').prop('selected', true))
return
}
// set to default edition
$('#translationdropdown option[value="' + defaultEdition + '"]').prop('selected', true)
}
function setInitChapter() {
// Set chapter by url
if (window.location.hash !== '') {
const chapterVerse = window.location.hash.substring(1).split(':')
$('#chapter option[value="' + chapterVerse[0] + '"]').prop('selected', true)
return
}
// Set chapter by param
if ((new URL(window.location)).searchParams.get('chapter') !== null) {
const chapter = (new URL(window.location)).searchParams.get('chapter')
$('#chapter option[value="' + chapter + '"]').prop('selected', true)
return
}
// Set chapter by cookie
const chapterCookie = Cookies.get('chapter')
if (chapterCookie !== undefined) {
$('#chapter option[value="' + chapterCookie + '"]').prop('selected', true)
return
}
// Set chapter to 1 if all the above doesn't work
$('#chapter option[value="1"]').prop('selected', true)
}
function setInitVerse() {
// Stores the chapter & verse from link hash , eg: #4:3
const chapterVerse = window.location.hash.substring(1).split(':')
// scroll to specific verse if it existed in link hash
if (chapterVerse.length > 1)
$('#verse option[value="' + window.location.hash + '"]').prop('selected', true)
}
// Creates and add listing to the dropdown based on editions.json
async function createDropdown() {
// Sorts language & author , edition Name
const langEdition = []
for (const value of Object.values(editionsJSON)) {
let dropdownText
// check edition name ends with -la, then
if (/\-la$/i.test(value.name)) { dropdownText = value.language + ' Latin - ' + value.author } else if (/\-lad$/i.test(value.name)) { dropdownText = value.language + ' LatinD - ' + value.author } else { dropdownText = value.language + ' - ' + value.author }
langEdition.push([dropdownText, value.name, value.direction])
}
// sort by dropdowntext
langEdition.sort()
for (const [value, key, dir] of langEdition) { $('#translationdropdown').append('<option value="' + key + '" data-dir="' + dir + '">' + value + '</option>') }
// Create chapter dropdown
for (let i = 1; i <= CHAPTER_LENGTH; i++) { $('#chapter').append('<option value="' + i + '">' + i + ' - ' + arabicChapters[i - 1] + ' (' + englishChapters[i - 1] + ')</option>') }
}
window.showTranslations = async function showTranslations(event) {
lock = true
// Not a great way to do
$('#versescolumn').empty()
// Add the card element, so verses get shown in cards
$('#versescolumn').append('<div id="verseslist" class="card list-group list-group-flush"></div>')
const selectedValues = $('#translationdropdown').val().filter(elem => !/^\s*$/.test(elem))
// Holds chapter & editionName
let chapEdDirHolder = []
const chapterNo = $('#chapter').val()
const endpointsArr = []
if (chapterNo === '') { return }
// Set the cookies
if (selectedValues.length > 0) {
Cookies.set('editions', JSON.stringify(selectedValues), { expires: 1000, path: '' })
Cookies.set('chapter', chapterNo, { expires: 1000, path: '' })
showSpinningWheel('#versescolumn','afterbegin')
}
for (const edName of selectedValues) {
const endpoint = 'editions' + '/' + edName + '/' + chapterNo
endpointsArr.push(endpoint)
}
const chaptersArr = await getChapterArr(endpointsArr)
chapEdDirHolder = chaptersArr.map((e, i) => [e, selectedValues[i], $('#translationdropdown option[value="' + selectedValues[i] + '"]').attr('data-dir'), $('#translationdropdown option[value="' + selectedValues[i] + '"]').text()])
// offset by these verses due for better scrolling due to fixed header
const offset = 1
// create empty element with verse 1 id , so to avoid issues due to offset
$('#verseslist').append('<span id="' + chapterNo + ':1"> </span>')
removeSpinningWheel()
let classValues
for (let i = 1; i <= chaplength[chapterNo - 1]; i++) {
for (const [chapter, edName, dir, dropDownText] of chapEdDirHolder) {
const id = chapterNo + ':' + (i + offset)
classValues = edName + ' list-group-item p-2'
$('#verseslist').append('<div class="' + classValues + '" dir="' + dir + '" id="' + id + '"><span class="badge bg-light text-dark" data-bs-toggle="tooltip" title="' + dropDownText + '">' + i + '</span>' + ' - ' + chapter[i - 1] + '</div>')
}
}
initializeTooltip()
createVerseDropDown()
// Add editions in current url
let currenturl = new window.URL(window.location)
currenturl.searchParams.set('editions', selectedValues.join(','));
currenturl.searchParams.set('chapter', document.querySelector('#chapter').value);
//let [chapterValue ]= document.querySelector('#verse').value.substring(1).split(':')
if(event?.id != "translationdropdown")
currenturl.hash = window.currentVerse ? `${document.querySelector('#chapter').value}:${window.currentVerse}` : document.querySelector('#chapter').value
// Change url without reload
window.history.pushState({}, "", currenturl);
// Set variables to initial value
window.currentVerse=undefined;
lock = false
}
function initializeTooltip() {
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
const tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new window.bootstrap.Tooltip(tooltipTriggerEl)
})
}
function createVerseDropDown() {
$('#verse').empty()
$('#verse').append('<option value="" selected>Verse</option>')
const chapterNo = $('#chapter').val()
for (let i = 1; i <= chaplength[chapterNo - 1]; i++) {
const anchor = '#' + chapterNo + ':' + i
$('#verse').append('<option value="' + anchor + '">' + i + '</option>')
}
}
// Fetches the translationLinks and returns the translations in optimized array form
// Also assigns it to global translationsArr
async function getChapterArr(endpointsArr) {
const transJSON = await window.getJSON(endpointsArr)
return transJSON.map(e => e.chapter.map(e => e.text))
}
// Hash with Text Fragment
function getHashTextFragment(){
let hashWithFragment;
// https://web.dev/text-fragments/#obtaining-text-fragments-for-analytics-purposes
try{
hashWithFragment = new URL(performance.getEntries().find(({ type }) => type === 'navigate').name).hash
}catch(e){}
return hashWithFragment || window.location.hash
}
// Call initializer function in the beginning itself, to fetch all necessary JSON's
let initVar
window.addEventListener('DOMContentLoaded', (event) => {
initVar = oneTimeFunc()
})
/*
function getDirection (str) {
const divelem = document.createElement('div')
divelem.dir = 'auto'
divelem.innerHTML = str
divelem.style.display = 'none'
document.body.appendChild(divelem)
const direction = window.getComputedStyle(divelem).getPropertyValue('direction')
divelem.remove()
return direction
}
async function getFont(url) {
let fontName = url.replace(/\.[^\.]*$/,"").replace(/.*\//,"")
const font = new FontFace(fontName, 'url('+url+')');
// wait for font to be loaded
await font.load();
// add font to document
document.fonts.add(font);
return fontName
}
const fontsLink = apiLink + '/fonts';
let fontEdition={
'ara-quranindopak': 'nastaleeq-v10-full',
'ara-qurannastaleeqn': 'hafs-nastaleeq-ver10',
'ara-quranbazzi': 'bazzi-v7-full',
'ara-qurandoori': 'doori-v8-full',
'ara-qurandoorinonun': 'uthmanic-doori1-ver08',
'ara-quranuthmanihaf': 'hafs-uthmanic-v14-full',
'ara-quranqaloon': 'qaloon-v8-full',
'ara-quranqumbul': 'qumbul-v7-full',
'ara-quranshouba': 'shouba-v7-full',
'ara-quransoosi': 'soosi-v8-full',
'ara-quransoosinonun': 'uthmanic-soosi1-ver08',
'ara-quranwarsh': 'warsh-v8-full'
};
for(const [key , value] of Object.entries(fontEdition))
fontEdition[key] = fontsLink+'/'+value+'.woff2'
*/