-
Notifications
You must be signed in to change notification settings - Fork 101
/
controller.js
591 lines (501 loc) · 21.5 KB
/
controller.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
define(["jquery", "underscore", "./lib/class", "./helpers", "./models/group"],
function($, _, Class, HighlightHelpers, HighlightGroup) {
var HighlightsController = Class.extend({
highlights: [],
annotationHash: {},
offsetTopAddition: 0,
offsetLeftAddition: 0,
readerBoundElement: undefined,
scale: 0,
init: function(context, options) {
this.context = context;
this.epubCFI = EPUBcfi;
this.readerBoundElement = this.context.document.documentElement;
if (options.getVisibleCfiRangeFn) {
this.getVisibleCfiRange = options.getVisibleCfiRangeFn;
}
// inject annotation CSS into iframe
if (this.context.cssUrl) {
this._injectAnnotationCSS(this.context.cssUrl);
}
// emit an event when user selects some text.
var that = this;
this.context.document.addEventListener("mouseup", function(event) {
var range = that._getCurrentSelectionRange();
if (range === undefined) {
return;
}
if (range.startOffset - range.endOffset) {
that.context.manager.trigger("textSelectionEvent", event, range, that.context.iframe);
}
});
if (!rangy.initialized) {
rangy.init();
}
},
getVisibleCfiRange: function() {
// returns {firstVisibleCfi: <>, lastVisibleCfi: <>}
// implemented in Readium.ReaderView, passed in via options
},
// ------------------------------------------------------------------------------------ //
// "PUBLIC" METHODS (THE API) //
// ------------------------------------------------------------------------------------ //
redraw: function() {
var that = this;
var paginationOffsets = this._getPaginationOffsets();
var visibleCfiRange = this.getVisibleCfiRange();
// Highlights
_.each(this.highlights, function(highlightGroup) {
var visible = true;
if (visibleCfiRange &&
visibleCfiRange.firstVisibleCfi &&
visibleCfiRange.firstVisibleCfi.contentCFI &&
visibleCfiRange.lastVisibleCfi &&
visibleCfiRange.lastVisibleCfi.contentCFI) {
visible = that._cfiIsBetweenTwoCfis(
highlightGroup.CFI,
visibleCfiRange.firstVisibleCfi.contentCFI,
visibleCfiRange.lastVisibleCfi.contentCFI);
}
highlightGroup.visible = visible;
highlightGroup.resetHighlights(that.readerBoundElement, paginationOffsets.top, paginationOffsets.left);
});
},
getHighlight: function(id) {
var highlight = this.annotationHash[id];
if (highlight) {
return highlight.toInfo();
} else {
return undefined;
}
},
getHighlights: function() {
var highlights = [];
_.each(this.highlights, function(highlight) {
highlights.push(highlight.toInfo());
});
return highlights;
},
removeHighlight: function(annotationId) {
var annotationHash = this.annotationHash;
var highlights = this.highlights;
delete annotationHash[annotationId];
highlights = _.reject(highlights, function(highlightGroup) {
if (highlightGroup.id == annotationId) {
highlightGroup.destroyCurrentHighlights();
return true;
} else {
return false;
}
});
this.highlights = highlights;
},
removeHighlightsByType: function(type) {
var annotationHash = this.annotationHash;
var highlights = this.highlights;
// the returned list only contains HLs for which the function returns false
highlights = _.reject(highlights, function(highlightGroup) {
if (highlightGroup.type === type) {
delete annotationHash[highlightGroup.id];
highlightGroup.destroyCurrentHighlights();
return true;
} else {
return false;
}
});
this.highlights = highlights;
},
// generate unique prefix for HL ids
generateIdPrefix: function() {
var idPrefix = 'xxxxxxxx'.replace(/[x]/g, function(c) {
var r = Math.random() * 16 | 0;
return r.toString(16);
});
idPrefix += "_";
return idPrefix;
},
// takes partial CFI as parameter
addHighlight: function(CFI, id, type, styles) {
var CFIRangeInfo;
var range;
var selectedElements;
var contentDoc = this.context.document;
//get transform scale of content document
var scale = 1.0;
var matrix = HighlightHelpers.getMatrix($('html', contentDoc));
if (matrix) {
scale = HighlightHelpers.getScaleFromMatrix(matrix);
}
//create a dummy test div to determine if the browser provides
// client rectangles that take transform scaling into consideration
var $div = $('<div style="font-size: 50px; position: absolute; background: red; top:-9001px;">##</div>');
$(contentDoc.documentElement).append($div);
range = contentDoc.createRange();
range.selectNode($div[0]);
var renderedWidth = this._normalizeRectangle(range.getBoundingClientRect()).width;
var clientWidth = $div[0].clientWidth;
$div.remove();
var renderedVsClientWidthFactor = renderedWidth / clientWidth;
if (renderedVsClientWidthFactor === 1) {
//browser doesn't provide scaled client rectangles (firefox)
scale = 1;
} else if (this.context.isIe9 || this.context.isIe10) {
//use the test scale factor as our scale value for IE 9/10
scale = renderedVsClientWidthFactor;
}
this.scale = scale;
// form fake full CFI to satisfy getRangeTargetNodes
var arbitraryPackageDocCFI = "/99!"
var fullFakeCFI = "epubcfi(" + arbitraryPackageDocCFI + CFI + ")";
if (this.epubCFI.Interpreter.isRangeCfi(fullFakeCFI)) {
CFIRangeInfo = this.epubCFI.getRangeTargetElements(fullFakeCFI, contentDoc, ["cfi-marker", "cfi-blacklist", "mo-cfi-highlight"], [], ["MathJax_Message", "MathJax_SVG_Hidden"]);
var startNode = CFIRangeInfo.startElement,
endNode = CFIRangeInfo.endElement;
range = rangy.createRange(contentDoc);
if (startNode.length < CFIRangeInfo.startOffset) {
//this is a workaround
// "Uncaught IndexSizeError: Index or size was negative, or greater than the allowed value." errors
// the range cfi generator outputs a cfi like /4/2,/1:125,/16
// can't explain, investigating..
CFIRangeInfo.startOffset = startNode.length;
}
range.setStart(startNode, CFIRangeInfo.startOffset);
range.setEnd(endNode, CFIRangeInfo.endOffset);
selectedElements = range.getNodes();
} else {
var element = this.epubCFI.getTargetElement(fullFakeCFI, contentDoc, ["cfi-marker", "cfi-blacklist", "mo-cfi-highlight"], [], ["MathJax_Message", "MathJax_SVG_Hidden"]);
selectedElements = [element ? element[0] : null];
range = null;
}
var paginationOffsets = this._getPaginationOffsets();
this._addHighlightHelper(
CFI, id, type, styles, selectedElements, range,
startNode, endNode, paginationOffsets.top, paginationOffsets.left
);
return {
selectedElements: selectedElements,
CFI: CFI
};
},
// this returns a partial CFI only!!
getCurrentSelectionCFI: function() {
var currentSelection = this._getCurrentSelectionRange();
var CFI;
if (currentSelection) {
selectionInfo = this._getSelectionInfo(currentSelection);
CFI = selectionInfo.CFI;
}
return CFI;
},
// this returns a partial CFI only!!
getCurrentSelectionOffsetCFI: function() {
var currentSelection = this._getCurrentSelectionRange();
var CFI;
if (currentSelection) {
CFI = this._generateCharOffsetCFI(currentSelection);
}
return CFI;
},
addSelectionHighlight: function(id, type, styles, clearSelection) {
var CFI = this.getCurrentSelectionCFI();
if (CFI) {
// if clearSelection is true
if (clearSelection) {
var iframeDocument = this.context.document;
if (iframeDocument.getSelection) {
var currentSelection = iframeDocument.getSelection();
currentSelection.collapseToStart();
}
}
return this.addHighlight(CFI, id, type, styles);
} else {
throw new Error("Nothing selected");
}
},
updateAnnotation: function(id, type, styles) {
var annotationViews = this.annotationHash[id];
if (annotationViews) {
annotationViews.update(type, styles);
}
return annotationViews;
},
replaceAnnotation: function(id, cfi, type, styles) {
var annotationViews = this.annotationHash[id];
if (annotationViews) {
// remove an existing annotatio
this.removeHighlight(id);
// create a new HL
this.addHighlight(cfi, id, type, styles);
}
return annotationViews;
},
updateAnnotationView: function(id, styles) {
var annotationViews = this.annotationHash[id];
if (annotationViews) {
annotationViews.setStyles(styles);
}
return annotationViews;
},
setAnnotationViewState: function(id, state, value) {
var annotationViews = this.annotationHash[id];
if (annotationViews) {
annotationViews.setState(state, value);
}
return annotationViews;
},
setAnnotationViewStateForAll: function(state, value) {
var annotationViews = this.annotationHash;
_.each(annotationViews, function(annotationView) {
annotationView.setState(state, value);
});
},
// ------------------------------------------------------------------------------------ //
// "PRIVATE" HELPERS //
// ------------------------------------------------------------------------------------ //
//return an array of all numbers in the content cfi
_parseContentCfi: function(cont) {
return cont.replace(/\[(.*?)\]/, "").split(/[\/,:]/).map(function(n) {
return parseInt(n);
}).filter(Boolean);
},
_contentCfiComparator: function(cont1, cont2) {
cont1 = this._parseContentCfi(cont1);
cont2 = this._parseContentCfi(cont2);
//compare cont arrays looking for differences
for (var i = 0; i < cont1.length; i++) {
if (cont1[i] > cont2[i]) {
return 1;
} else if (cont1[i] < cont2[i]) {
return -1;
}
}
//no differences found, so confirm that cont2 did not have values we didn't check
if (cont1.length < cont2.length) {
return -1;
}
//cont arrays are identical
return 0;
},
// determine if a given Cfi falls between two other cfis.2
_cfiIsBetweenTwoCfis: function(cfi, firstVisibleCfi, lastVisibleCfi) {
if (!firstVisibleCfi || !lastVisibleCfi) {
return null;
}
var first = this._contentCfiComparator(cfi, firstVisibleCfi);
var second = this._contentCfiComparator(cfi, lastVisibleCfi);
return first >= 0 && second <= 0;
},
_addHighlightHelper: function(CFI, annotationId, type, styles, highlightedNodes,
range, startNode, endNode, offsetTop, offsetLeft) {
if (!offsetTop) {
offsetTop = this.offsetTopAddition;
}
if (!offsetLeft) {
offsetLeft = this.offsetLeftAddition;
}
var visible;
// check if the options specify lastVisibleCfi/firstVisibleCfi. If they don't fall back to displaying the highlights anyway.
var visibleCfiRange = this.getVisibleCfiRange();
if (visibleCfiRange &&
visibleCfiRange.firstVisibleCfi &&
visibleCfiRange.firstVisibleCfi.contentCFI &&
visibleCfiRange.lastVisibleCfi &&
visibleCfiRange.lastVisibleCfi.contentCFI) {
visible = this._cfiIsBetweenTwoCfis(CFI, visibleCfiRange.firstVisibleCfi.contentCFI, visibleCfiRange.lastVisibleCfi.contentCFI);
} else {
visible = true;
}
annotationId = annotationId.toString();
if (this.annotationHash[annotationId]) {
throw new Error("That annotation id already exists; annotation not added");
}
var highlightGroup = new HighlightGroup(this.context, {
CFI: CFI,
selectedNodes: highlightedNodes,
offsetTopAddition: offsetTop,
offsetLeftAddition: offsetLeft,
styles: styles,
id: annotationId,
type: type,
scale: this.scale,
selectionText: range ? range.toString() : "",
visible: visible,
rangeInfo: range ? {
startNode: startNode,
startOffset: range.startOffset,
endNode: endNode,
endOffset: range.endOffset
} : null
});
this.annotationHash[annotationId] = highlightGroup;
this.highlights.push(highlightGroup);
highlightGroup.renderHighlights(this.readerBoundElement);
},
_normalizeRectangle: function(rect) {
return {
left: rect.left,
right: rect.right,
top: rect.top,
bottom: rect.bottom,
width: rect.right - rect.left,
height: rect.bottom - rect.top
};
},
_getSelectionInfo: function(selectedRange, elementType) {
// Generate CFI for selected text
var CFI = this._generateRangeCFI(selectedRange);
var intervalState = {
startElementFound: false,
endElementFound: false
};
var selectedElements = [];
if (!elementType) {
elementType = ["text"];
}
this._findSelectedElements(
selectedRange.commonAncestorContainer,
selectedRange.startContainer,
selectedRange.endContainer,
intervalState,
selectedElements,
elementType
);
// Return a list of selected text nodes and the CFI
return {
CFI: CFI,
selectedElements: selectedElements
};
},
_generateRangeCFI: function(selectedRange) {
var startNode = selectedRange.startContainer;
var endNode = selectedRange.endContainer;
var commonAncestor = selectedRange.commonAncestorContainer;
var startOffset;
var endOffset;
var rangeCFIComponent;
startOffset = selectedRange.startOffset;
endOffset = selectedRange.endOffset;
rangeCFIComponent = this.epubCFI.generateRangeComponent(
startNode,
startOffset,
endNode,
endOffset, ["cfi-marker", "cfi-blacklist", "mo-cfi-highlight"], [], ["MathJax_Message", "MathJax_SVG_Hidden"]
);
return rangeCFIComponent;
},
_generateCharOffsetCFI: function(selectedRange) {
// Character offset
var startNode = selectedRange.startContainer;
var startOffset = selectedRange.startOffset;
var charOffsetCFI;
if (startNode.nodeType === Node.TEXT_NODE) {
charOffsetCFI = this.epubCFI.generateCharacterOffsetCFIComponent(
startNode,
startOffset, ["cfi-marker", "cfi-blacklist", "mo-cfi-highlight"], [], ["MathJax_Message", "MathJax_SVG_Hidden"]
);
}
return charOffsetCFI;
},
// REFACTORING CANDIDATE: Convert this to jquery
_findSelectedElements: function(
currElement, startElement, endElement, intervalState, selectedElements, elementTypes) {
if (currElement === startElement) {
intervalState.startElementFound = true;
}
if (intervalState.startElementFound === true) {
this._addElement(currElement, selectedElements, elementTypes);
}
if (currElement === endElement) {
intervalState.endElementFound = true;
return;
}
if (currElement.firstChild) {
this._findSelectedElements(currElement.firstChild, startElement, endElement,
intervalState, selectedElements, elementTypes);
if (intervalState.endElementFound) {
return;
}
}
if (currElement.nextSibling) {
this._findSelectedElements(currElement.nextSibling, startElement, endElement,
intervalState, selectedElements, elementTypes);
if (intervalState.endElementFound) {
return;
}
}
},
_addElement: function(currElement, selectedElements, elementTypes) {
// Check if the node is one of the types
_.each(elementTypes, function(elementType) {
if (elementType === "text") {
if (currElement.nodeType === Node.TEXT_NODE) {
selectedElements.push(currElement);
}
} else {
if ($(currElement).is(elementType)) {
selectedElements.push(currElement);
}
}
});
},
// Rationale: This is a cross-browser method to get the currently selected text
_getCurrentSelectionRange: function() {
var currentSelection;
var iframeDocument = this.context.document;
if (iframeDocument.getSelection) {
currentSelection = iframeDocument.getSelection();
if (!currentSelection || currentSelection.rangeCount === 0) {
return undefined;
}
var range = currentSelection.getRangeAt(0);
if (range.toString() !== '') {
return range;
} else {
return undefined;
}
} else if (iframeDocument.selection) {
return iframeDocument.selection.createRange();
} else {
return undefined;
}
},
_getPaginationOffsets: function() {
if (!this.context.paginationInfo) {
return {
top: 0,
left: 0
}
}
var offset;
if (this.context.isRTL && !this.context.isVerticalWritingMode) {
offset = -this.context.paginationInfo.pageOffset;
} else {
offset = this.context.paginationInfo.pageOffset;
}
if (this.context.isVerticalWritingMode) {
return {
top: offset,
left: 0
};
}
return {
top: 0,
left: offset
};
},
_injectAnnotationCSS: function(annotationCSSUrl) {
var doc = this.context.document;
setTimeout(function(){
var $contentDocHead = $("head", doc);
$contentDocHead.append(
$("<link/>", {
rel: "stylesheet",
href: annotationCSSUrl,
type: "text/css"
})
);
}, 0);
}
});
return HighlightsController;
});