Browse Source

Merge pull request #8582 from timvandermeij/es6-text-layer-builder

Convert the text layer builder to ES6 syntax
Jonas Jenwald 8 years ago committed by GitHub
parent
commit
80c33253ed
  1. 214
      web/text_layer_builder.js

214
web/text_layer_builder.js

@ -16,7 +16,7 @@
import { getGlobalEventBus } from './dom_events'; import { getGlobalEventBus } from './dom_events';
import { renderTextLayer } from 'pdfjs-lib'; import { renderTextLayer } from 'pdfjs-lib';
var EXPAND_DIVS_TIMEOUT = 300; // ms const EXPAND_DIVS_TIMEOUT = 300; // ms
/** /**
* @typedef {Object} TextLayerBuilderOptions * @typedef {Object} TextLayerBuilderOptions
@ -30,40 +30,40 @@ var EXPAND_DIVS_TIMEOUT = 300; // ms
*/ */
/** /**
* TextLayerBuilder provides text-selection functionality for the PDF. * The text layer builder provides text selection functionality for the PDF.
* It does this by creating overlay divs over the PDF text. These divs * It does this by creating overlay divs over the PDF's text. These divs
* contain text that matches the PDF text they are overlaying. This object * contain text that matches the PDF text they are overlaying. This object
* also provides a way to highlight text that is being searched for. * also provides a way to highlight text that is being searched for.
* @class
*/ */
var TextLayerBuilder = (function TextLayerBuilderClosure() { class TextLayerBuilder {
function TextLayerBuilder(options) { constructor({ textLayerDiv, eventBus, pageIndex, viewport,
this.textLayerDiv = options.textLayerDiv; findController = null, enhanceTextSelection = false, }) {
this.eventBus = options.eventBus || getGlobalEventBus(); this.textLayerDiv = textLayerDiv;
this.eventBus = eventBus || getGlobalEventBus();
this.textContent = null; this.textContent = null;
this.textContentItemsStr = []; this.textContentItemsStr = [];
this.textContentStream = null; this.textContentStream = null;
this.renderingDone = false; this.renderingDone = false;
this.pageIdx = options.pageIndex; this.pageIdx = pageIndex;
this.pageNumber = this.pageIdx + 1; this.pageNumber = this.pageIdx + 1;
this.matches = []; this.matches = [];
this.viewport = options.viewport; this.viewport = viewport;
this.textDivs = []; this.textDivs = [];
this.findController = options.findController || null; this.findController = findController;
this.textLayerRenderTask = null; this.textLayerRenderTask = null;
this.enhanceTextSelection = options.enhanceTextSelection; this.enhanceTextSelection = enhanceTextSelection;
this._bindMouse(); this._bindMouse();
} }
TextLayerBuilder.prototype = {
/** /**
* @private * @private
*/ */
_finishRendering: function TextLayerBuilder_finishRendering() { _finishRendering() {
this.renderingDone = true; this.renderingDone = true;
if (!this.enhanceTextSelection) { if (!this.enhanceTextSelection) {
var endOfContent = document.createElement('div'); let endOfContent = document.createElement('div');
endOfContent.className = 'endOfContent'; endOfContent.className = 'endOfContent';
this.textLayerDiv.appendChild(endOfContent); this.textLayerDiv.appendChild(endOfContent);
} }
@ -73,21 +73,22 @@ var TextLayerBuilder = (function TextLayerBuilderClosure() {
pageNumber: this.pageNumber, pageNumber: this.pageNumber,
numTextDivs: this.textDivs.length, numTextDivs: this.textDivs.length,
}); });
}, }
/** /**
* Renders the text layer. * Renders the text layer.
* @param {number} timeout (optional) if specified, the rendering waits *
* for specified amount of ms. * @param {number} timeout - (optional) wait for a specified amount of
* milliseconds before rendering
*/ */
render: function TextLayerBuilder_render(timeout) { render(timeout = 0) {
if (!(this.textContent || this.textContentStream) || this.renderingDone) { if (!(this.textContent || this.textContentStream) || this.renderingDone) {
return; return;
} }
this.cancel(); this.cancel();
this.textDivs = []; this.textDivs = [];
var textLayerFrag = document.createDocumentFragment(); let textLayerFrag = document.createDocumentFragment();
this.textLayerRenderTask = renderTextLayer({ this.textLayerRenderTask = renderTextLayer({
textContent: this.textContent, textContent: this.textContent,
textContentStream: this.textContentStream, textContentStream: this.textContentStream,
@ -103,45 +104,44 @@ var TextLayerBuilder = (function TextLayerBuilderClosure() {
this._finishRendering(); this._finishRendering();
this.updateMatches(); this.updateMatches();
}, function (reason) { }, function (reason) {
// cancelled or failed to render text layer -- skipping errors // Cancelled or failed to render text layer; skipping errors.
}); });
}, }
/** /**
* Cancels rendering of the text layer. * Cancel rendering of the text layer.
*/ */
cancel: function TextLayerBuilder_cancel() { cancel() {
if (this.textLayerRenderTask) { if (this.textLayerRenderTask) {
this.textLayerRenderTask.cancel(); this.textLayerRenderTask.cancel();
this.textLayerRenderTask = null; this.textLayerRenderTask = null;
} }
}, }
setTextContentStream(readableStream) { setTextContentStream(readableStream) {
this.cancel(); this.cancel();
this.textContentStream = readableStream; this.textContentStream = readableStream;
}, }
setTextContent: function TextLayerBuilder_setTextContent(textContent) { setTextContent(textContent) {
this.cancel(); this.cancel();
this.textContent = textContent; this.textContent = textContent;
}, }
convertMatches: function TextLayerBuilder_convertMatches(matches, convertMatches(matches, matchesLength) {
matchesLength) { let i = 0;
var i = 0; let iIndex = 0;
var iIndex = 0;
let textContentItemsStr = this.textContentItemsStr; let textContentItemsStr = this.textContentItemsStr;
var end = textContentItemsStr.length - 1; let end = textContentItemsStr.length - 1;
var queryLen = (this.findController === null ? let queryLen = (this.findController === null ?
0 : this.findController.state.query.length); 0 : this.findController.state.query.length);
var ret = []; let ret = [];
if (!matches) { if (!matches) {
return ret; return ret;
} }
for (var m = 0, len = matches.length; m < len; m++) { for (let m = 0, len = matches.length; m < len; m++) {
// Calculate the start position. // Calculate the start position.
var matchIdx = matches[m]; let matchIdx = matches[m];
// Loop over the divIdxs. // Loop over the divIdxs.
while (i !== end && matchIdx >= while (i !== end && matchIdx >=
@ -154,7 +154,7 @@ var TextLayerBuilder = (function TextLayerBuilderClosure() {
console.error('Could not find a matching mapping'); console.error('Could not find a matching mapping');
} }
var match = { let match = {
begin: { begin: {
divIdx: i, divIdx: i,
offset: matchIdx - iIndex, offset: matchIdx - iIndex,
@ -162,9 +162,9 @@ var TextLayerBuilder = (function TextLayerBuilderClosure() {
}; };
// Calculate the end position. // Calculate the end position.
if (matchesLength) { // multiterm search if (matchesLength) { // Multiterm search.
matchIdx += matchesLength[m]; matchIdx += matchesLength[m];
} else { // phrase search } else { // Phrase search.
matchIdx += queryLen; matchIdx += queryLen;
} }
@ -184,42 +184,41 @@ var TextLayerBuilder = (function TextLayerBuilderClosure() {
} }
return ret; return ret;
}, }
renderMatches: function TextLayerBuilder_renderMatches(matches) { renderMatches(matches) {
// Early exit if there is nothing to render. // Early exit if there is nothing to render.
if (matches.length === 0) { if (matches.length === 0) {
return; return;
} }
let textContentItemsStr = this.textContentItemsStr; let textContentItemsStr = this.textContentItemsStr;
var textDivs = this.textDivs; let textDivs = this.textDivs;
var prevEnd = null; let prevEnd = null;
var pageIdx = this.pageIdx; let pageIdx = this.pageIdx;
var isSelectedPage = (this.findController === null ? let isSelectedPage = (this.findController === null ?
false : (pageIdx === this.findController.selected.pageIdx)); false : (pageIdx === this.findController.selected.pageIdx));
var selectedMatchIdx = (this.findController === null ? let selectedMatchIdx = (this.findController === null ?
-1 : this.findController.selected.matchIdx); -1 : this.findController.selected.matchIdx);
var highlightAll = (this.findController === null ? let highlightAll = (this.findController === null ?
false : this.findController.state.highlightAll); false : this.findController.state.highlightAll);
var infinity = { let infinity = {
divIdx: -1, divIdx: -1,
offset: undefined, offset: undefined,
}; };
function beginText(begin, className) { function beginText(begin, className) {
var divIdx = begin.divIdx; let divIdx = begin.divIdx;
textDivs[divIdx].textContent = ''; textDivs[divIdx].textContent = '';
appendTextToDiv(divIdx, 0, begin.offset, className); appendTextToDiv(divIdx, 0, begin.offset, className);
} }
function appendTextToDiv(divIdx, fromOffset, toOffset, className) { function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
var div = textDivs[divIdx]; let div = textDivs[divIdx];
var content = let content = textContentItemsStr[divIdx].substring(fromOffset, toOffset);
textContentItemsStr[divIdx].substring(fromOffset, toOffset); let node = document.createTextNode(content);
var node = document.createTextNode(content);
if (className) { if (className) {
var span = document.createElement('span'); let span = document.createElement('span');
span.className = className; span.className = className;
span.appendChild(node); span.appendChild(node);
div.appendChild(span); div.appendChild(span);
@ -228,7 +227,7 @@ var TextLayerBuilder = (function TextLayerBuilderClosure() {
div.appendChild(node); div.appendChild(node);
} }
var i0 = selectedMatchIdx, i1 = i0 + 1; let i0 = selectedMatchIdx, i1 = i0 + 1;
if (highlightAll) { if (highlightAll) {
i0 = 0; i0 = 0;
i1 = matches.length; i1 = matches.length;
@ -237,12 +236,12 @@ var TextLayerBuilder = (function TextLayerBuilderClosure() {
return; return;
} }
for (var i = i0; i < i1; i++) { for (let i = i0; i < i1; i++) {
var match = matches[i]; let match = matches[i];
var begin = match.begin; let begin = match.begin;
var end = match.end; let end = match.end;
var isSelected = (isSelectedPage && i === selectedMatchIdx); let isSelected = (isSelectedPage && i === selectedMatchIdx);
var highlightSuffix = (isSelected ? ' selected' : ''); let highlightSuffix = (isSelected ? ' selected' : '');
if (this.findController) { if (this.findController) {
this.findController.updateMatchPosition(pageIdx, i, textDivs, this.findController.updateMatchPosition(pageIdx, i, textDivs,
@ -267,7 +266,7 @@ var TextLayerBuilder = (function TextLayerBuilderClosure() {
} else { } else {
appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
'highlight begin' + highlightSuffix); 'highlight begin' + highlightSuffix);
for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) { for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
textDivs[n0].className = 'highlight middle' + highlightSuffix; textDivs[n0].className = 'highlight middle' + highlightSuffix;
} }
beginText(end, 'highlight end' + highlightSuffix); beginText(end, 'highlight end' + highlightSuffix);
@ -278,26 +277,26 @@ var TextLayerBuilder = (function TextLayerBuilderClosure() {
if (prevEnd) { if (prevEnd) {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
} }
}, }
updateMatches: function TextLayerBuilder_updateMatches() { updateMatches() {
// Only show matches when all rendering is done. // Only show matches when all rendering is done.
if (!this.renderingDone) { if (!this.renderingDone) {
return; return;
} }
// Clear all matches. // Clear all matches.
var matches = this.matches; let matches = this.matches;
var textDivs = this.textDivs; let textDivs = this.textDivs;
let textContentItemsStr = this.textContentItemsStr; let textContentItemsStr = this.textContentItemsStr;
var clearedUntilDivIdx = -1; let clearedUntilDivIdx = -1;
// Clear all current matches. // Clear all current matches.
for (var i = 0, len = matches.length; i < len; i++) { for (let i = 0, len = matches.length; i < len; i++) {
var match = matches[i]; let match = matches[i];
var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); let begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
for (var n = begin, end = match.end.divIdx; n <= end; n++) { for (let n = begin, end = match.end.divIdx; n <= end; n++) {
var div = textDivs[n]; let div = textDivs[n];
div.textContent = textContentItemsStr[n]; div.textContent = textContentItemsStr[n];
div.className = ''; div.className = '';
} }
@ -310,7 +309,7 @@ var TextLayerBuilder = (function TextLayerBuilderClosure() {
// Convert the matches on the page controller into the match format // Convert the matches on the page controller into the match format
// used for the textLayer. // used for the textLayer.
var pageMatches, pageMatchesLength; let pageMatches, pageMatchesLength;
if (this.findController !== null) { if (this.findController !== null) {
pageMatches = this.findController.pageMatches[this.pageIdx] || null; pageMatches = this.findController.pageMatches[this.pageIdx] || null;
pageMatchesLength = (this.findController.pageMatchesLength) ? pageMatchesLength = (this.findController.pageMatchesLength) ?
@ -319,21 +318,22 @@ var TextLayerBuilder = (function TextLayerBuilderClosure() {
this.matches = this.convertMatches(pageMatches, pageMatchesLength); this.matches = this.convertMatches(pageMatches, pageMatchesLength);
this.renderMatches(this.matches); this.renderMatches(this.matches);
}, }
/** /**
* Fixes text selection: adds additional div where mouse was clicked. * Improves text selection by adding an additional div where the mouse was
* This reduces flickering of the content if mouse slowly dragged down/up. * clicked. This reduces flickering of the content if the mouse is slowly
* dragged up or down.
*
* @private * @private
*/ */
_bindMouse: function TextLayerBuilder_bindMouse() { _bindMouse() {
var div = this.textLayerDiv; let div = this.textLayerDiv;
var self = this; let expandDivsTimer = null;
var expandDivsTimer = null;
div.addEventListener('mousedown', (evt) => {
div.addEventListener('mousedown', function (e) { if (this.enhanceTextSelection && this.textLayerRenderTask) {
if (self.enhanceTextSelection && self.textLayerRenderTask) { this.textLayerRenderTask.expandTextDivs(true);
self.textLayerRenderTask.expandTextDivs(true);
if ((typeof PDFJSDev === 'undefined' || if ((typeof PDFJSDev === 'undefined' ||
!PDFJSDev.test('FIREFOX || MOZCENTRAL')) && !PDFJSDev.test('FIREFOX || MOZCENTRAL')) &&
expandDivsTimer) { expandDivsTimer) {
@ -342,46 +342,48 @@ var TextLayerBuilder = (function TextLayerBuilderClosure() {
} }
return; return;
} }
var end = div.querySelector('.endOfContent');
let end = div.querySelector('.endOfContent');
if (!end) { if (!end) {
return; return;
} }
if (typeof PDFJSDev === 'undefined' || if (typeof PDFJSDev === 'undefined' ||
!PDFJSDev.test('FIREFOX || MOZCENTRAL')) { !PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
// On non-Firefox browsers, the selection will feel better if the height // On non-Firefox browsers, the selection will feel better if the height
// of the endOfContent div will be adjusted to start at mouse click // of the `endOfContent` div is adjusted to start at mouse click
// location -- this will avoid flickering when selections moves up. // location. This avoids flickering when the selection moves up.
// However it does not work when selection started on empty space. // However it does not work when selection is started on empty space.
var adjustTop = e.target !== div; let adjustTop = evt.target !== div;
if (typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC')) { if (typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC')) {
adjustTop = adjustTop && window.getComputedStyle(end). adjustTop = adjustTop && window.getComputedStyle(end).
getPropertyValue('-moz-user-select') !== 'none'; getPropertyValue('-moz-user-select') !== 'none';
} }
if (adjustTop) { if (adjustTop) {
var divBounds = div.getBoundingClientRect(); let divBounds = div.getBoundingClientRect();
var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height); let r = Math.max(0, (evt.pageY - divBounds.top) / divBounds.height);
end.style.top = (r * 100).toFixed(2) + '%'; end.style.top = (r * 100).toFixed(2) + '%';
} }
} }
end.classList.add('active'); end.classList.add('active');
}); });
div.addEventListener('mouseup', function (e) { div.addEventListener('mouseup', () => {
if (self.enhanceTextSelection && self.textLayerRenderTask) { if (this.enhanceTextSelection && this.textLayerRenderTask) {
if (typeof PDFJSDev === 'undefined' || if (typeof PDFJSDev === 'undefined' ||
!PDFJSDev.test('FIREFOX || MOZCENTRAL')) { !PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
expandDivsTimer = setTimeout(function() { expandDivsTimer = setTimeout(() => {
if (self.textLayerRenderTask) { if (this.textLayerRenderTask) {
self.textLayerRenderTask.expandTextDivs(false); this.textLayerRenderTask.expandTextDivs(false);
} }
expandDivsTimer = null; expandDivsTimer = null;
}, EXPAND_DIVS_TIMEOUT); }, EXPAND_DIVS_TIMEOUT);
} else { } else {
self.textLayerRenderTask.expandTextDivs(false); this.textLayerRenderTask.expandTextDivs(false);
} }
return; return;
} }
var end = div.querySelector('.endOfContent');
let end = div.querySelector('.endOfContent');
if (!end) { if (!end) {
return; return;
} }
@ -391,17 +393,13 @@ var TextLayerBuilder = (function TextLayerBuilderClosure() {
} }
end.classList.remove('active'); end.classList.remove('active');
}); });
}, }
}; }
return TextLayerBuilder;
})();
/** /**
* @constructor
* @implements IPDFTextLayerFactory * @implements IPDFTextLayerFactory
*/ */
function DefaultTextLayerFactory() {} class DefaultTextLayerFactory {
DefaultTextLayerFactory.prototype = {
/** /**
* @param {HTMLDivElement} textLayerDiv * @param {HTMLDivElement} textLayerDiv
* @param {number} pageIndex * @param {number} pageIndex
@ -417,8 +415,8 @@ DefaultTextLayerFactory.prototype = {
viewport, viewport,
enhanceTextSelection, enhanceTextSelection,
}); });
}, }
}; }
export { export {
TextLayerBuilder, TextLayerBuilder,

Loading…
Cancel
Save