@internetarchive/bookreader 5.0.0-38 → 5.0.0-39
Sign up to get free protection for your applications and to get access to all the features.
- package/BookReader/BookReader.css +8 -0
- package/BookReader/BookReader.js +1 -1
- package/BookReader/BookReader.js.map +1 -1
- package/BookReader/ia-bookreader-bundle.js +99 -75
- package/BookReader/ia-bookreader-bundle.js.map +1 -1
- package/BookReader/icons/magnify-minus.svg +1 -1
- package/BookReader/icons/magnify-plus.svg +1 -1
- package/BookReader/plugins/plugin.autoplay.js +1 -1
- package/BookReader/plugins/plugin.autoplay.js.map +1 -1
- package/BookReader/plugins/plugin.chapters.js +1 -1
- package/BookReader/plugins/plugin.chapters.js.map +1 -1
- package/BookReader/plugins/plugin.mobile_nav.js +1 -1
- package/BookReader/plugins/plugin.mobile_nav.js.map +1 -1
- package/BookReader/plugins/plugin.resume.js +1 -1
- package/BookReader/plugins/plugin.resume.js.map +1 -1
- package/BookReader/plugins/plugin.search.js +1 -1
- package/BookReader/plugins/plugin.search.js.map +1 -1
- package/BookReader/plugins/plugin.text_selection.js +1 -1
- package/BookReader/plugins/plugin.text_selection.js.map +1 -1
- package/BookReader/plugins/plugin.tts.js +1 -1
- package/BookReader/plugins/plugin.tts.js.map +1 -1
- package/BookReader/plugins/plugin.url.js +1 -1
- package/BookReader/plugins/plugin.url.js.map +1 -1
- package/CHANGELOG.md +5 -0
- package/README.md +13 -0
- package/package.json +14 -14
- package/renovate.json +1 -1
- package/src/BookReader/Mode1UpLit.js +7 -1
- package/src/BookReader/Mode2Up.js +11 -0
- package/src/BookReader/ModeSmoothZoom.js +2 -0
- package/src/BookReader/PageContainer.js +10 -4
- package/src/BookReader/utils/ScrollClassAdder.js +31 -0
- package/src/assets/icons/magnify-minus.svg +3 -7
- package/src/assets/icons/magnify-plus.svg +3 -7
- package/src/css/_TextSelection.scss +13 -0
- package/tests/jest/BookReader/PageContainer.test.js +5 -4
- package/tests/jest/BookReader/utils/ScrollClassAdder.test.js +49 -0
- package/.husky/_/husky.sh +0 -30
- package/stat/BookNavigator/BookModel.js +0 -14
- package/stat/BookNavigator/BookNavigator.js +0 -524
- package/stat/BookNavigator/assets/bookmark-colors.js +0 -15
- package/stat/BookNavigator/assets/button-base.js +0 -61
- package/stat/BookNavigator/assets/ia-logo.js +0 -17
- package/stat/BookNavigator/assets/icon_checkmark.js +0 -6
- package/stat/BookNavigator/assets/icon_close.js +0 -3
- package/stat/BookNavigator/assets/icon_sort_asc.js +0 -5
- package/stat/BookNavigator/assets/icon_sort_desc.js +0 -5
- package/stat/BookNavigator/assets/icon_sort_neutral.js +0 -5
- package/stat/BookNavigator/assets/icon_volumes.js +0 -11
- package/stat/BookNavigator/bookmarks/bookmark-button.js +0 -64
- package/stat/BookNavigator/bookmarks/bookmark-edit.js +0 -215
- package/stat/BookNavigator/bookmarks/bookmarks-list.js +0 -285
- package/stat/BookNavigator/bookmarks/bookmarks-loginCTA.js +0 -28
- package/stat/BookNavigator/bookmarks/bookmarks-provider.js +0 -56
- package/stat/BookNavigator/bookmarks/ia-bookmarks.js +0 -523
- package/stat/BookNavigator/br-fullscreen-mgr.js +0 -82
- package/stat/BookNavigator/delete-modal-actions.js +0 -49
- package/stat/BookNavigator/downloads/downloads-provider.js +0 -72
- package/stat/BookNavigator/downloads/downloads.js +0 -139
- package/stat/BookNavigator/provider-config.js +0 -0
- package/stat/BookNavigator/search/a-search-result.js +0 -55
- package/stat/BookNavigator/search/search-provider.js +0 -180
- package/stat/BookNavigator/search/search-results.js +0 -360
- package/stat/BookNavigator/sharing.js +0 -31
- package/stat/BookNavigator/visual-adjustments/visual-adjustments-provider.js +0 -94
- package/stat/BookNavigator/visual-adjustments/visual-adjustments.js +0 -280
- package/stat/BookNavigator/volumes/volumes-provider.js +0 -83
- package/stat/BookNavigator/volumes/volumes.js +0 -178
- package/stat/BookReader/BookModel.js +0 -518
- package/stat/BookReader/DebugConsole.js +0 -54
- package/stat/BookReader/DragScrollable.js +0 -233
- package/stat/BookReader/ImageCache.js +0 -116
- package/stat/BookReader/Mode1Up.js +0 -102
- package/stat/BookReader/Mode1UpLit.js +0 -434
- package/stat/BookReader/Mode2Up.js +0 -1372
- package/stat/BookReader/ModeSmoothZoom.js +0 -177
- package/stat/BookReader/ModeThumb.js +0 -344
- package/stat/BookReader/Navbar/Navbar.js +0 -310
- package/stat/BookReader/PageContainer.js +0 -120
- package/stat/BookReader/ReduceSet.js +0 -26
- package/stat/BookReader/Toolbar/Toolbar.js +0 -384
- package/stat/BookReader/events.js +0 -20
- package/stat/BookReader/options.js +0 -324
- package/stat/BookReader/utils/HTMLDimensionsCacher.js +0 -44
- package/stat/BookReader/utils/classes.js +0 -36
- package/stat/BookReader/utils.js +0 -240
- package/stat/BookReader.js +0 -2550
- package/stat/BookReaderComponent/BookReaderComponent.js +0 -117
- package/stat/assets/icons/1up.svg +0 -12
- package/stat/assets/icons/2up.svg +0 -15
- package/stat/assets/icons/advance.svg +0 -26
- package/stat/assets/icons/chevron-right.svg +0 -1
- package/stat/assets/icons/close-circle-dark.svg +0 -1
- package/stat/assets/icons/close-circle.svg +0 -1
- package/stat/assets/icons/fullscreen.svg +0 -17
- package/stat/assets/icons/fullscreen_exit.svg +0 -17
- package/stat/assets/icons/hamburger.svg +0 -15
- package/stat/assets/icons/left-arrow.svg +0 -12
- package/stat/assets/icons/magnify-minus.svg +0 -16
- package/stat/assets/icons/magnify-plus.svg +0 -17
- package/stat/assets/icons/magnify.svg +0 -15
- package/stat/assets/icons/pause.svg +0 -23
- package/stat/assets/icons/play.svg +0 -22
- package/stat/assets/icons/playback-speed.svg +0 -34
- package/stat/assets/icons/read-aloud.svg +0 -22
- package/stat/assets/icons/review.svg +0 -22
- package/stat/assets/icons/thumbnails.svg +0 -17
- package/stat/assets/icons/voice.svg +0 -1
- package/stat/assets/icons/volume-full.svg +0 -22
- package/stat/assets/images/BRicons.png +0 -0
- package/stat/assets/images/BRicons.svg +0 -94
- package/stat/assets/images/BRicons_ia.png +0 -0
- package/stat/assets/images/back_pages.png +0 -0
- package/stat/assets/images/book_bottom_icon.png +0 -0
- package/stat/assets/images/book_down_icon.png +0 -0
- package/stat/assets/images/book_left_icon.png +0 -0
- package/stat/assets/images/book_leftmost_icon.png +0 -0
- package/stat/assets/images/book_right_icon.png +0 -0
- package/stat/assets/images/book_rightmost_icon.png +0 -0
- package/stat/assets/images/book_top_icon.png +0 -0
- package/stat/assets/images/book_up_icon.png +0 -0
- package/stat/assets/images/books_graphic.svg +0 -177
- package/stat/assets/images/booksplit.png +0 -0
- package/stat/assets/images/control_pause_icon.png +0 -0
- package/stat/assets/images/control_play_icon.png +0 -0
- package/stat/assets/images/embed_icon.png +0 -0
- package/stat/assets/images/icon-home-ia.png +0 -0
- package/stat/assets/images/icon_OL-logo-xs.png +0 -0
- package/stat/assets/images/icon_alert-xs.png +0 -0
- package/stat/assets/images/icon_book.svg +0 -12
- package/stat/assets/images/icon_bookmark.svg +0 -12
- package/stat/assets/images/icon_close-pop.png +0 -0
- package/stat/assets/images/icon_download.png +0 -0
- package/stat/assets/images/icon_gear.svg +0 -14
- package/stat/assets/images/icon_hamburger.svg +0 -20
- package/stat/assets/images/icon_home.png +0 -0
- package/stat/assets/images/icon_home.svg +0 -21
- package/stat/assets/images/icon_home_ia.png +0 -0
- package/stat/assets/images/icon_indicator.png +0 -0
- package/stat/assets/images/icon_info.svg +0 -11
- package/stat/assets/images/icon_one_page.svg +0 -8
- package/stat/assets/images/icon_pause.svg +0 -1
- package/stat/assets/images/icon_play.svg +0 -1
- package/stat/assets/images/icon_playback-rate.svg +0 -15
- package/stat/assets/images/icon_return.png +0 -0
- package/stat/assets/images/icon_search_button.svg +0 -8
- package/stat/assets/images/icon_share.svg +0 -9
- package/stat/assets/images/icon_skip-ahead.svg +0 -6
- package/stat/assets/images/icon_skip-back.svg +0 -13
- package/stat/assets/images/icon_speaker.svg +0 -18
- package/stat/assets/images/icon_speaker_open.svg +0 -10
- package/stat/assets/images/icon_thumbnails.svg +0 -12
- package/stat/assets/images/icon_toc.svg +0 -5
- package/stat/assets/images/icon_two_pages.svg +0 -9
- package/stat/assets/images/icon_zoomer.png +0 -0
- package/stat/assets/images/loading.gif +0 -0
- package/stat/assets/images/logo_icon.png +0 -0
- package/stat/assets/images/marker_chap-off.png +0 -0
- package/stat/assets/images/marker_chap-off.svg +0 -11
- package/stat/assets/images/marker_chap-off_ia.png +0 -0
- package/stat/assets/images/marker_chap-on.png +0 -0
- package/stat/assets/images/marker_chap-on.svg +0 -11
- package/stat/assets/images/marker_srch-on.svg +0 -11
- package/stat/assets/images/marker_srchchap-off.png +0 -0
- package/stat/assets/images/marker_srchchap-on.png +0 -0
- package/stat/assets/images/nav_control-dn.png +0 -0
- package/stat/assets/images/nav_control-dn_ia.png +0 -0
- package/stat/assets/images/nav_control-up.png +0 -0
- package/stat/assets/images/nav_control-up_ia.png +0 -0
- package/stat/assets/images/nav_control.png +0 -0
- package/stat/assets/images/one_page_mode_icon.png +0 -0
- package/stat/assets/images/paper-badge.png +0 -0
- package/stat/assets/images/print_icon.png +0 -0
- package/stat/assets/images/progressbar.gif +0 -0
- package/stat/assets/images/right_edges.png +0 -0
- package/stat/assets/images/slider.png +0 -0
- package/stat/assets/images/slider_ia.png +0 -0
- package/stat/assets/images/thumbnail_mode_icon.png +0 -0
- package/stat/assets/images/transparent.png +0 -0
- package/stat/assets/images/two_page_mode_icon.png +0 -0
- package/stat/assets/images/zoom_in_icon.png +0 -0
- package/stat/assets/images/zoom_out_icon.png +0 -0
- package/stat/css/BookReader.scss +0 -89
- package/stat/css/_BRBookmarks.scss +0 -29
- package/stat/css/_BRComponent.scss +0 -13
- package/stat/css/_BRfloat.scss +0 -197
- package/stat/css/_BRicon.scss +0 -48
- package/stat/css/_BRmain.scss +0 -251
- package/stat/css/_BRnav.scss +0 -359
- package/stat/css/_BRpages.scss +0 -139
- package/stat/css/_BRsearch.scss +0 -226
- package/stat/css/_BRtoolbar.scss +0 -84
- package/stat/css/_BRvendor.scss +0 -5
- package/stat/css/_MobileNav.scss +0 -194
- package/stat/css/_TextSelection.scss +0 -32
- package/stat/css/_colorbox.scss +0 -52
- package/stat/css/_controls.scss +0 -253
- package/stat/css/_icons.scss +0 -121
- package/stat/jquery-wrapper.js +0 -4
- package/stat/plugins/plugin.archive_analytics.js +0 -86
- package/stat/plugins/plugin.autoplay.js +0 -129
- package/stat/plugins/plugin.chapters.js +0 -248
- package/stat/plugins/plugin.iframe.js +0 -48
- package/stat/plugins/plugin.mobile_nav.js +0 -288
- package/stat/plugins/plugin.resume.js +0 -68
- package/stat/plugins/plugin.text_selection.js +0 -291
- package/stat/plugins/plugin.url.js +0 -198
- package/stat/plugins/plugin.vendor-fullscreen.js +0 -247
- package/stat/plugins/search/plugin.search.js +0 -439
- package/stat/plugins/search/view.js +0 -439
- package/stat/plugins/tts/AbstractTTSEngine.js +0 -249
- package/stat/plugins/tts/FestivalTTSEngine.js +0 -169
- package/stat/plugins/tts/PageChunk.js +0 -107
- package/stat/plugins/tts/PageChunkIterator.js +0 -163
- package/stat/plugins/tts/WebTTSEngine.js +0 -357
- package/stat/plugins/tts/plugin.tts.js +0 -357
- package/stat/plugins/tts/tooltip_dict.js +0 -15
- package/stat/plugins/tts/utils.js +0 -91
- package/stat/util/browserSniffing.js +0 -30
- package/stat/util/debouncer.js +0 -26
- package/stat/util/docCookies.js +0 -67
- package/stat/util/strings.js +0 -34
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"plugins/plugin.search.js","mappings":"ihBAyCwCA,EC+YxC,EAxbMC,WASJ,cAAwD,IAA1CC,EAA0C,EAA1CA,GAA0C,IAAtCC,wBAAAA,OAAsC,MAAZ,aAAY,G,4FAAA,SACtDC,KAAKF,GAAKA,EAKVE,KAAKC,QAAU,IAAIC,OAAO,cAAe,KACzCF,KAAKG,QAAU,GACfH,KAAKI,mBACLJ,KAAKK,aACLL,KAAKM,aAAeP,E,qDAGtB,WACEC,KAAKO,IAAM,GAEXP,KAAKO,IAAIC,cAAgBR,KAAKS,uB,sBAMhC,SAASC,GACPV,KAAKF,GA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KwD,gBAcvB,OATAgF,EAAQrI,QAAQyQ,MAAK,SAAA1L,GACnB,OAAOA,EAAM5B,IAAI,GAAG0L,MAAM4B,MAAK,SAAA3B,GAC7B,IAAM7J,EAAY,EAAKC,eAAe4J,EAAI1L,MAC1C,GAAI8G,EAAOwG,QAAQzL,EAAWoL,IAAiB,EAC7C,OAAO,SAKN,I,qBE5aT,IAAI7P,EAAI,EAAQ,MACZmQ,EAAW,gBAIfnQ,EAAE,CAAE0G,OAAQ,SAAU0J,MAAM,GAAQ,CAClCvB,QAAS,SAAiBwB,GACxB,OAAOF,EAASE,Q","sources":["webpack://@internetarchive/bookreader/./src/plugins/search/plugin.search.js","webpack://@internetarchive/bookreader/./src/plugins/search/view.js","webpack://@internetarchive/bookreader/./node_modules/core-js/modules/es.object.entries.js"],"sourcesContent":["/* global BookReader */\n/**\n * Plugin for Archive.org book search\n * NOTE: This script must be loaded AFTER `plugin.mobile_nav.js`\n * as it mutates mobile nav drawer\n *\n * Events fired at various points throughout search processing are published\n * on the document DOM element. These can be subscribed to using jQuery's event\n * binding method `$.fn.on`. All of the events are prefixed with a BookReader\n * namespace. The events are:\n *\n * @event BookReader:SearchStarted - When a search form is submitted, immediately\n * before an AJAX call is made to request search results\n * @event BookReader:SearchCallback - When the search AJAX call is returned and at\n * least one result is returned. The event callback receives an object\n * with the `results`, plugin `options`, and the BookReader `instance`\n * @event BookReader:SearchCallbackError - When the AJAX request returns an error.\n * Receives the `results` and `instance`\n * @event BookReader:SearchCallbackNotIndexed - When a message is received that\n * the book has not had OCR text indexed yet. Receives `instance`\n * @event BookReader:SearchCallbackEmpty - When no results found. Receives\n * `instance`\n * @event BookReader:SearchCanceled - When no results found. Receives\n * `instance`\n */\nimport { renderBoxesInPageContainerLayer } from '../../BookReader/PageContainer.js';\nimport SearchView from './view.js';\n/** @typedef {import('../../BookReader/PageContainer').PageContainer} PageContainer */\n/** @typedef {import('../../BookReader/BookModel').PageIndex} PageIndex */\n\njQuery.extend(BookReader.defaultOptions, {\n server: 'ia600609.us.archive.org',\n bookId: '',\n subPrefix: '',\n bookPath: '',\n enableSearch: true,\n searchInsideUrl: '/fulltext/inside.php',\n initialSearchTerm: null,\n});\n\n/** @override */\nBookReader.prototype.setup = (function (super_) {\n return function (options) {\n super_.call(this, options);\n\n this.searchTerm = '';\n this.searchResults = null;\n this.searchInsideUrl = options.searchInsideUrl;\n this.enableSearch = options.enableSearch;\n\n // Base server used by some api calls\n this.bookId = options.bookId;\n this.server = options.server;\n this.subPrefix = options.subPrefix;\n this.bookPath = options.bookPath;\n\n this.searchXHR = null;\n this._cancelSearch.bind(this);\n this.cancelSearchRequest.bind(this);\n\n /** @type { {[pageIndex: number]: SearchInsideMatchBox[]} } */\n this._searchBoxesByIndex = {};\n\n this.searchView = undefined;\n };\n})(BookReader.prototype.setup);\n\n/** @override */\nBookReader.prototype.init = (function (super_) {\n return function () {\n super_.call(this);\n // give SearchView the most complete bookreader state\n this.searchView = new SearchView({\n br: this,\n searchCancelledCallback: () => {\n this._cancelSearch();\n this.trigger('SearchCanceled', { term: this.searchTerm, instance: this });\n }\n });\n if (this.options.enableSearch && this.options.initialSearchTerm) {\n /**\n * this.search() take two parameter\n * 1. this.options.initialSearchTerm - search term\n * 2. {\n * goToFirstResult: this.options.goToFirstResult,\n * suppressFragmentChange: false // always want to change fragment in URL\n * }\n */\n this.search(\n this.options.initialSearchTerm,\n { goToFirstResult: this.options.goToFirstResult, suppressFragmentChange: false }\n );\n }\n };\n})(BookReader.prototype.init);\n\n/** @override */\nBookReader.prototype.buildToolbarElement = (function (super_) {\n return function () {\n const $el = super_.call(this);\n if (!this.enableSearch) { return; }\n if (this.searchView.dom.toolbarSearch) {\n $el.find('.BRtoolbarSectionInfo').after(this.searchView.dom.toolbarSearch);\n }\n return $el;\n };\n})(BookReader.prototype.buildToolbarElement);\n\n/** @override */\nBookReader.prototype._createPageContainer = (function (super_) {\n return function (index) {\n const pageContainer = super_.call(this, index);\n if (this.enableSearch && pageContainer.page && index in this._searchBoxesByIndex) {\n const pageIndex = pageContainer.page.index;\n renderBoxesInPageContainerLayer('searchHiliteLayer', this._searchBoxesByIndex[pageIndex], pageContainer.page, pageContainer.$container[0]);\n }\n return pageContainer;\n };\n})(BookReader.prototype._createPageContainer);\n\n/**\n * @typedef {object} SearchOptions\n * @property {boolean} goToFirstResult\n * @property {boolean} disablePopup\n * @property {(null|function)} error - @deprecated at v.5.0\n * @property {(null|function)} success - @deprecated at v.5.0\n */\n\n/**\n * Submits search request\n *\n * @param {string} term\n * @param {SearchOptions} overrides\n */\nBookReader.prototype.search = async function(term = '', overrides = {}) {\n /** @type {SearchOptions} */\n const defaultOptions = {\n goToFirstResult: false, /* jump to the first result (default=false) */\n disablePopup: false, /* don't show the modal progress (default=false) */\n suppressFragmentChange: false, /* don't change the URL on initial load */\n error: null, /* optional error handler (default=null) */\n success: null, /* optional success handler (default=null) */\n\n };\n const options = jQuery.extend({}, defaultOptions, overrides);\n this.suppressFragmentChange = options.suppressFragmentChange;\n this.searchCancelled = false;\n\n // strip slashes, since this goes in the url\n this.searchTerm = term.replace(/\\//g, ' ');\n\n if (!options.suppressFragmentChange) {\n this.trigger(BookReader.eventNames.fragmentChange);\n }\n\n // Add quotes to the term. This is to compenstate for the backends default OR query\n // term = term.replace(/['\"]+/g, '');\n // term = '\"' + term + '\"';\n\n // Remove the port and userdir\n const serverPath = this.server.replace(/:.+/, '');\n const baseUrl = `https://${serverPath}${this.searchInsideUrl}?`;\n\n // Remove subPrefix from end of path\n let path = this.bookPath;\n const subPrefixWithSlash = `/${this.subPrefix}`;\n if (this.bookPath.length - this.bookPath.lastIndexOf(subPrefixWithSlash) == subPrefixWithSlash.length) {\n path = this.bookPath.substr(0, this.bookPath.length - subPrefixWithSlash.length);\n }\n\n const urlParams = {\n item_id: this.bookId,\n doc: this.subPrefix,\n path,\n q: term,\n };\n\n // NOTE that the API does not expect / (slashes) to be encoded. (%2F) won't work\n const paramStr = $.param(urlParams).replace(/%2F/g, '/');\n\n const url = `${baseUrl}${paramStr}`;\n\n const processSearchResults = (searchInsideResults) => {\n if (this.searchCancelled) {\n return;\n }\n const responseHasError = searchInsideResults.error || !searchInsideResults.matches.length;\n const hasCustomError = typeof options.error === 'function';\n const hasCustomSuccess = typeof options.success === 'function';\n\n if (responseHasError) {\n hasCustomError\n ? options.error.call(this, searchInsideResults, options)\n : this.BRSearchCallbackError(searchInsideResults, options);\n } else {\n hasCustomSuccess\n ? options.success.call(this, searchInsideResults, options)\n : this.BRSearchCallback(searchInsideResults, options);\n }\n };\n\n this.trigger('SearchStarted', { term: this.searchTerm, instance: this });\n return processSearchResults(await $.ajax({\n url: url,\n dataType: 'jsonp',\n cache: true,\n beforeSend: xhr => { this.searchXHR = xhr; },\n }));\n};\n\n/**\n * cancels AJAX Call\n * emits custom event\n */\nBookReader.prototype._cancelSearch = function () {\n this.searchXHR?.abort();\n this.searchView.clearSearchFieldAndResults(false);\n this.searchTerm = '';\n this.searchXHR = null;\n this.searchCancelled = true;\n this.searchResults = [];\n};\n\n/**\n * External function to cancel search\n * checks for term & xhr in flight before running\n */\nBookReader.prototype.cancelSearchRequest = function () {\n this.searchCancelled = true;\n if (this.searchXHR !== null) {\n this._cancelSearch();\n this.searchView.toggleSearchPending();\n this.trigger('SearchCanceled', { term: this.searchTerm, instance: this });\n }\n};\n\n/**\n * @typedef {object} SearchInsideMatchBox\n * @property {number} page\n * @property {number} r\n * @property {number} l\n * @property {number} b\n * @property {number} t\n * @property {HTMLDivElement} [div]\n */\n\n/**\n * @typedef {object} SearchInsideMatch\n * @property {string} text\n * @property {Array<{ page: number, boxes: SearchInsideMatchBox[] }>} par\n */\n\n/**\n * @typedef {object} SearchInsideResults\n * @property {string} error\n * @property {SearchInsideMatch[]} matches\n * @property {boolean} indexed\n */\n\n/**\n * Search Results return handler\n * @callback\n * @param {SearchInsideResults} results\n * @param {object} options\n * @param {boolean} options.goToFirstResult\n */\nBookReader.prototype.BRSearchCallback = function(results, options) {\n this.searchResults = results || [];\n\n this.updateSearchHilites();\n this.removeProgressPopup();\n if (options.goToFirstResult) {\n const pageIndex = this._models.book.leafNumToIndex(results.matches[0].par[0].page);\n this._searchPluginGoToResult(pageIndex);\n }\n this.trigger('SearchCallback', { results, options, instance: this });\n};\n\n/**\n * Main search results error handler\n * @callback\n * @param {SearchInsideResults} results\n */\nBookReader.prototype.BRSearchCallbackError = function(results) {\n this._BRSearchCallbackError(results);\n};\n\n/**\n * @private draws search results error\n * @callback\n * @param {SearchInsideResults} results\n * @param {jQuery} $el\n * @param {boolean} fade\n */\nBookReader.prototype._BRSearchCallbackError = function(results) {\n this.searchResults = results;\n const basePayload = {\n term: this.searchTerm,\n instance: this,\n };\n if (results.error) {\n const payload = Object.assign({}, basePayload, { results });\n this.trigger('SearchCallbackError', payload);\n } else if (0 == results.matches.length) {\n if (false === results.indexed) {\n this.trigger('SearchCallbackBookNotIndexed', basePayload);\n return;\n }\n this.trigger('SearchCallbackEmpty', basePayload);\n }\n};\n\n/**\n * updates search on-page highlights controller\n */\nBookReader.prototype.updateSearchHilites = function() {\n /** @type {SearchInsideMatch[]} */\n const matches = this.searchResults?.matches || [];\n /** @type { {[pageIndex: number]: SearchInsideMatch[]} } */\n const boxesByIndex = {};\n\n // Clear any existing svg layers\n this.removeSearchHilites();\n\n // Group by pageIndex\n for (const match of matches) {\n for (const box of match.par[0].boxes) {\n const pageIndex = this.leafNumToIndex(box.page);\n const pageMatches = boxesByIndex[pageIndex] || (boxesByIndex[pageIndex] = []);\n pageMatches.push(box);\n }\n }\n\n // update any already created pages\n for (const [pageIndexString, boxes] of Object.entries(boxesByIndex)) {\n const pageIndex = parseFloat(pageIndexString);\n const page = this._models.book.getPage(pageIndex);\n const pageContainers = this.getActivePageContainerElementsForIndex(pageIndex);\n pageContainers.forEach(container => renderBoxesInPageContainerLayer('searchHiliteLayer', boxes, page, container));\n }\n\n this._searchBoxesByIndex = boxesByIndex;\n};\n\n/**\n * remove search highlights\n */\nBookReader.prototype.removeSearchHilites = function() {\n $(this.getActivePageContainerElements()).find('.searchHiliteLayer').remove();\n};\n\n/**\n * @private\n * Goes to the page specified. If the page is not viewable, tries to load the page\n * FIXME Most of this logic is IA specific, and should be less integrated into here\n * or at least more configurable.\n * @param {PageIndex} pageIndex\n */\nBookReader.prototype._searchPluginGoToResult = async function (pageIndex) {\n const { book } = this._models;\n const page = book.getPage(pageIndex);\n let makeUnviewableAtEnd = false;\n if (!page.isViewable) {\n const resp = await fetch('/services/bookreader/request_page?' + new URLSearchParams({\n id: this.options.bookId,\n subprefix: this.options.subPrefix,\n leafNum: page.leafNum,\n })).then(r => r.json());\n\n for (const leafNum of resp.value) {\n book.getPage(book.leafNumToIndex(leafNum)).makeViewable();\n }\n\n // not able to show page; make the page viewable anyways so that it can\n // actually open. On IA, it has a fallback to a special error page.\n if (!resp.value.length) {\n book.getPage(pageIndex).makeViewable();\n makeUnviewableAtEnd = true;\n }\n }\n /* this updates the URL */\n this.suppressFragmentChange = false;\n this.jumpToIndex(pageIndex);\n\n // Reset it to unviewable if it wasn't resolved\n if (makeUnviewableAtEnd) {\n book.getPage(pageIndex).makeViewable(false);\n }\n};\n\n/**\n * Removes all search pins\n */\nBookReader.prototype.removeSearchResults = function(suppressFragmentChange = false) {\n this.removeSearchHilites(); //be sure to set all box.divs to null\n this.searchTerm = null;\n this.searchResults = null;\n if (!suppressFragmentChange) {\n this.trigger(BookReader.eventNames.fragmentChange);\n }\n};\n\n/**\n * Returns true if a search highlight is currently being displayed\n * @returns {boolean}\n */\nBookReader.prototype.searchHighlightVisible = function() {\n const results = this.searchResults;\n let visiblePages = [];\n if (null == results) return false;\n\n if (this.constMode2up == this.mode) {\n visiblePages = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];\n } else if (this.constMode1up == this.mode) {\n visiblePages = [this.currentIndex()];\n } else {\n return false;\n }\n\n results.matches.some(match => {\n return match.par[0].boxes.some(box => {\n const pageIndex = this.leafNumToIndex(box.page);\n if (jQuery.inArray(pageIndex, visiblePages) >= 0) {\n return true;\n }\n });\n });\n\n return false;\n};\n","class SearchView {\n /**\n * @param {object} params\n * @param {object} params.br The BookReader instance\n * @param {function} params.cancelSearch callback when a user wants to cancel search\n *\n * @event BookReader:SearchResultsCleared - when the search results nav gets cleared\n * @event BookReader:ToggleSearchMenu - when search results menu should toggle\n */\n constructor({ br, searchCancelledCallback = () => {} }) {\n this.br = br;\n\n // Search results are returned as a text blob with the hits wrapped in\n // triple mustaches. Hits occasionally include text beyond the search\n // term, so everything within the staches is captured and wrapped.\n this.matcher = new RegExp('{{{(.+?)}}}', 'g');\n this.matches = [];\n this.cacheDOMElements();\n this.bindEvents();\n this.cancelSearch = searchCancelledCallback;\n }\n\n cacheDOMElements() {\n this.dom = {};\n // Search input within the top toolbar. Will be removed once the mobile menu is replaced.\n this.dom.toolbarSearch = this.buildToolbarSearch();\n }\n\n /**\n * @param {string} query\n */\n setQuery(query) {\n this.br.$('[name=\"query\"]').val(query);\n }\n\n emptyMatches() {\n this.matches = [];\n }\n\n removeResultPins() {\n this.br.$('.BRnavpos .BRsearch').remove();\n }\n\n clearSearchFieldAndResults(dispatchEventWhenComplete = true) {\n this.br.removeSearchResults();\n this.removeResultPins();\n this.emptyMatches();\n this.setQuery('');\n this.teardownSearchNavigation();\n if (dispatchEventWhenComplete) {\n this.br.trigger('SearchResultsCleared');\n }\n }\n\n toggleSidebar() {\n this.br.trigger('ToggleSearchMenu');\n }\n\n renderSearchNavigation() {\n const selector = 'BRsearch-navigation';\n $('.BRnav').before(`\n <div class=\"${selector}\">\n <button class=\"toggle-sidebar\">\n <h4>\n <span class=\"icon icon-search\"></span> Results\n </h4>\n </button>\n <div class=\"pagination\">\n <button class=\"prev\" title=\"Previous result\"><span class=\"icon icon-chevron hflip\"></span></button>\n <span data-id=\"resultsCount\">${this.resultsPosition()}</span>\n <button class=\"next\" title=\"Next result\"><span class=\"icon icon-chevron\"></button>\n </div>\n <button class=\"clear\" title=\"Clear search results\">\n <span class=\"icon icon-close\"></span>\n </button>\n </div>\n `);\n this.dom.searchNavigation = $(`.${selector}`);\n }\n\n resultsPosition() {\n let positionMessage = `${this.matches.length} result${this.matches.length === 1 ? '' : 's'}`;\n if (~this.currentMatchIndex) {\n positionMessage = `${this.currentMatchIndex + 1} / ${this.matches.length}`;\n }\n return positionMessage;\n }\n\n bindSearchNavigationEvents() {\n if (!this.dom.searchNavigation) { return; }\n const namespace = 'searchNavigation';\n\n this.dom.searchNavigation\n .on(`click.${namespace}`, '.clear', this.clearSearchFieldAndResults.bind(this))\n .on(`click.${namespace}`, '.prev', this.showPrevResult.bind(this))\n .on(`click.${namespace}`, '.next', this.showNextResult.bind(this))\n .on(`click.${namespace}`, '.toggle-sidebar', this.toggleSidebar.bind(this))\n .on(`click.${namespace}`, false);\n }\n\n showPrevResult() {\n if (this.currentMatchIndex === 0) { return; }\n if (this.br.mode === this.br.constModeThumb) { this.br.switchMode(this.br.constMode1up); }\n if (!~this.currentMatchIndex) {\n this.currentMatchIndex = this.getClosestMatchIndex((start, end, comparator) => end[0] > comparator) + 1;\n }\n this.br.$('.BRnavline .BRsearch').eq(--this.currentMatchIndex).click();\n this.updateResultsPosition();\n this.updateSearchNavigationButtons();\n }\n\n showNextResult() {\n if (this.currentMatchIndex + 1 === this.matches.length) { return; }\n if (this.br.mode === this.br.constModeThumb) { this.br.switchMode(this.br.constMode1up); }\n if (!~this.currentMatchIndex) {\n this.currentMatchIndex = this.getClosestMatchIndex((start, end, comparator) => start[start.length - 1] > comparator) - 1;\n }\n this.br.$('.BRnavline .BRsearch').eq(++this.currentMatchIndex).click();\n this.updateResultsPosition();\n this.updateSearchNavigationButtons();\n }\n\n /**\n * Obtains closest match based on the logical comparison function passed in.\n * When the comparison function returns true, the starting (left) half of the\n * matches array is used in the binary split, else the ending (right) half is\n * used. A recursive call is made to perform the same split and comparison\n * on the winning half of the matches. This is traditionally known as binary\n * search (https://en.wikipedia.org/wiki/Binary_search_algorithm), and in\n * most cases (medium to large search result arrays) should outperform\n * traversing the array from start to finish. In the case of small arrays,\n * the speed difference is negligible.\n *\n * @param {function} comparisonFn\n * @return {number} matchIndex\n */\n getClosestMatchIndex(comparisonFn) {\n const matchPages = this.matches.map((m) => m.par[0].page);\n const currentPage = this.br.currentIndex() + 1;\n const closestTo = (pool, comparator) => {\n if (pool.length === 1) { return pool[0]; }\n const start = pool.slice(0, pool.length / 2);\n const end = pool.slice(pool.length / 2);\n return closestTo((comparisonFn(start, end, comparator) ? start : end), comparator);\n };\n\n const closestPage = closestTo(matchPages, currentPage);\n return this.matches.indexOf(this.matches.find((m) => m.par[0].page === closestPage));\n }\n\n updateResultsPosition() {\n if (!this.dom.searchNavigation) return;\n this.dom.searchNavigation.find('[data-id=resultsCount]').text(this.resultsPosition());\n }\n\n updateSearchNavigationButtons() {\n if (!this.dom.searchNavigation) return;\n this.dom.searchNavigation.find('.prev').attr('disabled', !this.currentMatchIndex);\n this.dom.searchNavigation.find('.next').attr('disabled', this.currentMatchIndex + 1 === this.matches.length);\n }\n\n teardownSearchNavigation() {\n if (!this.dom.searchNavigation) {\n this.dom.searchNavigation = $('.BRsearch-navigation');\n }\n if (!this.dom.searchNavigation.length) { return; }\n\n this.dom.searchNavigation.off('.searchNavigation').remove();\n this.dom.searchNavigation = null;\n this.br.resize();\n }\n\n setCurrentMatchIndex() {\n let matchingSearchResult;\n if (this.br.mode === this.br.constModeThumb) {\n this.currentMatchIndex = -1;\n return;\n }\n if (this.br.mode === this.br.constMode2up) {\n matchingSearchResult = this.find2upMatchingSearchResult();\n }\n else {\n matchingSearchResult = this.find1upMatchingSearchResult();\n }\n this.currentMatchIndex = this.matches.indexOf(matchingSearchResult);\n }\n\n find1upMatchingSearchResult() {\n return this.matches.find((m) => this.br.currentIndex() === m.par[0].page - 1);\n }\n\n find2upMatchingSearchResult() {\n return this.matches.find((m) => this.br._isIndexDisplayed(m.par[0].page - 1));\n }\n\n updateSearchNavigation() {\n if (!this.matches.length) { return; }\n\n this.setCurrentMatchIndex();\n this.updateResultsPosition();\n this.updateSearchNavigationButtons();\n }\n\n /**\n * @param {boolean} bool\n */\n togglePinsFor(bool) {\n const pinsVisibleState = bool ? 'visible' : 'hidden';\n this.br.refs.$BRfooter.find('.BRsearch').css({ visibility: pinsVisibleState });\n }\n\n buildToolbarSearch() {\n const toolbarSearch = document.createElement('span');\n toolbarSearch.classList.add('BRtoolbarSection', 'BRtoolbarSectionSearch');\n toolbarSearch.innerHTML = `\n <form class=\"BRbooksearch desktop\">\n <input type=\"search\" name=\"query\" class=\"BRsearchInput\" value=\"\" placeholder=\"Search inside\"/>\n <button type=\"submit\" class=\"BRsearchSubmit\">\n <img src=\"${this.br.imagesBaseURL}icon_search_button.svg\" />\n </button>\n </form>\n `;\n return toolbarSearch;\n }\n\n /**\n * @param {array} matches\n */\n renderPins(matches) {\n matches.forEach((match) => {\n const queryString = match.text;\n const pageIndex = this.br.leafNumToIndex(match.par[0].page);\n const pageNumber = this.br.getPageNum(pageIndex);\n const uiStringSearch = \"Search result\"; // i18n\n const uiStringPage = \"Page\"; // i18n\n\n const percentThrough = this.br.constructor.util.cssPercentage(pageIndex, this.br.getNumLeafs() - 1);\n\n const queryStringWithB = queryString.replace(this.matcher, '<b>$1</b>');\n\n let queryStringWithBTruncated = '';\n\n if (queryString.length > 100) {\n queryStringWithBTruncated = queryString\n .replace(/^(.{100}[^\\s]*).*/, \"$1\")\n .replace(this.matcher, '<b>$1</b>')\n + '...';\n }\n\n // draw marker\n $('<div>')\n .addClass('BRsearch')\n .css({\n left: percentThrough,\n })\n .attr('title', uiStringSearch)\n .append(`\n <div class=\"BRquery\">\n <div>${queryStringWithBTruncated || queryStringWithB}</div>\n <div>${uiStringPage} ${pageNumber}</div>\n </div>\n `)\n .data({ pageIndex })\n .appendTo(this.br.$('.BRnavline'))\n .on(\"mouseenter\", (event) => {\n // remove from other markers then turn on just for this\n // XXX should be done when nav slider moves\n const marker = event.currentTarget;\n const tooltip = marker.querySelector('.BRquery');\n const tooltipOffset = tooltip.getBoundingClientRect();\n const targetOffset = marker.getBoundingClientRect();\n const boxSizeAdjust = parseInt(getComputedStyle(tooltip).paddingLeft) * 2;\n if (tooltipOffset.x - boxSizeAdjust < 0) {\n tooltip.style.setProperty('transform', `translateX(-${targetOffset.left - boxSizeAdjust}px)`);\n }\n $('.BRsearch,.BRchapter').removeClass('front');\n $(event.target).addClass('front');\n })\n .on(\"mouseleave\", (event) => $(event.target).removeClass('front'))\n .on(\"click\", function (event) {\n // closures are nested and deep, using an arrow function breaks references.\n // Todo: update to arrow function & clean up closures\n // to remove `bind` dependency\n this.br._searchPluginGoToResult(+$(event.target).data('pageIndex'));\n }.bind(this));\n });\n }\n\n /**\n * @param {boolean} bool\n */\n toggleSearchPending(bool) {\n if (bool) {\n this.br.showProgressPopup(\"Search results will appear below...\", () => this.progressPopupClosed());\n }\n else {\n this.br.removeProgressPopup();\n }\n }\n\n /**\n * Primary callback when user cancels search popup\n */\n progressPopupClosed() {\n this.toggleSearchPending();\n this.cancelSearch();\n }\n\n renderErrorModal(textIsProcessing = false) {\n const errorDetails = `${!textIsProcessing ? 'The text may still be processing. ' : ''}Please try again.`;\n this.renderModalMessage(`\n Sorry, there was an error with your search.\n <br />\n ${errorDetails}\n `);\n this.delayModalRemovalFor(4000);\n }\n\n renderBookNotIndexedModal() {\n this.renderModalMessage(`\n <p>\n This book hasn't been indexed for searching yet.\n We've just started indexing it, so search should be available soon.\n <br />\n Please try again later. Thanks!\n </p>\n `);\n this.delayModalRemovalFor(5000);\n }\n\n renderResultsEmptyModal() {\n this.renderModalMessage('No matches were found.');\n this.delayModalRemovalFor(2000);\n }\n\n /**\n * @param {string} messageHTML The innerHTML string used to popupate the modal contents\n */\n renderModalMessage(messageHTML) {\n const modal = document.createElement('div');\n modal.classList.add('BRprogresspopup', 'search_modal');\n modal.innerHTML = messageHTML;\n document.querySelector(this.br.el).append(modal);\n }\n\n /**\n * @param {number} timeoutMS\n */\n delayModalRemovalFor(timeoutMS) {\n setTimeout(this.br.removeProgressPopup.bind(this.br), timeoutMS);\n }\n\n /**\n * @param {Event} e\n */\n submitHandler(e) {\n e.preventDefault();\n const query = e.target.querySelector('[name=\"query\"]').value;\n if (!query.length) { return false; }\n this.br.search(query);\n this.emptyMatches();\n this.toggleSearchPending(true);\n return false;\n }\n\n /**\n * @param {Event} e\n * @param {object} properties\n * @param {object} properties.results\n * @param {object} properties.options\n */\n handleSearchCallback(e, { results, options }) {\n this.matches = results.matches;\n this.setCurrentMatchIndex();\n this.teardownSearchNavigation();\n this.renderSearchNavigation();\n this.bindSearchNavigationEvents();\n this.renderPins(results.matches);\n this.toggleSearchPending(false);\n if (options.goToFirstResult) {\n $(document).one('BookReader:pageChanged', () => {\n this.br.resize();\n });\n } else {\n this.br.resize();\n }\n }\n\n /**\n * @param {Event} e\n */\n handleNavToggledCallback(e) {\n const is_visible = this.br.navigationIsVisible();\n this.togglePinsFor(is_visible);\n }\n\n handleSearchStarted() {\n this.emptyMatches();\n this.br.removeSearchHilites();\n this.removeResultPins();\n this.toggleSearchPending(true);\n this.teardownSearchNavigation();\n this.setQuery(this.br.searchTerm);\n }\n\n /**\n * Event listener for: `BookReader:SearchCallbackError`\n * @param {CustomEvent} event\n */\n handleSearchCallbackError(event = {}) {\n this.toggleSearchPending(false);\n const isIndexed = event?.detail?.props?.results?.indexed;\n this.renderErrorModal(isIndexed);\n }\n\n handleSearchCallbackBookNotIndexed() {\n this.toggleSearchPending(false);\n this.renderBookNotIndexedModal();\n }\n\n handleSearchCallbackEmpty() {\n this.toggleSearchPending(false);\n this.renderResultsEmptyModal();\n }\n\n bindEvents() {\n const namespace = 'BookReader:';\n\n window.addEventListener(`${namespace}SearchCallbackError`, this.handleSearchCallbackError.bind(this));\n $(document).on(`${namespace}SearchCallback`, this.handleSearchCallback.bind(this))\n .on(`${namespace}navToggled`, this.handleNavToggledCallback.bind(this))\n .on(`${namespace}SearchStarted`, this.handleSearchStarted.bind(this))\n .on(`${namespace}SearchCallbackBookNotIndexed`, this.handleSearchCallbackBookNotIndexed.bind(this))\n .on(`${namespace}SearchCallbackEmpty`, this.handleSearchCallbackEmpty.bind(this))\n .on(`${namespace}pageChanged`, this.updateSearchNavigation.bind(this));\n\n this.dom.toolbarSearch.querySelector('form').addEventListener('submit', this.submitHandler.bind(this));\n }\n}\n\nexport default SearchView;\n","var $ = require('../internals/export');\nvar $entries = require('../internals/object-to-array').entries;\n\n// `Object.entries` method\n// https://tc39.es/ecma262/#sec-object.entries\n$({ target: 'Object', stat: true }, {\n entries: function entries(O) {\n return $entries(O);\n }\n});\n"],"names":["super_","SearchView","br","searchCancelledCallback","this","matcher","RegExp","matches","cacheDOMElements","bindEvents","cancelSearch","dom","toolbarSearch","buildToolbarSearch","query","$","val","remove","dispatchEventWhenComplete","removeSearchResults","removeResultPins","emptyMatches","setQuery","teardownSearchNavigation","trigger","selector","before","resultsPosition","searchNavigation","positionMessage","length","currentMatchIndex","namespace","on","clearSearchFieldAndResults","bind","showPrevResult","showNextResult","toggleSidebar","mode","constModeThumb","switchMode","constMode1up","getClosestMatchIndex","start","end","comparator","eq","click","updateResultsPosition","updateSearchNavigationButtons","comparisonFn","closestPage","closestTo","pool","slice","map","m","par","page","currentIndex","indexOf","find","text","attr","off","resize","matchingSearchResult","constMode2up","find2upMatchingSearchResult","find1upMatchingSearchResult","_isIndexDisplayed","setCurrentMatchIndex","bool","pinsVisibleState","refs","$BRfooter","css","visibility","document","createElement","classList","add","innerHTML","imagesBaseURL","forEach","match","queryString","pageIndex","leafNumToIndex","pageNumber","getPageNum","percentThrough","constructor","util","cssPercentage","getNumLeafs","queryStringWithB","replace","queryStringWithBTruncated","addClass","left","append","data","appendTo","event","marker","currentTarget","tooltip","querySelector","tooltipOffset","getBoundingClientRect","targetOffset","boxSizeAdjust","parseInt","getComputedStyle","paddingLeft","x","style","setProperty","removeClass","target","_searchPluginGoToResult","showProgressPopup","progressPopupClosed","removeProgressPopup","toggleSearchPending","textIsProcessing","errorDetails","renderModalMessage","delayModalRemovalFor","messageHTML","modal","el","timeoutMS","setTimeout","e","preventDefault","value","search","results","options","renderSearchNavigation","bindSearchNavigationEvents","renderPins","goToFirstResult","one","is_visible","navigationIsVisible","togglePinsFor","removeSearchHilites","searchTerm","isIndexed","detail","props","indexed","renderErrorModal","renderBookNotIndexedModal","renderResultsEmptyModal","window","addEventListener","handleSearchCallbackError","handleSearchCallback","handleNavToggledCallback","handleSearchStarted","handleSearchCallbackBookNotIndexed","handleSearchCallbackEmpty","updateSearchNavigation","submitHandler","jQuery","extend","BookReader","defaultOptions","server","bookId","subPrefix","bookPath","enableSearch","searchInsideUrl","initialSearchTerm","prototype","setup","call","searchResults","searchXHR","_cancelSearch","cancelSearchRequest","_searchBoxesByIndex","searchView","undefined","init","term","instance","suppressFragmentChange","buildToolbarElement","$el","after","_createPageContainer","index","pageContainer","renderBoxesInPageContainerLayer","$container","overrides","disablePopup","error","success","searchCancelled","eventNames","fragmentChange","serverPath","baseUrl","path","subPrefixWithSlash","lastIndexOf","substr","urlParams","item_id","doc","q","paramStr","param","url","processSearchResults","searchInsideResults","responseHasError","hasCustomError","hasCustomSuccess","BRSearchCallbackError","BRSearchCallback","ajax","dataType","cache","beforeSend","xhr","abort","updateSearchHilites","_models","book","_BRSearchCallbackError","basePayload","payload","Object","assign","boxesByIndex","boxes","box","push","pageIndexString","parseFloat","getPage","getActivePageContainerElementsForIndex","container","entries","getActivePageContainerElements","makeUnviewableAtEnd","isViewable","fetch","URLSearchParams","id","subprefix","leafNum","then","r","json","resp","makeViewable","jumpToIndex","searchHighlightVisible","visiblePages","twoPage","currentIndexL","currentIndexR","some","inArray","$entries","stat","O"],"sourceRoot":""}
|
1
|
+
{"version":3,"file":"plugins/plugin.search.js","mappings":"kiBAyCwCA,EC+YxC,EAxbMC,WASJ,cAAwD,IAA1CC,EAA0C,EAA1CA,GAA0C,IAAtCC,wBAAAA,OAAsC,MAAZ,aAAY,G,4FAAA,SACtDC,KAAKF,GAAKA,EAKVE,KAAKC,QAAU,IAAIC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AAIxI,KAAKgE,cAAgBhE,KAAKmC,KAC5BqO,EAAe,CAACxQ,KAAKyQ,QAAQC,cAAe1Q,KAAKyQ,QAAQE,mBACpD,IAAI3Q,KAAKsC,cAAgBtC,KAAKmC,KAGnC,OAAO,EAFPqO,EAAe,CAACxQ,KAAKwD,gBAcvB,OATAgF,EAAQrI,QAAQyQ,MAAK,SAAA1L,GACnB,OAAOA,EAAM5B,IAAI,GAAG0L,MAAM4B,MAAK,SAAA3B,GAC7B,IAAM7J,EAAY,EAAKC,eAAe4J,EAAI1L,MAC1C,GAAI8G,EAAOwG,QAAQzL,EAAWoL,IAAiB,EAC7C,OAAO,SAKN,I,qBE5aT,IAAIM,EAAS,EAAQ,MACjBC,EAAW,EAAQ,MACnBC,EAAO,aACPC,EAAc,EAAQ,MAEtBC,EAAcJ,EAAO1B,WACrB+B,EAAS,EAAID,EAAYD,EAAc,QAAU,IAIrDG,EAAOC,QAAUF,EAAS,SAAoBG,GAC5C,IAAIC,EAAgBP,EAAKD,EAASO,IAC9BE,EAASN,EAAYK,GACzB,OAAkB,IAAXC,GAA2C,KAA3BD,EAAcE,OAAO,IAAa,EAAID,GAC3DN,G,qBCdJ,IAAIvQ,EAAI,EAAQ,MACZ+Q,EAAW,gBAIf/Q,EAAE,CAAE0G,OAAQ,SAAUsK,MAAM,GAAQ,CAClCnC,QAAS,SAAiBoC,GACxB,OAAOF,EAASE,O,qBCPpB,IAAIjR,EAAI,EAAQ,MACZkR,EAA2B,EAAQ,MAIvClR,EAAE,CAAEmQ,QAAQ,EAAMgB,OAAQ1C,YAAcyC,GAA4B,CAClEzC,WAAYyC,M","sources":["webpack://@internetarchive/bookreader/./src/plugins/search/plugin.search.js","webpack://@internetarchive/bookreader/./src/plugins/search/view.js","webpack://@internetarchive/bookreader/./node_modules/core-js/internals/number-parse-float.js","webpack://@internetarchive/bookreader/./node_modules/core-js/modules/es.object.entries.js","webpack://@internetarchive/bookreader/./node_modules/core-js/modules/es.parse-float.js"],"sourcesContent":["/* global BookReader */\n/**\n * Plugin for Archive.org book search\n * NOTE: This script must be loaded AFTER `plugin.mobile_nav.js`\n * as it mutates mobile nav drawer\n *\n * Events fired at various points throughout search processing are published\n * on the document DOM element. These can be subscribed to using jQuery's event\n * binding method `$.fn.on`. All of the events are prefixed with a BookReader\n * namespace. The events are:\n *\n * @event BookReader:SearchStarted - When a search form is submitted, immediately\n * before an AJAX call is made to request search results\n * @event BookReader:SearchCallback - When the search AJAX call is returned and at\n * least one result is returned. The event callback receives an object\n * with the `results`, plugin `options`, and the BookReader `instance`\n * @event BookReader:SearchCallbackError - When the AJAX request returns an error.\n * Receives the `results` and `instance`\n * @event BookReader:SearchCallbackNotIndexed - When a message is received that\n * the book has not had OCR text indexed yet. Receives `instance`\n * @event BookReader:SearchCallbackEmpty - When no results found. Receives\n * `instance`\n * @event BookReader:SearchCanceled - When no results found. Receives\n * `instance`\n */\nimport { renderBoxesInPageContainerLayer } from '../../BookReader/PageContainer.js';\nimport SearchView from './view.js';\n/** @typedef {import('../../BookReader/PageContainer').PageContainer} PageContainer */\n/** @typedef {import('../../BookReader/BookModel').PageIndex} PageIndex */\n\njQuery.extend(BookReader.defaultOptions, {\n server: 'ia600609.us.archive.org',\n bookId: '',\n subPrefix: '',\n bookPath: '',\n enableSearch: true,\n searchInsideUrl: '/fulltext/inside.php',\n initialSearchTerm: null,\n});\n\n/** @override */\nBookReader.prototype.setup = (function (super_) {\n return function (options) {\n super_.call(this, options);\n\n this.searchTerm = '';\n this.searchResults = null;\n this.searchInsideUrl = options.searchInsideUrl;\n this.enableSearch = options.enableSearch;\n\n // Base server used by some api calls\n this.bookId = options.bookId;\n this.server = options.server;\n this.subPrefix = options.subPrefix;\n this.bookPath = options.bookPath;\n\n this.searchXHR = null;\n this._cancelSearch.bind(this);\n this.cancelSearchRequest.bind(this);\n\n /** @type { {[pageIndex: number]: SearchInsideMatchBox[]} } */\n this._searchBoxesByIndex = {};\n\n this.searchView = undefined;\n };\n})(BookReader.prototype.setup);\n\n/** @override */\nBookReader.prototype.init = (function (super_) {\n return function () {\n super_.call(this);\n // give SearchView the most complete bookreader state\n this.searchView = new SearchView({\n br: this,\n searchCancelledCallback: () => {\n this._cancelSearch();\n this.trigger('SearchCanceled', { term: this.searchTerm, instance: this });\n }\n });\n if (this.options.enableSearch && this.options.initialSearchTerm) {\n /**\n * this.search() take two parameter\n * 1. this.options.initialSearchTerm - search term\n * 2. {\n * goToFirstResult: this.options.goToFirstResult,\n * suppressFragmentChange: false // always want to change fragment in URL\n * }\n */\n this.search(\n this.options.initialSearchTerm,\n { goToFirstResult: this.options.goToFirstResult, suppressFragmentChange: false }\n );\n }\n };\n})(BookReader.prototype.init);\n\n/** @override */\nBookReader.prototype.buildToolbarElement = (function (super_) {\n return function () {\n const $el = super_.call(this);\n if (!this.enableSearch) { return; }\n if (this.searchView.dom.toolbarSearch) {\n $el.find('.BRtoolbarSectionInfo').after(this.searchView.dom.toolbarSearch);\n }\n return $el;\n };\n})(BookReader.prototype.buildToolbarElement);\n\n/** @override */\nBookReader.prototype._createPageContainer = (function (super_) {\n return function (index) {\n const pageContainer = super_.call(this, index);\n if (this.enableSearch && pageContainer.page && index in this._searchBoxesByIndex) {\n const pageIndex = pageContainer.page.index;\n renderBoxesInPageContainerLayer('searchHiliteLayer', this._searchBoxesByIndex[pageIndex], pageContainer.page, pageContainer.$container[0]);\n }\n return pageContainer;\n };\n})(BookReader.prototype._createPageContainer);\n\n/**\n * @typedef {object} SearchOptions\n * @property {boolean} goToFirstResult\n * @property {boolean} disablePopup\n * @property {(null|function)} error - @deprecated at v.5.0\n * @property {(null|function)} success - @deprecated at v.5.0\n */\n\n/**\n * Submits search request\n *\n * @param {string} term\n * @param {SearchOptions} overrides\n */\nBookReader.prototype.search = async function(term = '', overrides = {}) {\n /** @type {SearchOptions} */\n const defaultOptions = {\n goToFirstResult: false, /* jump to the first result (default=false) */\n disablePopup: false, /* don't show the modal progress (default=false) */\n suppressFragmentChange: false, /* don't change the URL on initial load */\n error: null, /* optional error handler (default=null) */\n success: null, /* optional success handler (default=null) */\n\n };\n const options = jQuery.extend({}, defaultOptions, overrides);\n this.suppressFragmentChange = options.suppressFragmentChange;\n this.searchCancelled = false;\n\n // strip slashes, since this goes in the url\n this.searchTerm = term.replace(/\\//g, ' ');\n\n if (!options.suppressFragmentChange) {\n this.trigger(BookReader.eventNames.fragmentChange);\n }\n\n // Add quotes to the term. This is to compenstate for the backends default OR query\n // term = term.replace(/['\"]+/g, '');\n // term = '\"' + term + '\"';\n\n // Remove the port and userdir\n const serverPath = this.server.replace(/:.+/, '');\n const baseUrl = `https://${serverPath}${this.searchInsideUrl}?`;\n\n // Remove subPrefix from end of path\n let path = this.bookPath;\n const subPrefixWithSlash = `/${this.subPrefix}`;\n if (this.bookPath.length - this.bookPath.lastIndexOf(subPrefixWithSlash) == subPrefixWithSlash.length) {\n path = this.bookPath.substr(0, this.bookPath.length - subPrefixWithSlash.length);\n }\n\n const urlParams = {\n item_id: this.bookId,\n doc: this.subPrefix,\n path,\n q: term,\n };\n\n // NOTE that the API does not expect / (slashes) to be encoded. (%2F) won't work\n const paramStr = $.param(urlParams).replace(/%2F/g, '/');\n\n const url = `${baseUrl}${paramStr}`;\n\n const processSearchResults = (searchInsideResults) => {\n if (this.searchCancelled) {\n return;\n }\n const responseHasError = searchInsideResults.error || !searchInsideResults.matches.length;\n const hasCustomError = typeof options.error === 'function';\n const hasCustomSuccess = typeof options.success === 'function';\n\n if (responseHasError) {\n hasCustomError\n ? options.error.call(this, searchInsideResults, options)\n : this.BRSearchCallbackError(searchInsideResults, options);\n } else {\n hasCustomSuccess\n ? options.success.call(this, searchInsideResults, options)\n : this.BRSearchCallback(searchInsideResults, options);\n }\n };\n\n this.trigger('SearchStarted', { term: this.searchTerm, instance: this });\n return processSearchResults(await $.ajax({\n url: url,\n dataType: 'jsonp',\n cache: true,\n beforeSend: xhr => { this.searchXHR = xhr; },\n }));\n};\n\n/**\n * cancels AJAX Call\n * emits custom event\n */\nBookReader.prototype._cancelSearch = function () {\n this.searchXHR?.abort();\n this.searchView.clearSearchFieldAndResults(false);\n this.searchTerm = '';\n this.searchXHR = null;\n this.searchCancelled = true;\n this.searchResults = [];\n};\n\n/**\n * External function to cancel search\n * checks for term & xhr in flight before running\n */\nBookReader.prototype.cancelSearchRequest = function () {\n this.searchCancelled = true;\n if (this.searchXHR !== null) {\n this._cancelSearch();\n this.searchView.toggleSearchPending();\n this.trigger('SearchCanceled', { term: this.searchTerm, instance: this });\n }\n};\n\n/**\n * @typedef {object} SearchInsideMatchBox\n * @property {number} page\n * @property {number} r\n * @property {number} l\n * @property {number} b\n * @property {number} t\n * @property {HTMLDivElement} [div]\n */\n\n/**\n * @typedef {object} SearchInsideMatch\n * @property {string} text\n * @property {Array<{ page: number, boxes: SearchInsideMatchBox[] }>} par\n */\n\n/**\n * @typedef {object} SearchInsideResults\n * @property {string} error\n * @property {SearchInsideMatch[]} matches\n * @property {boolean} indexed\n */\n\n/**\n * Search Results return handler\n * @callback\n * @param {SearchInsideResults} results\n * @param {object} options\n * @param {boolean} options.goToFirstResult\n */\nBookReader.prototype.BRSearchCallback = function(results, options) {\n this.searchResults = results || [];\n\n this.updateSearchHilites();\n this.removeProgressPopup();\n if (options.goToFirstResult) {\n const pageIndex = this._models.book.leafNumToIndex(results.matches[0].par[0].page);\n this._searchPluginGoToResult(pageIndex);\n }\n this.trigger('SearchCallback', { results, options, instance: this });\n};\n\n/**\n * Main search results error handler\n * @callback\n * @param {SearchInsideResults} results\n */\nBookReader.prototype.BRSearchCallbackError = function(results) {\n this._BRSearchCallbackError(results);\n};\n\n/**\n * @private draws search results error\n * @callback\n * @param {SearchInsideResults} results\n * @param {jQuery} $el\n * @param {boolean} fade\n */\nBookReader.prototype._BRSearchCallbackError = function(results) {\n this.searchResults = results;\n const basePayload = {\n term: this.searchTerm,\n instance: this,\n };\n if (results.error) {\n const payload = Object.assign({}, basePayload, { results });\n this.trigger('SearchCallbackError', payload);\n } else if (0 == results.matches.length) {\n if (false === results.indexed) {\n this.trigger('SearchCallbackBookNotIndexed', basePayload);\n return;\n }\n this.trigger('SearchCallbackEmpty', basePayload);\n }\n};\n\n/**\n * updates search on-page highlights controller\n */\nBookReader.prototype.updateSearchHilites = function() {\n /** @type {SearchInsideMatch[]} */\n const matches = this.searchResults?.matches || [];\n /** @type { {[pageIndex: number]: SearchInsideMatch[]} } */\n const boxesByIndex = {};\n\n // Clear any existing svg layers\n this.removeSearchHilites();\n\n // Group by pageIndex\n for (const match of matches) {\n for (const box of match.par[0].boxes) {\n const pageIndex = this.leafNumToIndex(box.page);\n const pageMatches = boxesByIndex[pageIndex] || (boxesByIndex[pageIndex] = []);\n pageMatches.push(box);\n }\n }\n\n // update any already created pages\n for (const [pageIndexString, boxes] of Object.entries(boxesByIndex)) {\n const pageIndex = parseFloat(pageIndexString);\n const page = this._models.book.getPage(pageIndex);\n const pageContainers = this.getActivePageContainerElementsForIndex(pageIndex);\n pageContainers.forEach(container => renderBoxesInPageContainerLayer('searchHiliteLayer', boxes, page, container));\n }\n\n this._searchBoxesByIndex = boxesByIndex;\n};\n\n/**\n * remove search highlights\n */\nBookReader.prototype.removeSearchHilites = function() {\n $(this.getActivePageContainerElements()).find('.searchHiliteLayer').remove();\n};\n\n/**\n * @private\n * Goes to the page specified. If the page is not viewable, tries to load the page\n * FIXME Most of this logic is IA specific, and should be less integrated into here\n * or at least more configurable.\n * @param {PageIndex} pageIndex\n */\nBookReader.prototype._searchPluginGoToResult = async function (pageIndex) {\n const { book } = this._models;\n const page = book.getPage(pageIndex);\n let makeUnviewableAtEnd = false;\n if (!page.isViewable) {\n const resp = await fetch('/services/bookreader/request_page?' + new URLSearchParams({\n id: this.options.bookId,\n subprefix: this.options.subPrefix,\n leafNum: page.leafNum,\n })).then(r => r.json());\n\n for (const leafNum of resp.value) {\n book.getPage(book.leafNumToIndex(leafNum)).makeViewable();\n }\n\n // not able to show page; make the page viewable anyways so that it can\n // actually open. On IA, it has a fallback to a special error page.\n if (!resp.value.length) {\n book.getPage(pageIndex).makeViewable();\n makeUnviewableAtEnd = true;\n }\n }\n /* this updates the URL */\n this.suppressFragmentChange = false;\n this.jumpToIndex(pageIndex);\n\n // Reset it to unviewable if it wasn't resolved\n if (makeUnviewableAtEnd) {\n book.getPage(pageIndex).makeViewable(false);\n }\n};\n\n/**\n * Removes all search pins\n */\nBookReader.prototype.removeSearchResults = function(suppressFragmentChange = false) {\n this.removeSearchHilites(); //be sure to set all box.divs to null\n this.searchTerm = null;\n this.searchResults = null;\n if (!suppressFragmentChange) {\n this.trigger(BookReader.eventNames.fragmentChange);\n }\n};\n\n/**\n * Returns true if a search highlight is currently being displayed\n * @returns {boolean}\n */\nBookReader.prototype.searchHighlightVisible = function() {\n const results = this.searchResults;\n let visiblePages = [];\n if (null == results) return false;\n\n if (this.constMode2up == this.mode) {\n visiblePages = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];\n } else if (this.constMode1up == this.mode) {\n visiblePages = [this.currentIndex()];\n } else {\n return false;\n }\n\n results.matches.some(match => {\n return match.par[0].boxes.some(box => {\n const pageIndex = this.leafNumToIndex(box.page);\n if (jQuery.inArray(pageIndex, visiblePages) >= 0) {\n return true;\n }\n });\n });\n\n return false;\n};\n","class SearchView {\n /**\n * @param {object} params\n * @param {object} params.br The BookReader instance\n * @param {function} params.cancelSearch callback when a user wants to cancel search\n *\n * @event BookReader:SearchResultsCleared - when the search results nav gets cleared\n * @event BookReader:ToggleSearchMenu - when search results menu should toggle\n */\n constructor({ br, searchCancelledCallback = () => {} }) {\n this.br = br;\n\n // Search results are returned as a text blob with the hits wrapped in\n // triple mustaches. Hits occasionally include text beyond the search\n // term, so everything within the staches is captured and wrapped.\n this.matcher = new RegExp('{{{(.+?)}}}', 'g');\n this.matches = [];\n this.cacheDOMElements();\n this.bindEvents();\n this.cancelSearch = searchCancelledCallback;\n }\n\n cacheDOMElements() {\n this.dom = {};\n // Search input within the top toolbar. Will be removed once the mobile menu is replaced.\n this.dom.toolbarSearch = this.buildToolbarSearch();\n }\n\n /**\n * @param {string} query\n */\n setQuery(query) {\n this.br.$('[name=\"query\"]').val(query);\n }\n\n emptyMatches() {\n this.matches = [];\n }\n\n removeResultPins() {\n this.br.$('.BRnavpos .BRsearch').remove();\n }\n\n clearSearchFieldAndResults(dispatchEventWhenComplete = true) {\n this.br.removeSearchResults();\n this.removeResultPins();\n this.emptyMatches();\n this.setQuery('');\n this.teardownSearchNavigation();\n if (dispatchEventWhenComplete) {\n this.br.trigger('SearchResultsCleared');\n }\n }\n\n toggleSidebar() {\n this.br.trigger('ToggleSearchMenu');\n }\n\n renderSearchNavigation() {\n const selector = 'BRsearch-navigation';\n $('.BRnav').before(`\n <div class=\"${selector}\">\n <button class=\"toggle-sidebar\">\n <h4>\n <span class=\"icon icon-search\"></span> Results\n </h4>\n </button>\n <div class=\"pagination\">\n <button class=\"prev\" title=\"Previous result\"><span class=\"icon icon-chevron hflip\"></span></button>\n <span data-id=\"resultsCount\">${this.resultsPosition()}</span>\n <button class=\"next\" title=\"Next result\"><span class=\"icon icon-chevron\"></button>\n </div>\n <button class=\"clear\" title=\"Clear search results\">\n <span class=\"icon icon-close\"></span>\n </button>\n </div>\n `);\n this.dom.searchNavigation = $(`.${selector}`);\n }\n\n resultsPosition() {\n let positionMessage = `${this.matches.length} result${this.matches.length === 1 ? '' : 's'}`;\n if (~this.currentMatchIndex) {\n positionMessage = `${this.currentMatchIndex + 1} / ${this.matches.length}`;\n }\n return positionMessage;\n }\n\n bindSearchNavigationEvents() {\n if (!this.dom.searchNavigation) { return; }\n const namespace = 'searchNavigation';\n\n this.dom.searchNavigation\n .on(`click.${namespace}`, '.clear', this.clearSearchFieldAndResults.bind(this))\n .on(`click.${namespace}`, '.prev', this.showPrevResult.bind(this))\n .on(`click.${namespace}`, '.next', this.showNextResult.bind(this))\n .on(`click.${namespace}`, '.toggle-sidebar', this.toggleSidebar.bind(this))\n .on(`click.${namespace}`, false);\n }\n\n showPrevResult() {\n if (this.currentMatchIndex === 0) { return; }\n if (this.br.mode === this.br.constModeThumb) { this.br.switchMode(this.br.constMode1up); }\n if (!~this.currentMatchIndex) {\n this.currentMatchIndex = this.getClosestMatchIndex((start, end, comparator) => end[0] > comparator) + 1;\n }\n this.br.$('.BRnavline .BRsearch').eq(--this.currentMatchIndex).click();\n this.updateResultsPosition();\n this.updateSearchNavigationButtons();\n }\n\n showNextResult() {\n if (this.currentMatchIndex + 1 === this.matches.length) { return; }\n if (this.br.mode === this.br.constModeThumb) { this.br.switchMode(this.br.constMode1up); }\n if (!~this.currentMatchIndex) {\n this.currentMatchIndex = this.getClosestMatchIndex((start, end, comparator) => start[start.length - 1] > comparator) - 1;\n }\n this.br.$('.BRnavline .BRsearch').eq(++this.currentMatchIndex).click();\n this.updateResultsPosition();\n this.updateSearchNavigationButtons();\n }\n\n /**\n * Obtains closest match based on the logical comparison function passed in.\n * When the comparison function returns true, the starting (left) half of the\n * matches array is used in the binary split, else the ending (right) half is\n * used. A recursive call is made to perform the same split and comparison\n * on the winning half of the matches. This is traditionally known as binary\n * search (https://en.wikipedia.org/wiki/Binary_search_algorithm), and in\n * most cases (medium to large search result arrays) should outperform\n * traversing the array from start to finish. In the case of small arrays,\n * the speed difference is negligible.\n *\n * @param {function} comparisonFn\n * @return {number} matchIndex\n */\n getClosestMatchIndex(comparisonFn) {\n const matchPages = this.matches.map((m) => m.par[0].page);\n const currentPage = this.br.currentIndex() + 1;\n const closestTo = (pool, comparator) => {\n if (pool.length === 1) { return pool[0]; }\n const start = pool.slice(0, pool.length / 2);\n const end = pool.slice(pool.length / 2);\n return closestTo((comparisonFn(start, end, comparator) ? start : end), comparator);\n };\n\n const closestPage = closestTo(matchPages, currentPage);\n return this.matches.indexOf(this.matches.find((m) => m.par[0].page === closestPage));\n }\n\n updateResultsPosition() {\n if (!this.dom.searchNavigation) return;\n this.dom.searchNavigation.find('[data-id=resultsCount]').text(this.resultsPosition());\n }\n\n updateSearchNavigationButtons() {\n if (!this.dom.searchNavigation) return;\n this.dom.searchNavigation.find('.prev').attr('disabled', !this.currentMatchIndex);\n this.dom.searchNavigation.find('.next').attr('disabled', this.currentMatchIndex + 1 === this.matches.length);\n }\n\n teardownSearchNavigation() {\n if (!this.dom.searchNavigation) {\n this.dom.searchNavigation = $('.BRsearch-navigation');\n }\n if (!this.dom.searchNavigation.length) { return; }\n\n this.dom.searchNavigation.off('.searchNavigation').remove();\n this.dom.searchNavigation = null;\n this.br.resize();\n }\n\n setCurrentMatchIndex() {\n let matchingSearchResult;\n if (this.br.mode === this.br.constModeThumb) {\n this.currentMatchIndex = -1;\n return;\n }\n if (this.br.mode === this.br.constMode2up) {\n matchingSearchResult = this.find2upMatchingSearchResult();\n }\n else {\n matchingSearchResult = this.find1upMatchingSearchResult();\n }\n this.currentMatchIndex = this.matches.indexOf(matchingSearchResult);\n }\n\n find1upMatchingSearchResult() {\n return this.matches.find((m) => this.br.currentIndex() === m.par[0].page - 1);\n }\n\n find2upMatchingSearchResult() {\n return this.matches.find((m) => this.br._isIndexDisplayed(m.par[0].page - 1));\n }\n\n updateSearchNavigation() {\n if (!this.matches.length) { return; }\n\n this.setCurrentMatchIndex();\n this.updateResultsPosition();\n this.updateSearchNavigationButtons();\n }\n\n /**\n * @param {boolean} bool\n */\n togglePinsFor(bool) {\n const pinsVisibleState = bool ? 'visible' : 'hidden';\n this.br.refs.$BRfooter.find('.BRsearch').css({ visibility: pinsVisibleState });\n }\n\n buildToolbarSearch() {\n const toolbarSearch = document.createElement('span');\n toolbarSearch.classList.add('BRtoolbarSection', 'BRtoolbarSectionSearch');\n toolbarSearch.innerHTML = `\n <form class=\"BRbooksearch desktop\">\n <input type=\"search\" name=\"query\" class=\"BRsearchInput\" value=\"\" placeholder=\"Search inside\"/>\n <button type=\"submit\" class=\"BRsearchSubmit\">\n <img src=\"${this.br.imagesBaseURL}icon_search_button.svg\" />\n </button>\n </form>\n `;\n return toolbarSearch;\n }\n\n /**\n * @param {array} matches\n */\n renderPins(matches) {\n matches.forEach((match) => {\n const queryString = match.text;\n const pageIndex = this.br.leafNumToIndex(match.par[0].page);\n const pageNumber = this.br.getPageNum(pageIndex);\n const uiStringSearch = \"Search result\"; // i18n\n const uiStringPage = \"Page\"; // i18n\n\n const percentThrough = this.br.constructor.util.cssPercentage(pageIndex, this.br.getNumLeafs() - 1);\n\n const queryStringWithB = queryString.replace(this.matcher, '<b>$1</b>');\n\n let queryStringWithBTruncated = '';\n\n if (queryString.length > 100) {\n queryStringWithBTruncated = queryString\n .replace(/^(.{100}[^\\s]*).*/, \"$1\")\n .replace(this.matcher, '<b>$1</b>')\n + '...';\n }\n\n // draw marker\n $('<div>')\n .addClass('BRsearch')\n .css({\n left: percentThrough,\n })\n .attr('title', uiStringSearch)\n .append(`\n <div class=\"BRquery\">\n <div>${queryStringWithBTruncated || queryStringWithB}</div>\n <div>${uiStringPage} ${pageNumber}</div>\n </div>\n `)\n .data({ pageIndex })\n .appendTo(this.br.$('.BRnavline'))\n .on(\"mouseenter\", (event) => {\n // remove from other markers then turn on just for this\n // XXX should be done when nav slider moves\n const marker = event.currentTarget;\n const tooltip = marker.querySelector('.BRquery');\n const tooltipOffset = tooltip.getBoundingClientRect();\n const targetOffset = marker.getBoundingClientRect();\n const boxSizeAdjust = parseInt(getComputedStyle(tooltip).paddingLeft) * 2;\n if (tooltipOffset.x - boxSizeAdjust < 0) {\n tooltip.style.setProperty('transform', `translateX(-${targetOffset.left - boxSizeAdjust}px)`);\n }\n $('.BRsearch,.BRchapter').removeClass('front');\n $(event.target).addClass('front');\n })\n .on(\"mouseleave\", (event) => $(event.target).removeClass('front'))\n .on(\"click\", function (event) {\n // closures are nested and deep, using an arrow function breaks references.\n // Todo: update to arrow function & clean up closures\n // to remove `bind` dependency\n this.br._searchPluginGoToResult(+$(event.target).data('pageIndex'));\n }.bind(this));\n });\n }\n\n /**\n * @param {boolean} bool\n */\n toggleSearchPending(bool) {\n if (bool) {\n this.br.showProgressPopup(\"Search results will appear below...\", () => this.progressPopupClosed());\n }\n else {\n this.br.removeProgressPopup();\n }\n }\n\n /**\n * Primary callback when user cancels search popup\n */\n progressPopupClosed() {\n this.toggleSearchPending();\n this.cancelSearch();\n }\n\n renderErrorModal(textIsProcessing = false) {\n const errorDetails = `${!textIsProcessing ? 'The text may still be processing. ' : ''}Please try again.`;\n this.renderModalMessage(`\n Sorry, there was an error with your search.\n <br />\n ${errorDetails}\n `);\n this.delayModalRemovalFor(4000);\n }\n\n renderBookNotIndexedModal() {\n this.renderModalMessage(`\n <p>\n This book hasn't been indexed for searching yet.\n We've just started indexing it, so search should be available soon.\n <br />\n Please try again later. Thanks!\n </p>\n `);\n this.delayModalRemovalFor(5000);\n }\n\n renderResultsEmptyModal() {\n this.renderModalMessage('No matches were found.');\n this.delayModalRemovalFor(2000);\n }\n\n /**\n * @param {string} messageHTML The innerHTML string used to popupate the modal contents\n */\n renderModalMessage(messageHTML) {\n const modal = document.createElement('div');\n modal.classList.add('BRprogresspopup', 'search_modal');\n modal.innerHTML = messageHTML;\n document.querySelector(this.br.el).append(modal);\n }\n\n /**\n * @param {number} timeoutMS\n */\n delayModalRemovalFor(timeoutMS) {\n setTimeout(this.br.removeProgressPopup.bind(this.br), timeoutMS);\n }\n\n /**\n * @param {Event} e\n */\n submitHandler(e) {\n e.preventDefault();\n const query = e.target.querySelector('[name=\"query\"]').value;\n if (!query.length) { return false; }\n this.br.search(query);\n this.emptyMatches();\n this.toggleSearchPending(true);\n return false;\n }\n\n /**\n * @param {Event} e\n * @param {object} properties\n * @param {object} properties.results\n * @param {object} properties.options\n */\n handleSearchCallback(e, { results, options }) {\n this.matches = results.matches;\n this.setCurrentMatchIndex();\n this.teardownSearchNavigation();\n this.renderSearchNavigation();\n this.bindSearchNavigationEvents();\n this.renderPins(results.matches);\n this.toggleSearchPending(false);\n if (options.goToFirstResult) {\n $(document).one('BookReader:pageChanged', () => {\n this.br.resize();\n });\n } else {\n this.br.resize();\n }\n }\n\n /**\n * @param {Event} e\n */\n handleNavToggledCallback(e) {\n const is_visible = this.br.navigationIsVisible();\n this.togglePinsFor(is_visible);\n }\n\n handleSearchStarted() {\n this.emptyMatches();\n this.br.removeSearchHilites();\n this.removeResultPins();\n this.toggleSearchPending(true);\n this.teardownSearchNavigation();\n this.setQuery(this.br.searchTerm);\n }\n\n /**\n * Event listener for: `BookReader:SearchCallbackError`\n * @param {CustomEvent} event\n */\n handleSearchCallbackError(event = {}) {\n this.toggleSearchPending(false);\n const isIndexed = event?.detail?.props?.results?.indexed;\n this.renderErrorModal(isIndexed);\n }\n\n handleSearchCallbackBookNotIndexed() {\n this.toggleSearchPending(false);\n this.renderBookNotIndexedModal();\n }\n\n handleSearchCallbackEmpty() {\n this.toggleSearchPending(false);\n this.renderResultsEmptyModal();\n }\n\n bindEvents() {\n const namespace = 'BookReader:';\n\n window.addEventListener(`${namespace}SearchCallbackError`, this.handleSearchCallbackError.bind(this));\n $(document).on(`${namespace}SearchCallback`, this.handleSearchCallback.bind(this))\n .on(`${namespace}navToggled`, this.handleNavToggledCallback.bind(this))\n .on(`${namespace}SearchStarted`, this.handleSearchStarted.bind(this))\n .on(`${namespace}SearchCallbackBookNotIndexed`, this.handleSearchCallbackBookNotIndexed.bind(this))\n .on(`${namespace}SearchCallbackEmpty`, this.handleSearchCallbackEmpty.bind(this))\n .on(`${namespace}pageChanged`, this.updateSearchNavigation.bind(this));\n\n this.dom.toolbarSearch.querySelector('form').addEventListener('submit', this.submitHandler.bind(this));\n }\n}\n\nexport default SearchView;\n","var global = require('../internals/global');\nvar toString = require('../internals/to-string');\nvar trim = require('../internals/string-trim').trim;\nvar whitespaces = require('../internals/whitespaces');\n\nvar $parseFloat = global.parseFloat;\nvar FORCED = 1 / $parseFloat(whitespaces + '-0') !== -Infinity;\n\n// `parseFloat` method\n// https://tc39.es/ecma262/#sec-parsefloat-string\nmodule.exports = FORCED ? function parseFloat(string) {\n var trimmedString = trim(toString(string));\n var result = $parseFloat(trimmedString);\n return result === 0 && trimmedString.charAt(0) == '-' ? -0 : result;\n} : $parseFloat;\n","var $ = require('../internals/export');\nvar $entries = require('../internals/object-to-array').entries;\n\n// `Object.entries` method\n// https://tc39.es/ecma262/#sec-object.entries\n$({ target: 'Object', stat: true }, {\n entries: function entries(O) {\n return $entries(O);\n }\n});\n","var $ = require('../internals/export');\nvar parseFloatImplementation = require('../internals/number-parse-float');\n\n// `parseFloat` method\n// https://tc39.es/ecma262/#sec-parsefloat-string\n$({ global: true, forced: parseFloat != parseFloatImplementation }, {\n parseFloat: parseFloatImplementation\n});\n"],"names":["super_","SearchView","br","searchCancelledCallback","this","matcher","RegExp","matches","cacheDOMElements","bindEvents","cancelSearch","dom","toolbarSearch","buildToolbarSearch","query","$","val","remove","dispatchEventWhenComplete","removeSearchResults","removeResultPins","emptyMatches","setQuery","teardownSearchNavigation","trigger","selector","before","resultsPosition","searchNavigation","positionMessage","length","currentMatchIndex","namespace","on","clearSearchFieldAndResults","bind","showPrevResult","showNextResult","toggleSidebar","mode","constModeThumb","switchMode","constMode1up","getClosestMatchIndex","start","end","comparator","eq","click","updateResultsPosition","updateSearchNavigationButtons","comparisonFn","closestPage","closestTo","pool","slice","map","m","par","page","currentIndex","indexOf","find","text","attr","off","resize","matchingSearchResult","constMode2up","find2upMatchingSearchResult","find1upMatchingSearchResult","_isIndexDisplayed","setCurrentMatchIndex","bool","pinsVisibleState","refs","$BRfooter","css","visibility","document","createElement","classList","add","innerHTML","imagesBaseURL","forEach","match","queryString","pageIndex","leafNumToIndex","pageNumber","getPageNum","percentThrough","constructor","util","cssPercentage","getNumLeafs","queryStringWithB","replace","queryStringWithBTruncated","addClass","left","append","data","appendTo","event","marker","currentTarget","tooltip","querySelector","tooltipOffset","getBoundingClientRect","targetOffset","boxSizeAdjust","parseInt","getComputedStyle","paddingLeft","x","style","setProperty","removeClass","target","_searchPluginGoToResult","showProgressPopup","progressPopupClosed","removeProgressPopup","toggleSearchPending","textIsProcessing","errorDetails","renderModalMessage","delayModalRemovalFor","messageHTML","modal","el","timeoutMS","setTimeout","e","preventDefault","value","search","results","options","renderSearchNavigation","bindSearchNavigationEvents","renderPins","goToFirstResult","one","is_visible","navigationIsVisible","togglePinsFor","removeSearchHilites","searchTerm","isIndexed","detail","props","indexed","renderErrorModal","renderBookNotIndexedModal","renderResultsEmptyModal","window","addEventListener","handleSearchCallbackError","handleSearchCallback","handleNavToggledCallback","handleSearchStarted","handleSearchCallbackBookNotIndexed","handleSearchCallbackEmpty","updateSearchNavigation","submitHandler","jQuery","extend","BookReader","defaultOptions","server","bookId","subPrefix","bookPath","enableSearch","searchInsideUrl","initialSearchTerm","prototype","setup","call","searchResults","searchXHR","_cancelSearch","cancelSearchRequest","_searchBoxesByIndex","searchView","undefined","init","term","instance","suppressFragmentChange","buildToolbarElement","$el","after","_createPageContainer","index","pageContainer","renderBoxesInPageContainerLayer","$container","overrides","disablePopup","error","success","searchCancelled","eventNames","fragmentChange","serverPath","baseUrl","path","subPrefixWithSlash","lastIndexOf","substr","urlParams","item_id","doc","q","paramStr","param","url","processSearchResults","searchInsideResults","responseHasError","hasCustomError","hasCustomSuccess","BRSearchCallbackError","BRSearchCallback","ajax","dataType","cache","beforeSend","xhr","abort","updateSearchHilites","_models","book","_BRSearchCallbackError","basePayload","payload","Object","assign","boxesByIndex","boxes","box","push","pageIndexString","parseFloat","getPage","getActivePageContainerElementsForIndex","container","entries","getActivePageContainerElements","makeUnviewableAtEnd","isViewable","fetch","URLSearchParams","id","subprefix","leafNum","then","r","json","resp","makeViewable","jumpToIndex","searchHighlightVisible","visiblePages","twoPage","currentIndexL","currentIndexR","some","inArray","global","toString","trim","whitespaces","$parseFloat","FORCED","module","exports","string","trimmedString","result","charAt","$entries","stat","O","parseFloatImplementation","forced"],"sourceRoot":""}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
(self.webpackChunk_internetarchive_bookreader=self.webpackChunk_internetarchive_bookreader||[]).push([[423],{7967:function(t,e,n){"use strict";n(5666),n(6992),n(1539),n(3948),n(9826),n(9714),n(2222),n(1249),n(4916),n(3123),n(2707),n(9601),n(8674),n(2526),n(1817),n(2165),n(8783),n(7042),n(8309),n(1038),n(489),n(2419),n(4819),n(5003);var r=n(9860),o=n(7775);function i(t){return function(t){if(Array.isArray(t))return t}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return a(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?a(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function u(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:s;return null==t?void 0:t.replace(/\{\{([^}]*?)\}\}/g,(function(t,o){if(!o)return t;var a=i(o.split("|").map((function(t){return t.trim()}))),u=a[0],s=a.slice(1);if(!(u in n)&&!(u in e))return t;var l=u in n?n[u]:u in e?e[u]:null;return s.map((function(t){return r[t]})).reduce((function(t,e){return e(t)}),l&&l.toString())}))}n(5306),n(3210),n(5827);var s={urlencode:encodeURIComponent},l=n(3609);function c(t){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function f(t,e,n){return(f="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){var r=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=g(t)););return t}(t,e);if(r){var o=Object.getOwnPropertyDescriptor(r,e);return o.get?o.get.call(n):o.value}})(t,e,n||t)}function p(t,e){return(p=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function h(t,e){if(e&&("object"===c(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function g(t){return(g=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function d(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i=[],a=!0,u=!1;try{for(n=n.call(t);!(a=(r=n.next()).done)&&(i.push(r.value),!e||i.length!==e);a=!0);}catch(t){u=!0,o=t}finally{try{a||null==n.return||n.return()}finally{if(u)throw o}}return i}}(t,e)||function(t,e){if(t){if("string"==typeof t)return v(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?v(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function v(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function y(t,e,n,r,o,i,a){try{var u=t[i](a),s=u.value}catch(t){return void n(t)}u.done?e(s):Promise.resolve(s).then(r,o)}function m(t){return function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){y(i,r,o,a,u,"next",t)}function u(t){y(i,r,o,a,u,"throw",t)}a(void 0)}))}}function b(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function x(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function w(t,e,n){return e&&x(t.prototype,e),n&&x(t,n),t}var S=window.BookReader,P={enabled:!0,fullDjvuXmlUrl:null,singlePageDjvuXmlUrl:null},A=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;b(this,t),this.maxSize=e,this.entries=[]}return w(t,[{key:"add",value:function(t){this.entries.length>=this.maxSize&&this.entries.shift(),this.entries.push(t)}}]),t}(),j=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:P,n=arguments.length>1?arguments[1]:void 0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(0,o.vU)(),i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:(0,o.G6)();b(this,t),this.options=e,this.optionVariables=n,this.djvuPagesPromise=null,this.svgParagraphElement="text",this.svgWordElement="tspan",this.insertNewlines=r,this.pointerEventsOnParagraph=i,r&&(this.svgParagraphElement="g",this.svgWordElement="text"),this.pageTextCache=new A,this.maxWordRendered=2500}var e,n;return w(t,[{key:"init",value:function(){this.options.singlePageDjvuXmlUrl||(this.djvuPagesPromise=l.ajax({type:"GET",url:u(this.options.fullDjvuXmlUrl,this.optionVariables),dataType:"html",error:function(t){}}).then((function(t){try{var e=l.parseXML(t);return e&&l(e).find("OBJECT")}catch(t){return}})))}},{key:"getPageText",value:(n=m(regeneratorRuntime.mark((function t(e){var n,r,o,i,a;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.options.singlePageDjvuXmlUrl){t.next=19;break}if(!(n=this.pageTextCache.entries.find((function(t){return t.index==e})))){t.next=4;break}return t.abrupt("return",n.response);case 4:return t.next=6,l.ajax({type:"GET",url:u(this.options.singlePageDjvuXmlUrl,this.optionVariables,{pageIndex:e}),dataType:"html",error:function(t){}});case 6:return r=t.sent,t.prev=7,o=l.parseXML(r),i=o&&l(o).find("OBJECT")[0],this.pageTextCache.add({index:e,response:i}),t.abrupt("return",i);case 14:return t.prev=14,t.t0=t.catch(7),t.abrupt("return",void 0);case 17:t.next=24;break;case 19:return t.next=21,this.djvuPagesPromise;case 21:if(!(a=t.sent)){t.next=24;break}return t.abrupt("return",a[e]);case 24:case"end":return t.stop()}}),t,this,[[7,14]])}))),function(t){return n.apply(this,arguments)})},{key:"interceptCopy",value:function(t){t[0].addEventListener("copy",(function(t){var e=document.getSelection();t.clipboardData.setData("text/plain",e.toString()),t.preventDefault()}))}},{key:"defaultMode",value:function(t){var e=this;t.classList.remove("selectingSVG"),l(t).on("mousedown.textSelectPluginHandler",(function(n){l(n.target).is(".BRwordElement")&&(n.stopPropagation(),t.classList.add("selectingSVG"),l(t).one("mouseup.textSelectPluginHandler",(function(n){""!=window.getSelection().toString()?(n.stopPropagation(),l(t).off(".textSelectPluginHandler"),e.textSelectingMode(t)):t.classList.remove("selectingSVG")})))}))}},{key:"textSelectingMode",value:function(t){var e=this;l(t).on("mousedown.textSelectPluginHandler",(function(t){l(t.target).is(".BRwordElement")||""!=window.getSelection().toString()&&window.getSelection().removeAllRanges(),t.stopPropagation()})),l(t).on("mouseup.textSelectPluginHandler",(function(n){n.stopPropagation(),""==window.getSelection().toString()&&(l(t).off(".textSelectPluginHandler"),e.defaultMode(t))}))}},{key:"stopPageFlip",value:function(t){var e=this,n=t.find("svg.textSelectionSVG");n.length&&(n.each((function(t,n){return e.defaultMode(n)})),this.interceptCopy(t))}},{key:"createTextLayer",value:(e=m(regeneratorRuntime.mark((function t(e){var n,o,i,a,u,s=this;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=e.page.index,!(o=e.$container).find(".textSelectionSVG").length){t.next=5;break}return t.abrupt("return");case 5:return t.next=7,this.getPageText(n);case 7:if(i=t.sent){t.next=10;break}return t.abrupt("return");case 10:if(!((a=l(i).find("WORD").length)>this.maxWordRendered)){t.next=14;break}return console.log("Page ".concat(n," has too many words (").concat(a," > ").concat(this.maxWordRendered,"). Not rendering text layer.")),t.abrupt("return");case 14:u=(0,r.hy)(e.page,"textSelectionSVG"),o.append(u),l(i).find("PARAGRAPH").each((function(t,e){var n=l(e).find("WORD");if(n.length){var r=document.createElementNS("http://www.w3.org/2000/svg",s.svgParagraphElement);r.setAttribute("class","BRparagElement"),s.pointerEventsOnParagraph&&(r.style.pointerEvents="all");for(var o=[],i=0;i<n.length;i++){var a=n[i],c=d(l(a).attr("coords").split(",").map(parseFloat),4),f=c[0],p=c[1],h=c[2],g=p-c[3];o.push(g);var v=document.createElementNS("http://www.w3.org/2000/svg",s.svgWordElement);if(v.setAttribute("class","BRwordElement"),v.setAttribute("x",f.toString()),v.setAttribute("y",p.toString()),v.setAttribute("textLength",(h-f).toString()),v.setAttribute("lengthAdjust","spacingAndGlyphs"),v.textContent=a.textContent,r.appendChild(v),i<n.length-1){var y=n[i+1],m=d(l(y).attr("coords").split(",").map(parseFloat),4),b=m[0],x=(m[1],m[2],m[3],document.createElementNS("http://www.w3.org/2000/svg",s.svgWordElement));x.setAttribute("class","BRwordElement"),x.setAttribute("x",h.toString()),x.setAttribute("y",p.toString()),b-h>0&&x.setAttribute("textLength",(b-h).toString()),x.setAttribute("lengthAdjust","spacingAndGlyphs"),x.textContent=" ",r.appendChild(x)}i==n.length-1&&s.insertNewlines&&r.appendChild(document.createTextNode("\n"))}o.sort();var w=o[Math.floor(.85*o.length)];r.setAttribute("font-size",w.toString()),u.appendChild(r)}})),this.stopPageFlip(o);case 18:case"end":return t.stop()}}),t,this)}))),function(t){return e.apply(this,arguments)})}]),t}(),E=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&p(t,e)}(o,t);var e,n,r=(e=o,n=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}(),function(){var t,r=g(e);if(n){var o=g(this).constructor;t=Reflect.construct(r,arguments,o)}else t=r.apply(this,arguments);return h(this,t)});function o(){return b(this,o),r.apply(this,arguments)}return w(o,[{key:"init",value:function(){var t=Object.assign({},P,this.options.plugins.textSelection);t.enabled&&(this.textSelectionPlugin=new j(t,this.options.vars),this.options.plugins.textSelection=t,this.textSelectionPlugin.init()),f(g(o.prototype),"init",this).call(this)}},{key:"_createPageContainer",value:function(t){var e,n=f(g(o.prototype),"_createPageContainer",this).call(this,t);return this.mode!==this.constModeThumb&&n.page&&(null===(e=this.textSelectionPlugin)||void 0===e||e.createTextLayer(n)),n}}]),o}(S);window.BookReader=E},7775:function(t,e,n){"use strict";function r(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:navigator.userAgent,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:navigator.vendor;return/chrome/i.test(t)&&/google inc/i.test(e)}function o(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:navigator.userAgent;return/firefox/i.test(t)}function i(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:navigator.userAgent;return/safari/i.test(t)&&!/chrome|chromium/i.test(t)}n.d(e,{i7:function(){return r},vU:function(){return o},G6:function(){return i}})},6091:function(t,e,n){var r=n(7293),o=n(1361);t.exports=function(t){return r((function(){return!!o[t]()||"
"!="
"[t]()||o[t].name!==t}))}},3210:function(t,e,n){"use strict";var r=n(2109),o=n(3111).trim;r({target:"String",proto:!0,forced:n(6091)("trim")},{trim:function(){return o(this)}})}},function(t){t(t.s=7967)}]);
|
1
|
+
(self.webpackChunk_internetarchive_bookreader=self.webpackChunk_internetarchive_bookreader||[]).push([[423],{7967:function(t,e,n){"use strict";n(5666),n(6992),n(1539),n(3948),n(9826),n(9714),n(2222),n(1249),n(4916),n(3123),n(4678),n(2707),n(9601),n(8674),n(2526),n(1817),n(2165),n(8783),n(7042),n(8309),n(1038),n(489),n(2419),n(4819),n(5003);var r=n(9860),o=n(7775);function i(t){return function(t){if(Array.isArray(t))return t}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return a(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?a(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function u(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:s;return null==t?void 0:t.replace(/\{\{([^}]*?)\}\}/g,(function(t,o){if(!o)return t;var a=i(o.split("|").map((function(t){return t.trim()}))),u=a[0],s=a.slice(1);if(!(u in n)&&!(u in e))return t;var l=u in n?n[u]:u in e?e[u]:null;return s.map((function(t){return r[t]})).reduce((function(t,e){return e(t)}),l&&l.toString())}))}n(5306),n(3210),n(5827);var s={urlencode:encodeURIComponent},l=n(3609);function c(t){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function f(){return(f="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){var r=p(t,e);if(r){var o=Object.getOwnPropertyDescriptor(r,e);return o.get?o.get.call(arguments.length<3?t:n):o.value}}).apply(this,arguments)}function p(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=d(t)););return t}function h(t,e){return(h=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function g(t,e){if(e&&("object"===c(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function d(t){return(d=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function v(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i=[],a=!0,u=!1;try{for(n=n.call(t);!(a=(r=n.next()).done)&&(i.push(r.value),!e||i.length!==e);a=!0);}catch(t){u=!0,o=t}finally{try{a||null==n.return||n.return()}finally{if(u)throw o}}return i}}(t,e)||function(t,e){if(t){if("string"==typeof t)return y(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?y(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function m(t,e,n,r,o,i,a){try{var u=t[i](a),s=u.value}catch(t){return void n(t)}u.done?e(s):Promise.resolve(s).then(r,o)}function b(t){return function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){m(i,r,o,a,u,"next",t)}function u(t){m(i,r,o,a,u,"throw",t)}a(void 0)}))}}function x(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function w(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function S(t,e,n){return e&&w(t.prototype,e),n&&w(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}var P=window.BookReader,A={enabled:!0,fullDjvuXmlUrl:null,singlePageDjvuXmlUrl:null},j=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;x(this,t),this.maxSize=e,this.entries=[]}return S(t,[{key:"add",value:function(t){this.entries.length>=this.maxSize&&this.entries.shift(),this.entries.push(t)}}]),t}(),E=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:A,n=arguments.length>1?arguments[1]:void 0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(0,o.vU)(),i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:(0,o.G6)();x(this,t),this.options=e,this.optionVariables=n,this.djvuPagesPromise=null,this.svgParagraphElement="text",this.svgWordElement="tspan",this.insertNewlines=r,this.pointerEventsOnParagraph=i,r&&(this.svgParagraphElement="g",this.svgWordElement="text"),this.pageTextCache=new j,this.maxWordRendered=2500}var e,n;return S(t,[{key:"init",value:function(){this.options.singlePageDjvuXmlUrl||(this.djvuPagesPromise=l.ajax({type:"GET",url:u(this.options.fullDjvuXmlUrl,this.optionVariables),dataType:"html",error:function(t){}}).then((function(t){try{var e=l.parseXML(t);return e&&l(e).find("OBJECT")}catch(t){return}})))}},{key:"getPageText",value:(n=b(regeneratorRuntime.mark((function t(e){var n,r,o,i,a;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.options.singlePageDjvuXmlUrl){t.next=19;break}if(!(n=this.pageTextCache.entries.find((function(t){return t.index==e})))){t.next=4;break}return t.abrupt("return",n.response);case 4:return t.next=6,l.ajax({type:"GET",url:u(this.options.singlePageDjvuXmlUrl,this.optionVariables,{pageIndex:e}),dataType:"html",error:function(t){}});case 6:return r=t.sent,t.prev=7,o=l.parseXML(r),i=o&&l(o).find("OBJECT")[0],this.pageTextCache.add({index:e,response:i}),t.abrupt("return",i);case 14:return t.prev=14,t.t0=t.catch(7),t.abrupt("return",void 0);case 17:t.next=24;break;case 19:return t.next=21,this.djvuPagesPromise;case 21:if(!(a=t.sent)){t.next=24;break}return t.abrupt("return",a[e]);case 24:case"end":return t.stop()}}),t,this,[[7,14]])}))),function(t){return n.apply(this,arguments)})},{key:"interceptCopy",value:function(t){t[0].addEventListener("copy",(function(t){var e=document.getSelection();t.clipboardData.setData("text/plain",e.toString()),t.preventDefault()}))}},{key:"defaultMode",value:function(t){var e=this;t.classList.remove("selectingSVG"),l(t).on("mousedown.textSelectPluginHandler",(function(n){l(n.target).is(".BRwordElement")&&(n.stopPropagation(),t.classList.add("selectingSVG"),l(t).one("mouseup.textSelectPluginHandler",(function(n){""!=window.getSelection().toString()?(n.stopPropagation(),l(t).off(".textSelectPluginHandler"),e.textSelectingMode(t)):t.classList.remove("selectingSVG")})))}))}},{key:"textSelectingMode",value:function(t){var e=this;l(t).on("mousedown.textSelectPluginHandler",(function(t){l(t.target).is(".BRwordElement")||""!=window.getSelection().toString()&&window.getSelection().removeAllRanges(),t.stopPropagation()})),l(t).on("mouseup.textSelectPluginHandler",(function(n){n.stopPropagation(),""==window.getSelection().toString()&&(l(t).off(".textSelectPluginHandler"),e.defaultMode(t))}))}},{key:"stopPageFlip",value:function(t){var e=this,n=t.find("svg.textSelectionSVG");n.length&&(n.each((function(t,n){return e.defaultMode(n)})),this.interceptCopy(t))}},{key:"createTextLayer",value:(e=b(regeneratorRuntime.mark((function t(e){var n,o,i,a,u,s=this;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=e.page.index,!(o=e.$container).find(".textSelectionSVG").length){t.next=5;break}return t.abrupt("return");case 5:return t.next=7,this.getPageText(n);case 7:if(i=t.sent){t.next=10;break}return t.abrupt("return");case 10:if(!((a=l(i).find("WORD").length)>this.maxWordRendered)){t.next=14;break}return console.log("Page ".concat(n," has too many words (").concat(a," > ").concat(this.maxWordRendered,"). Not rendering text layer.")),t.abrupt("return");case 14:u=(0,r.hy)(e.page,"textSelectionSVG"),o.append(u),l(i).find("PARAGRAPH").each((function(t,e){var n=l(e).find("WORD");if(n.length){var r=document.createElementNS("http://www.w3.org/2000/svg",s.svgParagraphElement);r.setAttribute("class","BRparagElement"),s.pointerEventsOnParagraph&&(r.style.pointerEvents="all");for(var o=[],i=0;i<n.length;i++){var a=n[i],c=v(l(a).attr("coords").split(",").map(parseFloat),4),f=c[0],p=c[1],h=c[2],g=p-c[3];o.push(g);var d=document.createElementNS("http://www.w3.org/2000/svg",s.svgWordElement);if(d.setAttribute("class","BRwordElement"),d.setAttribute("x",f.toString()),d.setAttribute("y",p.toString()),d.setAttribute("textLength",(h-f).toString()),d.setAttribute("lengthAdjust","spacingAndGlyphs"),d.textContent=a.textContent,r.appendChild(d),i<n.length-1){var y=n[i+1],m=v(l(y).attr("coords").split(",").map(parseFloat),4),b=m[0],x=(m[1],m[2],m[3],document.createElementNS("http://www.w3.org/2000/svg",s.svgWordElement));x.setAttribute("class","BRwordElement"),x.setAttribute("x",h.toString()),x.setAttribute("y",p.toString()),b-h>0&&x.setAttribute("textLength",(b-h).toString()),x.setAttribute("lengthAdjust","spacingAndGlyphs"),x.textContent=" ",r.appendChild(x)}i==n.length-1&&s.insertNewlines&&r.appendChild(document.createTextNode("\n"))}o.sort();var w=o[Math.floor(.85*o.length)];r.setAttribute("font-size",w.toString()),u.appendChild(r)}})),this.stopPageFlip(o);case 18:case"end":return t.stop()}}),t,this)}))),function(t){return e.apply(this,arguments)})}]),t}(),R=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&h(t,e)}(o,t);var e,n,r=(e=o,n=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}(),function(){var t,r=d(e);if(n){var o=d(this).constructor;t=Reflect.construct(r,arguments,o)}else t=r.apply(this,arguments);return g(this,t)});function o(){return x(this,o),r.apply(this,arguments)}return S(o,[{key:"init",value:function(){var t=Object.assign({},A,this.options.plugins.textSelection);t.enabled&&(this.textSelectionPlugin=new E(t,this.options.vars),this.options.plugins.textSelection=t,this.textSelectionPlugin.init()),f(d(o.prototype),"init",this).call(this)}},{key:"_createPageContainer",value:function(t){var e,n=f(d(o.prototype),"_createPageContainer",this).call(this,t);return this.mode!==this.constModeThumb&&n.page&&(null===(e=this.textSelectionPlugin)||void 0===e||e.createTextLayer(n)),n}}]),o}(P);window.BookReader=R},7775:function(t,e,n){"use strict";function r(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:navigator.userAgent,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:navigator.vendor;return/chrome/i.test(t)&&/google inc/i.test(e)}function o(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:navigator.userAgent;return/firefox/i.test(t)}function i(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:navigator.userAgent;return/safari/i.test(t)&&!/chrome|chromium/i.test(t)}n.d(e,{i7:function(){return r},vU:function(){return o},G6:function(){return i}}),n(4916)},2814:function(t,e,n){var r=n(7854),o=n(1340),i=n(3111).trim,a=n(1361),u=r.parseFloat,s=1/u(a+"-0")!=-1/0;t.exports=s?function(t){var e=i(o(t)),n=u(e);return 0===n&&"-"==e.charAt(0)?-0:n}:u},6091:function(t,e,n){var r=n(7293),o=n(1361);t.exports=function(t){return r((function(){return!!o[t]()||"
"!="
"[t]()||o[t].name!==t}))}},4678:function(t,e,n){var r=n(2109),o=n(2814);r({global:!0,forced:parseFloat!=o},{parseFloat:o})},3210:function(t,e,n){"use strict";var r=n(2109),o=n(3111).trim;r({target:"String",proto:!0,forced:n(6091)("trim")},{trim:function(){return o(this)}})}},function(t){t(t.s=7967)}]);
|
2
2
|
//# sourceMappingURL=plugin.text_selection.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"plugins/plugin.text_selection.js","mappings":"wlCAYO,SAASA,EAA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IAAItG,EAAI,EAAQ,MACZwG,EAAQ,aAKZxG,EAAE,CAAEkC,OAAQ,SAAUuE,OAAO,EAAMC,OAJN,EAAQ,KAIMC,CAAuB,SAAW,CAC3EjJ,KAAM,WACJ,OAAO8I,EAAM3H,W","sources":["webpack://@internetarchive/bookreader/./src/util/strings.js","webpack://@internetarchive/bookreader/./src/plugins/plugin.text_selection.js","webpack://@internetarchive/bookreader/./src/util/browserSniffing.js","webpack://@internetarchive/bookreader/./node_modules/core-js/internals/string-trim-forced.js","webpack://@internetarchive/bookreader/./node_modules/core-js/modules/es.string.trim.js"],"sourcesContent":["/**\n * @typedef {String} StringWithVars\n * A template string with {{foo}} style variables\n * Also supports filters, like {{bookPath|urlencode}} (See APPLY_FILTERS for the\n * supported list of filters)\n **/\n\n/**\n * @param {StringWithVars|String} template\n * @param { {[varName: string]: { toString: () => string} } } vars\n * @param { {[varName: string]: { toString: () => string} } } [overrides]\n */\nexport function applyVariables(template, vars, overrides = {}, possibleFilters = APPLY_FILTERS) {\n return template?.replace(/\\{\\{([^}]*?)\\}\\}/g, ($0, $1) => {\n if (!$1) return $0;\n /** @type {string} */\n const expression = $1;\n const [varName, ...filterNames] = expression.split('|').map(x => x.trim());\n const defined = varName in overrides || varName in vars;\n\n // If it's not defined, don't expand it at all\n if (!defined) return $0;\n\n const value = varName in overrides ? overrides[varName]\n : varName in vars ? vars[varName] : null;\n const filters = filterNames.map(n => possibleFilters[n]);\n return filters.reduce((acc, cur) => cur(acc), value && value.toString());\n });\n}\n\n/** @type { {[filterName: String]:( string => string)} } */\nexport const APPLY_FILTERS = {\n urlencode: encodeURIComponent,\n};\n","//@ts-check\nimport { createSVGPageLayer } from '../BookReader/PageContainer.js';\nimport { isFirefox, isSafari } from '../util/browserSniffing.js';\nimport { applyVariables } from '../util/strings.js';\n/** @typedef {import('../util/strings.js').StringWithVars} StringWithVars */\n/** @typedef {import('../BookReader/PageContainer.js').PageContainer} PageContainer */\n\nconst BookReader = /** @type {typeof import('../BookReader').default} */(window.BookReader);\n\nexport const DEFAULT_OPTIONS = {\n enabled: true,\n /** @type {StringWithVars} The URL to fetch the entire DJVU xml. Supports options.vars */\n fullDjvuXmlUrl: null,\n /** @type {StringWithVars} The URL to fetch a single page of the DJVU xml. Supports options.vars. Also has {{pageIndex}} */\n singlePageDjvuXmlUrl: null,\n};\n/** @typedef {typeof DEFAULT_OPTIONS} TextSelectionPluginOptions */\n\n/**\n * @template T\n */\nexport class Cache {\n constructor(maxSize = 10) {\n this.maxSize = maxSize;\n /** @type {T[]} */\n this.entries = [];\n }\n\n /**\n * @param {T} entry\n */\n add(entry) {\n if (this.entries.length >= this.maxSize) {\n this.entries.shift();\n }\n this.entries.push(entry);\n }\n}\n\nexport class TextSelectionPlugin {\n\n constructor(options = DEFAULT_OPTIONS, optionVariables, avoidTspans = isFirefox(), pointerEventsOnParagraph = isSafari()) {\n this.options = options;\n this.optionVariables = optionVariables;\n /**@type {PromiseLike<JQuery<HTMLElement>|undefined>} */\n this.djvuPagesPromise = null;\n // Using text elements instead of tspans for words because Firefox does not allow svg tspan stretch.\n // Tspans are necessary on Chrome because they prevent newline character after every word when copying\n this.svgParagraphElement = \"text\";\n this.svgWordElement = \"tspan\";\n this.insertNewlines = avoidTspans;\n // Safari has a bug where `pointer-events` doesn't work on `<tspans>`. So\n // there we will set `pointer-events: all` on the paragraph element. We don't\n // do this everywhere, because it's a worse experience. Thanks Safari :/\n this.pointerEventsOnParagraph = pointerEventsOnParagraph;\n if (avoidTspans) {\n this.svgParagraphElement = \"g\";\n this.svgWordElement = \"text\";\n }\n\n /** @type {Cache<{index: number, response: any}>} */\n this.pageTextCache = new Cache();\n\n /**\n * Sometimes there are too many words on a page, and the browser becomes near\n * unusable. For now don't render text layer for pages with too many words.\n */\n this.maxWordRendered = 2500;\n }\n\n init() {\n // Only fetch the full djvu xml if the single page url isn't there\n if (this.options.singlePageDjvuXmlUrl) return;\n this.djvuPagesPromise = $.ajax({\n type: \"GET\",\n url: applyVariables(this.options.fullDjvuXmlUrl, this.optionVariables),\n dataType: \"html\",\n error: (e) => undefined\n }).then((res) => {\n try {\n const xmlMap = $.parseXML(res);\n return xmlMap && $(xmlMap).find(\"OBJECT\");\n } catch (e) {\n return undefined;\n }\n });\n }\n\n /**\n * @param {number} index\n * @returns {Promise<HTMLElement|undefined>}\n */\n async getPageText(index) {\n if (this.options.singlePageDjvuXmlUrl) {\n const cachedEntry = this.pageTextCache.entries.find(x => x.index == index);\n if (cachedEntry) {\n return cachedEntry.response;\n }\n const res = await $.ajax({\n type: \"GET\",\n url: applyVariables(this.options.singlePageDjvuXmlUrl, this.optionVariables, { pageIndex: index }),\n dataType: \"html\",\n error: (e) => undefined,\n });\n try {\n const xmlDoc = $.parseXML(res);\n const result = xmlDoc && $(xmlDoc).find(\"OBJECT\")[0];\n this.pageTextCache.add({ index, response: result });\n return result;\n } catch (e) {\n return undefined;\n }\n } else {\n const XMLpagesArr = await this.djvuPagesPromise;\n if (XMLpagesArr) return XMLpagesArr[index];\n }\n }\n\n /**\n * Intercept copied text to remove any styling applied to it\n * @param {JQuery} $container\n */\n interceptCopy($container) {\n $container[0].addEventListener('copy', (event) => {\n const selection = document.getSelection();\n event.clipboardData.setData('text/plain', selection.toString());\n event.preventDefault();\n });\n }\n\n /**\n * Applies mouse events when in default mode\n * @param {SVGElement} svg\n */\n defaultMode(svg) {\n svg.classList.remove(\"selectingSVG\");\n $(svg).on(\"mousedown.textSelectPluginHandler\", (event) => {\n if (!$(event.target).is(\".BRwordElement\")) return;\n event.stopPropagation();\n svg.classList.add(\"selectingSVG\");\n $(svg).one(\"mouseup.textSelectPluginHandler\", (event) => {\n if (window.getSelection().toString() != \"\") {\n event.stopPropagation();\n $(svg).off(\".textSelectPluginHandler\");\n this.textSelectingMode(svg);\n }\n else svg.classList.remove(\"selectingSVG\");\n });\n });\n }\n\n /**\n * Applies mouse events when in textSelecting mode\n * @param {SVGElement} svg\n */\n textSelectingMode(svg) {\n $(svg).on('mousedown.textSelectPluginHandler', (event) => {\n if (!$(event.target).is(\".BRwordElement\")) {\n if (window.getSelection().toString() != \"\") window.getSelection().removeAllRanges();\n }\n event.stopPropagation();\n });\n $(svg).on('mouseup.textSelectPluginHandler', (event) => {\n event.stopPropagation();\n if (window.getSelection().toString() == \"\") {\n $(svg).off(\".textSelectPluginHandler\");\n this.defaultMode(svg); }\n });\n }\n\n /**\n * Initializes text selection modes if there is an svg on the page\n * @param {JQuery} $container\n */\n stopPageFlip($container) {\n /** @type {JQuery<SVGElement>} */\n const $svg = $container.find('svg.textSelectionSVG');\n if (!$svg.length) return;\n $svg.each((i, s) => this.defaultMode(s));\n this.interceptCopy($container);\n }\n\n /**\n * @param {PageContainer} pageContainer\n */\n async createTextLayer(pageContainer) {\n const pageIndex = pageContainer.page.index;\n const $container = pageContainer.$container;\n const $svgLayers = $container.find('.textSelectionSVG');\n if ($svgLayers.length) return;\n const XMLpage = await this.getPageText(pageIndex);\n if (!XMLpage) return;\n\n const totalWords = $(XMLpage).find(\"WORD\").length;\n if (totalWords > this.maxWordRendered) {\n console.log(`Page ${pageIndex} has too many words (${totalWords} > ${this.maxWordRendered}). Not rendering text layer.`);\n return;\n }\n\n const svg = createSVGPageLayer(pageContainer.page, 'textSelectionSVG');\n $container.append(svg);\n\n $(XMLpage).find(\"PARAGRAPH\").each((i, paragraph) => {\n // Adding text element for each paragraph in the page\n const words = $(paragraph).find(\"WORD\");\n if (!words.length) return;\n const paragSvg = document.createElementNS(\"http://www.w3.org/2000/svg\", this.svgParagraphElement);\n paragSvg.setAttribute(\"class\", \"BRparagElement\");\n if (this.pointerEventsOnParagraph) {\n paragSvg.style.pointerEvents = \"all\";\n }\n\n const wordHeightArr = [];\n\n for (let i = 0; i < words.length; i++) {\n // Adding tspan for each word in paragraph\n const currWord = words[i];\n // eslint-disable-next-line no-unused-vars\n const [left, bottom, right, top] = $(currWord).attr(\"coords\").split(',').map(parseFloat);\n const wordHeight = bottom - top;\n wordHeightArr.push(wordHeight);\n\n const wordTspan = document.createElementNS(\"http://www.w3.org/2000/svg\", this.svgWordElement);\n wordTspan.setAttribute(\"class\", \"BRwordElement\");\n wordTspan.setAttribute(\"x\", left.toString());\n wordTspan.setAttribute(\"y\", bottom.toString());\n wordTspan.setAttribute(\"textLength\", (right - left).toString());\n wordTspan.setAttribute(\"lengthAdjust\", \"spacingAndGlyphs\");\n wordTspan.textContent = currWord.textContent;\n paragSvg.appendChild(wordTspan);\n\n // Adding spaces after words except at the end of the paragraph\n // TODO: assumes left-to-right text\n if (i < words.length - 1) {\n const nextWord = words[i + 1];\n // eslint-disable-next-line no-unused-vars\n const [leftNext, bottomNext, rightNext, topNext] = $(nextWord).attr(\"coords\").split(',').map(parseFloat);\n const spaceTspan = document.createElementNS(\"http://www.w3.org/2000/svg\", this.svgWordElement);\n spaceTspan.setAttribute(\"class\", \"BRwordElement\");\n spaceTspan.setAttribute(\"x\", right.toString());\n spaceTspan.setAttribute(\"y\", bottom.toString());\n if ((leftNext - right) > 0) spaceTspan.setAttribute(\"textLength\", (leftNext - right).toString());\n spaceTspan.setAttribute(\"lengthAdjust\", \"spacingAndGlyphs\");\n spaceTspan.textContent = \" \";\n paragSvg.appendChild(spaceTspan);\n }\n\n // Adds newline at the end of paragraph on Firefox\n if ((i == words.length - 1 && (this.insertNewlines))) {\n paragSvg.appendChild(document.createTextNode(\"\\n\"));\n }\n }\n\n wordHeightArr.sort();\n const paragWordHeight = wordHeightArr[Math.floor(wordHeightArr.length * 0.85)];\n paragSvg.setAttribute(\"font-size\", paragWordHeight.toString());\n svg.appendChild(paragSvg);\n });\n this.stopPageFlip($container);\n }\n}\n\nexport class BookreaderWithTextSelection extends BookReader {\n init() {\n const options = Object.assign({}, DEFAULT_OPTIONS, this.options.plugins.textSelection);\n if (options.enabled) {\n this.textSelectionPlugin = new TextSelectionPlugin(options, this.options.vars);\n // Write this back; this way the plugin is the source of truth, and BR just\n // contains a reference to it.\n this.options.plugins.textSelection = options;\n this.textSelectionPlugin.init();\n }\n super.init();\n }\n\n /**\n * @param {number} index\n */\n _createPageContainer(index) {\n const pageContainer = super._createPageContainer(index);\n // Disable if thumb mode; it's too janky\n // .page can be null for \"pre-cover\" region\n if (this.mode !== this.constModeThumb && pageContainer.page) {\n this.textSelectionPlugin?.createTextLayer(pageContainer);\n }\n return pageContainer;\n }\n}\nwindow.BookReader = BookreaderWithTextSelection;\nexport default BookreaderWithTextSelection;\n","\n/**\n * Checks whether the current browser is a Chrome/Chromium browser\n * Code from https://stackoverflow.com/a/4565120/2317712\n * @param {string} [userAgent]\n * @param {string} [vendor]\n * @return {boolean}\n */\nexport function isChrome(userAgent = navigator.userAgent, vendor = navigator.vendor) {\n return /chrome/i.test(userAgent) && /google inc/i.test(vendor);\n}\n\n/**\n * Checks whether the current browser is firefox\n * @param {string} [userAgent]\n * @return {boolean}\n */\nexport function isFirefox(userAgent = navigator.userAgent) {\n return /firefox/i.test(userAgent);\n}\n\n/**\n * Checks whether the current browser is safari\n * https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent#Browser_Name\n * @param {string} [userAgent]\n * @return {boolean}\n */\nexport function isSafari(userAgent = navigator.userAgent) {\n return /safari/i.test(userAgent) && !/chrome|chromium/i.test(userAgent);\n}\n","var fails = require('../internals/fails');\nvar whitespaces = require('../internals/whitespaces');\n\nvar non = '\\u200B\\u0085\\u180E';\n\n// check that a method works with the correct list\n// of whitespaces and has a correct name\nmodule.exports = function (METHOD_NAME) {\n return fails(function () {\n return !!whitespaces[METHOD_NAME]() || non[METHOD_NAME]() != non || whitespaces[METHOD_NAME].name !== METHOD_NAME;\n });\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar $trim = require('../internals/string-trim').trim;\nvar forcedStringTrimMethod = require('../internals/string-trim-forced');\n\n// `String.prototype.trim` method\n// https://tc39.es/ecma262/#sec-string.prototype.trim\n$({ target: 'String', proto: true, forced: forcedStringTrimMethod('trim') }, {\n trim: function trim() {\n return $trim(this);\n }\n});\n"],"names":["applyVariables","template","vars","overrides","possibleFilters","APPLY_FILTERS","replace","$0","$1","split","map","x","trim","varName","filterNames","value","n","reduce","acc","cur","toString","urlencode","encodeURIComponent","BookReader","window","DEFAULT_OPTIONS","enabled","fullDjvuXmlUrl","singlePageDjvuXmlUrl","Cache","maxSize","this","entries","entry","length","shift","push","TextSelectionPlugin","options","optionVariables","avoidTspans","isFirefox","pointerEventsOnParagraph","isSafari","djvuPagesPromise","svgParagraphElement","svgWordElement","insertNewlines","pageTextCache","maxWordRendered","$","ajax","type","url","dataType","error","e","then","res","xmlMap","parseXML","find","index","cachedEntry","response","pageIndex","xmlDoc","result","add","undefined","XMLpagesArr","$container","addEventListener","event","selection","document","getSelection","clipboardData","setData","preventDefault","svg","classList","remove","on","target","is","stopPropagation","one","off","textSelectingMode","removeAllRanges","defaultMode","$svg","each","i","s","interceptCopy","pageContainer","page","getPageText","XMLpage","totalWords","console","log","createSVGPageLayer","append","paragraph","words","paragSvg","createElementNS","setAttribute","style","pointerEvents","wordHeightArr","currWord","attr","parseFloat","left","bottom","right","wordHeight","wordTspan","textContent","appendChild","nextWord","leftNext","spaceTspan","createTextNode","sort","paragWordHeight","Math","floor","stopPageFlip","BookreaderWithTextSelection","Object","assign","plugins","textSelection","textSelectionPlugin","init","mode","constModeThumb","createTextLayer","isChrome","userAgent","navigator","vendor","test","fails","whitespaces","module","exports","METHOD_NAME","name","$trim","proto","forced","forcedStringTrimMethod"],"sourceRoot":""}
|
1
|
+
{"version":3,"file":"plugins/plugin.text_selection.js","mappings":"gmCAYO,SAASA,EAAeC,EAAUC,GAAuD,IAAjDC,EAAiD,uDAArC,GAAIC,EAAiC,uDAAfC,EAC/E,OAAOJ,MAAAA,OAAP,EAAOA,EAAUK,QAAQ,qBAAqB,SAACC,EAAIC,GACjD,IAAKA,EAAI,OAAOD,EAEhB,IACA,IADmBC,EAC0BC,MAAM,KAAKC,KAAI,SAAAC,GAAC,OAAIA,EAAEC,WAA5DC,EAAP,KAAmBC,EAAnB,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AAYS,MANf,aAMqCA,MAAyBT,EAAYS,GAAaC,OAASD,O,qBCT1G,IAAI5G,EAAI,EAAQ,MACZ8G,EAA2B,EAAQ,MAIvC9G,EAAE,CAAEkG,QAAQ,EAAMa,OAAQ7C,YAAc4C,GAA4B,CAClE5C,WAAY4C,K,kCCLd,IAAI9G,EAAI,EAAQ,MACZgH,EAAQ,aAKZhH,EAAE,CAAEkC,OAAQ,SAAU+E,OAAO,EAAMF,OAJN,EAAQ,KAIMG,CAAuB,SAAW,CAC3ExJ,KAAM,WACJ,OAAOsJ,EAAMnI,W","sources":["webpack://@internetarchive/bookreader/./src/util/strings.js","webpack://@internetarchive/bookreader/./src/plugins/plugin.text_selection.js","webpack://@internetarchive/bookreader/./src/util/browserSniffing.js","webpack://@internetarchive/bookreader/./node_modules/core-js/internals/number-parse-float.js","webpack://@internetarchive/bookreader/./node_modules/core-js/internals/string-trim-forced.js","webpack://@internetarchive/bookreader/./node_modules/core-js/modules/es.parse-float.js","webpack://@internetarchive/bookreader/./node_modules/core-js/modules/es.string.trim.js"],"sourcesContent":["/**\n * @typedef {String} StringWithVars\n * A template string with {{foo}} style variables\n * Also supports filters, like {{bookPath|urlencode}} (See APPLY_FILTERS for the\n * supported list of filters)\n **/\n\n/**\n * @param {StringWithVars|String} template\n * @param { {[varName: string]: { toString: () => string} } } vars\n * @param { {[varName: string]: { toString: () => string} } } [overrides]\n */\nexport function applyVariables(template, vars, overrides = {}, possibleFilters = APPLY_FILTERS) {\n return template?.replace(/\\{\\{([^}]*?)\\}\\}/g, ($0, $1) => {\n if (!$1) return $0;\n /** @type {string} */\n const expression = $1;\n const [varName, ...filterNames] = expression.split('|').map(x => x.trim());\n const defined = varName in overrides || varName in vars;\n\n // If it's not defined, don't expand it at all\n if (!defined) return $0;\n\n const value = varName in overrides ? overrides[varName]\n : varName in vars ? vars[varName] : null;\n const filters = filterNames.map(n => possibleFilters[n]);\n return filters.reduce((acc, cur) => cur(acc), value && value.toString());\n });\n}\n\n/** @type { {[filterName: String]:( string => string)} } */\nexport const APPLY_FILTERS = {\n urlencode: encodeURIComponent,\n};\n","//@ts-check\nimport { createSVGPageLayer } from '../BookReader/PageContainer.js';\nimport { isFirefox, isSafari } from '../util/browserSniffing.js';\nimport { applyVariables } from '../util/strings.js';\n/** @typedef {import('../util/strings.js').StringWithVars} StringWithVars */\n/** @typedef {import('../BookReader/PageContainer.js').PageContainer} PageContainer */\n\nconst BookReader = /** @type {typeof import('../BookReader').default} */(window.BookReader);\n\nexport const DEFAULT_OPTIONS = {\n enabled: true,\n /** @type {StringWithVars} The URL to fetch the entire DJVU xml. Supports options.vars */\n fullDjvuXmlUrl: null,\n /** @type {StringWithVars} The URL to fetch a single page of the DJVU xml. Supports options.vars. Also has {{pageIndex}} */\n singlePageDjvuXmlUrl: null,\n};\n/** @typedef {typeof DEFAULT_OPTIONS} TextSelectionPluginOptions */\n\n/**\n * @template T\n */\nexport class Cache {\n constructor(maxSize = 10) {\n this.maxSize = maxSize;\n /** @type {T[]} */\n this.entries = [];\n }\n\n /**\n * @param {T} entry\n */\n add(entry) {\n if (this.entries.length >= this.maxSize) {\n this.entries.shift();\n }\n this.entries.push(entry);\n }\n}\n\nexport class TextSelectionPlugin {\n\n constructor(options = DEFAULT_OPTIONS, optionVariables, avoidTspans = isFirefox(), pointerEventsOnParagraph = isSafari()) {\n this.options = options;\n this.optionVariables = optionVariables;\n /**@type {PromiseLike<JQuery<HTMLElement>|undefined>} */\n this.djvuPagesPromise = null;\n // Using text elements instead of tspans for words because Firefox does not allow svg tspan stretch.\n // Tspans are necessary on Chrome because they prevent newline character after every word when copying\n this.svgParagraphElement = \"text\";\n this.svgWordElement = \"tspan\";\n this.insertNewlines = avoidTspans;\n // Safari has a bug where `pointer-events` doesn't work on `<tspans>`. So\n // there we will set `pointer-events: all` on the paragraph element. We don't\n // do this everywhere, because it's a worse experience. Thanks Safari :/\n this.pointerEventsOnParagraph = pointerEventsOnParagraph;\n if (avoidTspans) {\n this.svgParagraphElement = \"g\";\n this.svgWordElement = \"text\";\n }\n\n /** @type {Cache<{index: number, response: any}>} */\n this.pageTextCache = new Cache();\n\n /**\n * Sometimes there are too many words on a page, and the browser becomes near\n * unusable. For now don't render text layer for pages with too many words.\n */\n this.maxWordRendered = 2500;\n }\n\n init() {\n // Only fetch the full djvu xml if the single page url isn't there\n if (this.options.singlePageDjvuXmlUrl) return;\n this.djvuPagesPromise = $.ajax({\n type: \"GET\",\n url: applyVariables(this.options.fullDjvuXmlUrl, this.optionVariables),\n dataType: \"html\",\n error: (e) => undefined\n }).then((res) => {\n try {\n const xmlMap = $.parseXML(res);\n return xmlMap && $(xmlMap).find(\"OBJECT\");\n } catch (e) {\n return undefined;\n }\n });\n }\n\n /**\n * @param {number} index\n * @returns {Promise<HTMLElement|undefined>}\n */\n async getPageText(index) {\n if (this.options.singlePageDjvuXmlUrl) {\n const cachedEntry = this.pageTextCache.entries.find(x => x.index == index);\n if (cachedEntry) {\n return cachedEntry.response;\n }\n const res = await $.ajax({\n type: \"GET\",\n url: applyVariables(this.options.singlePageDjvuXmlUrl, this.optionVariables, { pageIndex: index }),\n dataType: \"html\",\n error: (e) => undefined,\n });\n try {\n const xmlDoc = $.parseXML(res);\n const result = xmlDoc && $(xmlDoc).find(\"OBJECT\")[0];\n this.pageTextCache.add({ index, response: result });\n return result;\n } catch (e) {\n return undefined;\n }\n } else {\n const XMLpagesArr = await this.djvuPagesPromise;\n if (XMLpagesArr) return XMLpagesArr[index];\n }\n }\n\n /**\n * Intercept copied text to remove any styling applied to it\n * @param {JQuery} $container\n */\n interceptCopy($container) {\n $container[0].addEventListener('copy', (event) => {\n const selection = document.getSelection();\n event.clipboardData.setData('text/plain', selection.toString());\n event.preventDefault();\n });\n }\n\n /**\n * Applies mouse events when in default mode\n * @param {SVGElement} svg\n */\n defaultMode(svg) {\n svg.classList.remove(\"selectingSVG\");\n $(svg).on(\"mousedown.textSelectPluginHandler\", (event) => {\n if (!$(event.target).is(\".BRwordElement\")) return;\n event.stopPropagation();\n svg.classList.add(\"selectingSVG\");\n $(svg).one(\"mouseup.textSelectPluginHandler\", (event) => {\n if (window.getSelection().toString() != \"\") {\n event.stopPropagation();\n $(svg).off(\".textSelectPluginHandler\");\n this.textSelectingMode(svg);\n }\n else svg.classList.remove(\"selectingSVG\");\n });\n });\n }\n\n /**\n * Applies mouse events when in textSelecting mode\n * @param {SVGElement} svg\n */\n textSelectingMode(svg) {\n $(svg).on('mousedown.textSelectPluginHandler', (event) => {\n if (!$(event.target).is(\".BRwordElement\")) {\n if (window.getSelection().toString() != \"\") window.getSelection().removeAllRanges();\n }\n event.stopPropagation();\n });\n $(svg).on('mouseup.textSelectPluginHandler', (event) => {\n event.stopPropagation();\n if (window.getSelection().toString() == \"\") {\n $(svg).off(\".textSelectPluginHandler\");\n this.defaultMode(svg); }\n });\n }\n\n /**\n * Initializes text selection modes if there is an svg on the page\n * @param {JQuery} $container\n */\n stopPageFlip($container) {\n /** @type {JQuery<SVGElement>} */\n const $svg = $container.find('svg.textSelectionSVG');\n if (!$svg.length) return;\n $svg.each((i, s) => this.defaultMode(s));\n this.interceptCopy($container);\n }\n\n /**\n * @param {PageContainer} pageContainer\n */\n async createTextLayer(pageContainer) {\n const pageIndex = pageContainer.page.index;\n const $container = pageContainer.$container;\n const $svgLayers = $container.find('.textSelectionSVG');\n if ($svgLayers.length) return;\n const XMLpage = await this.getPageText(pageIndex);\n if (!XMLpage) return;\n\n const totalWords = $(XMLpage).find(\"WORD\").length;\n if (totalWords > this.maxWordRendered) {\n console.log(`Page ${pageIndex} has too many words (${totalWords} > ${this.maxWordRendered}). Not rendering text layer.`);\n return;\n }\n\n const svg = createSVGPageLayer(pageContainer.page, 'textSelectionSVG');\n $container.append(svg);\n\n $(XMLpage).find(\"PARAGRAPH\").each((i, paragraph) => {\n // Adding text element for each paragraph in the page\n const words = $(paragraph).find(\"WORD\");\n if (!words.length) return;\n const paragSvg = document.createElementNS(\"http://www.w3.org/2000/svg\", this.svgParagraphElement);\n paragSvg.setAttribute(\"class\", \"BRparagElement\");\n if (this.pointerEventsOnParagraph) {\n paragSvg.style.pointerEvents = \"all\";\n }\n\n const wordHeightArr = [];\n\n for (let i = 0; i < words.length; i++) {\n // Adding tspan for each word in paragraph\n const currWord = words[i];\n // eslint-disable-next-line no-unused-vars\n const [left, bottom, right, top] = $(currWord).attr(\"coords\").split(',').map(parseFloat);\n const wordHeight = bottom - top;\n wordHeightArr.push(wordHeight);\n\n const wordTspan = document.createElementNS(\"http://www.w3.org/2000/svg\", this.svgWordElement);\n wordTspan.setAttribute(\"class\", \"BRwordElement\");\n wordTspan.setAttribute(\"x\", left.toString());\n wordTspan.setAttribute(\"y\", bottom.toString());\n wordTspan.setAttribute(\"textLength\", (right - left).toString());\n wordTspan.setAttribute(\"lengthAdjust\", \"spacingAndGlyphs\");\n wordTspan.textContent = currWord.textContent;\n paragSvg.appendChild(wordTspan);\n\n // Adding spaces after words except at the end of the paragraph\n // TODO: assumes left-to-right text\n if (i < words.length - 1) {\n const nextWord = words[i + 1];\n // eslint-disable-next-line no-unused-vars\n const [leftNext, bottomNext, rightNext, topNext] = $(nextWord).attr(\"coords\").split(',').map(parseFloat);\n const spaceTspan = document.createElementNS(\"http://www.w3.org/2000/svg\", this.svgWordElement);\n spaceTspan.setAttribute(\"class\", \"BRwordElement\");\n spaceTspan.setAttribute(\"x\", right.toString());\n spaceTspan.setAttribute(\"y\", bottom.toString());\n if ((leftNext - right) > 0) spaceTspan.setAttribute(\"textLength\", (leftNext - right).toString());\n spaceTspan.setAttribute(\"lengthAdjust\", \"spacingAndGlyphs\");\n spaceTspan.textContent = \" \";\n paragSvg.appendChild(spaceTspan);\n }\n\n // Adds newline at the end of paragraph on Firefox\n if ((i == words.length - 1 && (this.insertNewlines))) {\n paragSvg.appendChild(document.createTextNode(\"\\n\"));\n }\n }\n\n wordHeightArr.sort();\n const paragWordHeight = wordHeightArr[Math.floor(wordHeightArr.length * 0.85)];\n paragSvg.setAttribute(\"font-size\", paragWordHeight.toString());\n svg.appendChild(paragSvg);\n });\n this.stopPageFlip($container);\n }\n}\n\nexport class BookreaderWithTextSelection extends BookReader {\n init() {\n const options = Object.assign({}, DEFAULT_OPTIONS, this.options.plugins.textSelection);\n if (options.enabled) {\n this.textSelectionPlugin = new TextSelectionPlugin(options, this.options.vars);\n // Write this back; this way the plugin is the source of truth, and BR just\n // contains a reference to it.\n this.options.plugins.textSelection = options;\n this.textSelectionPlugin.init();\n }\n super.init();\n }\n\n /**\n * @param {number} index\n */\n _createPageContainer(index) {\n const pageContainer = super._createPageContainer(index);\n // Disable if thumb mode; it's too janky\n // .page can be null for \"pre-cover\" region\n if (this.mode !== this.constModeThumb && pageContainer.page) {\n this.textSelectionPlugin?.createTextLayer(pageContainer);\n }\n return pageContainer;\n }\n}\nwindow.BookReader = BookreaderWithTextSelection;\nexport default BookreaderWithTextSelection;\n","\n/**\n * Checks whether the current browser is a Chrome/Chromium browser\n * Code from https://stackoverflow.com/a/4565120/2317712\n * @param {string} [userAgent]\n * @param {string} [vendor]\n * @return {boolean}\n */\nexport function isChrome(userAgent = navigator.userAgent, vendor = navigator.vendor) {\n return /chrome/i.test(userAgent) && /google inc/i.test(vendor);\n}\n\n/**\n * Checks whether the current browser is firefox\n * @param {string} [userAgent]\n * @return {boolean}\n */\nexport function isFirefox(userAgent = navigator.userAgent) {\n return /firefox/i.test(userAgent);\n}\n\n/**\n * Checks whether the current browser is safari\n * https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent#Browser_Name\n * @param {string} [userAgent]\n * @return {boolean}\n */\nexport function isSafari(userAgent = navigator.userAgent) {\n return /safari/i.test(userAgent) && !/chrome|chromium/i.test(userAgent);\n}\n","var global = require('../internals/global');\nvar toString = require('../internals/to-string');\nvar trim = require('../internals/string-trim').trim;\nvar whitespaces = require('../internals/whitespaces');\n\nvar $parseFloat = global.parseFloat;\nvar FORCED = 1 / $parseFloat(whitespaces + '-0') !== -Infinity;\n\n// `parseFloat` method\n// https://tc39.es/ecma262/#sec-parsefloat-string\nmodule.exports = FORCED ? function parseFloat(string) {\n var trimmedString = trim(toString(string));\n var result = $parseFloat(trimmedString);\n return result === 0 && trimmedString.charAt(0) == '-' ? -0 : result;\n} : $parseFloat;\n","var fails = require('../internals/fails');\nvar whitespaces = require('../internals/whitespaces');\n\nvar non = '\\u200B\\u0085\\u180E';\n\n// check that a method works with the correct list\n// of whitespaces and has a correct name\nmodule.exports = function (METHOD_NAME) {\n return fails(function () {\n return !!whitespaces[METHOD_NAME]() || non[METHOD_NAME]() != non || whitespaces[METHOD_NAME].name !== METHOD_NAME;\n });\n};\n","var $ = require('../internals/export');\nvar parseFloatImplementation = require('../internals/number-parse-float');\n\n// `parseFloat` method\n// https://tc39.es/ecma262/#sec-parsefloat-string\n$({ global: true, forced: parseFloat != parseFloatImplementation }, {\n parseFloat: parseFloatImplementation\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar $trim = require('../internals/string-trim').trim;\nvar forcedStringTrimMethod = require('../internals/string-trim-forced');\n\n// `String.prototype.trim` method\n// https://tc39.es/ecma262/#sec-string.prototype.trim\n$({ target: 'String', proto: true, forced: forcedStringTrimMethod('trim') }, {\n trim: function trim() {\n return $trim(this);\n }\n});\n"],"names":["applyVariables","template","vars","overrides","possibleFilters","APPLY_FILTERS","replace","$0","$1","split","map","x","trim","varName","filterNames","value","n","reduce","acc","cur","toString","urlencode","encodeURIComponent","BookReader","window","DEFAULT_OPTIONS","enabled","fullDjvuXmlUrl","singlePageDjvuXmlUrl","Cache","maxSize","this","entries","entry","length","shift","push","TextSelectionPlugin","options","optionVariables","avoidTspans","isFirefox","pointerEventsOnParagraph","isSafari","djvuPagesPromise","svgParagraphElement","svgWordElement","insertNewlines","pageTextCache","maxWordRendered","$","ajax","type","url","dataType","error","e","then","res","xmlMap","parseXML","find","index","cachedEntry","response","pageIndex","xmlDoc","result","add","undefined","XMLpagesArr","$container","addEventListener","event","selection","document","getSelection","clipboardData","setData","preventDefault","svg","classList","remove","on","target","is","stopPropagation","one","off","textSelectingMode","removeAllRanges","defaultMode","$svg","each","i","s","interceptCopy","pageContainer","page","getPageText","XMLpage","totalWords","console","log","createSVGPageLayer","append","paragraph","words","paragSvg","createElementNS","setAttribute","style","pointerEvents","wordHeightArr","currWord","attr","parseFloat","left","bottom","right","wordHeight","wordTspan","textContent","appendChild","nextWord","leftNext","spaceTspan","createTextNode","sort","paragWordHeight","Math","floor","stopPageFlip","BookreaderWithTextSelection","Object","assign","plugins","textSelection","textSelectionPlugin","init","mode","constModeThumb","createTextLayer","isChrome","userAgent","navigator","vendor","test","global","whitespaces","$parseFloat","FORCED","module","exports","string","trimmedString","charAt","fails","METHOD_NAME","name","parseFloatImplementation","forced","$trim","proto","forcedStringTrimMethod"],"sourceRoot":""}
|