Browse Source

Convert the text layer builder to ES6 syntax

Tim van der Meij 8 years ago
parent
commit
19f56ec5c1
No known key found for this signature in database
GPG Key ID: 8C3FD2925A5F2762
  1. 626
      web/text_layer_builder.js

626
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,378 +30,376 @@ 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() {
_finishRendering: function TextLayerBuilder_finishRendering() { this.renderingDone = true;
this.renderingDone = true;
if (!this.enhanceTextSelection) {
if (!this.enhanceTextSelection) { let endOfContent = document.createElement('div');
var endOfContent = document.createElement('div'); endOfContent.className = 'endOfContent';
endOfContent.className = 'endOfContent'; this.textLayerDiv.appendChild(endOfContent);
this.textLayerDiv.appendChild(endOfContent); }
}
this.eventBus.dispatch('textlayerrendered', {
source: this,
pageNumber: this.pageNumber,
numTextDivs: this.textDivs.length,
});
}
this.eventBus.dispatch('textlayerrendered', { /**
source: this, * Renders the text layer.
pageNumber: this.pageNumber, *
numTextDivs: this.textDivs.length, * @param {number} timeout - (optional) wait for a specified amount of
}); * milliseconds before rendering
}, */
render(timeout = 0) {
/** if (!(this.textContent || this.textContentStream) || this.renderingDone) {
* Renders the text layer. return;
* @param {number} timeout (optional) if specified, the rendering waits }
* for specified amount of ms. this.cancel();
*/
render: function TextLayerBuilder_render(timeout) {
if (!(this.textContent || this.textContentStream) || this.renderingDone) {
return;
}
this.cancel();
this.textDivs = [];
var textLayerFrag = document.createDocumentFragment();
this.textLayerRenderTask = renderTextLayer({
textContent: this.textContent,
textContentStream: this.textContentStream,
container: textLayerFrag,
viewport: this.viewport,
textDivs: this.textDivs,
textContentItemsStr: this.textContentItemsStr,
timeout,
enhanceTextSelection: this.enhanceTextSelection,
});
this.textLayerRenderTask.promise.then(() => {
this.textLayerDiv.appendChild(textLayerFrag);
this._finishRendering();
this.updateMatches();
}, function (reason) {
// cancelled or failed to render text layer -- skipping errors
});
},
/**
* Cancels rendering of the text layer.
*/
cancel: function TextLayerBuilder_cancel() {
if (this.textLayerRenderTask) {
this.textLayerRenderTask.cancel();
this.textLayerRenderTask = null;
}
},
setTextContentStream(readableStream) {
this.cancel();
this.textContentStream = readableStream;
},
setTextContent: function TextLayerBuilder_setTextContent(textContent) {
this.cancel();
this.textContent = textContent;
},
convertMatches: function TextLayerBuilder_convertMatches(matches,
matchesLength) {
var i = 0;
var iIndex = 0;
let textContentItemsStr = this.textContentItemsStr;
var end = textContentItemsStr.length - 1;
var queryLen = (this.findController === null ?
0 : this.findController.state.query.length);
var ret = [];
if (!matches) {
return ret;
}
for (var m = 0, len = matches.length; m < len; m++) {
// Calculate the start position.
var matchIdx = matches[m];
// Loop over the divIdxs.
while (i !== end && matchIdx >=
(iIndex + textContentItemsStr[i].length)) {
iIndex += textContentItemsStr[i].length;
i++;
}
if (i === textContentItemsStr.length) { this.textDivs = [];
console.error('Could not find a matching mapping'); let textLayerFrag = document.createDocumentFragment();
} this.textLayerRenderTask = renderTextLayer({
textContent: this.textContent,
textContentStream: this.textContentStream,
container: textLayerFrag,
viewport: this.viewport,
textDivs: this.textDivs,
textContentItemsStr: this.textContentItemsStr,
timeout,
enhanceTextSelection: this.enhanceTextSelection,
});
this.textLayerRenderTask.promise.then(() => {
this.textLayerDiv.appendChild(textLayerFrag);
this._finishRendering();
this.updateMatches();
}, function (reason) {
// Cancelled or failed to render text layer; skipping errors.
});
}
var match = { /**
begin: { * Cancel rendering of the text layer.
divIdx: i, */
offset: matchIdx - iIndex, cancel() {
}, if (this.textLayerRenderTask) {
}; this.textLayerRenderTask.cancel();
this.textLayerRenderTask = null;
// Calculate the end position. }
if (matchesLength) { // multiterm search }
matchIdx += matchesLength[m];
} else { // phrase search
matchIdx += queryLen;
}
// Somewhat the same array as above, but use > instead of >= to get setTextContentStream(readableStream) {
// the end position right. this.cancel();
while (i !== end && matchIdx > this.textContentStream = readableStream;
(iIndex + textContentItemsStr[i].length)) { }
iIndex += textContentItemsStr[i].length;
i++;
}
match.end = { setTextContent(textContent) {
divIdx: i, this.cancel();
offset: matchIdx - iIndex, this.textContent = textContent;
}; }
ret.push(match);
}
convertMatches(matches, matchesLength) {
let i = 0;
let iIndex = 0;
let textContentItemsStr = this.textContentItemsStr;
let end = textContentItemsStr.length - 1;
let queryLen = (this.findController === null ?
0 : this.findController.state.query.length);
let ret = [];
if (!matches) {
return ret; return ret;
}, }
for (let m = 0, len = matches.length; m < len; m++) {
// Calculate the start position.
let matchIdx = matches[m];
// Loop over the divIdxs.
while (i !== end && matchIdx >=
(iIndex + textContentItemsStr[i].length)) {
iIndex += textContentItemsStr[i].length;
i++;
}
renderMatches: function TextLayerBuilder_renderMatches(matches) { if (i === textContentItemsStr.length) {
// Early exit if there is nothing to render. console.error('Could not find a matching mapping');
if (matches.length === 0) {
return;
} }
let textContentItemsStr = this.textContentItemsStr; let match = {
var textDivs = this.textDivs; begin: {
var prevEnd = null; divIdx: i,
var pageIdx = this.pageIdx; offset: matchIdx - iIndex,
var isSelectedPage = (this.findController === null ? },
false : (pageIdx === this.findController.selected.pageIdx));
var selectedMatchIdx = (this.findController === null ?
-1 : this.findController.selected.matchIdx);
var highlightAll = (this.findController === null ?
false : this.findController.state.highlightAll);
var infinity = {
divIdx: -1,
offset: undefined,
}; };
function beginText(begin, className) { // Calculate the end position.
var divIdx = begin.divIdx; if (matchesLength) { // Multiterm search.
textDivs[divIdx].textContent = ''; matchIdx += matchesLength[m];
appendTextToDiv(divIdx, 0, begin.offset, className); } else { // Phrase search.
matchIdx += queryLen;
} }
function appendTextToDiv(divIdx, fromOffset, toOffset, className) { // Somewhat the same array as above, but use > instead of >= to get
var div = textDivs[divIdx]; // the end position right.
var content = while (i !== end && matchIdx >
textContentItemsStr[divIdx].substring(fromOffset, toOffset); (iIndex + textContentItemsStr[i].length)) {
var node = document.createTextNode(content); iIndex += textContentItemsStr[i].length;
if (className) { i++;
var span = document.createElement('span');
span.className = className;
span.appendChild(node);
div.appendChild(span);
return;
}
div.appendChild(node);
} }
var i0 = selectedMatchIdx, i1 = i0 + 1; match.end = {
if (highlightAll) { divIdx: i,
i0 = 0; offset: matchIdx - iIndex,
i1 = matches.length; };
} else if (!isSelectedPage) { ret.push(match);
// Not highlighting all and this isn't the selected page, so do nothing. }
return;
}
for (var i = i0; i < i1; i++) { return ret;
var match = matches[i]; }
var begin = match.begin;
var end = match.end;
var isSelected = (isSelectedPage && i === selectedMatchIdx);
var highlightSuffix = (isSelected ? ' selected' : '');
if (this.findController) { renderMatches(matches) {
this.findController.updateMatchPosition(pageIdx, i, textDivs, // Early exit if there is nothing to render.
begin.divIdx); if (matches.length === 0) {
} return;
}
let textContentItemsStr = this.textContentItemsStr;
let textDivs = this.textDivs;
let prevEnd = null;
let pageIdx = this.pageIdx;
let isSelectedPage = (this.findController === null ?
false : (pageIdx === this.findController.selected.pageIdx));
let selectedMatchIdx = (this.findController === null ?
-1 : this.findController.selected.matchIdx);
let highlightAll = (this.findController === null ?
false : this.findController.state.highlightAll);
let infinity = {
divIdx: -1,
offset: undefined,
};
function beginText(begin, className) {
let divIdx = begin.divIdx;
textDivs[divIdx].textContent = '';
appendTextToDiv(divIdx, 0, begin.offset, className);
}
function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
let div = textDivs[divIdx];
let content = textContentItemsStr[divIdx].substring(fromOffset, toOffset);
let node = document.createTextNode(content);
if (className) {
let span = document.createElement('span');
span.className = className;
span.appendChild(node);
div.appendChild(span);
return;
}
div.appendChild(node);
}
let i0 = selectedMatchIdx, i1 = i0 + 1;
if (highlightAll) {
i0 = 0;
i1 = matches.length;
} else if (!isSelectedPage) {
// Not highlighting all and this isn't the selected page, so do nothing.
return;
}
for (let i = i0; i < i1; i++) {
let match = matches[i];
let begin = match.begin;
let end = match.end;
let isSelected = (isSelectedPage && i === selectedMatchIdx);
let highlightSuffix = (isSelected ? ' selected' : '');
if (this.findController) {
this.findController.updateMatchPosition(pageIdx, i, textDivs,
begin.divIdx);
}
// Match inside new div. // Match inside new div.
if (!prevEnd || begin.divIdx !== prevEnd.divIdx) { if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
// If there was a previous div, then add the text at the end. // If there was a previous div, then add the text at the end.
if (prevEnd !== null) { if (prevEnd !== null) {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
}
// Clear the divs and set the content until the starting point.
beginText(begin);
} else {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
} }
// Clear the divs and set the content until the starting point.
beginText(begin);
} else {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
}
if (begin.divIdx === end.divIdx) { if (begin.divIdx === end.divIdx) {
appendTextToDiv(begin.divIdx, begin.offset, end.offset, appendTextToDiv(begin.divIdx, begin.offset, end.offset,
'highlight' + highlightSuffix); 'highlight' + highlightSuffix);
} 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);
} }
prevEnd = end; beginText(end, 'highlight end' + highlightSuffix);
} }
prevEnd = end;
}
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.
let matches = this.matches;
let textDivs = this.textDivs;
let textContentItemsStr = this.textContentItemsStr;
let clearedUntilDivIdx = -1;
// Clear all current matches.
for (let i = 0, len = matches.length; i < len; i++) {
let match = matches[i];
let begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
for (let n = begin, end = match.end.divIdx; n <= end; n++) {
let div = textDivs[n];
div.textContent = textContentItemsStr[n];
div.className = '';
} }
clearedUntilDivIdx = match.end.divIdx + 1;
}
if (this.findController === null || !this.findController.active) {
return;
}
// Convert the matches on the page controller into the match format
// used for the textLayer.
let pageMatches, pageMatchesLength;
if (this.findController !== null) {
pageMatches = this.findController.pageMatches[this.pageIdx] || null;
pageMatchesLength = (this.findController.pageMatchesLength) ?
this.findController.pageMatchesLength[this.pageIdx] || null : null;
}
this.matches = this.convertMatches(pageMatches, pageMatchesLength);
this.renderMatches(this.matches);
}
// Clear all matches. /**
var matches = this.matches; * Improves text selection by adding an additional div where the mouse was
var textDivs = this.textDivs; * clicked. This reduces flickering of the content if the mouse is slowly
let textContentItemsStr = this.textContentItemsStr; * dragged up or down.
var clearedUntilDivIdx = -1; *
* @private
// Clear all current matches. */
for (var i = 0, len = matches.length; i < len; i++) { _bindMouse() {
var match = matches[i]; let div = this.textLayerDiv;
var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); let expandDivsTimer = null;
for (var n = begin, end = match.end.divIdx; n <= end; n++) {
var div = textDivs[n]; div.addEventListener('mousedown', (evt) => {
div.textContent = textContentItemsStr[n]; if (this.enhanceTextSelection && this.textLayerRenderTask) {
div.className = ''; this.textLayerRenderTask.expandTextDivs(true);
if ((typeof PDFJSDev === 'undefined' ||
!PDFJSDev.test('FIREFOX || MOZCENTRAL')) &&
expandDivsTimer) {
clearTimeout(expandDivsTimer);
expandDivsTimer = null;
} }
clearedUntilDivIdx = match.end.divIdx + 1;
}
if (this.findController === null || !this.findController.active) {
return; return;
} }
// Convert the matches on the page controller into the match format let end = div.querySelector('.endOfContent');
// used for the textLayer. if (!end) {
var pageMatches, pageMatchesLength; return;
if (this.findController !== null) {
pageMatches = this.findController.pageMatches[this.pageIdx] || null;
pageMatchesLength = (this.findController.pageMatchesLength) ?
this.findController.pageMatchesLength[this.pageIdx] || null : null;
} }
if (typeof PDFJSDev === 'undefined' ||
this.matches = this.convertMatches(pageMatches, pageMatchesLength); !PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
this.renderMatches(this.matches);
},
/**
* Fixes text selection: adds additional div where mouse was clicked.
* This reduces flickering of the content if mouse slowly dragged down/up.
* @private
*/
_bindMouse: function TextLayerBuilder_bindMouse() {
var div = this.textLayerDiv;
var self = this;
var expandDivsTimer = null;
div.addEventListener('mousedown', function (e) {
if (self.enhanceTextSelection && self.textLayerRenderTask) {
self.textLayerRenderTask.expandTextDivs(true);
if ((typeof PDFJSDev === 'undefined' ||
!PDFJSDev.test('FIREFOX || MOZCENTRAL')) &&
expandDivsTimer) {
clearTimeout(expandDivsTimer);
expandDivsTimer = null;
}
return;
}
var end = div.querySelector('.endOfContent');
if (!end) {
return;
}
if (typeof PDFJSDev === 'undefined' ||
!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' ||
!PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
expandDivsTimer = setTimeout(function() {
if (self.textLayerRenderTask) {
self.textLayerRenderTask.expandTextDivs(false);
}
expandDivsTimer = null;
}, EXPAND_DIVS_TIMEOUT);
} else {
self.textLayerRenderTask.expandTextDivs(false);
}
return;
}
var end = div.querySelector('.endOfContent');
if (!end) {
return;
}
if (typeof PDFJSDev === 'undefined' || if (typeof PDFJSDev === 'undefined' ||
!PDFJSDev.test('FIREFOX || MOZCENTRAL')) { !PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
end.style.top = ''; expandDivsTimer = setTimeout(() => {
if (this.textLayerRenderTask) {
this.textLayerRenderTask.expandTextDivs(false);
}
expandDivsTimer = null;
}, EXPAND_DIVS_TIMEOUT);
} else {
this.textLayerRenderTask.expandTextDivs(false);
} }
end.classList.remove('active'); return;
}); }
},
}; let end = div.querySelector('.endOfContent');
return TextLayerBuilder; if (!end) {
})(); return;
}
if (typeof PDFJSDev === 'undefined' ||
!PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
end.style.top = '';
}
end.classList.remove('active');
});
}
}
/** /**
* @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