From 380ee1acac1c0b7972d7d423cf804af146dc0edf Mon Sep 17 00:00:00 2001 From: bobzel Date: Sun, 10 Dec 2023 20:19:27 -0500 Subject: massive changes to use mobx 6 which means not accessing props directly in @computed functions. --- src/client/views/pdf/PDFViewer.tsx | 151 ++++++++++++++++++++----------------- 1 file changed, 81 insertions(+), 70 deletions(-) (limited to 'src/client/views/pdf/PDFViewer.tsx') diff --git a/src/client/views/pdf/PDFViewer.tsx b/src/client/views/pdf/PDFViewer.tsx index b2373b190..62df77c0a 100644 --- a/src/client/views/pdf/PDFViewer.tsx +++ b/src/client/views/pdf/PDFViewer.tsx @@ -1,4 +1,4 @@ -import { action, computed, IReactionDisposer, observable, ObservableMap, reaction, runInAction } from 'mobx'; +import { action, computed, IReactionDisposer, makeObservable, observable, ObservableMap, reaction, runInAction } from 'mobx'; import { observer } from 'mobx-react'; import * as Pdfjs from 'pdfjs-dist'; import 'pdfjs-dist/web/pdf_viewer.css'; @@ -8,7 +8,7 @@ import { Id } from '../../../fields/FieldSymbols'; import { InkTool } from '../../../fields/InkField'; import { Cast, NumCast, StrCast } from '../../../fields/Types'; import { TraceMobx } from '../../../fields/util'; -import { addStyleSheet, addStyleSheetRule, clearStyleSheetRules, emptyFunction, returnAll, returnFalse, returnNone, returnZero, smoothScroll, Utils } from '../../../Utils'; +import { addStyleSheet, addStyleSheetRule, clearStyleSheetRules, copyProps, emptyFunction, returnAll, returnFalse, returnNone, returnZero, smoothScroll, Utils } from '../../../Utils'; import { DocUtils } from '../../documents/Documents'; import { SelectionManager } from '../../util/SelectionManager'; import { SnappingManager } from '../../util/SnappingManager'; @@ -58,6 +58,17 @@ export class PDFViewer extends React.Component { @observable private _showWaiting = true; @observable private Index: number = -1; + _prevProps: IViewerProps; + @observable _props: IViewerProps; + constructor(props: IViewerProps) { + super(props); + this._prevProps = this._props = props; + makeObservable(this); + } + componentDidUpdate() { + copyProps(this); + } + private _pdfViewer: any; private _styleRule: any; // stylesheet rule for making hyperlinks clickable private _retries = 0; // number of times tried to create the PDF viewer @@ -84,7 +95,7 @@ export class PDFViewer extends React.Component { @observable isAnnotating = false; // key where data is stored @computed get allAnnotations() { - return DocUtils.FilterDocs(DocListCast(this.props.dataDoc[this.props.fieldKey + '_annotations']), this.props.childFilters(), this.props.childFiltersByRanges()); + return DocUtils.FilterDocs(DocListCast(this._props.dataDoc[this._props.fieldKey + '_annotations']), this._props.childFilters(), this._props.childFiltersByRanges()); } @computed get inlineTextAnnotations() { return this.allAnnotations.filter(a => a.text_inlineAnnotations); @@ -96,22 +107,22 @@ export class PDFViewer extends React.Component { this._mainCont.current?.addEventListener('scroll', e => ((e.target as any).scrollLeft = 0)); this._disposers.layout_autoHeight = reaction( - () => this.props.layoutDoc._layout_autoHeight, + () => this._props.layoutDoc._layout_autoHeight, layout_autoHeight => { if (layout_autoHeight) { - this.props.layoutDoc._nativeHeight = NumCast(this.props.Document[this.props.fieldKey + '_nativeHeight']); - this.props.setHeight?.(NumCast(this.props.Document[this.props.fieldKey + '_nativeHeight']) * (this.props.NativeDimScaling?.() || 1)); + this._props.layoutDoc._nativeHeight = NumCast(this._props.Document[this._props.fieldKey + '_nativeHeight']); + this._props.setHeight?.(NumCast(this._props.Document[this._props.fieldKey + '_nativeHeight']) * (this._props.NativeDimScaling?.() || 1)); } } ); this._disposers.selected = reaction( - () => this.props.isSelected(), + () => this._props.isSelected(), selected => SelectionManager.Views().length === 1 && this.setupPdfJsViewer(), { fireImmediately: true } ); this._disposers.curPage = reaction( - () => Cast(this.props.Document._layout_curPage, 'number', null), + () => Cast(this._props.Document._layout_curPage, 'number', null), page => page !== undefined && page !== this._pdfViewer?.currentPageNumber && this.gotoPage(page), { fireImmediately: true } ); @@ -123,7 +134,7 @@ export class PDFViewer extends React.Component { }; copy = (e: ClipboardEvent) => { - if (this.props.isContentActive() && e.clipboardData) { + if (this._props.isContentActive() && e.clipboardData) { e.clipboardData.setData('text/plain', this._selectionText); const anchor = this._getAnchor(undefined, false); if (anchor) { @@ -139,18 +150,18 @@ export class PDFViewer extends React.Component { @action initialLoad = async () => { if (this._pageSizes.length === 0) { - this._pageSizes = Array<{ width: number; height: number }>(this.props.pdf.numPages); + this._pageSizes = Array<{ width: number; height: number }>(this._props.pdf.numPages); await Promise.all( this._pageSizes.map((val, i) => - this.props.pdf.getPage(i + 1).then( + this._props.pdf.getPage(i + 1).then( action((page: Pdfjs.PDFPageProxy) => { const page0or180 = page.rotate === 0 || page.rotate === 180; this._pageSizes.splice(i, 1, { width: page.view[page0or180 ? 2 : 3] - page.view[page0or180 ? 0 : 1], height: page.view[page0or180 ? 3 : 2] - page.view[page0or180 ? 1 : 0], }); - if (i === this.props.pdf.numPages - 1) { - this.props.loaded?.(page.view[page0or180 ? 2 : 3] - page.view[page0or180 ? 0 : 1], page.view[page0or180 ? 3 : 2] - page.view[page0or180 ? 1 : 0], this.props.pdf.numPages); + if (i === this._props.pdf.numPages - 1) { + this._props.loaded?.(page.view[page0or180 ? 2 : 3] - page.view[page0or180 ? 0 : 1], page.view[page0or180 ? 3 : 2] - page.view[page0or180 ? 1 : 0], this._props.pdf.numPages); } }) ) @@ -167,27 +178,27 @@ export class PDFViewer extends React.Component { scrollFocus = (doc: Doc, scrollTop: number, options: DocFocusOptions) => { const mainCont = this._mainCont.current; let focusSpeed: Opt; - if (doc !== this.props.Document && mainCont) { - const windowHeight = this.props.PanelHeight() / (this.props.NativeDimScaling?.() || 1); - const scrollTo = Utils.scrollIntoView(scrollTop, doc[Height](), NumCast(this.props.layoutDoc._layout_scrollTop), windowHeight, windowHeight * 0.1, this._scrollHeight); - if (scrollTo !== undefined && scrollTo !== this.props.layoutDoc._layout_scrollTop) { + if (doc !== this._props.Document && mainCont) { + const windowHeight = this._props.PanelHeight() / (this._props.NativeDimScaling?.() || 1); + const scrollTo = Utils.scrollIntoView(scrollTop, doc[Height](), NumCast(this._props.layoutDoc._layout_scrollTop), windowHeight, windowHeight * 0.1, this._scrollHeight); + if (scrollTo !== undefined && scrollTo !== this._props.layoutDoc._layout_scrollTop) { if (!this._pdfViewer) this._initialScroll = { loc: scrollTo, easeFunc: options.easeFunc }; else if (!options.instant) this._scrollStopper = smoothScroll((focusSpeed = options.zoomTime ?? 500), mainCont, scrollTo, options.easeFunc, this._scrollStopper); else this._mainCont.current?.scrollTo({ top: Math.abs(scrollTo || 0) }); } } else { - this._initialScroll = { loc: NumCast(this.props.layoutDoc._layout_scrollTop), easeFunc: options.easeFunc }; + this._initialScroll = { loc: NumCast(this._props.layoutDoc._layout_scrollTop), easeFunc: options.easeFunc }; } return focusSpeed; }; - crop = (region: Doc | undefined, addCrop?: boolean) => this.props.crop(region, addCrop); + crop = (region: Doc | undefined, addCrop?: boolean) => this._props.crop(region, addCrop); @action setupPdfJsViewer = async () => { if (this._viewerIsSetup) return; this._viewerIsSetup = true; this._showWaiting = true; - this.props.setPdfViewer(this); + this._props.setPdfViewer(this); await this.initialLoad(); this.createPdfViewer(); @@ -195,22 +206,22 @@ export class PDFViewer extends React.Component { pagesinit = () => { if (this._pdfViewer._setDocumentViewerElement?.offsetParent) { - runInAction(() => (this._pdfViewer.currentScaleValue = this.props.layoutDoc._freeform_scale = 1)); - this.gotoPage(NumCast(this.props.Document._layout_curPage, 1)); + runInAction(() => (this._pdfViewer.currentScaleValue = this._props.layoutDoc._freeform_scale = 1)); + this.gotoPage(NumCast(this._props.Document._layout_curPage, 1)); } document.removeEventListener('pagesinit', this.pagesinit); var quickScroll: { loc?: string; easeFunc?: 'ease' | 'linear' } | undefined = { loc: this._initialScroll ? this._initialScroll.loc?.toString() : '', easeFunc: this._initialScroll ? this._initialScroll.easeFunc : undefined }; this._disposers.scale = reaction( - () => NumCast(this.props.layoutDoc._freeform_scale, 1), + () => NumCast(this._props.layoutDoc._freeform_scale, 1), scale => (this._pdfViewer.currentScaleValue = scale), { fireImmediately: true } ); this._disposers.scroll = reaction( - () => Math.abs(NumCast(this.props.Document._layout_scrollTop)), + () => Math.abs(NumCast(this._props.Document._layout_scrollTop)), pos => { if (!this._ignoreScroll) { this._showWaiting && this.setupPdfJsViewer(); - const viewTrans = quickScroll?.loc ?? StrCast(this.props.Document._viewTransition); + const viewTrans = quickScroll?.loc ?? StrCast(this._props.Document._viewTransition); const durationMiliStr = viewTrans.match(/([0-9]*)ms/); const durationSecStr = viewTrans.match(/([0-9.]*)s/); const duration = durationMiliStr ? Number(durationMiliStr[1]) : durationSecStr ? Number(durationSecStr[1]) * 1000 : 0; @@ -268,8 +279,8 @@ export class PDFViewer extends React.Component { eventBus, }); pdfLinkService.setViewer(this._pdfViewer); - pdfLinkService.setDocument(this.props.pdf, null); - this._pdfViewer.setDocument(this.props.pdf); + pdfLinkService.setDocument(this._props.pdf, null); + this._pdfViewer.setDocument(this._props.pdf); } @action @@ -303,12 +314,12 @@ export class PDFViewer extends React.Component { if (this._mainCont.current && !this._forcedScroll) { this._ignoreScroll = true; // the pdf scrolled, so we need to tell the Doc to scroll but we don't want the doc to then try to set the PDF scroll pos (which would interfere with the smooth scroll animation) if (!LinkDocPreview.LinkInfo) { - this.props.layoutDoc._layout_scrollTop = this._mainCont.current.scrollTop; + this._props.layoutDoc._layout_scrollTop = this._mainCont.current.scrollTop; } this._ignoreScroll = false; if (this._scrollTimer) clearTimeout(this._scrollTimer); // wait until a scrolling pause, then create an anchor to audio this._scrollTimer = setTimeout(() => { - DocUtils.MakeLinkToActiveAudio(() => this.props.DocumentView?.().ComponentView?.getAnchor!(true)!, false); + DocUtils.MakeLinkToActiveAudio(() => this._props.DocumentView?.().ComponentView?.getAnchor!(true)!, false); this._scrollTimer = undefined; }, 200); } @@ -358,12 +369,12 @@ export class PDFViewer extends React.Component { // if alt+left click, drag and annotate this._downX = e.clientX; this._downY = e.clientY; - if ((this.props.Document._freeform_scale || 1) !== 1) return; - if ((e.button !== 0 || e.altKey) && this.props.isContentActive(true)) { - this._setPreviewCursor?.(e.clientX, e.clientY, true, false, this.props.Document); + if ((this._props.Document._freeform_scale || 1) !== 1) return; + if ((e.button !== 0 || e.altKey) && this._props.isContentActive(true)) { + this._setPreviewCursor?.(e.clientX, e.clientY, true, false, this._props.Document); } - if (!e.altKey && e.button === 0 && this.props.isContentActive(true) && ![InkTool.Highlighter, InkTool.Pen, InkTool.Write].includes(Doc.ActiveTool)) { - this.props.select(false); + if (!e.altKey && e.button === 0 && this._props.isContentActive(true) && ![InkTool.Highlighter, InkTool.Pen, InkTool.Write].includes(Doc.ActiveTool)) { + this._props.select(false); MarqueeAnnotator.clearAnnotations(this._savedAnnotations); this._marqueeref.current?.onInitiateSelection([e.clientX, e.clientY]); this.isAnnotating = true; @@ -393,7 +404,7 @@ export class PDFViewer extends React.Component { this._getAnchor = AnchorMenu.Instance?.GetAnchor; this.isAnnotating = false; clearStyleSheetRules(PDFViewer._annotationStyle); - this.props.select(false); + this._props.select(false); document.removeEventListener('pointerup', this.onSelectEnd); const sel = window.getSelection(); @@ -408,21 +419,21 @@ export class PDFViewer extends React.Component { // Changing which document to add the annotation to (the currently selected PDF) GPTPopup.Instance.setSidebarId('data_sidebar'); - GPTPopup.Instance.addDoc = this.props.sidebarAddDoc; + GPTPopup.Instance.addDoc = this._props.sidebarAddDoc; }; @action createTextAnnotation = (sel: Selection, selRange: Range) => { if (this._mainCont.current) { - this._mainCont.current.style.transform = `rotate(${NumCast(this.props.DocumentView!().screenToLocalTransform().RotateDeg)}deg)`; + this._mainCont.current.style.transform = `rotate(${NumCast(this._props.DocumentView!().screenToLocalTransform().RotateDeg)}deg)`; const boundingRect = this._mainCont.current.getBoundingClientRect(); const clientRects = selRange.getClientRects(); for (let i = 0; i < clientRects.length; i++) { const rect = clientRects.item(i); - if (rect && rect?.width && rect.width < this._mainCont.current.clientWidth / this.props.ScreenToLocalTransform().Scale) { + if (rect && rect?.width && rect.width < this._mainCont.current.clientWidth / this._props.ScreenToLocalTransform().Scale) { const scaleX = this._mainCont.current.offsetWidth / boundingRect.width; const scaleY = this._mainCont.current.offsetHeight / boundingRect.height; - const pdfScale = NumCast(this.props.layoutDoc._freeform_scale, 1); + const pdfScale = NumCast(this._props.layoutDoc._freeform_scale, 1); const annoBox = document.createElement('div'); annoBox.className = 'marqueeAnnotator-annotationBox'; // transforms the positions from screen onto the pdf div @@ -451,7 +462,7 @@ export class PDFViewer extends React.Component { onClick = (e: React.MouseEvent) => { this._scrollStopper?.(); if (this._setPreviewCursor && e.button === 0 && Math.abs(e.clientX - this._downX) < Utils.DRAG_THRESHOLD && Math.abs(e.clientY - this._downY) < Utils.DRAG_THRESHOLD) { - this._setPreviewCursor(e.clientX, e.clientY, false, false, this.props.Document); + this._setPreviewCursor(e.clientX, e.clientY, false, false, this._props.Document); } // e.stopPropagation(); // bcz: not sure why this was here. We need to allow the DocumentView to get clicks to process doubleClicks }; @@ -460,48 +471,48 @@ export class PDFViewer extends React.Component { @action onZoomWheel = (e: React.WheelEvent) => { - if (this.props.isContentActive(true)) { + if (this._props.isContentActive(true)) { e.stopPropagation(); if (e.ctrlKey) { const curScale = Number(this._pdfViewer.currentScaleValue); this._pdfViewer.currentScaleValue = Math.max(1, Math.min(10, curScale - (curScale * e.deltaY) / 1000)); - this.props.layoutDoc._freeform_scale = Number(this._pdfViewer.currentScaleValue); + this._props.layoutDoc._freeform_scale = Number(this._pdfViewer.currentScaleValue); } } }; pointerEvents = () => - this.props.isContentActive() && !MarqueeOptionsMenu.Instance.isShown() + this._props.isContentActive() && !MarqueeOptionsMenu.Instance.isShown() ? 'all' // : 'none'; @computed get annotationLayer() { const inlineAnnos = this.inlineTextAnnotations.sort((a, b) => NumCast(a.y) - NumCast(b.y)).filter(anno => !anno.hidden); return ( -
+
{inlineAnnos.map(anno => ( - + ))}
); } getScrollHeight = () => this._scrollHeight; - scrollXf = () => (this._mainCont.current ? this.props.ScreenToLocalTransform().translate(0, NumCast(this.props.layoutDoc._layout_scrollTop)) : this.props.ScreenToLocalTransform()); - overlayTransform = () => this.scrollXf().scale(1 / NumCast(this.props.layoutDoc._freeform_scale, 1)); - panelWidth = () => this.props.PanelWidth() / (this.props.NativeDimScaling?.() || 1); - panelHeight = () => this.props.PanelHeight() / (this.props.NativeDimScaling?.() || 1); - transparentFilter = () => [...this.props.childFilters(), Utils.TransparentBackgroundFilter]; - opaqueFilter = () => [...this.props.childFilters(), Utils.noDragDocsFilter, ...(SnappingManager.GetCanEmbed() && this.props.isContentActive() ? [] : [Utils.OpaqueBackgroundFilter])]; + scrollXf = () => (this._mainCont.current ? this._props.ScreenToLocalTransform().translate(0, NumCast(this._props.layoutDoc._layout_scrollTop)) : this._props.ScreenToLocalTransform()); + overlayTransform = () => this.scrollXf().scale(1 / NumCast(this._props.layoutDoc._freeform_scale, 1)); + panelWidth = () => this._props.PanelWidth() / (this._props.NativeDimScaling?.() || 1); + panelHeight = () => this._props.PanelHeight() / (this._props.NativeDimScaling?.() || 1); + transparentFilter = () => [...this._props.childFilters(), Utils.TransparentBackgroundFilter]; + opaqueFilter = () => [...this._props.childFilters(), Utils.noDragDocsFilter, ...(SnappingManager.GetCanEmbed() && this._props.isContentActive() ? [] : [Utils.OpaqueBackgroundFilter])]; childStyleProvider = (doc: Doc | undefined, props: Opt, property: string): any => { if (doc instanceof Doc && property === StyleProp.PointerEvents) { - if (this.inlineTextAnnotations.includes(doc) || this.props.isContentActive() === false) return 'none'; + if (this.inlineTextAnnotations.includes(doc) || this._props.isContentActive() === false) return 'none'; const isInk = doc.layout_isSvg && !props?.LayoutTemplateString; return isInk ? 'visiblePainted' : 'all'; } - return this.props.styleProvider?.(doc, props, property); + return this._props.styleProvider?.(doc, props, property); }; - childPointerEvents = () => (this.props.isContentActive() !== false ? 'all' : 'none'); + childPointerEvents = () => (this._props.isContentActive() !== false ? 'all' : 'none'); renderAnnotations = (childFilters: () => string[], mixBlendMode?: any, display?: string) => (
{ pointerEvents: Doc.ActiveTool !== InkTool.None ? 'all' : undefined, }}> {
); @computed get overlayTransparentAnnotations() { - const transparentChildren = DocUtils.FilterDocs(DocListCast(this.props.dataDoc[this.props.fieldKey + '_annotations']), this.transparentFilter(), []); - return !transparentChildren.length ? null : this.renderAnnotations(this.transparentFilter, 'multiply', SnappingManager.GetCanEmbed() && this.props.isContentActive() ? 'none' : undefined); + const transparentChildren = DocUtils.FilterDocs(DocListCast(this._props.dataDoc[this._props.fieldKey + '_annotations']), this.transparentFilter(), []); + return !transparentChildren.length ? null : this.renderAnnotations(this.transparentFilter, 'multiply', SnappingManager.GetCanEmbed() && this._props.isContentActive() ? 'none' : undefined); } @computed get overlayOpaqueAnnotations() { return this.renderAnnotations(this.opaqueFilter, this.allAnnotations.some(anno => anno.mixBlendMode) ? 'hard-light' : undefined); } @computed get overlayLayer() { return ( -
+
{this.overlayTransparentAnnotations} {this.overlayOpaqueAnnotations}
); } @computed get pdfViewerDiv() { - return
; + return
; } savedAnnotations = () => this._savedAnnotations; - addDocumentWrapper = (doc: Doc | Doc[]) => this.props.addDocument!(doc); + addDocumentWrapper = (doc: Doc | Doc[]) => this._props.addDocument!(doc); render() { TraceMobx(); return (
600 ? Doc.NativeHeight(this.props.Document) : `100%`, + overflowX: NumCast(this._props.layoutDoc._freeform_scale, 1) !== 1 ? 'scroll' : undefined, + height: !this._props.Document._layout_fitWidth && window.screen.width > 600 ? Doc.NativeHeight(this._props.Document) : `100%`, }}> {this.pdfViewerDiv} {this.annotationLayer} @@ -576,13 +587,13 @@ export class PDFViewer extends React.Component { {!this._mainCont.current || !this._annotationLayer.current ? null : (