UNPKG

ngx-extended-pdf-viewer

Version:

Embedding PDF files in your Angular application. Highly configurable viewer including the toolbar, sidebar, and all the features you're used to.

21 lines 300 kB
/** * @licstart The following is the entire license notice for the * JavaScript code in this page * * Copyright 2023 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @licend The above is the entire license notice for the * JavaScript code in this page */var t={d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e=globalThis.pdfjsLib={};t.d(e,{AbortException:()=>AbortException,AnnotationEditorLayer:()=>AnnotationEditorLayer,AnnotationEditorParamsType:()=>m,AnnotationEditorType:()=>g,AnnotationEditorUIManager:()=>AnnotationEditorUIManager,AnnotationLayer:()=>AnnotationLayer,AnnotationMode:()=>p,CMapCompressionType:()=>X,ColorPicker:()=>ColorPicker,DOMSVGFactory:()=>DOMSVGFactory,DrawLayer:()=>DrawLayer,FeatureTest:()=>util_FeatureTest,GlobalWorkerOptions:()=>yt,ImageKind:()=>x,InvalidPDFException:()=>InvalidPDFException,MissingPDFException:()=>MissingPDFException,OPS:()=>K,Outliner:()=>Outliner,PDFDataRangeTransport:()=>PDFDataRangeTransport,PDFDateString:()=>PDFDateString,PDFWorker:()=>PDFWorker,PasswordResponses:()=>Y,PermissionFlag:()=>f,PixelsPerInch:()=>PixelsPerInch,PromiseCapability:()=>PromiseCapability,RenderingCancelledException:()=>RenderingCancelledException,UnexpectedResponseException:()=>UnexpectedResponseException,Util:()=>Util,VerbosityLevel:()=>$,XfaLayer:()=>XfaLayer,build:()=>Wt,createValidAbsoluteUrl:()=>createValidAbsoluteUrl,fetchData:()=>fetchData,getDocument:()=>getDocument,getFilenameFromUrl:()=>getFilenameFromUrl,getPdfFilenameFromUrl:()=>getPdfFilenameFromUrl,getXfaPageViewport:()=>getXfaPageViewport,isDataScheme:()=>isDataScheme,isPdfFile:()=>isPdfFile,noContextMenu:()=>noContextMenu,normalizeUnicode:()=>normalizeUnicode,renderTextLayer:()=>renderTextLayer,setLayerDimensions:()=>setLayerDimensions,shadow:()=>shadow,updateTextLayer:()=>updateTextLayer,version:()=>jt});const i=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),s=[1,0,0,1,0,0],n=[.001,0,0,.001,0,0],a=1.35,r=1,o=2,l=4,h=16,d=32,c=64,u=256,p={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},g={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},m={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32},f={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},b=0,v=1,A=2,y=3,w=3,_=4,x={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},E=1,C=2,S=3,T=4,M=5,k=6,P=7,F=8,R=9,D=10,I=11,L=12,O=13,B=14,U=15,z=16,N=17,H=20,V=1,j=2,W=3,q=4,G=5,$={ERRORS:0,WARNINGS:1,INFOS:5},X={NONE:0,BINARY:1},K={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91},Y={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Q=$.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(Q=t)}function getVerbosityLevel(){return Q}function info(t){Q>=$.INFOS&&("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?console.log(`Info: ${t}`):Window&&globalThis.ngxConsole?globalThis.ngxConsole.log(`Info: ${t}`):console.log(`Info: ${t}`))}function warn(t){Q>=$.WARNINGS&&("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?console.log(`Warning: ${t}`):Window&&globalThis.ngxConsole?globalThis.ngxConsole.log(`Warning: ${t}`):console.log(`Warning: ${t}`))}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function createValidAbsoluteUrl(t,e=null,i=null){if(!t)return null;try{if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=function stringToUTF8String(t){return decodeURIComponent(escape(t))}(t)}catch{}}const s=e?new URL(t,e):new URL(t);if(function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":case"capacitor":return!0;default:return!1}}(s))return s}catch{}return null}function shadow(t,e,i,s=!1){Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1});return i}const J=function BaseExceptionClosure(){function BaseException(t,e){this.constructor===BaseException&&unreachable("Cannot initialize BaseException.");this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends J{constructor(t,e){super(t,"PasswordException");this.code=e}}class UnknownErrorException extends J{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends J{constructor(t){super(t,"InvalidPDFException")}}class MissingPDFException extends J{constructor(t){super(t,"MissingPDFException")}}class UnexpectedResponseException extends J{constructor(t,e){super(t,"UnexpectedResponseException");this.status=e}}class FormatError extends J{constructor(t){super(t,"FormatError")}}class AbortException extends J{constructor(t){super(t,"AbortException")}}function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("Invalid argument for bytesToString");const e=t.length,i=8192;if(e<i)return String.fromCharCode.apply(null,t);const s=[];for(let n=0;n<e;n+=i){const a=Math.min(n+i,e),r=t.subarray(n,a);s.push(String.fromCharCode.apply(null,r))}return s.join("")}function stringToBytes(t){"string"!=typeof t&&unreachable("Invalid argument for stringToBytes");const e=t.length,i=new Uint8Array(e);for(let s=0;s<e;++s)i[s]=255&t.charCodeAt(s);return i}function objectFromMap(t){const e=Object.create(null);for(const[i,s]of t)e[i]=s;return e}class util_FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const t=new Uint8Array(4);t[0]=1;return 1===new Uint32Array(t.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?shadow(this,"platform",{isMac:navigator.platform.includes("Mac")}):shadow(this,"platform",{isMac:!1})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const Z=[...Array(256).keys()].map((t=>t.toString(16).padStart(2,"0")));class Util{static makeHexColor(t,e,i){return`#${Z[t]}${Z[e]}${Z[i]}`}static scaleMinMax(t,e){let i;if(t[0]){if(t[0]<0){i=e[0];e[0]=e[1];e[1]=i}e[0]*=t[0];e[1]*=t[0];if(t[3]<0){i=e[2];e[2]=e[3];e[3]=i}e[2]*=t[3];e[3]*=t[3]}else{i=e[0];e[0]=e[2];e[2]=i;i=e[1];e[1]=e[3];e[3]=i;if(t[1]<0){i=e[2];e[2]=e[3];e[3]=i}e[2]*=t[1];e[3]*=t[1];if(t[2]<0){i=e[0];e[0]=e[1];e[1]=i}e[0]*=t[2];e[1]*=t[2]}e[0]+=t[4];e[1]+=t[4];e[2]+=t[5];e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const i=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/i,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/i]}static getAxialAlignedBoundingBox(t,e){const i=this.applyTransform(t,e),s=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],s[0],n[0],a[0]),Math.min(i[1],s[1],n[1],a[1]),Math.max(i[0],s[0],n[0],a[0]),Math.max(i[1],s[1],n[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],i=t[0]*e[0]+t[1]*e[2],s=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(i+a)/2,o=Math.sqrt((i+a)**2-4*(i*a-n*s))/2,l=r+o||1,h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[i,n,s,a]}static bezierBoundingBox(t,e,i,s,n,a,r,o){const l=[],h=[[],[]];let d,c,u,p,g,m,f,b;for(let h=0;h<2;++h){if(0===h){c=6*t-12*i+6*n;d=-3*t+9*i-9*n+3*r;u=3*i-3*t}else{c=6*e-12*s+6*a;d=-3*e+9*s-9*a+3*o;u=3*s-3*e}if(Math.abs(d)<1e-12){if(Math.abs(c)<1e-12)continue;p=-u/c;0<p&&p<1&&l.push(p)}else{f=c*c-4*u*d;b=Math.sqrt(f);if(!(f<0)){g=(-c+b)/(2*d);0<g&&g<1&&l.push(g);m=(-c-b)/(2*d);0<m&&m<1&&l.push(m)}}}let v,A=l.length;const y=A;for(;A--;){p=l[A];v=1-p;h[0][A]=v*v*v*t+3*v*v*p*i+3*v*p*p*n+p*p*p*r;h[1][A]=v*v*v*e+3*v*v*p*s+3*v*p*p*a+p*p*p*o}h[0][y]=t;h[1][y]=e;h[0][y+1]=r;h[1][y+1]=o;h[0].length=h[1].length=y+2;return[Math.min(...h[0]),Math.min(...h[1]),Math.max(...h[0]),Math.max(...h[1])]}}function isArrayBuffer(t){return"object"==typeof t&&void 0!==t?.byteLength}class PromiseCapability{#t=!1;constructor(){this.promise=new Promise(((t,e)=>{this.resolve=e=>{this.#t=!0;t(e)};this.reject=t=>{this.#t=!0;e(t)}}))}get settled(){return this.#t}}let tt=null,et=null;function normalizeUnicode(t){if(!tt){tt=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;et=new Map([["ſt","ſt"]])}return t.replaceAll(tt,((t,e,i)=>e?e.normalize("NFKC"):et.get(i)))}const it="pdfjs_internal_id_";class BaseFilterFactory{constructor(){this.constructor===BaseFilterFactory&&unreachable("Cannot initialize BaseFilterFactory.")}addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addHighlightHCMFilter(t,e,i,s){return"none"}destroy(t=!1){}}class BaseCanvasFactory{constructor(){this.constructor===BaseCanvasFactory&&unreachable("Cannot initialize BaseCanvasFactory.")}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e),s=window.pdfDefaultOptions.activateWillReadFrequentlyFlag?{willReadFrequently:!0}:void 0,n=i.getContext("2d",s);return{canvas:i,context:n}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e;t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0;t.canvas.height=0;t.canvas=null;t.context=null}_createCanvas(t,e){unreachable("Abstract method `_createCanvas` called.")}}class BaseCMapReaderFactory{constructor({baseUrl:t=null,isCompressed:e=!0}){this.constructor===BaseCMapReaderFactory&&unreachable("Cannot initialize BaseCMapReaderFactory.");this.baseUrl=t;this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error('The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.');if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":""),i=this.isCompressed?X.BINARY:X.NONE;return this._fetchData(e,i).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}_fetchData(t,e){unreachable("Abstract method `_fetchData` called.")}}class BaseStandardFontDataFactory{constructor({baseUrl:t=null}){this.constructor===BaseStandardFontDataFactory&&unreachable("Cannot initialize BaseStandardFontDataFactory.");this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error('The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.');if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetchData(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}_fetchData(t){unreachable("Abstract method `_fetchData` called.")}}class BaseSVGFactory{constructor(){this.constructor===BaseSVGFactory&&unreachable("Cannot initialize BaseSVGFactory.")}create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");s.setAttribute("version","1.1");if(!i){s.setAttribute("width",`${t}px`);s.setAttribute("height",`${e}px`)}s.setAttribute("preserveAspectRatio","none");s.setAttribute("viewBox",`0 0 ${t} ${e}`);return s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){unreachable("Abstract method `_createSVG` called.")}}const st="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise(((i,s)=>{const n=new XMLHttpRequest;n.open("GET",t,!0);n.responseType=e;n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE){if(200===n.status||0===n.status){let t;switch(e){case"arraybuffer":case"blob":case"json":t=n.response;break;default:t=n.responseText}if(t){i(t);return}}s(new Error(n.statusText))}};n.send(null)}))}class DOMCMapReaderFactory extends BaseCMapReaderFactory{_fetchData(t,e){return fetchData(t,this.isCompressed?"arraybuffer":"text").then((t=>({cMapData:t instanceof ArrayBuffer?new Uint8Array(t):stringToBytes(t),compressionType:e})))}}class DOMStandardFontDataFactory extends BaseStandardFontDataFactory{_fetchData(t){return fetchData(t,"arraybuffer").then((t=>new Uint8Array(t)))}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(st,t)}}class PageViewport{constructor({viewBox:t,scale:e,rotation:i,offsetX:s=0,offsetY:n=0,dontFlip:a=!1}){this.viewBox=t;this.scale=e;this.rotation=i;this.offsetX=s;this.offsetY=n;const r=(t[2]+t[0])/2,o=(t[3]+t[1])/2;let l,h,d,c,u,p,g,m;(i%=360)<0&&(i+=360);switch(i){case 180:l=-1;h=0;d=0;c=1;break;case 90:l=0;h=1;d=1;c=0;break;case 270:l=0;h=-1;d=-1;c=0;break;case 0:l=1;h=0;d=0;c=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(a){d=-d;c=-c}if(0===l){u=Math.abs(o-t[1])*e+s;p=Math.abs(r-t[0])*e+n;g=(t[3]-t[1])*e;m=(t[2]-t[0])*e}else{u=Math.abs(r-t[0])*e+s;p=Math.abs(o-t[1])*e+n;g=(t[2]-t[0])*e;m=(t[3]-t[1])*e}this.transform=[l*e,h*e,d*e,c*e,u-l*e*r-d*e*o,p-h*e*r-c*e*o];this.width=g;this.height=m}get rawDims(){const{viewBox:t}=this;return shadow(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){return Util.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=Util.applyTransform([t[0],t[1]],this.transform),i=Util.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){return Util.applyInverseTransform([t,e],this.transform)}}class RenderingCancelledException extends J{constructor(t,e=0){super(t,"RenderingCancelledException");this.extraDelay=e}}function isDataScheme(t){const e=t.length;let i=0;for(;i<e&&""===t[i].trim();)i++;return"data:"===t.substring(i,i+5).toLowerCase()}function isPdfFile(t){return"string"==typeof t&&/\.pdf$/i.test(t)}function getFilenameFromUrl(t,e=!1){e||([t]=t.split(/[#?]/,1));return t.substring(t.lastIndexOf("/")+1)}function getPdfFilenameFromUrl(t,e="document.pdf"){if(window.PDFViewerApplication.appConfig.filenameForDownload)return window.PDFViewerApplication.appConfig.filenameForDownload;if("string"!=typeof t)return e;if(isDataScheme(t)){warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');return e}const i=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,s=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(t);let n=i.exec(s[1])||i.exec(s[2])||i.exec(s[3]);if(n){n=n[0];if(n.includes("%"))try{n=i.exec(decodeURIComponent(n))[0]}catch{}}return n||e}class StatTimer{started=Object.create(null);times=[];time(t){t in this.started&&warn(`Timer is already running for ${t}`);this.started[t]=Date.now()}timeEnd(t){t in this.started||warn(`Timer has not been started for ${t}`);this.times.push({name:t,start:this.started[t],end:Date.now()});delete this.started[t]}toString(){const t=[];let e=0;for(const{name:t}of this.times)e=Math.max(t.length,e);for(const{name:i,start:s,end:n}of this.times)t.push(`${i.padEnd(e)} ${n-s}ms\n`);return t.join("")}}function isValidFetchUrl(t,e){try{const{protocol:i}=e?new URL(t,e):new URL(t);return"http:"===i||"https:"===i||"capacitor:"===i}catch{return!1}}function noContextMenu(t){t.preventDefault()}let nt;class PDFDateString{static toDateObject(t){if(!t||"string"!=typeof t)return null;nt||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=nt.exec(t);if(!e)return null;const i=parseInt(e[1],10);let s=parseInt(e[2],10);s=s>=1&&s<=12?s-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;d=d>=0&&d<=59?d:0;if("-"===l){a+=h;r+=d}else if("+"===l){a-=h;r-=d}return new Date(Date.UTC(i,s,n,a,r,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,a=[0,0,parseInt(s),parseInt(n)];return new PageViewport({viewBox:a,scale:e,rotation:i})}function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}if(t.startsWith("rgb("))return t.slice(4,-1).split(",").map((t=>parseInt(t)));if(t.startsWith("rgba("))return t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3);warn(`Not a valid color format: "${t}"`);return[0,0,0]}function getCurrentTransform(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform();return[e,i,s,n,a,r]}function getCurrentTransformInverse(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,i,s,n,a,r]}function setLayerDimensions(t,e,i=!1,s=!0){if(e instanceof PageViewport){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:a}=t,r=util_FeatureTest.isCSSRoundSupported,o=`var(--scale-factor) * ${s}px`,l=`var(--scale-factor) * ${n}px`,h=r?`round(${o}, 1px)`:`calc(${o})`,d=r?`round(${l}, 1px)`:`calc(${l})`;if(i&&e.rotation%180!=0){a.width=d;a.height=h}else{a.width=h;a.height=d}}s&&t.setAttribute("data-main-rotation",e.rotation)}function bindEvents(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class IdManager{#e=0;getId(){return"pdfjs_internal_editor_"+this.#e++}}class ImageManager{#i=function getUuid(){if("undefined"!=typeof crypto&&"function"==typeof crypto?.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);if("undefined"!=typeof crypto&&"function"==typeof crypto?.getRandomValues)crypto.getRandomValues(t);else for(let e=0;e<32;e++)t[e]=Math.floor(255*Math.random());return bytesToString(t)}();#e=0;#s=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d"),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>';return shadow(this,"_isSVGFittingCanvas",e.decode().then((()=>{t.drawImage(e,0,0,1,1,0,0,1,3);return 0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]})))}async#n(t,e){this.#s||=new Map;let i=this.#s.get(t);if(null===i)return null;if(i?.bitmap){i.refCounter+=1;return i}try{i||={bitmap:null,id:`image_${this.#i}_${this.#e++}`,refCounter:0,isSvg:!1};let t;if("string"==typeof e){i.url=e;t=await fetchData(e,"blob")}else t=i.file=e;if("image/svg+xml"===t.type){const e=ImageManager._isSVGFittingCanvas,s=new FileReader,n=new Image,a=new Promise(((t,a)=>{n.onload=()=>{i.bitmap=n;i.isSvg=!0;t()};s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t};n.onerror=s.onerror=a}));s.readAsDataURL(t);await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){console.error(t);i=null}this.#s.set(t,i);i&&this.#s.set(i.id,i);return i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#n(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#n(t,t)}async getFromId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e)return null;if(e.bitmap){e.refCounter+=1;return e}return e.file?this.getFromFile(e.file):this.getFromUrl(e.url)}getSvgUrl(t){const e=this.#s.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#s||=new Map;const e=this.#s.get(t);if(e){e.refCounter-=1;0===e.refCounter&&(e.bitmap=null)}}isValidId(t){return t.startsWith(`image_${this.#i}_`)}}class CommandManager{#a=[];#r=!1;#o;#l=-1;constructor(t=128){this.#o=t}add({cmd:t,undo:e,mustExec:i,type:s=NaN,overwriteIfSameType:n=!1,keepUndo:a=!1}){i&&t();if(this.#r)return;const r={cmd:t,undo:e,type:s};if(-1===this.#l){this.#a.length>0&&(this.#a.length=0);this.#l=0;this.#a.push(r);return}if(n&&this.#a[this.#l].type===s){a&&(r.undo=this.#a[this.#l].undo);this.#a[this.#l]=r;return}const o=this.#l+1;if(o===this.#o)this.#a.splice(0,1);else{this.#l=o;o<this.#a.length&&this.#a.splice(o)}this.#a.push(r)}undo(){if(-1!==this.#l){this.#r=!0;this.#a[this.#l].undo();this.#r=!1;this.#l-=1}}redo(){if(this.#l<this.#a.length-1){this.#l+=1;this.#r=!0;this.#a[this.#l].cmd();this.#r=!1}}hasSomethingToUndo(){return-1!==this.#l}hasSomethingToRedo(){return this.#l<this.#a.length-1}destroy(){this.#a=null}reset(){this.#a=[];this.#l=-1;this.#r=!1}}class KeyboardManager{constructor(t){this.buffer=[];this.callbacks=new Map;this.allKeys=new Set;const{isMac:e}=util_FeatureTest.platform;for(const[i,s,n={}]of t)for(const t of i){const i=t.startsWith("mac+");if(e&&i){this.callbacks.set(t.slice(4),{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}else if(!e&&!i){this.callbacks.set(t,{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}}}#h(t){t.altKey&&this.buffer.push("alt");t.ctrlKey&&this.buffer.push("ctrl");t.metaKey&&this.buffer.push("meta");t.shiftKey&&this.buffer.push("shift");this.buffer.push(t.key);const e=this.buffer.join("+");this.buffer.length=0;return e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#h(e));if(!i)return;const{callback:s,options:{bubbles:n=!1,args:a=[],checker:r=null}}=i;if(!r||r(t,e)){s.bind(t,...a,e)();if(!n){e.stopPropagation();e.preventDefault()}}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);!function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden";document.body.append(e);for(const i of t.keys()){e.style.color=i;const s=window.getComputedStyle(e).color;t.set(i,getRGB(s))}e.remove()}(t);return shadow(this,"_colors",t)}convert(t){const e=getRGB(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every(((t,i)=>t===e[i])))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#d=null;#c=new Map;#u=new Map;#p=null;#g=null;#m=new CommandManager;#f=0;#b=new Set;#v=null;#A=null;#y=new Set;#w=null;#_=null;#x=null;#E=new IdManager;#C=!1;#S=!1;#T=null;#M=null;#k=g.NONE;#P=new Set;#F=null;#R=this.blur.bind(this);#D=this.focus.bind(this);#I=this.copy.bind(this);#L=this.cut.bind(this);#O=this.paste.bind(this);#B=this.keydown.bind(this);#U=this.onEditingAction.bind(this);#z=this.onPageChanging.bind(this);#N=this.onScaleChanging.bind(this);#H=this.onRotationChanging.bind(this);#V={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1};#j=[0,0];#W=null;#q=null;#G=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,arrowChecker=t=>t.#q.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),textInputChecker=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},e=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:textInputChecker}],[["ctrl+z","mac+meta+z"],t.undo,{checker:textInputChecker}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:textInputChecker}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:textInputChecker}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#q.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:t=>t.#q.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:arrowChecker}]]))}constructor(t,e,i,s,n,a,r){this.#q=t;this.#G=e;this.#p=i;this._eventBus=s;this._eventBus._on("editingaction",this.#U);this._eventBus._on("pagechanging",this.#z);this._eventBus._on("scalechanging",this.#N);this._eventBus._on("rotationchanging",this.#H);this.#g=n.annotationStorage;this.#w=n.filterFactory;this.#F=a;this.#x=r||null;this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0}}destroy(){this.#$();this.#X();this._eventBus._off("editingaction",this.#U);this._eventBus._off("pagechanging",this.#z);this._eventBus._off("scalechanging",this.#N);this._eventBus._off("rotationchanging",this.#H);for(const t of this.#u.values())t.destroy();this.#u.clear();this.#c.clear();this.#y.clear();this.#d=null;this.#P.clear();this.#m.destroy();this.#p?.destroy();if(this.#_){clearTimeout(this.#_);this.#_=null}if(this.#W){clearTimeout(this.#W);this.#W=null}}get hcmFilter(){return shadow(this,"hcmFilter",this.#F?this.#w.addHCMFilter(this.#F.foreground,this.#F.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#q).direction)}get highlightColors(){return shadow(this,"highlightColors",this.#x?new Map(this.#x.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}setMainHighlightColorPicker(t){this.#M=t}editAltText(t){this.#p?.editAltText(this,t)}onPageChanging({pageNumber:t}){this.#f=t-1}focusMainContainer(){this.#q.focus()}findParent(t,e){for(const i of this.#u.values()){const{x:s,y:n,width:a,height:r}=i.div.getBoundingClientRect();if(t>=s&&t<=s+a&&e>=n&&e<=n+r)return i}return null}disableUserSelect(t=!1){this.#G.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#y.add(t)}removeShouldRescale(t){this.#y.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#y)t.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}addToAnnotationStorage(t){t.isEmpty()||!this.#g||this.#g.has(t.id)||this.#g.setValue(t.id,t)}#K(){window.addEventListener("focus",this.#D);window.addEventListener("blur",this.#R)}#X(){window.removeEventListener("focus",this.#D);window.removeEventListener("blur",this.#R)}blur(){if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#P)if(e.div.contains(t)){this.#T=[e,t];e._focusEventsAllowed=!1;break}}focus(){if(!this.#T)return;const[t,e]=this.#T;this.#T=null;e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0});e.focus()}#Y(){window.addEventListener("keydown",this.#B)}#$(){window.removeEventListener("keydown",this.#B)}#Q(){document.addEventListener("copy",this.#I);document.addEventListener("cut",this.#L);document.addEventListener("paste",this.#O)}#J(){document.removeEventListener("copy",this.#I);document.removeEventListener("cut",this.#L);document.removeEventListener("paste",this.#O)}addEditListeners(){this.#Y();this.#Q()}removeEditListeners(){this.#$();this.#J()}copy(t){t.preventDefault();this.#d?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#P){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t);this.delete()}paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#A)if(e.isHandlingMimeForPasting(t.type)){e.paste(t,this.currentLayer);return}const i=e.getData("application/pdfjs");this.addSerializedEditor(i)}addSerializedEditor(t,e=!1,i=!1,s=!0){if(!t)return;try{"string"==typeof t&&(t=JSON.parse(t))}catch(t){warn(`paste: "${t.message}".`);return}if(!Array.isArray(t))return;const n=this.#k;e&&n===g.NONE&&this.updateMode(g.FREETEXT);this.unselectAll();try{const e=[];for(const n of t){const t=void 0===n.pageIndex,a=(s||t?this.currentLayer:this.getLayer(n.pageIndex)).deserialize(n);if(!a)return;a.doNotMove=i;e.push(a)}const cmd=()=>{for(const t of e)this.#Z(t);this.#tt(e)},undo=()=>{for(const t of e)t.remove()};this.addCommands({cmd:cmd,undo:undo,mustExec:!0})}catch(t){warn(`paste: "${t.message}".`)}e&&n!==this.#k&&this.updateMode(n)}keydown(t){this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}onEditingAction(t){["undo","redo","delete","selectAll"].includes(t.name)&&this[t.name]()}#et(t){Object.entries(t).some((([t,e])=>this.#V[t]!==e))&&this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#V,t)})}#it(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#K();this.#Y();this.#Q();this.#et({isEditing:this.#k!==g.NONE,isEmpty:this.#st(),hasSomethingToUndo:this.#m.hasSomethingToUndo(),hasSomethingToRedo:this.#m.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#X();this.#$();this.#J();this.#et({isEditing:!1});this.disableUserSelect(!1)}}registerEditorTypes(t){if(!this.#A){this.#A=t;for(const t of this.#A)this.#it(t.defaultPropertiesToUpdate)}}getId(){return this.#E.getId()}get currentLayer(){return this.#u.get(this.#f)}getLayer(t){return this.#u.get(t)}get currentPageIndex(){return this.#f}addLayer(t){this.#u.set(t.pageIndex,t);this.#C?t.enable():t.disable()}removeLayer(t){this.#u.delete(t.pageIndex)}updateMode(t,e=null,i=!1){if(this.#k!==t){this.#k=t;if(t!==g.NONE){this.setEditingState(!0);this.#nt();this.unselectAll();for(const e of this.#u.values())e.updateMode(t);if(e||!i){if(e)for(const t of this.#c.values())if(t.annotationElementId===e){this.setSelected(t);t.enterInEditMode();break}}else this.addNewEditorFromKeyboard()}else{this.setEditingState(!1);this.#at()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#k&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#A){switch(t){case m.CREATE:this.currentLayer.addNewEditor();return;case m.HIGHLIGHT_DEFAULT_COLOR:this.#M?.updateColor(e)}for(const i of this.#P)i.updateParams(t,e);for(const i of this.#A)i.updateDefaultParams(t,e)}}enableWaiting(t=!1){if(this.#S!==t){this.#S=t;for(const e of this.#u.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}#nt(){if(!this.#C){this.#C=!0;for(const t of this.#u.values())t.enable()}}#at(){this.unselectAll();if(this.#C){this.#C=!1;for(const t of this.#u.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#c.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#c.get(t)}addEditor(t){this.#c.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#_&&clearTimeout(this.#_);this.#_=setTimeout((()=>{this.focusMainContainer();this.#_=null}),0)}this.#c.delete(t.id);this.unselect(t);t.annotationElementId&&this.#b.has(t.annotationElementId)||this.#g?.remove(t.id)}addDeletedAnnotationElement(t){this.#b.add(t.annotationElementId);t.deleted=!0}isDeletedAnnotationElement(t){return this.#b.has(t)}removeDeletedAnnotationElement(t){this.#b.delete(t.annotationElementId);t.deleted=!1}#Z(t){const e=this.#u.get(t.pageIndex);e?e.addOrRebuild(t):this.addEditor(t)}setActiveEditor(t){if(this.#d!==t){this.#d=t;t&&this.#it(t.propertiesToUpdate)}}toggleSelected(t){if(this.#P.has(t)){this.#P.delete(t);t.unselect();this.#et({hasSelectedEditor:this.hasSelection})}else{this.#P.add(t);t.select();this.#it(t.propertiesToUpdate);this.#et({hasSelectedEditor:!0})}}setSelected(t){for(const e of this.#P)e!==t&&e.unselect();this.#P.clear();this.#P.add(t);t.select();this.#it(t.propertiesToUpdate);this.#et({hasSelectedEditor:!0})}isSelected(t){return this.#P.has(t)}get firstSelectedEditor(){return this.#P.values().next().value}unselect(t){t.unselect();this.#P.delete(t);this.#et({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#P.size}get isEnterHandled(){return 1===this.#P.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#m.undo();this.#et({hasSomethingToUndo:this.#m.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#st()})}redo(){this.#m.redo();this.#et({hasSomethingToUndo:!0,hasSomethingToRedo:this.#m.hasSomethingToRedo(),isEmpty:this.#st()})}addCommands(t){this.#m.add(t);this.#et({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#st()})}#st(){if(0===this.#c.size)return!0;if(1===this.#c.size)for(const t of this.#c.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();if(!this.hasSelection)return;const t=[...this.#P];this.addCommands({cmd:()=>{for(const e of t)e.remove()},undo:()=>{for(const e of t)this.#Z(e)},mustExec:!0})}commitOrRemove(){this.#d?.commitOrRemove()}hasSomethingToControl(){return this.#d||this.hasSelection}#tt(t){this.#P.clear();for(const e of t)if(!e.isEmpty()){this.#P.add(e);e.select()}this.#et({hasSelectedEditor:!0})}selectAll(){for(const t of this.#P)t.commit();this.#tt(this.#c.values())}unselectAll(){if(this.#d){this.#d.commitOrRemove();if(this.#k!==g.NONE)return}if(this.hasSelection){for(const t of this.#P)t.unselect();this.#P.clear();this.#et({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){i||this.commitOrRemove();if(!this.hasSelection)return;this.#j[0]+=t;this.#j[1]+=e;const[s,n]=this.#j,a=[...this.#P];this.#W&&clearTimeout(this.#W);this.#W=setTimeout((()=>{this.#W=null;this.#j[0]=this.#j[1]=0;this.addCommands({cmd:()=>{for(const t of a)this.#c.has(t.id)&&t.translateInPage(s,n)},undo:()=>{for(const t of a)this.#c.has(t.id)&&t.translateInPage(-s,-n)},mustExec:!1})}),1e3);for(const i of a)i.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0);this.#v=new Map;for(const t of this.#P)this.#v.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#v)return!1;this.disableUserSelect(!1);const t=this.#v;this.#v=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},a]of t){a.newX=i;a.newY=s;a.newPageIndex=n;e||=i!==a.savedX||s!==a.savedY||n!==a.savedPageIndex}if(!e)return!1;const move=(t,e,i,s)=>{if(this.#c.has(t.id)){const n=this.#u.get(s);if(n)t._setParentAndPosition(n,e,i);else{t.pageIndex=s;t.x=e;t.y=i}}};this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:s,newPageIndex:n,savedX:a,savedY:r,savedPageIndex:o}]of t){move(e,i,s,n);this._eventBus?.dispatch("annotation-editor-event",{source:e,type:"moved",page:n+1,editorType:e.constructor.name,previousValue:{x:a,y:r,page:o+1},value:{x:i,y:s,page:n+1}})}},undo:()=>{for(const[e,{savedX:i,savedY:s,savedPageIndex:n}]of t)move(e,i,s,n)},mustExec:!0});return!0}dragSelectedEditors(t,e){if(this.#v)for(const i of this.#v.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);if(e){e.changeParent(t);e.addOrRebuild(t)}else{this.addEditor(t);this.addToAnnotationStorage(t);t.rebuild()}}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#P.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#d===t}getActive(){return this.#d}getMode(){return this.#k}get imageManager(){return shadow(this,"imageManager",new ImageManager)}removeEditors(t=(()=>!0)){let e=!1;this.#u.forEach((t=>t.setCleaningUp(!0)));this.#c.forEach((i=>{if(i?.serialize()&&t(i.serialize())){i.remove();e=!0}}));this.#u.forEach((t=>t.setCleaningUp(!1)));if(e){this.#et({hasSomethingToUndo:!1,hasSomethingToRedo:!1,isEmpty:this.#st()});this.#m.reset()}}}class AltText{#rt="";#ot=!1;#lt=null;#ht=null;#dt=null;#ct=!1;#ut=null;static _l10nPromise=null;constructor(t){this.#ut=t}static initialize(t){AltText._l10nPromise||=t}async render(){const t=this.#lt=document.createElement("button");t.className="altText";const e=await AltText._l10nPromise.get("pdfjs-editor-alt-text-button-label");t.textContent=e;t.setAttribute("aria-label",e);t.tabIndex="0";t.addEventListener("contextmenu",noContextMenu);t.addEventListener("pointerdown",(t=>t.stopPropagation()));const onClick=t=>{t.preventDefault();this.#ut._uiManager.editAltText(this.#ut)};t.addEventListener("click",onClick,{capture:!0});t.addEventListener("keydown",(e=>{if(e.target===t&&"Enter"===e.key){this.#ct=!0;onClick(e)}}));await this.#pt();return t}finish(){if(this.#lt){this.#lt.focus({focusVisible:this.#ct});this.#ct=!1}}get data(){return{altText:this.#rt,decorative:this.#ot}}set data({altText:t,decorative:e}){if(this.#rt!==t||this.#ot!==e){this.#rt=t;this.#ot=e;this.#pt()}}toggle(t=!1){if(this.#lt){if(!t&&this.#dt){clearTimeout(this.#dt);this.#dt=null}this.#lt.disabled=!t}}destroy(){this.#lt?.remove();this.#lt=null;this.#ht=null}async#pt(){const t=this.#lt;if(!t)return;if(!this.#rt&&!this.#ot){t.classList.remove("done");this.#ht?.remove();return}t.classList.add("done");AltText._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then((e=>{t.setAttribute("aria-label",e)}));let e=this.#ht;if(!e){this.#ht=e=document.createElement("span");e.className="tooltip";e.setAttribute("role","tooltip");const i=e.id=`alt-text-tooltip-${this.#ut.id}`;t.setAttribute("aria-describedby",i);const s=100;t.addEventListener("mouseenter",(()=>{this.#dt=setTimeout((()=>{this.#dt=null;this.#ht.classList.add("show");this.#ut._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",subtype:this.#ut.editorType,data:{action:"alt_text_tooltip"}}})}),s)}));t.addEventListener("mouseleave",(()=>{if(this.#dt){clearTimeout(this.#dt);this.#dt=null}this.#ht?.classList.remove("show")}))}e.innerText=this.#ot?await AltText._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#rt;e.parentNode||t.append(e);const i=this.#ut.getImageForAltText();i?.setAttribute("aria-describedby",e.id)}}class EditorToolbar{#gt=null;#mt=null;#ut;#ft=null;constructor(t){this.#ut=t}render(){const t=this.#gt=document.createElement("div");t.className="editToolbar";t.addEventListener("contextmenu",noContextMenu);t.addEventListener("pointerdown",EditorToolbar.#bt);const e=this.#ft=document.createElement("div");e.className="buttons";t.append(e);const i=this.#ut.toolbarPosition;if(i){const{style:e}=t,s="ltr"===this.#ut._uiManager.direction?1-i[0]:i[0];e.insetInlineEnd=100*s+"%";e.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}this.#vt();return t}static#bt(t){t.stopPropagation()}#At(t){this.#ut._focusEventsAllowed=!1;t.preventDefault();t.stopPropagation()}#yt(t){this.#ut._focusEventsAllowed=!0;t.preventDefault();t.stopPropagation()}#wt(t){t.addEventListener("focusin",this.#At.bind(this),{capture:!0});t.addEventListener("focusout",this.#yt.bind(this),{capture:!0});t.addEventListener("contextmenu",noContextMenu)}hide(){this.#gt.classList.add("hidden");this.#mt?.hideDropdown()}show(){this.#gt.classList.remove("hidden")}#vt(){const t=document.createElement("button");t.className="delete";t.tabIndex=0;t.setAttribute("data-l10n-id",`pdfjs-editor-remove-${this.#ut.editorType}-button`);this.#wt(t);t.addEventListener("click",(t=>{this.#ut._uiManager.delete()}));this.#ft.append(t)}get#_t(){const t=document.createElement("div");t.className="divider";return t}addAltTextButton(t){this.#wt(t);this.#ft.prepend(t,this.#_t)}addColorPicker(t){this.#mt=t;const e=t.renderButton();this.#wt(e);this.#ft.prepend(e,this.#_t)}remove(){this.#gt.remove();this.#mt?.destroy();this.#mt=null}}class AnnotationEditor{#xt=null;#rt=null;#Et=!1;#Ct=null;#St=null;#Tt=this.focusin.bind(this);#Mt=this.focusout.bind(this);#kt=null;#Pt="";#Ft=!1;#Rt=!1;#Dt=!1;#It=!1;#Lt=null;_initialOptions=Object.create(null);_uiManager=null;_focusEventsAllowed=!0;_l10nPromise=null;#Ot=!1;#Bt=AnnotationEditor._zIndex++;doNotMove=!1;static _borderLineWidth=-1;static _colorManager=new ColorManager;static _zIndex=1;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard,e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_resizerKeyboardManager",new KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],AnnotationEditor.prototype._stopResizingWithKeyboard]]))}constructor(t){this.constructor===AnnotationEditor&&unreachable("Cannot initialize AnnotationEditor.");this.parent=t.parent;this.id=t.id;this.width=this.height=null;this.pageIndex=t.parent.pageIndex;this.name=t.name;this.div=null;this._uiManager=t.uiManager;this.annotationElementId=null;this._willKeepAspectRatio=!1;this._initialOptions.isCentered=t.isCentered;this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[i,s];this.pageTranslation=[n,a];const[r,o]=this.parentDimensions;this.x=t.x/r;this.y=t.y/o;this.isAttachedToDOM=!1;this.deleted=!1;this.eventBus=t.eventBus}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return shadow(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId;e.deleted=!0;e._uiManager.addToAnnotationStorage(e)}static initialize(t,e=null){AnnotationEditor._l10nPromise||=new Map(["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-resizer-label-topLeft","pdfjs-editor-resizer-label-topMiddle","pdfjs-editor-resizer-label-topRight","pdfjs-editor-resizer-label-middleRight","pdfjs-editor-resizer-label-bottomRight","pdfjs-editor-resizer-label-bottomMiddle","pdfjs-editor-resizer-label-bottomLeft","pdfjs-editor-resizer-label-middleLeft"].map((e=>[e,t.get(e.replaceAll(/([A-Z])/g,(t=>`-${t.toLowerCase()}`)))])));if(e?.strings)for(const i of e.strings)AnnotationEditor._l10nPromise.set(i,t.get(i));if(-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){unreachable("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#Ot}set _isDraggable(t){this.#Ot=t;this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t);this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2;this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t);this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2;this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#Bt}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else this.#Ut();this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#Ft?this.#Ft=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!e?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage();this._eventBus?.dispatch("annotation-editor-event",{source:this,type:"commit",page:this.pageIndex+1,editorType:this.constructor.name,value:this})}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){const[n,a]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s);this.doNotMove&&([i,s]=[0,0]);this.x=(t+i)/n;this.y=(e+s)/a;this.fixAndSetPosition()}#zt([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s);this.x+=i/t;this.y+=s/e;this.fixAndSetPosition()}translate(t,e){this.#zt(this.parentDimensions,t,e)}translateInPage(t,e){this.#zt(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}drag(t,e){const[i,s]=this.parentDimensions;this.x+=t/i;this.y+=e/s;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x:n,y:a}=this;const[r,o]=this.#Nt();n+=r;a+=o;this.div.style.left=`${(100*n).toFixed(2)}%`;this.div.style.top=`${(100*a).toFixed(2)}%`;this.div.scrollIntoView({block:"nearest"})}#Nt(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}fixAndSetPosition(t=this.rotation){const[e,i]=this.pageDimensions;let{x:s,y:n,width:a,height:r}=this;a*=e;r*=i;s*=e;n*=i;switch(t){case 0:s=Math.max(0,Math.min(e-a,s));n=Math.max(0,Math.min(i-r,n));break;case 90:s=Math.max(0,Math.min(e-r,s));n=Math.min(i,Math.max(a,n));break;case 180:s=Math.min(e,Math.max(a,s));n=Math.min(i,Math.max(r,n));break;case 270:s=Math.min(e,Math.max(r,s));n=Math.max(0,Math.min(i-a,n))}this.x=s/=e;this.y=n/=i;const[o,l]=this.#Nt();s+=o;n+=l;const{style:h}=this.div;h.left=`${(100*s).toFixed(2)}%`;h.top=`${(100*n).toFixed(2)}%`;this.moveInDOM()}static#Ht(t,e,i){switch(i){case 90:retu