text_highlighter.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /* Copyright 2021 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. /** @typedef {import("./event_utils").EventBus} EventBus */
  16. // eslint-disable-next-line max-len
  17. /** @typedef {import("./pdf_find_controller").PDFFindController} PDFFindController */
  18. /**
  19. * @typedef {Object} TextHighlighterOptions
  20. * @property {PDFFindController} findController
  21. * @property {EventBus} eventBus - The application event bus.
  22. * @property {number} pageIndex - The page index.
  23. */
  24. /**
  25. * TextHighlighter handles highlighting matches from the FindController in
  26. * either the text layer or XFA layer depending on the type of document.
  27. */
  28. class TextHighlighter {
  29. /**
  30. * @param {TextHighlighterOptions} options
  31. */
  32. constructor({ findController, eventBus, pageIndex }) {
  33. this.findController = findController;
  34. this.matches = [];
  35. this.eventBus = eventBus;
  36. this.pageIdx = pageIndex;
  37. this._onUpdateTextLayerMatches = null;
  38. this.textDivs = null;
  39. this.textContentItemsStr = null;
  40. this.enabled = false;
  41. }
  42. /**
  43. * Store two arrays that will map DOM nodes to text they should contain.
  44. * The arrays should be of equal length and the array element at each index
  45. * should correspond to the other. e.g.
  46. * `items[0] = "<span>Item 0</span>" and texts[0] = "Item 0";
  47. *
  48. * @param {Array<Node>} divs
  49. * @param {Array<string>} texts
  50. */
  51. setTextMapping(divs, texts) {
  52. this.textDivs = divs;
  53. this.textContentItemsStr = texts;
  54. }
  55. /**
  56. * Start listening for events to update the highlighter and check if there are
  57. * any current matches that need be highlighted.
  58. */
  59. enable() {
  60. if (!this.textDivs || !this.textContentItemsStr) {
  61. throw new Error("Text divs and strings have not been set.");
  62. }
  63. if (this.enabled) {
  64. throw new Error("TextHighlighter is already enabled.");
  65. }
  66. this.enabled = true;
  67. if (!this._onUpdateTextLayerMatches) {
  68. this._onUpdateTextLayerMatches = evt => {
  69. if (evt.pageIndex === this.pageIdx || evt.pageIndex === -1) {
  70. this._updateMatches();
  71. }
  72. };
  73. this.eventBus._on(
  74. "updatetextlayermatches",
  75. this._onUpdateTextLayerMatches
  76. );
  77. }
  78. this._updateMatches();
  79. }
  80. disable() {
  81. if (!this.enabled) {
  82. return;
  83. }
  84. this.enabled = false;
  85. if (this._onUpdateTextLayerMatches) {
  86. this.eventBus._off(
  87. "updatetextlayermatches",
  88. this._onUpdateTextLayerMatches
  89. );
  90. this._onUpdateTextLayerMatches = null;
  91. }
  92. this._updateMatches(/* reset = */ true);
  93. }
  94. _convertMatches(matches, matchesLength) {
  95. // Early exit if there is nothing to convert.
  96. if (!matches) {
  97. return [];
  98. }
  99. const { textContentItemsStr } = this;
  100. let i = 0,
  101. iIndex = 0;
  102. const end = textContentItemsStr.length - 1;
  103. const result = [];
  104. for (let m = 0, mm = matches.length; m < mm; m++) {
  105. // Calculate the start position.
  106. let matchIdx = matches[m];
  107. // Loop over the divIdxs.
  108. while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) {
  109. iIndex += textContentItemsStr[i].length;
  110. i++;
  111. }
  112. if (i === textContentItemsStr.length) {
  113. console.error("Could not find a matching mapping");
  114. }
  115. const match = {
  116. begin: {
  117. divIdx: i,
  118. offset: matchIdx - iIndex,
  119. },
  120. };
  121. // Calculate the end position.
  122. matchIdx += matchesLength[m];
  123. // Somewhat the same array as above, but use > instead of >= to get
  124. // the end position right.
  125. while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) {
  126. iIndex += textContentItemsStr[i].length;
  127. i++;
  128. }
  129. match.end = {
  130. divIdx: i,
  131. offset: matchIdx - iIndex,
  132. };
  133. result.push(match);
  134. }
  135. return result;
  136. }
  137. _renderMatches(matches) {
  138. // Early exit if there is nothing to render.
  139. if (matches.length === 0) {
  140. return;
  141. }
  142. const { findController, pageIdx } = this;
  143. const { textContentItemsStr, textDivs } = this;
  144. const isSelectedPage = pageIdx === findController.selected.pageIdx;
  145. const selectedMatchIdx = findController.selected.matchIdx;
  146. const highlightAll = findController.state.highlightAll;
  147. let prevEnd = null;
  148. const infinity = {
  149. divIdx: -1,
  150. offset: undefined,
  151. };
  152. function beginText(begin, className) {
  153. const divIdx = begin.divIdx;
  154. textDivs[divIdx].textContent = "";
  155. return appendTextToDiv(divIdx, 0, begin.offset, className);
  156. }
  157. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  158. let div = textDivs[divIdx];
  159. if (div.nodeType === Node.TEXT_NODE) {
  160. const span = document.createElement("span");
  161. div.before(span);
  162. span.append(div);
  163. textDivs[divIdx] = span;
  164. div = span;
  165. }
  166. const content = textContentItemsStr[divIdx].substring(
  167. fromOffset,
  168. toOffset
  169. );
  170. const node = document.createTextNode(content);
  171. if (className) {
  172. const span = document.createElement("span");
  173. span.className = `${className} appended`;
  174. span.append(node);
  175. div.append(span);
  176. return className.includes("selected") ? span.offsetLeft : 0;
  177. }
  178. div.append(node);
  179. return 0;
  180. }
  181. let i0 = selectedMatchIdx,
  182. i1 = i0 + 1;
  183. if (highlightAll) {
  184. i0 = 0;
  185. i1 = matches.length;
  186. } else if (!isSelectedPage) {
  187. // Not highlighting all and this isn't the selected page, so do nothing.
  188. return;
  189. }
  190. for (let i = i0; i < i1; i++) {
  191. const match = matches[i];
  192. const begin = match.begin;
  193. const end = match.end;
  194. const isSelected = isSelectedPage && i === selectedMatchIdx;
  195. const highlightSuffix = isSelected ? " selected" : "";
  196. let selectedLeft = 0;
  197. // Match inside new div.
  198. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  199. // If there was a previous div, then add the text at the end.
  200. if (prevEnd !== null) {
  201. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  202. }
  203. // Clear the divs and set the content until the starting point.
  204. beginText(begin);
  205. } else {
  206. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  207. }
  208. if (begin.divIdx === end.divIdx) {
  209. selectedLeft = appendTextToDiv(
  210. begin.divIdx,
  211. begin.offset,
  212. end.offset,
  213. "highlight" + highlightSuffix
  214. );
  215. } else {
  216. selectedLeft = appendTextToDiv(
  217. begin.divIdx,
  218. begin.offset,
  219. infinity.offset,
  220. "highlight begin" + highlightSuffix
  221. );
  222. for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  223. textDivs[n0].className = "highlight middle" + highlightSuffix;
  224. }
  225. beginText(end, "highlight end" + highlightSuffix);
  226. }
  227. prevEnd = end;
  228. if (isSelected) {
  229. // Attempt to scroll the selected match into view.
  230. findController.scrollMatchIntoView({
  231. element: textDivs[begin.divIdx],
  232. selectedLeft,
  233. pageIndex: pageIdx,
  234. matchIndex: selectedMatchIdx,
  235. });
  236. }
  237. }
  238. if (prevEnd) {
  239. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  240. }
  241. }
  242. _updateMatches(reset = false) {
  243. if (!this.enabled && !reset) {
  244. return;
  245. }
  246. const { findController, matches, pageIdx } = this;
  247. const { textContentItemsStr, textDivs } = this;
  248. let clearedUntilDivIdx = -1;
  249. // Clear all current matches.
  250. for (const match of matches) {
  251. const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  252. for (let n = begin, end = match.end.divIdx; n <= end; n++) {
  253. const div = textDivs[n];
  254. div.textContent = textContentItemsStr[n];
  255. div.className = "";
  256. }
  257. clearedUntilDivIdx = match.end.divIdx + 1;
  258. }
  259. if (!findController?.highlightMatches || reset) {
  260. return;
  261. }
  262. // Convert the matches on the `findController` into the match format
  263. // used for the textLayer.
  264. const pageMatches = findController.pageMatches[pageIdx] || null;
  265. const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null;
  266. this.matches = this._convertMatches(pageMatches, pageMatchesLength);
  267. this._renderMatches(this.matches);
  268. }
  269. }
  270. export { TextHighlighter };