@internetarchive/bookreader 5.0.0-116 → 5.0.0-118-alpha1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/package.json +35 -31
- package/src/BookReader.js +16 -0
- package/src/css/_TextSelection.scss +51 -18
- package/src/plugins/plugin.chapters.js +8 -4
- package/src/plugins/plugin.iframe.js +36 -37
- package/src/plugins/plugin.text_selection.js +36 -11
- package/src/plugins/search/plugin.search.js +2 -8
- package/src/plugins/tts/plugin.tts.js +27 -8
- package/src/util/TextSelectionManager.js +53 -8
- package/src/util/dom.js +88 -0
- package/BookReader/474.js +0 -2
- package/BookReader/474.js.map +0 -1
- package/BookReader/BookReader.css +0 -2425
- package/BookReader/BookReader.js +0 -3
- package/BookReader/BookReader.js.LICENSE.txt +0 -72
- package/BookReader/BookReader.js.map +0 -1
- package/BookReader/bergamot-translator-worker.js +0 -2966
- package/BookReader/bergamot-translator-worker.wasm +0 -0
- package/BookReader/hypothesis/LICENSE +0 -50
- package/BookReader/hypothesis/README.md +0 -55
- package/BookReader/hypothesis/build/boot.js +0 -1
- package/BookReader/hypothesis/build/manifest.json +0 -20
- package/BookReader/hypothesis/build/scripts/annotator.bundle.js +0 -184
- package/BookReader/hypothesis/build/scripts/annotator.bundle.js.map +0 -1
- package/BookReader/hypothesis/build/scripts/sidebar.bundle.js +0 -798
- package/BookReader/hypothesis/build/scripts/sidebar.bundle.js.map +0 -1
- package/BookReader/hypothesis/build/scripts/ui-playground.bundle.js +0 -711
- package/BookReader/hypothesis/build/scripts/ui-playground.bundle.js.map +0 -1
- package/BookReader/hypothesis/build/styles/annotator.css +0 -2235
- package/BookReader/hypothesis/build/styles/annotator.css.map +0 -1
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_AMS-Regular.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Main-Bold.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Main-Italic.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Main-Regular.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Math-Italic.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Script-Regular.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Size1-Regular.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Size2-Regular.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Size3-Regular.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Size4-Regular.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
- package/BookReader/hypothesis/build/styles/highlights.css +0 -2
- package/BookReader/hypothesis/build/styles/highlights.css.map +0 -1
- package/BookReader/hypothesis/build/styles/katex.min.css +0 -2
- package/BookReader/hypothesis/build/styles/katex.min.css.map +0 -1
- package/BookReader/hypothesis/build/styles/pdfjs-overrides.css +0 -2
- package/BookReader/hypothesis/build/styles/pdfjs-overrides.css.map +0 -1
- package/BookReader/hypothesis/build/styles/sidebar.css +0 -2731
- package/BookReader/hypothesis/build/styles/sidebar.css.map +0 -1
- package/BookReader/hypothesis/build/styles/ui-playground.css +0 -2659
- package/BookReader/hypothesis/build/styles/ui-playground.css.map +0 -1
- package/BookReader/hypothesis/package.json +0 -126
- package/BookReader/ia-bookreader-bundle.js +0 -1886
- package/BookReader/ia-bookreader-bundle.js.LICENSE.txt +0 -19
- package/BookReader/ia-bookreader-bundle.js.map +0 -1
- package/BookReader/icons/1up.svg +0 -1
- package/BookReader/icons/2up.svg +0 -1
- package/BookReader/icons/advance.svg +0 -3
- package/BookReader/icons/chevron-right.svg +0 -1
- package/BookReader/icons/close-circle-dark.svg +0 -1
- package/BookReader/icons/close-circle.svg +0 -1
- package/BookReader/icons/fullscreen.svg +0 -1
- package/BookReader/icons/fullscreen_exit.svg +0 -1
- package/BookReader/icons/hamburger.svg +0 -1
- package/BookReader/icons/left-arrow.svg +0 -1
- package/BookReader/icons/magnify-minus.svg +0 -1
- package/BookReader/icons/magnify-plus.svg +0 -1
- package/BookReader/icons/magnify.svg +0 -1
- package/BookReader/icons/pause.svg +0 -1
- package/BookReader/icons/play.svg +0 -1
- package/BookReader/icons/playback-speed.svg +0 -1
- package/BookReader/icons/read-aloud.svg +0 -1
- package/BookReader/icons/review.svg +0 -3
- package/BookReader/icons/slider-toggle.svg +0 -1
- package/BookReader/icons/thumbnails.svg +0 -1
- package/BookReader/icons/voice.svg +0 -1
- package/BookReader/icons/volume-full.svg +0 -1
- package/BookReader/images/BRicons.png +0 -0
- package/BookReader/images/BRicons.svg +0 -5
- package/BookReader/images/BRicons_ia.png +0 -0
- package/BookReader/images/back_pages.png +0 -0
- package/BookReader/images/book_bottom_icon.png +0 -0
- package/BookReader/images/book_down_icon.png +0 -0
- package/BookReader/images/book_left_icon.png +0 -0
- package/BookReader/images/book_leftmost_icon.png +0 -0
- package/BookReader/images/book_right_icon.png +0 -0
- package/BookReader/images/book_rightmost_icon.png +0 -0
- package/BookReader/images/book_top_icon.png +0 -0
- package/BookReader/images/book_up_icon.png +0 -0
- package/BookReader/images/books_graphic.svg +0 -1
- package/BookReader/images/booksplit.png +0 -0
- package/BookReader/images/control_pause_icon.png +0 -0
- package/BookReader/images/control_play_icon.png +0 -0
- package/BookReader/images/embed_icon.png +0 -0
- package/BookReader/images/hypothesis.ico +0 -0
- package/BookReader/images/icon-home-ia.png +0 -0
- package/BookReader/images/icon_OL-logo-xs.png +0 -0
- package/BookReader/images/icon_alert-xs.png +0 -0
- package/BookReader/images/icon_book.svg +0 -1
- package/BookReader/images/icon_bookmark.svg +0 -1
- package/BookReader/images/icon_close-pop.png +0 -0
- package/BookReader/images/icon_download.png +0 -0
- package/BookReader/images/icon_experiment.svg +0 -1
- package/BookReader/images/icon_gear.svg +0 -1
- package/BookReader/images/icon_hamburger.svg +0 -1
- package/BookReader/images/icon_home.png +0 -0
- package/BookReader/images/icon_home.svg +0 -1
- package/BookReader/images/icon_home_ia.png +0 -0
- package/BookReader/images/icon_indicator.png +0 -0
- package/BookReader/images/icon_info.svg +0 -1
- package/BookReader/images/icon_one_page.svg +0 -1
- package/BookReader/images/icon_pause.svg +0 -1
- package/BookReader/images/icon_play.svg +0 -1
- package/BookReader/images/icon_playback-rate.svg +0 -1
- package/BookReader/images/icon_return.png +0 -0
- package/BookReader/images/icon_search_button.svg +0 -1
- package/BookReader/images/icon_share.svg +0 -1
- package/BookReader/images/icon_skip-ahead.svg +0 -1
- package/BookReader/images/icon_skip-back.svg +0 -2
- package/BookReader/images/icon_speaker.svg +0 -1
- package/BookReader/images/icon_speaker_open.svg +0 -1
- package/BookReader/images/icon_thumbnails.svg +0 -1
- package/BookReader/images/icon_toc.svg +0 -1
- package/BookReader/images/icon_two_pages.svg +0 -1
- package/BookReader/images/icon_zoomer.png +0 -0
- package/BookReader/images/loading.gif +0 -0
- package/BookReader/images/logo_icon.png +0 -0
- package/BookReader/images/marker_chap-off.png +0 -0
- package/BookReader/images/marker_chap-off.svg +0 -1
- package/BookReader/images/marker_chap-off_ia.png +0 -0
- package/BookReader/images/marker_chap-on.png +0 -0
- package/BookReader/images/marker_chap-on.svg +0 -1
- package/BookReader/images/marker_srch-on.svg +0 -1
- package/BookReader/images/marker_srchchap-off.png +0 -0
- package/BookReader/images/marker_srchchap-on.png +0 -0
- package/BookReader/images/nav_control-dn.png +0 -0
- package/BookReader/images/nav_control-dn_ia.png +0 -0
- package/BookReader/images/nav_control-up.png +0 -0
- package/BookReader/images/nav_control-up_ia.png +0 -0
- package/BookReader/images/nav_control.png +0 -0
- package/BookReader/images/one_page_mode_icon.png +0 -0
- package/BookReader/images/paper-badge.png +0 -0
- package/BookReader/images/print_icon.png +0 -0
- package/BookReader/images/progressbar.gif +0 -0
- package/BookReader/images/right_edges.png +0 -0
- package/BookReader/images/slider.png +0 -0
- package/BookReader/images/slider_ia.png +0 -0
- package/BookReader/images/thumbnail_mode_icon.png +0 -0
- package/BookReader/images/translate.svg +0 -1
- package/BookReader/images/transparent.png +0 -0
- package/BookReader/images/two_page_mode_icon.png +0 -0
- package/BookReader/images/unviewable_page.png +0 -0
- package/BookReader/images/zoom_in_icon.png +0 -0
- package/BookReader/images/zoom_out_icon.png +0 -0
- package/BookReader/jquery-3.js +0 -2
- package/BookReader/jquery-3.js.LICENSE.txt +0 -24
- package/BookReader/plugins/plugin.archive_analytics.js +0 -2
- package/BookReader/plugins/plugin.archive_analytics.js.map +0 -1
- package/BookReader/plugins/plugin.autoplay.js +0 -2
- package/BookReader/plugins/plugin.autoplay.js.map +0 -1
- package/BookReader/plugins/plugin.chapters.js +0 -23
- package/BookReader/plugins/plugin.chapters.js.LICENSE.txt +0 -1
- package/BookReader/plugins/plugin.chapters.js.map +0 -1
- package/BookReader/plugins/plugin.experiments.js +0 -3
- package/BookReader/plugins/plugin.experiments.js.LICENSE.txt +0 -1
- package/BookReader/plugins/plugin.experiments.js.map +0 -1
- package/BookReader/plugins/plugin.iframe.js +0 -2
- package/BookReader/plugins/plugin.iframe.js.map +0 -1
- package/BookReader/plugins/plugin.iiif.js +0 -2
- package/BookReader/plugins/plugin.iiif.js.map +0 -1
- package/BookReader/plugins/plugin.resume.js +0 -2
- package/BookReader/plugins/plugin.resume.js.map +0 -1
- package/BookReader/plugins/plugin.search.js +0 -3
- package/BookReader/plugins/plugin.search.js.LICENSE.txt +0 -1
- package/BookReader/plugins/plugin.search.js.map +0 -1
- package/BookReader/plugins/plugin.text_selection.js +0 -45
- package/BookReader/plugins/plugin.text_selection.js.LICENSE.txt +0 -1
- package/BookReader/plugins/plugin.text_selection.js.map +0 -1
- package/BookReader/plugins/plugin.translate.js +0 -179
- package/BookReader/plugins/plugin.translate.js.LICENSE.txt +0 -1
- package/BookReader/plugins/plugin.translate.js.map +0 -1
- package/BookReader/plugins/plugin.tts.js +0 -3
- package/BookReader/plugins/plugin.tts.js.LICENSE.txt +0 -29
- package/BookReader/plugins/plugin.tts.js.map +0 -1
- package/BookReader/plugins/plugin.url.js +0 -2
- package/BookReader/plugins/plugin.url.js.map +0 -1
- package/BookReader/plugins/plugin.vendor-fullscreen.js +0 -2
- package/BookReader/plugins/plugin.vendor-fullscreen.js.map +0 -1
- package/BookReader/plugins/translator-worker.js +0 -2
- package/BookReader/plugins/translator-worker.js.map +0 -1
- package/BookReader/silence.mp3 +0 -0
- package/BookReader/translator-worker.js +0 -475
- package/BookReader/webcomponents-bundle.js +0 -3
- package/BookReader/webcomponents-bundle.js.LICENSE.txt +0 -9
- package/BookReader/webcomponents-bundle.js.map +0 -1
|
@@ -7,6 +7,7 @@ import { customElement, property, query } from 'lit/decorators.js';
|
|
|
7
7
|
import { ifDefined } from 'lit/directives/if-defined.js';
|
|
8
8
|
import '@internetarchive/icon-share';
|
|
9
9
|
import '@internetarchive/icon-edit-pencil/icon-edit-pencil.js';
|
|
10
|
+
import '@internetarchive/icon-ellipses';
|
|
10
11
|
import { isIOS, isAndroid } from './browserSniffing.js';
|
|
11
12
|
import { genAt, genFilter } from './generators.js';
|
|
12
13
|
|
|
@@ -412,6 +413,9 @@ export class BRSelectMenuOption extends LitElement {
|
|
|
412
413
|
if (this.icon === 'edit-pencil') {
|
|
413
414
|
return html`<ia-icon-edit-pencil class="br-select-menu__icon" aria-hidden="true"></ia-icon-edit-pencil>`;
|
|
414
415
|
}
|
|
416
|
+
if (this.icon === 'ellipses') {
|
|
417
|
+
return html`<ia-icon-ellipses class="br-select-menu__icon" aria-hidden="true"></ia-icon-ellipses>`;
|
|
418
|
+
}
|
|
415
419
|
return '';
|
|
416
420
|
}
|
|
417
421
|
|
|
@@ -433,7 +437,9 @@ export class BRSelectMenuOption extends LitElement {
|
|
|
433
437
|
aria-label=${ifDefined(accessibleLabel)}
|
|
434
438
|
>
|
|
435
439
|
${this.renderIcon()}
|
|
436
|
-
${
|
|
440
|
+
${
|
|
441
|
+
!hasTemporaryText && !baseLabel ? '' :
|
|
442
|
+
hasTemporaryText ? html`
|
|
437
443
|
<span class="br-select-menu__label-wrap" style="display: inline-flex; position: relative; align-items: center;">
|
|
438
444
|
<span
|
|
439
445
|
class="br-select-menu__label"
|
|
@@ -459,8 +465,12 @@ class BRSelectMenu extends LitElement {
|
|
|
459
465
|
/** @type {import('../BookReader.js').default} */
|
|
460
466
|
br;
|
|
461
467
|
|
|
468
|
+
/** @type {boolean} */
|
|
469
|
+
@property({type: Boolean, reflect: true})
|
|
470
|
+
showExtended = false;
|
|
471
|
+
|
|
462
472
|
/** @type {BRSelectMenuOption | null} */
|
|
463
|
-
@query('#copy-link-option')
|
|
473
|
+
@query('#br-select-copy-link-option')
|
|
464
474
|
copyLinkOption;
|
|
465
475
|
|
|
466
476
|
@property({type: Boolean, reflect: true})
|
|
@@ -521,7 +531,7 @@ class BRSelectMenu extends LitElement {
|
|
|
521
531
|
// Mousedown needed to prevent selection from being cleared on iOS
|
|
522
532
|
return html`
|
|
523
533
|
<br-menu-option
|
|
524
|
-
id="copy-link-option"
|
|
534
|
+
id="br-select-copy-link-option"
|
|
525
535
|
@mousedown=${/** @param {MouseEvent} e */ (e) => e.preventDefault()}
|
|
526
536
|
@click=${this.handleCopyLinkToHighlight}
|
|
527
537
|
icon="share"
|
|
@@ -560,6 +570,19 @@ class BRSelectMenu extends LitElement {
|
|
|
560
570
|
></br-menu-option>
|
|
561
571
|
`;
|
|
562
572
|
}
|
|
573
|
+
|
|
574
|
+
renderShowMoreOption() {
|
|
575
|
+
return html`
|
|
576
|
+
<br-menu-option
|
|
577
|
+
id="br-select-more"
|
|
578
|
+
@mousedown=${/** @param {MouseEvent} e */ (e) => e.preventDefault()}
|
|
579
|
+
@click=${this.toggleExtendedMenu}
|
|
580
|
+
icon="ellipses"
|
|
581
|
+
aria-label="Show more options"
|
|
582
|
+
></br-menu-option>
|
|
583
|
+
`;
|
|
584
|
+
}
|
|
585
|
+
|
|
563
586
|
renderLocalStorageOptions() {
|
|
564
587
|
return html`
|
|
565
588
|
<br-menu-option
|
|
@@ -574,16 +597,30 @@ class BRSelectMenu extends LitElement {
|
|
|
574
597
|
></br-menu-option>`;
|
|
575
598
|
}
|
|
576
599
|
|
|
577
|
-
|
|
578
|
-
// TODO change the second button to use a different icon
|
|
600
|
+
renderDefaultOptions() {
|
|
579
601
|
return html`
|
|
580
602
|
${this.copyLinkToHighlightEnabled ? this.renderCopyLinkToHighlightOption() : ''}
|
|
581
603
|
${this.highlightAnnotationEnabled && !this.nodesForRemoval ? this.renderHighlightOption() : ''}
|
|
582
|
-
${this.highlightAnnotationEnabled ? this.renderLocalStorageOptions() : ''}
|
|
583
604
|
${this.nodesForRemoval ? this.renderRemoveOption() : ''}
|
|
584
605
|
`;
|
|
585
606
|
}
|
|
586
607
|
|
|
608
|
+
renderExtendedOptions() {
|
|
609
|
+
return html`
|
|
610
|
+
${this.renderDefaultOptions()}
|
|
611
|
+
${this.renderLocalStorageOptions()}
|
|
612
|
+
`;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
render() {
|
|
616
|
+
const hasMoreOptions = this.br.plugins.experiments?.isEnabled('annotateHighlight');
|
|
617
|
+
// TODO change the second button to use a different icon
|
|
618
|
+
return html`
|
|
619
|
+
${this.showExtended ? this.renderExtendedOptions() : this.renderDefaultOptions()}
|
|
620
|
+
${!this.showExtended && hasMoreOptions ? this.renderShowMoreOption() : ""}
|
|
621
|
+
`;
|
|
622
|
+
}
|
|
623
|
+
|
|
587
624
|
/**
|
|
588
625
|
* @param {MouseEvent} e
|
|
589
626
|
*/
|
|
@@ -615,6 +652,14 @@ class BRSelectMenu extends LitElement {
|
|
|
615
652
|
this.copyLinkOption?.showTemporaryText('Copied!');
|
|
616
653
|
}
|
|
617
654
|
|
|
655
|
+
/**
|
|
656
|
+
* @param {MouseEvent} e
|
|
657
|
+
*/
|
|
658
|
+
toggleExtendedMenu(e) {
|
|
659
|
+
e.preventDefault();
|
|
660
|
+
this.showExtended = !this.showExtended;
|
|
661
|
+
}
|
|
662
|
+
|
|
618
663
|
/**
|
|
619
664
|
* Returns the closest BRtextLayer element on the page that contains the target node
|
|
620
665
|
* @param {Node} node
|
|
@@ -761,12 +806,12 @@ class BRSelectMenu extends LitElement {
|
|
|
761
806
|
this.style.left = `${left}px`;
|
|
762
807
|
}
|
|
763
808
|
|
|
809
|
+
// Will always show the simplified menu when rendered after hiding
|
|
764
810
|
async show() {
|
|
765
811
|
if (this.br.plugins.translate?.userToggleTranslate) return;
|
|
766
812
|
|
|
767
813
|
this.style.zIndex = '1';
|
|
768
814
|
this.style.position = 'absolute';
|
|
769
|
-
this.style.display = 'block';
|
|
770
815
|
this.open = true;
|
|
771
816
|
this.classList.remove('br-select-menu__root--scrolling');
|
|
772
817
|
window.removeEventListener('scroll', this._onScroll, { capture: true });
|
|
@@ -778,7 +823,7 @@ class BRSelectMenu extends LitElement {
|
|
|
778
823
|
|
|
779
824
|
hide() {
|
|
780
825
|
if (!this.open) return;
|
|
781
|
-
this.
|
|
826
|
+
this.showExtended = false;
|
|
782
827
|
this.open = false;
|
|
783
828
|
window.removeEventListener('scroll', this._onScroll, { capture: true });
|
|
784
829
|
this.clearNodesForRemoval();
|
package/src/util/dom.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { clamp } from '../BookReader/utils.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Walks up the DOM tree starting at (but not including) the given element,
|
|
6
|
+
* returning the nearest ancestor that can actually scroll its overflow.
|
|
7
|
+
* @param {Element} el
|
|
8
|
+
* @return {Element | null}
|
|
9
|
+
*/
|
|
10
|
+
export function findScrollableAncestor(el) {
|
|
11
|
+
let current = el.parentElement;
|
|
12
|
+
while (current) {
|
|
13
|
+
const style = getComputedStyle(current);
|
|
14
|
+
const canScrollY = (style.overflowY === 'auto' || style.overflowY === 'scroll') && current.scrollHeight > current.clientHeight;
|
|
15
|
+
const canScrollX = (style.overflowX === 'auto' || style.overflowX === 'scroll') && current.scrollWidth > current.clientWidth;
|
|
16
|
+
if (canScrollY || canScrollX) return current;
|
|
17
|
+
current = current.parentElement;
|
|
18
|
+
}
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Computes the scroll offset for a single axis needed to align an element
|
|
24
|
+
* within a container, per the same semantics as scrollIntoView's block/inline.
|
|
25
|
+
* @param {number} elStart
|
|
26
|
+
* @param {number} elEnd
|
|
27
|
+
* @param {number} containerStart
|
|
28
|
+
* @param {number} containerEnd
|
|
29
|
+
* @param {number} currentScroll
|
|
30
|
+
* @param {'start' | 'center' | 'end' | 'nearest'} align
|
|
31
|
+
* @return {number}
|
|
32
|
+
*/
|
|
33
|
+
function computeAxisScroll(elStart, elEnd, containerStart, containerEnd, currentScroll, align) {
|
|
34
|
+
let delta = 0;
|
|
35
|
+
switch (align) {
|
|
36
|
+
case 'start':
|
|
37
|
+
delta = elStart - containerStart;
|
|
38
|
+
break;
|
|
39
|
+
case 'end':
|
|
40
|
+
delta = elEnd - containerEnd;
|
|
41
|
+
break;
|
|
42
|
+
case 'center':
|
|
43
|
+
delta = (elStart + elEnd) / 2 - (containerStart + containerEnd) / 2;
|
|
44
|
+
break;
|
|
45
|
+
case 'nearest':
|
|
46
|
+
default:
|
|
47
|
+
if (elStart < containerStart) delta = elStart - containerStart;
|
|
48
|
+
else if (elEnd > containerEnd) delta = elEnd - containerEnd;
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
return currentScroll + delta;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Scrolls the given element into view within a single scroll container.
|
|
56
|
+
*
|
|
57
|
+
* Unlike the native `Element.scrollIntoView`, this never walks up and scrolls
|
|
58
|
+
* every scrollable ancestor in turn (which can otherwise unexpectedly move
|
|
59
|
+
* the whole page) — it only ever adjusts the scroll position of one
|
|
60
|
+
* container: either the one explicitly passed in, or the nearest scrollable
|
|
61
|
+
* ancestor found via {@link findScrollableAncestor}.
|
|
62
|
+
* @param {Element} el
|
|
63
|
+
* @param {object} [options]
|
|
64
|
+
* @param {'auto' | 'smooth'} [options.behavior]
|
|
65
|
+
* @param {'start' | 'center' | 'end' | 'nearest'} [options.block]
|
|
66
|
+
* @param {'start' | 'center' | 'end' | 'nearest'} [options.inline]
|
|
67
|
+
* @param {Element} [options.scrollContainer] The scrollable element whose
|
|
68
|
+
* scroll position should be adjusted. Defaults to `findScrollableAncestor(el)`.
|
|
69
|
+
*/
|
|
70
|
+
export function singleScrollIntoView(el, options) {
|
|
71
|
+
const { block = 'start', inline = 'nearest', behavior = 'auto', scrollContainer = findScrollableAncestor(el) } = options || {};
|
|
72
|
+
if (!scrollContainer) {
|
|
73
|
+
el.scrollIntoView({ block, inline, behavior });
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const containerRect = scrollContainer.getBoundingClientRect();
|
|
78
|
+
const elRect = el.getBoundingClientRect();
|
|
79
|
+
|
|
80
|
+
const top = computeAxisScroll(elRect.top, elRect.bottom, containerRect.top, containerRect.bottom, scrollContainer.scrollTop, block);
|
|
81
|
+
const left = computeAxisScroll(elRect.left, elRect.right, containerRect.left, containerRect.right, scrollContainer.scrollLeft, inline);
|
|
82
|
+
|
|
83
|
+
scrollContainer.scrollTo({
|
|
84
|
+
top: clamp(top, 0, scrollContainer.scrollHeight - scrollContainer.clientHeight),
|
|
85
|
+
left: clamp(left, 0, scrollContainer.scrollWidth - scrollContainer.clientWidth),
|
|
86
|
+
behavior,
|
|
87
|
+
});
|
|
88
|
+
}
|
package/BookReader/474.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
!function(){"use strict";var e={};e.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}();var t={};"undefined"==typeof self&&(e.g.Module=t,e.g.self=new class{#e;constructor(){const{parentPort:e}=require("node:worker_threads");this.#e=e}addEventListener(e,t){this.#e.on(e,e=>t({data:e}))}postMessage(e){this.#e.postMessage(e)}importScripts(...t){const{readFileSync:n}=require("node:fs"),{join:r}=require("node:path");for(let s of t){const t=n(r(__dirname,s),{encoding:"utf-8"});eval.call(e.g,t)}}async fetch(e,t){if("file:"===e.protocol){const{readFile:t}=require("node:fs/promises"),n=await t(e.pathname),r=new Blob([n]);return new Response(r,{status:200,statusText:"OK",headers:{"Content-Type":"application/wasm","Content-Length":r.size.toString()}})}return await fetch(e,t)}get location(){return new URL(`file://${__filename}`)}});class n{static parse(e){const t={};return e.split("\n").reduce((e,n,r)=>{let s;if(s=n.match(/^\s*-\s+(.+?)$/))Array.isArray(t[e])||(t[e]=t[e].trim()?[t[e]]:[]),t[e].push(s[1].trim());else if(s=n.match(/^\s*([A-Za-z0-9_][A-Za-z0-9_-]*):\s*(.*)$/))e=s[1],t[e]=s[2].trim();else if(n.trim())throw Error(`Could not parse line ${r+1}: "${n}"`);return e},null),t}static stringify(e){return Object.entries(e).reduce((e,[t,n])=>{let r="";return r=Array.isArray(n)?n.map(e=>`\n - ${e}`).join(""):("number"==typeof n||"boolean"==typeof n||n.match(/^\d*(\.\d+)?$/),`${n}`),`${e}${t}: ${r}\n`},"")}}class r{static GEMM_TO_FALLBACK_FUNCTIONS_MAP={int8_prepare_a:"int8PrepareAFallback",int8_prepare_b:"int8PrepareBFallback",int8_prepare_b_from_transposed:"int8PrepareBFromTransposedFallback",int8_prepare_b_from_quantized_transposed:"int8PrepareBFromQuantizedTransposedFallback",int8_prepare_bias:"int8PrepareBiasFallback",int8_multiply_and_add_bias:"int8MultiplyAndAddBiasFallback",int8_select_columns_of_b:"int8SelectColumnsOfBFallback"};static NATIVE_INT_GEMM="mozIntGemm";constructor(e){}async initialize(e){this.options=e||{},this.models=new Map,this.module=await this.loadModule(),this.service=await this.loadTranslationService()}linkNativeIntGemm(e){if(!WebAssembly.mozIntGemm)return console.warn("Native gemm requested but not available, falling back to embedded gemm"),this.linkFallbackIntGemm(e);const t=new WebAssembly.Instance(WebAssembly.mozIntGemm(),{"":{memory:e.env.memory}});return Array.from(Object.keys(r.GEMM_TO_FALLBACK_FUNCTIONS_MAP)).every(e=>t.exports[e])?t.exports:(console.warn("Native gemm is missing expected functions, falling back to embedded gemm"),this.linkFallbackIntGemm(e))}linkFallbackIntGemm(e){const n=Object.entries(r.GEMM_TO_FALLBACK_FUNCTIONS_MAP).map(([e,n])=>[e,(...e)=>t.asm[n](...e)]);return Object.fromEntries(n)}loadModule(){return new Promise(async(e,n)=>{try{const r=await self.fetch(new URL("./bergamot-translator-worker.wasm",self.location));Object.assign(t,{instantiateWasm:(e,t)=>{try{WebAssembly.instantiateStreaming(r,{...e,wasm_gemm:this.options.useNativeIntGemm?this.linkNativeIntGemm(e):this.linkFallbackIntGemm(e)}).then(({instance:e})=>t(e)).catch(n)}catch(e){n(e)}return{}},onRuntimeInitialized:()=>{e(t)}}),self.Module=t,self.importScripts("bergamot-translator-worker.js")}catch(e){n(e)}})}loadTranslationService(){return new this.module.BlockingService({cacheSize:Math.max(this.options.cacheSize||0,0)})}hasTranslationModel({from:e,to:t}){const n=JSON.stringify({from:e,to:t});return this.models.has(n)}loadTranslationModel({from:e,to:t},r){const s=r.vocabs.filter((e,t,n)=>!n.slice(0,t).includes(e)),[i,a,o,...l]=[this.prepareAlignedMemoryFromBuffer(r.model,256),this.prepareAlignedMemoryFromBuffer(r.shortlist,64),r.qualityModel?this.prepareAlignedMemoryFromBuffer(r.qualityModel,64):null,...s.map(e=>this.prepareAlignedMemoryFromBuffer(e,64))],m=new this.module.AlignedMemoryList;l.forEach(e=>m.push_back(e));let c=n.parse("\n beam-size: 1\n normalize: 1.0\n word-penalty: 0\n cpu-threads: 0\n gemm-precision: int8shiftAlphaAll\n skip-cost: true\n ");r.config&&Object.assign(c,r.config),"int8"===c["gemm-precision"]&&(c["gemm-precision"]="int8shiftAll"),Object.assign(c,n.parse("\n alignment: soft\n quiet: true\n quiet-translation: true\n max-length-break: 128\n mini-batch-words: 1024\n workspace: 128\n max-length-factor: 2.0\n "));const d=JSON.stringify({from:e,to:t});this.models.set(d,new this.module.TranslationModel(n.stringify(c),i,a,m,o))}freeTranslationModel({from:e,to:t}){const n=JSON.stringify({from:e,to:t});if(!this.models.has(n))return;const r=this.models.get(n);this.models.delete(n),r.delete()}prepareAlignedMemoryFromBuffer(e,t){const n=new Int8Array(e),r=new this.module.AlignedMemory(n.byteLength,t);return r.getByteArrayView().set(n),r}translate({models:e,texts:t}){let n=new this.module.VectorString;t.forEach(({text:e})=>n.push_back(e));let r=new this.module.VectorResponseOptions;t.forEach(({html:e,qualityScores:t})=>r.push_back({alignment:!1,html:e,qualityScores:t}));const s=e.map(({from:e,to:t})=>{const n=JSON.stringify({from:e,to:t});return this.models.get(n)}),i=e.length>1?this.service.translateViaPivoting(...s,n,r):this.service.translate(...s,n,r);n.delete(),r.delete();const a=t.map((e,t)=>({target:{text:i.get(t).getTranslatedText()}}));return i.delete(),a}}function s(e){return{name:e.name,message:e.message,stack:e.stack}}const i=new r;self.addEventListener("message",async function({data:{id:e,name:t,args:n}}){e||console.error("Received message without id",arguments[0]);try{if("function"!=typeof i[t])throw TypeError(`worker[${t}] is not a function`);const r=await Promise.resolve(Reflect.apply(i[t],i,n));self.postMessage({id:e,result:r})}catch(t){self.postMessage({id:e,error:s(t)})}})}();
|
|
2
|
-
//# sourceMappingURL=474.js.map
|
package/BookReader/474.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"474.js","mappings":"yBACA,IAAAA,EAAA,GCDAA,EAAAC,EAAA,WACA,oBAAAC,WAAA,OAAAA,WACA,IACA,OAAAC,MAAA,IAAAC,SAAA,gBACA,CAAG,MAAAC,GACH,oBAAAC,OAAA,OAAAA,MACA,CACC,CAPD,GCKA,IAAAC,EAAA,GAMA,oBAAAC,OACIR,EAAAC,EAAMM,OAAAA,EAENP,EAAAC,EAAMO,KAAA,UAEVC,GAEA,WAAAC,GACA,MAAAC,WAAmBA,GAAYC,QAAA,uBAC/BT,MAAAM,EAAAE,CACA,CAOA,gBAAAE,CAAAC,EAAAC,GACAZ,MAAAM,EAAAO,GAAAF,EAAAG,GAAAF,EAAA,CAAyDE,SACzD,CAMA,WAAAC,CAAAC,GACAhB,MAAAM,EAAAS,YAAAC,EACA,CAKA,aAAAC,IAAAC,GACA,MAAAC,aAAmBA,GAAcV,QAAA,YACjCW,KAAmBA,GAAMX,QAAA,aACzB,QAAAY,KAAAH,EAAA,CACA,MAAAI,EAAAH,EAAAC,EAAAG,UAAAF,GAAA,CAAwEG,SAAA,UACxEC,KAAAC,KAA0B7B,EAAAC,EAAMwB,EAChC,CACA,CASA,WAAAK,CAAAC,EAAAC,GACA,aAAAD,EAAAE,SAAA,CACA,MAAAC,SAAuBA,GAAUtB,QAAA,oBACjCuB,QAAAD,EAAAH,EAAAP,UACAY,EAAA,IAAAC,KAAA,CAAAF,IACA,WAAAG,SAAAF,EAAA,CACAG,OAAA,IACAC,WAAA,KACAC,QAAA,CACA,kCACA,iBAAAL,EAAAM,KAAAC,aAGA,CAEA,aAAAb,MAAAC,EAAAC,EACA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CACA","sources":["webpack://@internetarchive/bookreader/webpack/bootstrap","webpack://@internetarchive/bookreader/webpack/runtime/global","webpack://@internetarchive/bookreader/./node_modules/@internetarchive/bergamot-translator/worker/translator-worker.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","/**\n * Wrapper around the dirty bits of Bergamot's WASM bindings.\n */\n\n// Global because importScripts is global.\nvar Module = {};\n\n/**\n * node.js compatibility: Fake GlobalWorkerScope that emulates being inside a\n * WebWorker\n */\nif (typeof self === 'undefined') {\n global.Module = Module;\n\n global.self = new class GlobalWorkerScope {\n /** @type {import(\"node:worker_threads\").MessagePort} */\n #port;\n\n constructor() {\n const {parentPort} = require(/* webpackIgnore: true */ 'node:worker_threads');\n this.#port = parentPort;\n }\n\n /**\n * Add event listener to listen for messages posted to the worker.\n * @param {string} eventName\n * @param {(object)} callback\n */\n addEventListener(eventName, callback) {\n this.#port.on(eventName, (data) => callback({data}));\n }\n\n /**\n * Post message outside, to the owner of the Worker.\n * @param {any} message\n */\n postMessage(message) {\n this.#port.postMessage(message);\n }\n\n /**\n * @param {...string} scripts - Paths to scripts to import in that order\n */\n importScripts(...scripts) {\n const {readFileSync} = require(/* webpackIgnore: true */ 'node:fs');\n const {join} = require(/* webpackIgnore: true */ 'node:path');\n for (let pathname of scripts) {\n const script = readFileSync(join(__dirname, pathname), {encoding: 'utf-8'});\n eval.call(global, script);\n }\n }\n\n /**\n * Adds support for local file urls. Assumes anything that doesn't start\n * with \"http\" to be a local path.\n * @param {string} url - path or url\n * @param {object?} options - See `fetch()` options\n * @return {Promise<Response>}\n */\n async fetch(url, options) {\n if (url.protocol === 'file:') {\n const {readFile} = require(/* webpackIgnore: true */ 'node:fs/promises');\n const buffer = await readFile(url.pathname);\n const blob = new Blob([buffer]);\n return new Response(blob, {\n status: 200,\n statusText: 'OK',\n headers: {\n 'Content-Type': 'application/wasm',\n 'Content-Length': blob.size.toString()\n }\n });\n }\n\n return await fetch(url, options);\n }\n\n get location() {\n return new URL(`file://${__filename}`);\n }\n }\n}\n\nclass YAML {\n /**\n * Parses YAML into dictionary. Does not interpret types, all values are a\n * string or a list of strings. No support for objects other than the top\n * level.\n * @param {string} yaml\n * @return {{[string]: string | string[]}}\n */\n static parse(yaml) {\n const out = {};\n\n yaml.split('\\n').reduce((key, line, i) => {\n let match;\n if (match = line.match(/^\\s*-\\s+(.+?)$/)) {\n if (!Array.isArray(out[key]))\n out[key] = out[key].trim() ? [out[key]] : [];\n out[key].push(match[1].trim());\n }\n else if (match = line.match(/^\\s*([A-Za-z0-9_][A-Za-z0-9_-]*):\\s*(.*)$/)) {\n key = match[1];\n out[key] = match[2].trim();\n }\n else if (!line.trim()) {\n // whitespace, ignore\n }\n else {\n throw Error(`Could not parse line ${i+1}: \"${line}\"`);\n }\n return key;\n }, null);\n\n return out;\n }\n\n /**\n * Turns an object into a YAML string. No support for objects, only simple\n * types and lists of simple types.\n * @param {{[string]: string | number | boolean | string[]}} data\n * @return {string}\n */\n static stringify(data) {\n return Object.entries(data).reduce((str, [key, value]) => {\n let valstr = '';\n if (Array.isArray(value))\n valstr = value.map(val => `\\n - ${val}`).join('');\n else if (typeof value === 'number' || typeof value === 'boolean' || value.match(/^\\d*(\\.\\d+)?$/))\n valstr = `${value}`;\n else\n valstr = `${value}`; // Quote?\n\n return `${str}${key}: ${valstr}\\n`;\n }, '');\n }\n}\n\n/**\n * Wrapper around the bergamot-translator exported module that hides the need\n * of working with C++ style data structures and does model management.\n */\nclass BergamotTranslatorWorker {\n /**\n * Map of expected symbol -> name of fallback symbol for functions that can\n * be swizzled for a faster implementation. Firefox Nightly makes use of\n * this.\n */\n static GEMM_TO_FALLBACK_FUNCTIONS_MAP = {\n 'int8_prepare_a': 'int8PrepareAFallback',\n 'int8_prepare_b': 'int8PrepareBFallback',\n 'int8_prepare_b_from_transposed': 'int8PrepareBFromTransposedFallback',\n 'int8_prepare_b_from_quantized_transposed': 'int8PrepareBFromQuantizedTransposedFallback',\n 'int8_prepare_bias': 'int8PrepareBiasFallback',\n 'int8_multiply_and_add_bias': 'int8MultiplyAndAddBiasFallback',\n 'int8_select_columns_of_b': 'int8SelectColumnsOfBFallback'\n };\n\n /**\n * Name of module exported by Firefox Nightly that exports an optimised\n * implementation of the symbols mentioned above.\n */\n static NATIVE_INT_GEMM = 'mozIntGemm';\n\n /**\n * Empty because we can't do async constructors yet. It is the\n * responsibility of whoever owns this WebWorker to call `initialize()`.\n */\n constructor(options) {}\n\n /**\n * Instantiates a new translation worker with optional options object.\n * If this call succeeds, the WASM runtime is loaded and ready.\n * \n * Available options are:\n * useNativeIntGemm: {true | false} defaults to false. If true, it will\n * attempt to link to the intgemm module available in\n * Firefox Nightly which makes translations much faster.\n * cacheSize: {Number} defaults to 0 which disables translation\n * cache entirely. Note that this is a theoretical\n * upper bound. In practice it will use about 1/3th of\n * the cache specified here. 2^14 is not a bad starting\n * value.\n * @param {{useNativeIntGemm: boolean, cacheSize: number}} options\n */\n async initialize(options) {\n this.options = options || {};\n this.models = new Map(); // Map<str,Promise<TranslationModel>>\n this.module = await this.loadModule();\n this.service = await this.loadTranslationService();\n }\n\n /**\n * Tries to load native IntGEMM module for bergamot-translator. If that\n * fails because it or any of the expected functions is not available, it\n * falls back to using the naive implementations that come with the wasm\n * binary itself through `linkFallbackIntGemm()`.\n * @param {{env: {memory: WebAssembly.Memory}}} info\n * @return {{[method:string]: (...any) => any}}\n */\n linkNativeIntGemm(info) {\n if (!WebAssembly['mozIntGemm']) {\n console.warn('Native gemm requested but not available, falling back to embedded gemm');\n return this.linkFallbackIntGemm(info);\n }\n\n const instance = new WebAssembly.Instance(WebAssembly['mozIntGemm'](), {\n '': {memory: info['env']['memory']}\n });\n\n if (!Array.from(Object.keys(BergamotTranslatorWorker.GEMM_TO_FALLBACK_FUNCTIONS_MAP)).every(fun => instance.exports[fun])) {\n console.warn('Native gemm is missing expected functions, falling back to embedded gemm');\n return this.linkFallbackIntGemm(info);\n }\n\n return instance.exports;\n }\n\n /**\n * Links intgemm functions that are already available in the wasm binary,\n * but just exports them under the name that is expected by\n * bergamot-translator.\n * @param {{env: {memory: WebAssembly.Memory}}} info\n * @return {{[method:string]: (...any) => any}}\n */\n linkFallbackIntGemm(info) {\n const mapping = Object.entries(BergamotTranslatorWorker.GEMM_TO_FALLBACK_FUNCTIONS_MAP).map(([key, name]) => {\n return [key, (...args) => Module['asm'][name](...args)]\n });\n\n return Object.fromEntries(mapping);\n }\n\n /**\n * Internal method. Reads and instantiates the WASM binary. Returns a\n * promise for the exported Module object that contains all the classes\n * and functions exported by bergamot-translator.\n * @return {Promise<BergamotTranslator>}\n */\n loadModule() {\n return new Promise(async (resolve, reject) => {\n try {\n const response = await self.fetch(new URL('./bergamot-translator-worker.wasm', self.location));\n\n Object.assign(Module, {\n instantiateWasm: (info, accept) => {\n try {\n WebAssembly.instantiateStreaming(response, {\n ...info,\n 'wasm_gemm': this.options.useNativeIntGemm\n ? this.linkNativeIntGemm(info)\n : this.linkFallbackIntGemm(info)\n }).then(({instance}) => accept(instance)).catch(reject);\n } catch (err) {\n reject(err);\n }\n return {};\n },\n onRuntimeInitialized: () => {\n resolve(Module);\n }\n });\n\n // Emscripten glue code. Webpack et al. should not mangle the `Module` property name!\n self.Module = Module;\n self.importScripts('bergamot-translator-worker.js');\n } catch (err) {\n reject(err);\n }\n });\n }\n\n /**\n * Internal method. Instantiates a BlockingService()\n * @return {BergamotTranslator.BlockingService}\n */\n loadTranslationService() {\n return new this.module.BlockingService({\n cacheSize: Math.max(this.options.cacheSize || 0, 0)\n });\n }\n\n /**\n * Returns whether a model has already been loaded in this worker. Marked\n * async because the message passing interface we use expects async methods.\n * @param {{from:string, to:string}}\n * @return boolean\n */ \n hasTranslationModel({from,to}) {\n const key = JSON.stringify({from,to});\n return this.models.has(key);\n }\n\n /**\n * Loads a translation model from a set of file buffers. After this, the\n * model is available to translate with and `hasTranslationModel()` will\n * return true for this pair.\n * @param {{from:string, to:string}}\n * @param {{\n * model: ArrayBuffer,\n * shortlist: ArrayBuffer,\n * vocabs: ArrayBuffer[],\n * qualityModel: ArrayBuffer?,\n * config?: {\n * [key:string]: string\n * }\n * }} buffers\n */ \n loadTranslationModel({from, to}, buffers) {\n // This because service_bindings.cpp:prepareVocabsSmartMemories :(\n const uniqueVocabs = buffers.vocabs.filter((vocab, index, vocabs) => {\n return !vocabs.slice(0, index).includes(vocab);\n });\n\n const [modelMemory, shortlistMemory, qualityModel, ...vocabMemory] = [\n this.prepareAlignedMemoryFromBuffer(buffers.model, 256),\n this.prepareAlignedMemoryFromBuffer(buffers.shortlist, 64),\n buffers.qualityModel // optional quality model\n ? this.prepareAlignedMemoryFromBuffer(buffers.qualityModel, 64)\n : null,\n ...uniqueVocabs.map(vocab => this.prepareAlignedMemoryFromBuffer(vocab, 64))\n ];\n\n const vocabs = new this.module.AlignedMemoryList();\n vocabMemory.forEach(vocab => vocabs.push_back(vocab));\n\n // Defaults\n let modelConfig = YAML.parse(`\n beam-size: 1\n normalize: 1.0\n word-penalty: 0\n cpu-threads: 0\n gemm-precision: int8shiftAlphaAll\n skip-cost: true\n `);\n\n if (buffers.config)\n Object.assign(modelConfig, buffers.config);\n\n // WASM marian is only compiled with support for shiftedAll.\n if (modelConfig['gemm-precision'] === 'int8')\n modelConfig['gemm-precision'] = 'int8shiftAll';\n\n // Override these\n Object.assign(modelConfig, YAML.parse(`\n alignment: soft\n quiet: true\n quiet-translation: true\n max-length-break: 128\n mini-batch-words: 1024\n workspace: 128\n max-length-factor: 2.0\n `));\n\n const key = JSON.stringify({from,to});\n this.models.set(key, new this.module.TranslationModel(YAML.stringify(modelConfig), modelMemory, shortlistMemory, vocabs, qualityModel));\n }\n\n /**\n * Frees up memory used by old translation model. Does nothing if model is\n * already deleted.\n * @param {{from:string, to:string}}\n */\n freeTranslationModel({from, to}) {\n const key = JSON.stringify({from,to});\n \n if (!this.models.has(key))\n return;\n \n const model = this.models.get(key);\n this.models.delete(key);\n\n model.delete();\n }\n\n /**\n * Internal function. Copies the data from an ArrayBuffer into memory that\n * can be used inside the WASM vm by Marian.\n * @param {{ArrayBuffer}} buffer\n * @param {number} alignmentSize\n * @return {BergamotTranslator.AlignedMemory}\n */\n prepareAlignedMemoryFromBuffer(buffer, alignmentSize) {\n const bytes = new Int8Array(buffer);\n const memory = new this.module.AlignedMemory(bytes.byteLength, alignmentSize);\n memory.getByteArrayView().set(bytes);\n return memory;\n }\n\n /**\n * Public. Does actual translation work. You have to make sure that the\n * models necessary for translating text are already loaded before calling\n * this method. Returns a promise with translation responses.\n * @param {{models: {from:string, to:string}[], texts: {text: string, html: boolean}[]}}\n * @return {Promise<{target: {text: string}}[]>}\n */\n translate({models, texts}) {\n // Convert texts array into a std::vector<std::string>.\n let input = new this.module.VectorString();\n texts.forEach(({text}) => input.push_back(text));\n\n // Extracts the texts[].html options into ResponseOption objects\n let options = new this.module.VectorResponseOptions();\n texts.forEach(({html, qualityScores}) => options.push_back({alignment: false, html, qualityScores}));\n\n // Turn our model names into a list of TranslationModel pointers\n const translationModels = models.map(({from,to}) => {\n const key = JSON.stringify({from,to});\n return this.models.get(key);\n });\n\n // translate the input, which is a vector<String>; the result is a vector<Response>\n const responses = models.length > 1\n ? this.service.translateViaPivoting(...translationModels, input, options)\n : this.service.translate(...translationModels, input, options);\n \n input.delete();\n options.delete();\n\n // Convert the Response WASM wrappers into native JavaScript types we\n // can send over the 'wire' (message passing) in the same format as we\n // use in bergamot-translator.\n const translations = texts.map((_, i) => ({\n target: {\n text: responses.get(i).getTranslatedText()\n }\n }));\n\n responses.delete();\n\n return translations;\n }\n}\n\n/**\n * Because you can't put an Error object in a message. But you can post a\n * generic object!\n * @param {Error} error\n * @return {{\n * name: string?,\n * message: string?,\n * stack: string?\n * }}\n */\nfunction cloneError(error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack\n };\n}\n\n// (Constructor doesn't really do anything, we need to call `initialize()`\n// first before using it. That happens from outside the worker.)\nconst worker = new BergamotTranslatorWorker();\n\nself.addEventListener('message', async function({data: {id, name, args}}) {\n if (!id)\n console.error('Received message without id', arguments[0]);\n\n try {\n if (typeof worker[name] !== 'function')\n throw TypeError(`worker[${name}] is not a function`);\n\n // Using `Promise.resolve` to await any promises that worker[name]\n // possibly returns.\n const result = await Promise.resolve(Reflect.apply(worker[name], worker, args));\n self.postMessage({id, result});\n } catch (error) {\n self.postMessage({\n id,\n error: cloneError(error)\n })\n }\n});\n"],"names":["__webpack_require__","g","globalThis","this","Function","e","window","Module","self","port","constructor","parentPort","require","addEventListener","eventName","callback","on","data","postMessage","message","importScripts","scripts","readFileSync","join","pathname","script","__dirname","encoding","eval","call","fetch","url","options","protocol","readFile","buffer","blob","Blob","Response","status","statusText","headers","size","toString","location","URL","__filename","YAML","parse","yaml","out","split","reduce","key","line","i","match","Array","isArray","trim","push","Error","stringify","Object","entries","str","value","valstr","map","val","BergamotTranslatorWorker","static","int8_prepare_a","int8_prepare_b","int8_prepare_b_from_transposed","int8_prepare_b_from_quantized_transposed","int8_prepare_bias","int8_multiply_and_add_bias","int8_select_columns_of_b","initialize","models","Map","module","loadModule","service","loadTranslationService","linkNativeIntGemm","info","WebAssembly","console","warn","linkFallbackIntGemm","instance","Instance","memory","from","keys","GEMM_TO_FALLBACK_FUNCTIONS_MAP","every","fun","exports","mapping","name","args","fromEntries","Promise","async","resolve","reject","response","assign","instantiateWasm","accept","instantiateStreaming","wasm_gemm","useNativeIntGemm","then","catch","err","onRuntimeInitialized","BlockingService","cacheSize","Math","max","hasTranslationModel","to","JSON","has","loadTranslationModel","buffers","uniqueVocabs","vocabs","filter","vocab","index","slice","includes","modelMemory","shortlistMemory","qualityModel","vocabMemory","prepareAlignedMemoryFromBuffer","model","shortlist","AlignedMemoryList","forEach","push_back","modelConfig","config","set","TranslationModel","freeTranslationModel","get","delete","alignmentSize","bytes","Int8Array","AlignedMemory","byteLength","getByteArrayView","translate","texts","input","VectorString","text","VectorResponseOptions","html","qualityScores","alignment","translationModels","responses","length","translateViaPivoting","translations","_","target","getTranslatedText","cloneError","error","stack","worker","id","arguments","TypeError","result","Reflect","apply"],"sourceRoot":""}
|