-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
382 lines (346 loc) · 10.4 KB
/
index.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
let synth = window.speechSynthesis;
let utterance = new SpeechSynthesisUtterance();
let __PDF_DOC,
__CURRENT_PAGE = 1, //This is the page which is currently being spoken
__TOTAL_PAGES,
__PAGE_RENDERING_IN_PROGRESS = 0;
let canvas_width = 1000;
let pageHeight = -1;
let __VIEWING_PAGE = __CURRENT_PAGE;
function populateVoiceList() {
if (
typeof synth === "undefined" ||
document.getElementById("voiceSelect").childNodes.length > 0
) {
return;
}
const voices = synth.getVoices();
for (const element of voices) {
if (element.lang.substring(0, 2) === "en") {
const option = document.createElement("option");
option.textContent = `${element.name} (${element.lang})`;
if (element.default) {
option.textContent += " — DEFAULT";
}
option.setAttribute("data-lang", element.lang);
option.setAttribute("data-name", element.name);
document.getElementById("voiceSelect").appendChild(option);
}
}
}
if (typeof synth !== "undefined" && synth.onvoiceschanged !== undefined) {
synth.onvoiceschanged = populateVoiceList;
}
function startTextToSpeech(startWord) {
if (synth.speaking) {
synth.cancel();
}
let voices = synth.getVoices();
if (prevId !== 0)
document
.getElementById("word-" + __CURRENT_PAGE + "-" + prevId)
.classList.remove("highlight");
prevId = 0;
let selectedVoice = voices.filter(
(element) => element.lang.substring(0, 2) === "en"
)[document.getElementById("voiceSelect").selectedIndex];
if (selectedVoice !== null) {
utterance.voice = selectedVoice;
}
let textContent = "";
__PDF_DOC
.getPage(__CURRENT_PAGE)
.then(function (page) {
return page.getTextContent();
})
.then(function (content) {
textContent = content.items
.map(function (item) {
return item.str;
})
.join(" ");
if (startWord) {
let startIndex = textContent.indexOf(startWord);
utterance.text = refineText(textContent.slice(startIndex));
} else {
utterance.text = refineText(textContent);
}
utterance.onerror = (error) => console.log(error);
utterance.onpause = () => console.log("Paused");
utterance.onmark = () => console.log("On Mark");
utterance.onboundary = (event) => {
// console.log(event);
highlightWord();
};
utterance.onend = function () {
console.log("Ended");
if (__CURRENT_PAGE != __TOTAL_PAGES) {
document
.getElementById("word-" + __CURRENT_PAGE + "-" + prevId)
.classList.remove("highlight");
__CURRENT_PAGE++;
prevId = 0;
startTextToSpeech();
scroll();
}
};
synth.speak(utterance);
resume();
})
.catch(function (error) {
console.log(error);
});
}
function loadPage(pageNumber) {
if (pageNumber > __TOTAL_PAGES) {
return;
}
let canvas = document.createElement("canvas");
canvas.id = "page" + pageNumber;
canvas.width = canvas_width;
let textLayer = document.createElement("div");
textLayer.id = "textLayer" + pageNumber;
let annotationLayer = document.createElement("div");
annotationLayer.id = "annotationLayer" + pageNumber;
canvas.classList.add("canvas");
textLayer.classList.add("textLayer");
annotationLayer.classList.add("annotationLayer");
let pdfContainer = document.getElementById("pdfContainer");
pdfContainer.appendChild(canvas);
pdfContainer.appendChild(textLayer);
pdfContainer.appendChild(annotationLayer);
showPage(pageNumber, canvas, canvas.getContext("2d"));
// Add click event listeners to each word in the text layer
$("#textLayer" + pageNumber).on("click", "span", function () {
if (prevId !== 0) {
document
.getElementById("word-" + __CURRENT_PAGE + "-" + prevId)
.classList.remove("highlight");
}
__CURRENT_PAGE = pageNumber;
prevId = parseInt($(this).attr("id").split("-")[2]) - 1;
const clickedWord = $(this).text().trim();
// Get the text content of the rest of the page
const nextPageWords =
$(this)
.nextAll("span")
.map(function () {
return $(this).text().trim();
})
.get()
.join(" ") +
" " +
$(this)
.parent()
.nextAll("div")
.map(function () {
return $(this).text().trim();
})
.get()
.join(" ");
// Set the text to the utterance
if (synth.speaking) {
synth.cancel();
}
let voices = synth.getVoices();
let selectedVoice = voices.filter(
(element) => element.lang.substring(0, 2) === "en"
)[document.getElementById("voiceSelect").selectedIndex];
if (selectedVoice !== null) {
utterance.voice = selectedVoice;
}
utterance.onerror = (error) => console.log(error);
utterance.onpause = () => console.log("Paused");
utterance.onmark = () => console.log("On Mark");
utterance.onboundary = (event) => {
highlightWord();
};
utterance.text = refineText(clickedWord + " " + nextPageWords);
// Start the text-to-speech feature
utterance.onend = function () {
console.log("Ended");
if (__CURRENT_PAGE != __TOTAL_PAGES) {
try {
document
.getElementById("word-" + __CURRENT_PAGE + "-" + prevId)
.classList.remove("highlight");
} catch {}
__CURRENT_PAGE++;
prevId = 0;
startTextToSpeech();
scroll();
}
};
synth.speak(utterance);
resume();
});
}
function showPDF(pdf_url) {
$("#pdf-loader").show();
PDFJS.getDocument({ url: pdf_url }).then(function (pdf_doc) {
__PDF_DOC = pdf_doc;
__TOTAL_PAGES = __PDF_DOC.numPages;
// Hide the pdf loader and show pdf container in HTML
$("#pdf-loader").hide();
$("#pdf-contents").show();
$("#pdf-total-pages").text(__TOTAL_PAGES);
loadPage(1);
$(window).on("scroll", function () {
let cont = document.getElementById("pdfContainer");
if (cont.scrollTop >= (cont.scrollHeight - cont.clientHeight) * 0.9) {
loadPage(++__VIEWING_PAGE);
}
});
});
}
let prevId = 0;
function highlightWord() {
let wordId = "word-" + __CURRENT_PAGE + "-";
if (document.getElementById(wordId + prevId) !== null)
document.getElementById(wordId + prevId).classList.remove("highlight");
if (document.getElementById(wordId + ++prevId) !== null)
document.getElementById(wordId + prevId).classList.add("highlight");
else {
console.log("Null id", prevId);
prevId = 0;
}
}
function showPage(page_no, newCanvas, newCtx) {
__PAGE_RENDERING_IN_PROGRESS = 1;
// While page is being rendered hide the canvas and show a loading message
$("#page" + page_no).hide();
$("#page-loader").show();
// Fetch the page
__PDF_DOC.getPage(page_no).then(function (page) {
// As the canvas is of a fixed width we need to set the scale of the viewport accordingly
let scale_required = newCanvas.width / page.getViewport(1).width;
// Get viewport of the page at required scale
let viewport = page.getViewport(scale_required);
// Set canvas height
newCanvas.height = viewport.height;
let renderContext = {
canvasContext: newCtx,
viewport: viewport,
};
// Render the page contents in the canvas
page
.render(renderContext)
.then(function () {
__PAGE_RENDERING_IN_PROGRESS = 0;
// Show the canvas and hide the page loader
$("#page" + page_no).show();
$("#page-loader").hide();
// Return annotation data of the page after the pdf has been rendered in the canvas
return page.getAnnotations();
})
.then(async function (annotationData) {
// Get canvas offset
let canvas_offset = $("#page" + page_no).offset();
if (annotationData.length !== 0) {
// Clear HTML for annotation layer and show
$("#annotationLayer" + page_no)
.html("")
.show();
// Assign the CSS created to the annotation-layer element
$("#annotationLayer" + page_no).css({
left: canvas_offset.left + "px",
top: canvas_offset.top + "px",
height: newCanvas.height + "px",
width: newCanvas.width + "px",
});
try {
PDFJS.AnnotationLayer.render({
viewport: viewport.clone({ dontFlip: true }),
div: $("#annotationLayer" + page_no).get(0),
annotations: annotationData,
page: page,
});
} catch {}
}
const text = await page.getTextContent();
// Assign the CSS created to the text-layer element
$(`#textLayer${page_no}`).css({
left: canvas_offset.left + "px",
top: canvas_offset.top + "px",
height: newCanvas.height + "px",
width: newCanvas.width + "px",
});
PDFJS.renderTextLayer({
textContent: text,
container: $(`#textLayer${page_no}`).get(0),
viewport: viewport,
textDivs: [],
});
})
.then(function () {
let allDivs = document.querySelectorAll(`#textLayer${page_no} > div`);
let sum = 1;
for (const element of allDivs) {
const words = element.innerText.split(" ");
let newSentence = "";
for (const word of words) {
if (word.length !== 0 && word.trim()[0] !== "-") {
const wordId = `word-${page_no}-${sum++}`;
newSentence += `<span id="${wordId}">${word.trim()} </span>`;
}
}
element.innerHTML = newSentence;
}
const currentPageElement = document.getElementById("pdf-current-page");
pageHeight = parseInt(
$("#page1")
.css("height")
.substring(0, $("#page1").css("height").length - 2)
);
$(window).scroll(function () {
const scrollTop = window.scrollY;
const currentPage = Math.floor(scrollTop / pageHeight) + 1;
currentPageElement.textContent = currentPage;
});
__PAGE_RENDERING_IN_PROGRESS = 0;
});
});
}
// Upon click this should should trigger click on the #file-to-upload file input element
// This is better than showing the not-good-looking file input element
$("#upload-button").on("click", function () {
$("#file-to-upload").trigger("click");
$("#pause-button").hide();
$("#resume-button").hide();
});
// When user chooses a PDF file
$("#file-to-upload").on("change", function () {
// Validate whether PDF
if (
["application/pdf"].indexOf($("#file-to-upload").get(0).files[0].type) == -1
) {
alert("Error : Not a PDF");
return;
}
$("#upload-button").hide();
// Send the object url of the pdf
showPDF(URL.createObjectURL($("#file-to-upload").get(0).files[0]));
});
function resume() {
$("#resume-button").hide();
$("#pause-button").show();
if (!synth.paused) synth.resume();
}
function pause() {
$("#pause-button").hide();
$("#resume-button").show();
if (synth.speaking) synth.pause();
}
window.onbeforeunload = function () {
synth.cancel();
};
function refineText(text) {
let newText = text.replace(/\x00/g, "").replace(/\s+/g, " ").trim();
return newText;
}
$("#scroll").on("click", function () {
scroll();
});
function scroll() {
document.getElementById("page" + __CURRENT_PAGE).scrollIntoView();
}