@embedpdf-editor/vue3-chapter-viewer 0.2.1 → 0.3.0
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 +221 -395
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +110 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4225 -1466
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),t=require("@embedpdf/core/vue"),a=require("@embedpdf/plugin-annotation"),s=require("@embedpdf/models"),i=require("@embedpdf/core"),o=require("@embedpdf/plugin-document-manager"),r=require("@embedpdf/plugin-interaction-manager"),n=require("@embedpdf/plugin-render"),l=require("@embedpdf/plugin-rotate"),h=require("@embedpdf/plugin-selection"),d=require("@embedpdf/plugin-history"),c=require("@embedpdf/plugin-redaction"),u=require("@embedpdf/plugin-form"),p=require("@embedpdf/plugin-stamp"),g=require("@embedpdf/plugin-signature"),f=require("@embedpdf/plugin-commands"),m=require("@embedpdf/plugin-i18n"),v=require("@embedpdf/plugin-ui"),b=require("@embedpdf/plugin-interaction-manager/vue"),P=require("@embedpdf/plugin-rotate/vue"),w=require("@embedpdf/plugin-selection/vue"),y=require("@embedpdf/plugin-annotation/vue"),C=require("@embedpdf/plugin-redaction/vue"),I=require("@embedpdf/plugin-render/vue"),M=require("@embedpdf/engines/vue"),S={position:"relative",height:"100%",width:"100%"},x={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:0},strikeout:{offsetY:0}},k={highlight:s.PdfAnnotationSubtype.HIGHLIGHT,underline:s.PdfAnnotationSubtype.UNDERLINE,squiggly:s.PdfAnnotationSubtype.SQUIGGLY,strikeout:s.PdfAnnotationSubtype.STRIKEOUT};function L(e,t){return 0===t?e:e.map(e=>({origin:{x:e.origin.x,y:e.origin.y+t},size:{...e.size}}))}function $(e){let t=1/0,a=1/0,s=-1/0,i=-1/0;for(const o of e)t=Math.min(t,o.origin.x),a=Math.min(a,o.origin.y),s=Math.max(s,o.origin.x+o.size.width),i=Math.max(i,o.origin.y+o.size.height);return{origin:{x:t,y:a},size:{width:s-t,height:i-a}}}function T(e,t,i,o,r){const n=i.forDocument(e),l=o.forDocument(e);if(!n||!l)return!1;const h="highlight"===t?"highlight":"underline"===t?"underline":"squiggly"===t?"squiggly":"strikeout",d=i.getTool(h);if(!d)return!1;const c=d.defaults,u={...x[g=t],...null==(f=r)?void 0:f[g]},p=l.getFormattedSelection();var g,f;if(0===p.length)return!1;n.setLocked({type:a.LockModeType.Exclude,categories:["markup","shape"]});for(const a of p){const e=s.uuidV4(),i=u.color??c.color??c.strokeColor,o=u.opacity??c.opacity,r=u.thickness??c.strokeWidth,l=u.offsetY??0,h="underline"===t||"squiggly"===t||"strikeout"===t?L(a.segmentRects,l):a.segmentRects,d="underline"===t||"squiggly"===t||"strikeout"===t?$(h):a.rect;n.createAnnotation(a.pageIndex,{id:e,created:new Date,flags:["print"],type:k[t],..."highlight"===t?{blendMode:s.PdfBlendMode.Multiply}:{},strokeColor:i,opacity:o,...null!=r?{strokeWidth:r}:{},pageIndex:a.pageIndex,rect:d,segmentRects:h})}return l.clear(),!0}function D(e,t){const a=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...a,enabled:!1!==(null==a?void 0:a.enabled)}}function z(e){const t=D(null==e?void 0:e.markup,{enabled:!0}),a=D(null==e?void 0:e.bookmarks,{enabled:!0}),s=D(null==e?void 0:e.notes,{enabled:!0});return{markup:t,bookmarks:a,notes:s,zoom:D(null==e?void 0:e.zoom,{enabled:!0,min:.5,max:3,initial:1}),selectionToolbar:D(void 0===(null==e?void 0:e.selectionToolbar)?!1!==t.enabled||!1!==s.enabled:e.selectionToolbar,{enabled:!0})}}class N{constructor(e){this.cb=e}resolvePassword(e,t){return this.cb(e,t)}}const E="chapter-manager",O={id:E,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}},A={kind:"first-wins"};function G(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let V=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const _=class e extends i.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=i.createBehaviorEmitter(),this.manifestChange$=i.createEmitter(),this.overlapStrategy=A,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??A,this.setManifestInternal(e.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,i]=s.globalPageRange,[o,r]=s.localPageRange;if(e>i&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${i}]`),o>r&&t.push(`${s.chapterId}: invalid localPageRange [${o},${r}]`),i-e!==r-o&&t.push(`${s.chapterId}: page-count mismatch (global ${i-e+1} vs local ${r-o+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>i)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)i.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=A){const a=function(e,t=A){const a=new Map;for(const i of e.chapters){const[e,t]=i.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(i):a.set(s,[i])}}const s=new Map;for(const[i,o]of a)s.set(i,G(i,o,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((e,t)=>e-t),o=[];let r=0;for(const n of i){const e=a.get(n),t=s.get(e);if(!t)continue;const[i]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-i);o.push({globalPageIndex:r++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new V(o)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const n of s){const e=i.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<i.length&&o.add(t)}const r=new Set;for(const n of o)r.add(i[n]);for(const n of r){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=i.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,i),i}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(e){var t;this.updateStatus(e.chapterId,"loading"),this.chapterLastUsed.set(e.chapterId,Date.now());const a=e.encrypted&&(null==(t=this.passwordProvider)?void 0:t.getCachedPassword)?this.passwordProvider.getCachedPassword(e.chapterId):null,s=await this.resolvePdfPayload(e),i=this.documentManager.provides(),o="url"in s?i.openDocumentUrl({documentId:e.chapterId,url:s.url,name:e.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:e.chapterId,buffer:s.buffer,name:e.title,password:a??void 0,autoActivate:!1});return await new Promise(e=>o.wait(()=>e(),()=>e())),this.waitForTerminalStatus(e.chapterId)}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>{"loaded"!==e&&"error"!==e&&"password-required"!==e&&"closed"!==e||(s(),t(e))},s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)});a(this.chapterStatus.get(e)??"idle")})}async handleDocumentError(t,a,i){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const o=this.findChapter(t);if(!o)return;const r=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,r);let n=null;try{n=await this.passwordProvider.resolvePassword(o,r-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};_.id="chapter-manager";let R=_;const B={manifest:O,create:e=>new R(E,e),reducer:e=>e,initialState:{}},U="chapter-scroll",F={id:U,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}},q={kind:"first-wins"};function W(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let H=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const j=class e extends i.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=i.createBehaviorEmitter(),this.manifestChange$=i.createEmitter(),this.overlapStrategy=q,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??q,this.setManifestInternal(e.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,i]=s.globalPageRange,[o,r]=s.localPageRange;if(e>i&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${i}]`),o>r&&t.push(`${s.chapterId}: invalid localPageRange [${o},${r}]`),i-e!==r-o&&t.push(`${s.chapterId}: page-count mismatch (global ${i-e+1} vs local ${r-o+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>i)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)i.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=q){const a=function(e,t=q){const a=new Map;for(const i of e.chapters){const[e,t]=i.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(i):a.set(s,[i])}}const s=new Map;for(const[i,o]of a)s.set(i,W(i,o,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((e,t)=>e-t),o=[];let r=0;for(const n of i){const e=a.get(n),t=s.get(e);if(!t)continue;const[i]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-i);o.push({globalPageIndex:r++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new H(o)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const n of s){const e=i.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<i.length&&o.add(t)}const r=new Set;for(const n of o)r.add(i[n]);for(const n of r){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=i.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,i),i}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(e){var t;this.updateStatus(e.chapterId,"loading"),this.chapterLastUsed.set(e.chapterId,Date.now());const a=e.encrypted&&(null==(t=this.passwordProvider)?void 0:t.getCachedPassword)?this.passwordProvider.getCachedPassword(e.chapterId):null,s=await this.resolvePdfPayload(e),i=this.documentManager.provides(),o="url"in s?i.openDocumentUrl({documentId:e.chapterId,url:s.url,name:e.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:e.chapterId,buffer:s.buffer,name:e.title,password:a??void 0,autoActivate:!1});return await new Promise(e=>o.wait(()=>e(),()=>e())),this.waitForTerminalStatus(e.chapterId)}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>{"loaded"!==e&&"error"!==e&&"password-required"!==e&&"closed"!==e||(s(),t(e))},s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)});a(this.chapterStatus.get(e)??"idle")})}async handleDocumentError(t,a,i){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const o=this.findChapter(t);if(!o)return;const r=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,r);let n=null;try{n=await this.passwordProvider.resolvePassword(o,r-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};j.id="chapter-manager";let Z=j;const Y=class extends i.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=i.createBehaviorEmitter(),this.visibleChange$=i.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Z.id),this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(e.chapterId)&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,a)=>this.scrollToGlobalPdfPoint(e,t,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,a=0;for(let s=0;s<e;s++){const{width:e,height:i}=this.getPageSize(s);this.offsets[s]=t,t+=i+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const i=this.pageSizes.get(t.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),i=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const o=this.getChapterDocumentScale(e),r=[];for(const n of i){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&r.push({localPageIndex:n.localPageIndex,width:e.size.width*o,height:e.size.height*o})}0!==r.length?this.applyChapterPageSizes(e,r):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let i=s;for(;i<e;){const e=this.getPageSize(i),t=this.offsets[i];if(e.height,t>=a)break;i++}const o=[];let r=s,n=-1;for(let l=s;l<i;l++){o.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,i=Math.max(0,Math.min(s,a)-Math.max(e,t));i>n&&(n=i,r=l)}this.currentVisible=o,this.currentGlobalPageIndex=r,this.visibleChange$.emit({visibleGlobalPageIndices:o,currentGlobalPageIndex:r}),this.chapterManager.provides().setVisibleGlobalPages(o),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const i=t+a>>1;this.offsets[i]<=e?(s=i,t=i+1):a=i-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let o=t;o<=s;o++){const e=this.virtualPageMap.atIndex(o);if(!e)continue;const t=this.getPageSize(o),a=!this.isChapterDocumentReady(e.chapterId);i.push({globalPageIndex:o,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[o],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,o=this.virtualPageMap.atIndex(e);if(!o)return void this.scrollToIndex(e,a);const r=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(o.chapterId))?void 0:s.pages[o.localPageIndex];if(!r||!n)return void this.scrollToIndex(e,a);const l=r.height/n.size.height,h=(this.offsets[e]??0)+t*l-i;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};Y.id="chapter-scroll";let K=Y;const X={manifest:F,create:e=>new K(U,e),reducer:e=>e,initialState:{}},Q="note",J={id:Q,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}},ee={kind:"first-wins"};function te(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let ae=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const se=class e extends i.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=i.createBehaviorEmitter(),this.manifestChange$=i.createEmitter(),this.overlapStrategy=ee,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ee,this.setManifestInternal(e.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,i]=s.globalPageRange,[o,r]=s.localPageRange;if(e>i&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${i}]`),o>r&&t.push(`${s.chapterId}: invalid localPageRange [${o},${r}]`),i-e!==r-o&&t.push(`${s.chapterId}: page-count mismatch (global ${i-e+1} vs local ${r-o+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>i)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)i.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=ee){const a=function(e,t=ee){const a=new Map;for(const i of e.chapters){const[e,t]=i.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(i):a.set(s,[i])}}const s=new Map;for(const[i,o]of a)s.set(i,te(i,o,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((e,t)=>e-t),o=[];let r=0;for(const n of i){const e=a.get(n),t=s.get(e);if(!t)continue;const[i]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-i);o.push({globalPageIndex:r++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new ae(o)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const n of s){const e=i.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<i.length&&o.add(t)}const r=new Set;for(const n of o)r.add(i[n]);for(const n of r){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=i.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,i),i}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(e){var t;this.updateStatus(e.chapterId,"loading"),this.chapterLastUsed.set(e.chapterId,Date.now());const a=e.encrypted&&(null==(t=this.passwordProvider)?void 0:t.getCachedPassword)?this.passwordProvider.getCachedPassword(e.chapterId):null,s=await this.resolvePdfPayload(e),i=this.documentManager.provides(),o="url"in s?i.openDocumentUrl({documentId:e.chapterId,url:s.url,name:e.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:e.chapterId,buffer:s.buffer,name:e.title,password:a??void 0,autoActivate:!1});return await new Promise(e=>o.wait(()=>e(),()=>e())),this.waitForTerminalStatus(e.chapterId)}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>{"loaded"!==e&&"error"!==e&&"password-required"!==e&&"closed"!==e||(s(),t(e))},s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)});a(this.chapterStatus.get(e)??"idle")})}async handleDocumentError(t,a,i){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const o=this.findChapter(t);if(!o)return;const r=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,r);let n=null;try{n=await this.passwordProvider.resolvePassword(o,r-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};se.id="chapter-manager";let ie=se;const oe={kind:"first-wins"};function re(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let ne=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const le=class e extends i.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=i.createBehaviorEmitter(),this.manifestChange$=i.createEmitter(),this.overlapStrategy=oe,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??oe,this.setManifestInternal(e.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,i]=s.globalPageRange,[o,r]=s.localPageRange;if(e>i&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${i}]`),o>r&&t.push(`${s.chapterId}: invalid localPageRange [${o},${r}]`),i-e!==r-o&&t.push(`${s.chapterId}: page-count mismatch (global ${i-e+1} vs local ${r-o+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>i)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)i.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=oe){const a=function(e,t=oe){const a=new Map;for(const i of e.chapters){const[e,t]=i.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(i):a.set(s,[i])}}const s=new Map;for(const[i,o]of a)s.set(i,re(i,o,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((e,t)=>e-t),o=[];let r=0;for(const n of i){const e=a.get(n),t=s.get(e);if(!t)continue;const[i]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-i);o.push({globalPageIndex:r++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new ne(o)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const n of s){const e=i.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<i.length&&o.add(t)}const r=new Set;for(const n of o)r.add(i[n]);for(const n of r){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=i.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,i),i}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(e){var t;this.updateStatus(e.chapterId,"loading"),this.chapterLastUsed.set(e.chapterId,Date.now());const a=e.encrypted&&(null==(t=this.passwordProvider)?void 0:t.getCachedPassword)?this.passwordProvider.getCachedPassword(e.chapterId):null,s=await this.resolvePdfPayload(e),i=this.documentManager.provides(),o="url"in s?i.openDocumentUrl({documentId:e.chapterId,url:s.url,name:e.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:e.chapterId,buffer:s.buffer,name:e.title,password:a??void 0,autoActivate:!1});return await new Promise(e=>o.wait(()=>e(),()=>e())),this.waitForTerminalStatus(e.chapterId)}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>{"loaded"!==e&&"error"!==e&&"password-required"!==e&&"closed"!==e||(s(),t(e))},s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)});a(this.chapterStatus.get(e)??"idle")})}async handleDocumentError(t,a,i){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const o=this.findChapter(t);if(!o)return;const r=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,r);let n=null;try{n=await this.passwordProvider.resolvePassword(o,r-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};le.id="chapter-manager";let he=le;const de=class extends i.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=i.createBehaviorEmitter(),this.visibleChange$=i.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(he.id),this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(e.chapterId)&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,a)=>this.scrollToGlobalPdfPoint(e,t,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,a=0;for(let s=0;s<e;s++){const{width:e,height:i}=this.getPageSize(s);this.offsets[s]=t,t+=i+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const i=this.pageSizes.get(t.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),i=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const o=this.getChapterDocumentScale(e),r=[];for(const n of i){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&r.push({localPageIndex:n.localPageIndex,width:e.size.width*o,height:e.size.height*o})}0!==r.length?this.applyChapterPageSizes(e,r):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let i=s;for(;i<e;){const e=this.getPageSize(i),t=this.offsets[i];if(e.height,t>=a)break;i++}const o=[];let r=s,n=-1;for(let l=s;l<i;l++){o.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,i=Math.max(0,Math.min(s,a)-Math.max(e,t));i>n&&(n=i,r=l)}this.currentVisible=o,this.currentGlobalPageIndex=r,this.visibleChange$.emit({visibleGlobalPageIndices:o,currentGlobalPageIndex:r}),this.chapterManager.provides().setVisibleGlobalPages(o),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const i=t+a>>1;this.offsets[i]<=e?(s=i,t=i+1):a=i-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let o=t;o<=s;o++){const e=this.virtualPageMap.atIndex(o);if(!e)continue;const t=this.getPageSize(o),a=!this.isChapterDocumentReady(e.chapterId);i.push({globalPageIndex:o,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[o],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,o=this.virtualPageMap.atIndex(e);if(!o)return void this.scrollToIndex(e,a);const r=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(o.chapterId))?void 0:s.pages[o.localPageIndex];if(!r||!n)return void this.scrollToIndex(e,a);const l=r.height/n.size.height,h=(this.offsets[e]??0)+t*l-i;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};de.id="chapter-scroll";let ce=de;const ue=class e extends i.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=i.createBehaviorEmitter([]),this.noteActivated$=i.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(ce.id),this.chapterManager=this.registry.getPlugin(ie.id),this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(e.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(a=>a.chapterId===e&&a.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,a;const s=this.notes.get(e);s&&(null==(a=(t=this.config.callbacks).onActivateNote)||a.call(t,e,s),this.noteActivated$.emit({noteId:e,anchor:s}))}listAll(){return Array.from(this.notes.values())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:ge(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:t,complete:async e=>{const a={...t,noteId:e};this.registerNote(a)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const a=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let i=null;try{i=await s(a)}catch(r){return this.logger.error(e.id,"OnCreateNote","Callback failed",r),null}if(!i)return null;const o={...a,noteId:i.noteId};return this.registerNote(o),o}async deleteNote(t){var a,s;if(this.notes.has(t)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,t))}catch(i){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",i)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,a){var s,i;const o=this.notes.get(t);if(!o)return;const r={...o,content:a};try{await(null==(i=(s=this.config.callbacks).onUpdateNote)?void 0:i.call(s,r))}catch(n){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",n)}this.notes.set(t,r),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const a=this.notes.get(e);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(t=this.documentManager.provides().getDocument(a.chapterId))?void 0:t.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),a=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{i(),a(null)},2500),i=t.onLayoutChange(t=>{const o=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);o&&(clearTimeout(s),i(),a(o))})})}};ue.id="note";let pe=ue;function ge(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const fe={manifest:J,create:e=>new pe(Q,e),reducer:e=>e,initialState:{}},me="paragraph-bookmark",ve={id:me,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}},be={kind:"first-wins"};function Pe(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let we=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const ye=class e extends i.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=i.createBehaviorEmitter(),this.manifestChange$=i.createEmitter(),this.overlapStrategy=be,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??be,this.setManifestInternal(e.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,i]=s.globalPageRange,[o,r]=s.localPageRange;if(e>i&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${i}]`),o>r&&t.push(`${s.chapterId}: invalid localPageRange [${o},${r}]`),i-e!==r-o&&t.push(`${s.chapterId}: page-count mismatch (global ${i-e+1} vs local ${r-o+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>i)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)i.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=be){const a=function(e,t=be){const a=new Map;for(const i of e.chapters){const[e,t]=i.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(i):a.set(s,[i])}}const s=new Map;for(const[i,o]of a)s.set(i,Pe(i,o,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((e,t)=>e-t),o=[];let r=0;for(const n of i){const e=a.get(n),t=s.get(e);if(!t)continue;const[i]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-i);o.push({globalPageIndex:r++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new we(o)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const n of s){const e=i.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<i.length&&o.add(t)}const r=new Set;for(const n of o)r.add(i[n]);for(const n of r){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=i.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,i),i}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(e){var t;this.updateStatus(e.chapterId,"loading"),this.chapterLastUsed.set(e.chapterId,Date.now());const a=e.encrypted&&(null==(t=this.passwordProvider)?void 0:t.getCachedPassword)?this.passwordProvider.getCachedPassword(e.chapterId):null,s=await this.resolvePdfPayload(e),i=this.documentManager.provides(),o="url"in s?i.openDocumentUrl({documentId:e.chapterId,url:s.url,name:e.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:e.chapterId,buffer:s.buffer,name:e.title,password:a??void 0,autoActivate:!1});return await new Promise(e=>o.wait(()=>e(),()=>e())),this.waitForTerminalStatus(e.chapterId)}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>{"loaded"!==e&&"error"!==e&&"password-required"!==e&&"closed"!==e||(s(),t(e))},s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)});a(this.chapterStatus.get(e)??"idle")})}async handleDocumentError(t,a,i){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const o=this.findChapter(t);if(!o)return;const r=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,r);let n=null;try{n=await this.passwordProvider.resolvePassword(o,r-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};ye.id="chapter-manager";let Ce=ye;const Ie={kind:"first-wins"};function Me(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let Se=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const xe=class e extends i.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=i.createBehaviorEmitter(),this.manifestChange$=i.createEmitter(),this.overlapStrategy=Ie,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Ie,this.setManifestInternal(e.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,i]=s.globalPageRange,[o,r]=s.localPageRange;if(e>i&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${i}]`),o>r&&t.push(`${s.chapterId}: invalid localPageRange [${o},${r}]`),i-e!==r-o&&t.push(`${s.chapterId}: page-count mismatch (global ${i-e+1} vs local ${r-o+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>i)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)i.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Ie){const a=function(e,t=Ie){const a=new Map;for(const i of e.chapters){const[e,t]=i.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(i):a.set(s,[i])}}const s=new Map;for(const[i,o]of a)s.set(i,Me(i,o,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((e,t)=>e-t),o=[];let r=0;for(const n of i){const e=a.get(n),t=s.get(e);if(!t)continue;const[i]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-i);o.push({globalPageIndex:r++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new Se(o)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const n of s){const e=i.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<i.length&&o.add(t)}const r=new Set;for(const n of o)r.add(i[n]);for(const n of r){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=i.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,i),i}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(e){var t;this.updateStatus(e.chapterId,"loading"),this.chapterLastUsed.set(e.chapterId,Date.now());const a=e.encrypted&&(null==(t=this.passwordProvider)?void 0:t.getCachedPassword)?this.passwordProvider.getCachedPassword(e.chapterId):null,s=await this.resolvePdfPayload(e),i=this.documentManager.provides(),o="url"in s?i.openDocumentUrl({documentId:e.chapterId,url:s.url,name:e.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:e.chapterId,buffer:s.buffer,name:e.title,password:a??void 0,autoActivate:!1});return await new Promise(e=>o.wait(()=>e(),()=>e())),this.waitForTerminalStatus(e.chapterId)}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>{"loaded"!==e&&"error"!==e&&"password-required"!==e&&"closed"!==e||(s(),t(e))},s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)});a(this.chapterStatus.get(e)??"idle")})}async handleDocumentError(t,a,i){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const o=this.findChapter(t);if(!o)return;const r=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,r);let n=null;try{n=await this.passwordProvider.resolvePassword(o,r-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};xe.id="chapter-manager";let ke=xe;const Le=class extends i.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=i.createBehaviorEmitter(),this.visibleChange$=i.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ke.id),this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(e.chapterId)&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,a)=>this.scrollToGlobalPdfPoint(e,t,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,a=0;for(let s=0;s<e;s++){const{width:e,height:i}=this.getPageSize(s);this.offsets[s]=t,t+=i+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const i=this.pageSizes.get(t.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),i=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const o=this.getChapterDocumentScale(e),r=[];for(const n of i){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&r.push({localPageIndex:n.localPageIndex,width:e.size.width*o,height:e.size.height*o})}0!==r.length?this.applyChapterPageSizes(e,r):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let i=s;for(;i<e;){const e=this.getPageSize(i),t=this.offsets[i];if(e.height,t>=a)break;i++}const o=[];let r=s,n=-1;for(let l=s;l<i;l++){o.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,i=Math.max(0,Math.min(s,a)-Math.max(e,t));i>n&&(n=i,r=l)}this.currentVisible=o,this.currentGlobalPageIndex=r,this.visibleChange$.emit({visibleGlobalPageIndices:o,currentGlobalPageIndex:r}),this.chapterManager.provides().setVisibleGlobalPages(o),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const i=t+a>>1;this.offsets[i]<=e?(s=i,t=i+1):a=i-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let o=t;o<=s;o++){const e=this.virtualPageMap.atIndex(o);if(!e)continue;const t=this.getPageSize(o),a=!this.isChapterDocumentReady(e.chapterId);i.push({globalPageIndex:o,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[o],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,o=this.virtualPageMap.atIndex(e);if(!o)return void this.scrollToIndex(e,a);const r=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(o.chapterId))?void 0:s.pages[o.localPageIndex];if(!r||!n)return void this.scrollToIndex(e,a);const l=r.height/n.size.height,h=(this.offsets[e]??0)+t*l-i;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};Le.id="chapter-scroll";let $e=Le;function Te(e){if(0===e.length)throw new Error("unionRects: empty rects");let t=1/0,a=1/0,s=-1/0,i=-1/0;for(const o of e)t=Math.min(t,o.origin.x),a=Math.min(a,o.origin.y),s=Math.max(s,o.origin.x+o.size.width),i=Math.max(i,o.origin.y+o.size.height);return{origin:{x:t,y:a},size:{width:s-t,height:i-a}}}function De(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function ze(e,t){const a=e.origin.y,s=e.origin.y+e.size.height,i=t.origin.y,o=t.origin.y+t.size.height,r=Math.max(s,o)-Math.min(a,i);return r<=0?0:Math.max(0,Math.min(s,o)-Math.max(a,i))/r}function Ne(e,t){var a,s;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const i=(null==(a=e.rectsPdfCoord)?void 0:a.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=(null==(s=t.rectsPdfCoord)?void 0:s.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=e.markerAnchor??De(i),n=t.markerAnchor??De(o);if(Math.hypot(r.x-n.x,r.y-n.y)<=6)return!0;for(const l of i)for(const e of o){if(ze(l,e)<.5)continue;const t=Math.max(l.origin.x,e.origin.x);if(Math.min(l.origin.x+l.size.width,e.origin.x+e.size.width)-t>.25*Math.min(l.size.width,e.size.width))return!0}return!1}function Ee(e,t,a,s){const i=a.length>0?a:[];if(0===i.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:e,localPageIndex:t,globalPageIndex:null==s?void 0:s.globalPageIndex,globalPageNumber:null==s?void 0:s.globalPageNumber,rectPdfCoord:Te(i),rectsPdfCoord:i,markerAnchor:De(i)}}const Oe=class e extends i.BasePlugin{constructor(e,t){super(e,t),this.change$=i.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin($e.id),this.chapterManager=this.registry.getPlugin(Ce.id),this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(t){var a;if(this.config=t,null==(a=t.callbacks)?void 0:a.load)try{const e=await t.callbacks.load();for(const t of e)this.entries.set(t.id,t);this.change$.emit(this.list())}catch(s){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:e=>this.addBookmark(e),removeBookmark:e=>this.removeBookmark(e),updateBookmark:(e,t)=>this.updateBookmark(e,t),listBookmarks:()=>this.list(),getBookmark:e=>this.entries.get(e)??null,scrollToBookmark:e=>this.scrollToBookmark(e),requestRemoveBookmark:e=>this.requestRemoveBookmark(e),onBookmarksChange:this.change$.on}}addBookmark(e){for(const s of this.entries.values())if(Ne(s.anchor,e.anchor))return s;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,a),this.notifyAndPersist(),a}removeBookmark(e){var t,a,s;this.entries.delete(e)&&(this.notifyAndPersist(),null==(s=null==(a=null==(t=this.config)?void 0:t.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,e))}async requestRemoveBookmark(t){var a,s;const i=this.entries.get(t);if(!i)return!1;const o=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(o)try{if(!(await o(i)))return!1}catch(r){return this.logger.error(e.id,"RequestRemove","callback failed",r),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const a=this.entries.get(e);a&&(this.entries.set(e,{...a,...t}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((e,t)=>e.createdAt-t.createdAt)}notifyAndPersist(){var t,a;const s=this.list();this.change$.emit(s),(null==(a=null==(t=this.config)?void 0:t.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(t=>this.logger.error(e.id,"Persist","persist callback rejected",t))}async scrollToBookmark(e){const t=this.entries.get(e);if(!t)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(t.anchor.chapterId);let s=t.anchor.globalPageIndex;if(void 0===s){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;s=e.globalPageIndex}const i=function(e){if(e.markerAnchor)return e.markerAnchor.y;const t=e.rectPdfCoord;return t.origin.y+t.size.height}(t.anchor);await async function(e,t,a){e.scrollToGlobalPageIndex(t),await function(e,t,a=2500){const s=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{o(),s(null)},a),o=e.onLayoutChange(e=>{const a=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);a&&(clearTimeout(i),o(),s(a))})})}(e,t),e.scrollToGlobalPdfPoint(t,a,{marginTop:80})}(a,s,i)}};Oe.id="paragraph-bookmark";let Ae=Oe;const Ge={manifest:ve,create:e=>new Ae(me,e),reducer:e=>e,initialState:{}},Ve={"annotation-toolbar":{id:"annotation-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"],show:["overflow-annotation-tools"]},md:{minWidth:640,hide:["overflow-annotation-tools"],show:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"]}}},permanent:!1,categories:["annotation"],items:[{type:"spacer",id:"spacer-3",flex:!0},{type:"group",id:"annotation-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-ink",commandId:"annotation:add-ink",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-ink-highlighter",commandId:"annotation:add-ink-highlighter",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-text",commandId:"annotation:add-text",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"add-insert-text",commandId:"annotation:add-insert-text",variant:"icon",categories:["annotation","annotation-markup","annotation-insert-text"]},{type:"command-button",id:"add-replace-text",commandId:"annotation:add-replace-text",variant:"icon",categories:["annotation","annotation-markup","annotation-replace-text"]},{type:"command-button",id:"add-comment",commandId:"annotation:add-comment",variant:"icon",categories:["annotation","annotation-comment-tool"]},{type:"command-button",id:"add-callout",commandId:"annotation:add-callout",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"overflow-annotation-tools",commandId:"annotation:overflow-tools",variant:"icon",categories:["annotation","annotation-overflow"]},{type:"divider",id:"annotation-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"annotation-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-4",flex:!0}]},"shapes-toolbar":{id:"shapes-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-polygon","add-polyline"],show:["overflow-shapes-tools"]},md:{minWidth:640,hide:["overflow-shapes-tools"],show:["add-polygon","add-polyline"]}}},permanent:!1,categories:["annotation","annotation-shape"],items:[{type:"spacer",id:"spacer-5",flex:!0},{type:"group",id:"shapes-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rectangle",commandId:"annotation:add-rectangle",variant:"icon",categories:["annotation","annotation-shape","annotation-rectangle"]},{type:"command-button",id:"add-circle",commandId:"annotation:add-circle",variant:"icon",categories:["annotation","annotation-shape","annotation-circle"]},{type:"command-button",id:"add-line",commandId:"annotation:add-line",variant:"icon",categories:["annotation","annotation-shape","annotation-line"]},{type:"command-button",id:"add-arrow",commandId:"annotation:add-arrow",variant:"icon",categories:["annotation","annotation-shape","annotation-arrow"]},{type:"command-button",id:"add-polygon",commandId:"annotation:add-polygon",variant:"icon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command-button",id:"add-polyline",commandId:"annotation:add-polyline",variant:"icon",categories:["annotation","annotation-shape","annotation-polyline"]},{type:"command-button",id:"overflow-shapes-tools",commandId:"annotation:overflow-shapes",variant:"icon",categories:["annotation","annotation-shape","annotation-overflow"]},{type:"divider",id:"shapes-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"shapes-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-6",flex:!0}]},"form-toolbar":{id:"form-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-form-select","add-form-listbox"],show:["overflow-forms-tools"]},md:{minWidth:640,hide:["overflow-forms-tools"],show:["add-form-select","add-form-listbox"]}}},permanent:!1,categories:["form"],items:[{type:"spacer",id:"spacer-form-1",flex:!0},{type:"group",id:"form-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-form-textfield",commandId:"form:add-textfield",variant:"icon",categories:["form","form-textfield"]},{type:"command-button",id:"add-form-checkbox",commandId:"form:add-checkbox",variant:"icon",categories:["form","form-checkbox"]},{type:"command-button",id:"add-form-radio",commandId:"form:add-radio",variant:"icon",categories:["form","form-radio"]},{type:"command-button",id:"add-form-select",commandId:"form:add-select",variant:"icon",categories:["form","form-select"]},{type:"command-button",id:"add-form-listbox",commandId:"form:add-listbox",variant:"icon",categories:["form","form-listbox"]},{type:"command-button",id:"overflow-forms-tools",commandId:"form:overflow-tools",variant:"icon",categories:["form","form-overflow"]},{type:"divider",id:"form-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"command-button",id:"toggle-form-fill-mode",commandId:"form:toggle-fill-mode",variant:"icon",categories:["form","form-fill-mode"]},{type:"divider",id:"form-tools-divider-2",orientation:"vertical"},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-form-2",flex:!0}]},"insert-toolbar":{id:"insert-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["insert"],items:[{type:"spacer",id:"spacer-insert-1",flex:!0},{type:"group",id:"insert-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rubber-stamp",commandId:"insert:add-rubber-stamp",variant:"icon",categories:["insert","insert-rubber-stamp"]},{type:"command-button",id:"add-signature",commandId:"insert:add-signature",variant:"icon",categories:["insert","insert-signature"]},{type:"command-button",id:"add-image",commandId:"insert:add-image",variant:"icon",categories:["insert","insert-image"]},{type:"divider",id:"insert-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"insert-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-insert-2",flex:!0}]},"redaction-toolbar":{id:"redaction-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["redaction"],items:[{type:"spacer",id:"spacer-7",flex:!0},{type:"group",id:"redaction-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"redact",commandId:"redaction:redact",variant:"icon",categories:["redaction","redaction-combined"]},{type:"divider",id:"redaction-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-redaction-panel",commandId:"panel:toggle-redaction",variant:"icon",categories:["panel","panel-redaction"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"redaction-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-8",flex:!0}]}};class _e{constructor(){this.specs=[]}register(e){if(this.specs.some(t=>t.id===e.id))throw new Error(`OperationRegistry: duplicate operation id "${e.id}"`);this.specs.push(e)}registerAll(e){for(const t of e)t&&this.register(t)}list(){return this.specs}buildToolbars(){const e=structuredClone(Ve);for(const t of this.specs){const a=e[t.toolbarSlot];if(!a)continue;const s={type:"command-button",id:t.id,commandId:t.commandId,variant:"icon",...t.icon?{icon:t.icon}:{},...t.i18nKey?{labelKey:t.i18nKey}:{},...t.label?{label:t.label}:{},categories:t.categories??[]};a.items=Re(a.items,s,t.position)}return e}}function Re(e,t,a){return(null==a?void 0:a.after)||(null==a?void 0:a.before)?function(e,t,a){const s=e=>{const i=[];for(const o of e)"group"!==o.type?a.before&&o.id===a.before?i.push(t,o):(i.push(o),a.after&&o.id===a.after&&i.push(t)):i.push({...o,items:s(o.items)});return i};return s(e)}(e,t,a):(s=t,e.map(e=>"group"===e.type?{...e,items:[...e.items,s]}:e));var s}const Be={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function Ue(e){var t,s,b,P,w,y;const C=e.toolbar??{},I=C.enabledModes??["view","annotate","shapes","insert","form","redact"],M=I.length>0,{schema:S,operationRegistry:x}=function(e={}){var t,a,s,i,o,r;const n=new Set(e.enabledModes??["view","annotate","shapes","insert","form","redact"]),l=new _e;(null==(t=e.customOperations)?void 0:t.length)&&l.registerAll(e.customOperations);const h=l.buildToolbars(),d={};for(const u of n){if("view"===u)continue;const e=Be[u];h[e]&&(d[e]=h[e])}const c=function(e){if(0===e.size)return null;const t=(e,t,a)=>({type:"command-button",id:`${e}-mode`,commandId:a,variant:"text",label:t,categories:["mode",e]});return{id:"chapter-editor-main-toolbar",position:{placement:"top",slot:"main",order:0},permanent:!0,items:[{type:"spacer",id:"main-spacer-left",flex:!0},{type:"group",id:"mode-group",alignment:"start",gap:2,items:[...e.has("view")?[t("view","View","mode:view")]:[],...e.has("annotate")?[t("annotate","Annotate","mode:annotate")]:[],...e.has("shapes")?[t("shapes","Shapes","mode:shapes")]:[],...e.has("insert")?[t("insert","Insert","mode:insert")]:[],...e.has("form")?[t("form","Form","mode:form")]:[],...e.has("redact")?[t("redact","Redact","mode:redact")]:[]]},{type:"spacer",id:"main-spacer-right",flex:!0}]}}(n);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(a=e.extend)?void 0:a.toolbars)&&Object.assign(d,e.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(s=e.extend)?void 0:s.menus)??{},sidebars:(null==(i=e.extend)?void 0:i.sidebars)??{},modals:(null==(o=e.extend)?void 0:o.modals)??{},selectionMenus:(null==(r=e.extend)?void 0:r.selectionMenus)??{}},operationRegistry:l}}({...C,enabledModes:I}),k={...M?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:e,documentId:t})=>{var s,i,o,r;const n=null==(s=e.getPlugin("ui"))?void 0:s.provides(),l=null==(i=e.getPlugin("interaction-manager"))?void 0:i.provides();n&&l&&(null==(o=l.forDocument(t))||o.activateDefaultMode(),n.forDocument(t).closeToolbarSlot("top","secondary"),null==(r=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(t).setLocked(e.getPluginConfig(a.ANNOTATION_PLUGIN_ID).locked??{type:a.LockModeType.None}))},active:({state:e,documentId:t})=>!v.isToolbarOpen(e.plugins,t,"top","secondary")},"mode:annotate":{id:"mode:annotate",label:"Annotate",categories:["mode","mode-annotate","annotation"],action:({registry:e,documentId:t})=>{var s,i;const o=null==(s=e.getPlugin("ui"))?void 0:s.provides();o&&(o.setActiveToolbar("top","secondary","annotation-toolbar",t),null==(i=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||i.provides().forDocument(t).setLocked({type:a.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","annotation-toolbar")},"mode:shapes":{id:"mode:shapes",label:"Shapes",categories:["mode","mode-shapes","annotation"],action:({registry:e,documentId:t})=>{var s,i;const o=null==(s=e.getPlugin("ui"))?void 0:s.provides();o&&(o.setActiveToolbar("top","secondary","shapes-toolbar",t),null==(i=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||i.provides().forDocument(t).setLocked({type:a.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","shapes-toolbar")},"mode:insert":{id:"mode:insert",label:"Insert",categories:["mode","mode-insert","insert"],action:({registry:e,documentId:t})=>{var s,i;const o=null==(s=e.getPlugin("ui"))?void 0:s.provides();o&&(o.setActiveToolbar("top","secondary","insert-toolbar",t),null==(i=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||i.provides().forDocument(t).setLocked({type:a.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","insert-toolbar")},"mode:form":{id:"mode:form",label:"Form",categories:["mode","mode-form","form"],action:({registry:e,documentId:t})=>{var s,i;const o=null==(s=e.getPlugin("ui"))?void 0:s.provides();o&&(o.setActiveToolbar("top","secondary","form-toolbar",t),null==(i=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||i.provides().forDocument(t).setLocked({type:a.LockModeType.None}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","form-toolbar")},"mode:redact":{id:"mode:redact",label:"Redact",categories:["mode","mode-redact","redaction"],action:({registry:e,documentId:t})=>{var s,i;const o=null==(s=e.getPlugin("ui"))?void 0:s.provides();o&&(o.setActiveToolbar("top","secondary","redaction-toolbar",t),null==(i=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||i.provides().forDocument(t).setLocked({type:a.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","redaction-toolbar")}}:{},...M?Fe(x.list()):{},...e.commands??{}},L=[i.createPluginRegistration(o.DocumentManagerPluginPackage,{initialDocuments:[]}),i.createPluginRegistration(B,{manifest:e.manifest,overlapStrategy:e.overlapStrategy,passwordProvider:e.passwordProvider,chapterPdfLoader:e.chapterPdfLoader,prefetchChapters:e.prefetchChapters,unloadTimeoutMs:e.unloadTimeoutMs}),i.createPluginRegistration(X,{placeholderPageHeight:e.placeholderPageHeight,placeholderPageWidth:e.placeholderPageWidth}),i.createPluginRegistration(r.InteractionManagerPluginPackage),i.createPluginRegistration(n.RenderPluginPackage),i.createPluginRegistration(l.RotatePluginPackage),i.createPluginRegistration(h.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),i.createPluginRegistration(d.HistoryPluginPackage),i.createPluginRegistration(a.AnnotationPluginPackage),i.createPluginRegistration(c.RedactionPluginPackage),i.createPluginRegistration(u.FormPluginPackage),i.createPluginRegistration(p.StampPluginPackage,!1===e.loadDefaultStampLibrary?{manifests:[]}:void 0),i.createPluginRegistration(g.SignaturePluginPackage),...Object.keys(k).length>0?[i.createPluginRegistration(f.CommandsPluginPackage,{commands:k})]:[],...M?[i.createPluginRegistration(m.I18nPluginPackage),i.createPluginRegistration(v.UIPluginPackage,{schema:S})]:[]];return e.notes&&L.push(i.createPluginRegistration(fe,{callbacks:e.notes.callbacks,ui:null==(s=null==(t=e.features)?void 0:t.notes)?void 0:s.marker})),e.bookmarks&&L.push(i.createPluginRegistration(Ge,{callbacks:e.bookmarks.callbacks,ui:null==(P=null==(b=e.features)?void 0:b.bookmarks)?void 0:P.marker,hover:null==(y=null==(w=e.features)?void 0:w.bookmarks)?void 0:y.hover})),{plugins:L,uiSchema:S,operationRegistry:x}}function Fe(e){const t={};for(const a of e)a.handler&&(t[a.commandId]={id:a.commandId,labelKey:a.i18nKey,label:a.label,icon:a.icon,categories:a.categories,action:({documentId:e})=>{var t;null==(t=a.handler)||t.call(a,{documentId:e,chapterId:e})}});return t}const qe=z();function We(e){return Ue({...e,toolbar:e.toolbar??{enabledModes:[]},features:z(e.features)})}const He={overlapStrategy:{kind:"first-wins"},passwordProvider:new N(async()=>null),prefetchChapters:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};function je(e){return"callbacks"in e.notes?{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,notes:e.notes.callbacks,bookmarks:e.bookmarks.callbacks}:e}function Ze(e){return{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,...He,notes:{callbacks:e.notes},bookmarks:{callbacks:e.bookmarks},features:z(e.features)}}function Ye(e){const t=Ze(je(e)),{plugins:a}=We(t);return{plugins:a,features:t.features,editorOptions:t}}function Ke(e,t=.5,a=3){return Math.min(a,Math.max(t,e))}function Xe(e,t,a){return Math.min(a,Math.max(t,e))}const Qe={chapters:[]};function Je(a){const s=e.ref(null),{provides:r}=t.useCapability(R.id),n=e.computed(()=>{var e;return(null==(e=r.value)?void 0:e.getManifest())??Qe}),l=e.computed(()=>{var e;return null==(e=a.value)?void 0:e.zoom}),{scale:h,setScale:d,zoomEnabled:c,minZoom:u,maxZoom:p}=function(a,s){var r;const n=e.isRef(a)?a:e.computed(()=>a),{registry:l}=t.useRegistry(),{provides:h}=t.useCapability(o.DocumentManagerPlugin.id),{provides:d}=t.useCapability(R.id),c=e.ref((null==(r=s.value)?void 0:r.initial)??1),u=e.ref(c.value),p=()=>{var e;return!1!==(null==(e=s.value)?void 0:e.enabled)},g=()=>{var e;return(null==(e=s.value)?void 0:e.min)??.5},f=()=>{var e;return(null==(e=s.value)?void 0:e.max)??3},m=()=>{var e;return null==(e=s.value)?void 0:e.pageWidth};function v(e){const t=Ke(e,g(),f());u.value=t,c.value=t,function(e,t,a,s=.5,o=3){const r=null==e?void 0:e.getStore();if(!r)return;const n=Ke(a,s,o);r.dispatchToCore(i.setDefaultScale(n));for(const l of t.chapters)r.getState().core.documents[l.chapterId]&&r.dispatchToCore(i.setScale(n,l.chapterId))}(l.value,n.value,t,g(),f())}function b(e){m()?function(e){const t=m();if(!t||!h.value)return;const a=h.value.getDocument(e);a&&v(function(e,t,a=0){var s;const i=e.pages[a];return(null==(s=null==i?void 0:i.size)?void 0:s.width)?t/i.size.width:1}(a,t))}(e):v(u.value)}return e.watch([l,()=>{var e;return null==(e=s.value)?void 0:e.initial},()=>{var e;return null==(e=s.value)?void 0:e.pageWidth}],()=>{var e;p()&&l.value&&(m()||v((null==(e=s.value)?void 0:e.initial)??1))},{immediate:!0}),e.watch([d,n,()=>{var e;return null==(e=s.value)?void 0:e.pageWidth}],()=>{const e=d.value;if(p()&&e){for(const t of n.value.chapters)"loaded"===e.getChapterStatus(t.chapterId)&&b(t.chapterId);return e.onChapterStatusChange(e=>{"loaded"===e.status&&b(e.chapterId)})}},{immediate:!0}),{scale:c,setScale:v,zoomEnabled:p,minZoom:g,maxZoom:f}}(n,l);return function(t,a){let s=null;e.watch([t,a],()=>{null==s||s();const e=a.value;s=function(e,t){if(!e||!1===t.enabled)return()=>{};let a=null,s=null,i=0;const o=()=>{const s=e.querySelector("[data-chapter-scroll-viewport]");return!!s&&(null==a||a(),a=function({container:e,getScale:t,setScale:a,minZoom:s=.5,maxZoom:i=3}){let o=0,r=1,n=null,l=1,h=1;const d=e=>{(e.ctrlKey||e.metaKey)&&(e.preventDefault(),null===n?(h=t(),l=1):clearTimeout(n),l*=1-.01*e.deltaY,l=Xe(l,.1,10),a(Xe(h*l,s,i)),n=setTimeout(()=>{n=null},120))},c=new Map,u=e=>{if(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size){const[e,a]=[...c.values()];o=Math.hypot(a.x-e.x,a.y-e.y),r=t()}},p=e=>{if(c.has(e.pointerId)&&(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size&&o>0)){e.preventDefault();const[t,n]=[...c.values()],l=Math.hypot(n.x-t.x,n.y-t.y);a(Xe(r*(l/o),s,i))}},g=e=>{c.delete(e.pointerId),c.size<2&&(o=0)};return e.addEventListener("wheel",d,{passive:!1}),e.addEventListener("pointerdown",u),e.addEventListener("pointermove",p,{passive:!1}),e.addEventListener("pointerup",g),e.addEventListener("pointercancel",g),()=>{e.removeEventListener("wheel",d),e.removeEventListener("pointerdown",u),e.removeEventListener("pointermove",p),e.removeEventListener("pointerup",g),e.removeEventListener("pointercancel",g),n&&clearTimeout(n)}}({container:s,getScale:t.getScale,setScale:t.setScale,minZoom:t.minZoom,maxZoom:t.maxZoom}),!0)};return o()||(s=new MutationObserver(()=>{o()&&(null==s||s.disconnect(),s=null)}),s.observe(e,{childList:!0,subtree:!0}),i=requestAnimationFrame(()=>o())),()=>{i&&cancelAnimationFrame(i),null==s||s.disconnect(),null==a||a()}}(t.value??null,{enabled:e.enabled,getScale:e.getScale,setScale:e.setScale,minZoom:e.minZoom,maxZoom:e.maxZoom})},{deep:!0,flush:"post"}),e.onBeforeUnmount(()=>null==s?void 0:s())}(s,e.computed(()=>({enabled:c(),getScale:()=>h.value,setScale:d,minZoom:u(),maxZoom:p()}))),{hostRef:s,scale:h,setScale:d,zoomEnabled:c}}const et={kind:"first-wins"};function tt(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let at=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const st=class e extends i.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=i.createBehaviorEmitter(),this.manifestChange$=i.createEmitter(),this.overlapStrategy=et,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??et,this.setManifestInternal(e.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,i]=s.globalPageRange,[o,r]=s.localPageRange;if(e>i&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${i}]`),o>r&&t.push(`${s.chapterId}: invalid localPageRange [${o},${r}]`),i-e!==r-o&&t.push(`${s.chapterId}: page-count mismatch (global ${i-e+1} vs local ${r-o+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>i)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)i.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=et){const a=function(e,t=et){const a=new Map;for(const i of e.chapters){const[e,t]=i.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(i):a.set(s,[i])}}const s=new Map;for(const[i,o]of a)s.set(i,tt(i,o,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((e,t)=>e-t),o=[];let r=0;for(const n of i){const e=a.get(n),t=s.get(e);if(!t)continue;const[i]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-i);o.push({globalPageIndex:r++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new at(o)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const n of s){const e=i.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<i.length&&o.add(t)}const r=new Set;for(const n of o)r.add(i[n]);for(const n of r){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=i.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,i),i}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(e){var t;this.updateStatus(e.chapterId,"loading"),this.chapterLastUsed.set(e.chapterId,Date.now());const a=e.encrypted&&(null==(t=this.passwordProvider)?void 0:t.getCachedPassword)?this.passwordProvider.getCachedPassword(e.chapterId):null,s=await this.resolvePdfPayload(e),i=this.documentManager.provides(),o="url"in s?i.openDocumentUrl({documentId:e.chapterId,url:s.url,name:e.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:e.chapterId,buffer:s.buffer,name:e.title,password:a??void 0,autoActivate:!1});return await new Promise(e=>o.wait(()=>e(),()=>e())),this.waitForTerminalStatus(e.chapterId)}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>{"loaded"!==e&&"error"!==e&&"password-required"!==e&&"closed"!==e||(s(),t(e))},s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)});a(this.chapterStatus.get(e)??"idle")})}async handleDocumentError(t,a,i){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const o=this.findChapter(t);if(!o)return;const r=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,r);let n=null;try{n=await this.passwordProvider.resolvePassword(o,r-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};st.id="chapter-manager";let it=st;const ot=class extends i.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=i.createBehaviorEmitter(),this.visibleChange$=i.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(it.id),this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(e.chapterId)&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,a)=>this.scrollToGlobalPdfPoint(e,t,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,a=0;for(let s=0;s<e;s++){const{width:e,height:i}=this.getPageSize(s);this.offsets[s]=t,t+=i+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const i=this.pageSizes.get(t.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),i=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const o=this.getChapterDocumentScale(e),r=[];for(const n of i){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&r.push({localPageIndex:n.localPageIndex,width:e.size.width*o,height:e.size.height*o})}0!==r.length?this.applyChapterPageSizes(e,r):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let i=s;for(;i<e;){const e=this.getPageSize(i),t=this.offsets[i];if(e.height,t>=a)break;i++}const o=[];let r=s,n=-1;for(let l=s;l<i;l++){o.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,i=Math.max(0,Math.min(s,a)-Math.max(e,t));i>n&&(n=i,r=l)}this.currentVisible=o,this.currentGlobalPageIndex=r,this.visibleChange$.emit({visibleGlobalPageIndices:o,currentGlobalPageIndex:r}),this.chapterManager.provides().setVisibleGlobalPages(o),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const i=t+a>>1;this.offsets[i]<=e?(s=i,t=i+1):a=i-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let o=t;o<=s;o++){const e=this.virtualPageMap.atIndex(o);if(!e)continue;const t=this.getPageSize(o),a=!this.isChapterDocumentReady(e.chapterId);i.push({globalPageIndex:o,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[o],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,o=this.virtualPageMap.atIndex(e);if(!o)return void this.scrollToIndex(e,a);const r=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(o.chapterId))?void 0:s.pages[o.localPageIndex];if(!r||!n)return void this.scrollToIndex(e,a);const l=r.height/n.size.height,h=(this.offsets[e]??0)+t*l-i;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};ot.id="chapter-scroll";let rt=ot;const nt=["data-global-page-index","data-chapter-id","data-local-page-index"],lt=(e=>{const t=e.__vccOpts||e;for(const[a,s]of[["__scopeId","data-v-8a737137"]])t[a]=s;return t})(e.defineComponent({__name:"ChapterScroller",props:{class:{},style:{}},setup(a){const{provides:s}=t.useCapability(rt.id),i=e.ref(null),o=e.ref(null);let r=null;const n=()=>{null==r||r(),r=null,s.value&&(s.value.registerViewport(i.value),r=s.value.onLayoutChange(e=>{o.value=e}))};return e.onMounted(n),e.onBeforeUnmount(()=>{var e;null==r||r(),null==(e=s.value)||e.registerViewport(null)}),e.watch(s,n),(t,a)=>{var s,r,n;return e.openBlock(),e.createElementBlock("div",{ref_key:"containerRef",ref:i,"data-chapter-scroll-viewport":"",class:e.normalizeClass(t.$props.class),style:e.normalizeStyle({overflow:"auto",position:"relative",width:"100%",height:"100%",...t.$props.style})},[e.createElementVNode("div",{style:e.normalizeStyle({position:"relative",width:`${(null==(s=o.value)?void 0:s.totalWidth)??0}px`,height:`${(null==(r=o.value)?void 0:r.totalHeight)??0}px`,margin:"0 auto"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList((null==(n=o.value)?void 0:n.items)??[],s=>(e.openBlock(),e.createElementBlock("div",{key:s.globalPageIndex,"data-global-page-index":s.globalPageIndex,"data-chapter-id":s.chapterId,"data-local-page-index":s.localPageIndex,style:e.normalizeStyle({position:"absolute",top:`${s.offsetTop}px`,left:"50%",transform:"translateX(-50%)",width:`${s.width}px`,height:`${s.height}px`,backgroundColor:s.isPlaceholder?"#f3f4f6":"#fff",boxShadow:"0 1px 4px rgba(0,0,0,0.08)"})},[s.isPlaceholder?e.renderSlot(t.$slots,"placeholder",{key:0,item:s},()=>[a[0]||(a[0]=e.createElementVNode("div",{class:"chapter-scroll-placeholder"},"Loading chapter…",-1))],!0):e.renderSlot(t.$slots,"page",{key:1,item:s},void 0,!0)],12,nt))),128))],4)],6)}}})),ht=e.defineComponent({__name:"ChapterRenderLayer",props:{chapterId:{},localPageIndex:{},scale:{},dpr:{},class:{}},setup:t=>(a,s)=>(e.openBlock(),e.createBlock(e.unref(I.RenderLayer),{"document-id":t.chapterId,"page-index":t.localPageIndex,scale:t.scale,dpr:t.dpr,class:e.normalizeClass(t.class),style:{pointerEvents:"none"}},null,8,["document-id","page-index","scale","dpr","class"]))}),dt={kind:"first-wins"};function ct(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let ut=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const pt=class e extends i.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=i.createBehaviorEmitter(),this.manifestChange$=i.createEmitter(),this.overlapStrategy=dt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??dt,this.setManifestInternal(e.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,i]=s.globalPageRange,[o,r]=s.localPageRange;if(e>i&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${i}]`),o>r&&t.push(`${s.chapterId}: invalid localPageRange [${o},${r}]`),i-e!==r-o&&t.push(`${s.chapterId}: page-count mismatch (global ${i-e+1} vs local ${r-o+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>i)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)i.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=dt){const a=function(e,t=dt){const a=new Map;for(const i of e.chapters){const[e,t]=i.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(i):a.set(s,[i])}}const s=new Map;for(const[i,o]of a)s.set(i,ct(i,o,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((e,t)=>e-t),o=[];let r=0;for(const n of i){const e=a.get(n),t=s.get(e);if(!t)continue;const[i]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-i);o.push({globalPageIndex:r++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new ut(o)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const n of s){const e=i.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<i.length&&o.add(t)}const r=new Set;for(const n of o)r.add(i[n]);for(const n of r){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=i.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,i),i}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(e){var t;this.updateStatus(e.chapterId,"loading"),this.chapterLastUsed.set(e.chapterId,Date.now());const a=e.encrypted&&(null==(t=this.passwordProvider)?void 0:t.getCachedPassword)?this.passwordProvider.getCachedPassword(e.chapterId):null,s=await this.resolvePdfPayload(e),i=this.documentManager.provides(),o="url"in s?i.openDocumentUrl({documentId:e.chapterId,url:s.url,name:e.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:e.chapterId,buffer:s.buffer,name:e.title,password:a??void 0,autoActivate:!1});return await new Promise(e=>o.wait(()=>e(),()=>e())),this.waitForTerminalStatus(e.chapterId)}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>{"loaded"!==e&&"error"!==e&&"password-required"!==e&&"closed"!==e||(s(),t(e))},s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)});a(this.chapterStatus.get(e)??"idle")})}async handleDocumentError(t,a,i){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const o=this.findChapter(t);if(!o)return;const r=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,r);let n=null;try{n=await this.passwordProvider.resolvePassword(o,r-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};pt.id="chapter-manager";let gt=pt;const ft={kind:"first-wins"};function mt(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}class vt{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}}const bt=class e extends i.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=i.createBehaviorEmitter(),this.manifestChange$=i.createEmitter(),this.overlapStrategy=ft,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ft,this.setManifestInternal(e.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,i]=s.globalPageRange,[o,r]=s.localPageRange;if(e>i&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${i}]`),o>r&&t.push(`${s.chapterId}: invalid localPageRange [${o},${r}]`),i-e!==r-o&&t.push(`${s.chapterId}: page-count mismatch (global ${i-e+1} vs local ${r-o+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>i)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)i.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=ft){const a=function(e,t=ft){const a=new Map;for(const i of e.chapters){const[e,t]=i.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(i):a.set(s,[i])}}const s=new Map;for(const[i,o]of a)s.set(i,mt(i,o,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((e,t)=>e-t),o=[];let r=0;for(const n of i){const e=a.get(n),t=s.get(e);if(!t)continue;const[i]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-i);o.push({globalPageIndex:r++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new vt(o)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const n of s){const e=i.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<i.length&&o.add(t)}const r=new Set;for(const n of o)r.add(i[n]);for(const n of r){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=i.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,i),i}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(e){var t;this.updateStatus(e.chapterId,"loading"),this.chapterLastUsed.set(e.chapterId,Date.now());const a=e.encrypted&&(null==(t=this.passwordProvider)?void 0:t.getCachedPassword)?this.passwordProvider.getCachedPassword(e.chapterId):null,s=await this.resolvePdfPayload(e),i=this.documentManager.provides(),o="url"in s?i.openDocumentUrl({documentId:e.chapterId,url:s.url,name:e.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:e.chapterId,buffer:s.buffer,name:e.title,password:a??void 0,autoActivate:!1});return await new Promise(e=>o.wait(()=>e(),()=>e())),this.waitForTerminalStatus(e.chapterId)}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>{"loaded"!==e&&"error"!==e&&"password-required"!==e&&"closed"!==e||(s(),t(e))},s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)});a(this.chapterStatus.get(e)??"idle")})}async handleDocumentError(t,a,i){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const o=this.findChapter(t);if(!o)return;const r=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,r);let n=null;try{n=await this.passwordProvider.resolvePassword(o,r-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};bt.id="chapter-manager";let Pt=bt;const wt=class extends i.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=i.createBehaviorEmitter(),this.visibleChange$=i.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Pt.id),this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(e.chapterId)&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,a)=>this.scrollToGlobalPdfPoint(e,t,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,a=0;for(let s=0;s<e;s++){const{width:e,height:i}=this.getPageSize(s);this.offsets[s]=t,t+=i+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const i=this.pageSizes.get(t.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),i=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const o=this.getChapterDocumentScale(e),r=[];for(const n of i){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&r.push({localPageIndex:n.localPageIndex,width:e.size.width*o,height:e.size.height*o})}0!==r.length?this.applyChapterPageSizes(e,r):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let i=s;for(;i<e;){const e=this.getPageSize(i),t=this.offsets[i];if(e.height,t>=a)break;i++}const o=[];let r=s,n=-1;for(let l=s;l<i;l++){o.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,i=Math.max(0,Math.min(s,a)-Math.max(e,t));i>n&&(n=i,r=l)}this.currentVisible=o,this.currentGlobalPageIndex=r,this.visibleChange$.emit({visibleGlobalPageIndices:o,currentGlobalPageIndex:r}),this.chapterManager.provides().setVisibleGlobalPages(o),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const i=t+a>>1;this.offsets[i]<=e?(s=i,t=i+1):a=i-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let o=t;o<=s;o++){const e=this.virtualPageMap.atIndex(o);if(!e)continue;const t=this.getPageSize(o),a=!this.isChapterDocumentReady(e.chapterId);i.push({globalPageIndex:o,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[o],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,o=this.virtualPageMap.atIndex(e);if(!o)return void this.scrollToIndex(e,a);const r=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(o.chapterId))?void 0:s.pages[o.localPageIndex];if(!r||!n)return void this.scrollToIndex(e,a);const l=r.height/n.size.height,h=(this.offsets[e]??0)+t*l-i;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};wt.id="chapter-scroll";let yt=wt;const Ct=class e extends i.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=i.createBehaviorEmitter([]),this.noteActivated$=i.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(yt.id),this.chapterManager=this.registry.getPlugin(gt.id),this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(e.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(a=>a.chapterId===e&&a.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,a;const s=this.notes.get(e);s&&(null==(a=(t=this.config.callbacks).onActivateNote)||a.call(t,e,s),this.noteActivated$.emit({noteId:e,anchor:s}))}listAll(){return Array.from(this.notes.values())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:Mt(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:t,complete:async e=>{const a={...t,noteId:e};this.registerNote(a)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const a=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let i=null;try{i=await s(a)}catch(r){return this.logger.error(e.id,"OnCreateNote","Callback failed",r),null}if(!i)return null;const o={...a,noteId:i.noteId};return this.registerNote(o),o}async deleteNote(t){var a,s;if(this.notes.has(t)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,t))}catch(i){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",i)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,a){var s,i;const o=this.notes.get(t);if(!o)return;const r={...o,content:a};try{await(null==(i=(s=this.config.callbacks).onUpdateNote)?void 0:i.call(s,r))}catch(n){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",n)}this.notes.set(t,r),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const a=this.notes.get(e);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(t=this.documentManager.provides().getDocument(a.chapterId))?void 0:t.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),a=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{i(),a(null)},2500),i=t.onLayoutChange(t=>{const o=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);o&&(clearTimeout(s),i(),a(o))})})}};Ct.id="note";let It=Ct;function Mt(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function St(e){const{markerPdf:t,lineRects:a,sx:s,sy:i,cssPageWidth:o,iconSize:r,gapPx:n=6}=e,l=(null==a?void 0:a.length)?a[a.length-1]:void 0;let h,d;l?(h=(l.origin.x+l.size.width)*s+n,d=l.origin.y*i+(l.size.height*i-r)/2):(h=t.x*s-r/2,d=t.y*i-r-n);const c=Math.max(0,o-r-2);return h>c&&(h=c),d<0&&(d=0),{left:h,top:d}}const xt={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none",zIndex:25}},kt=["onMouseenter"],Lt=["data-note-marker-zone","onMouseenter","onMouseleave"],$t=["onClick"],Tt=["onClick"],Dt=["onClick"],zt=e.defineComponent({__name:"NoteMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(a){const s=a,{provides:i}=t.useCapability(It.id),o=e.ref([]),r=e.ref(null),n=e.ref(null);e.watch(i,e=>{if(e)return e.onNotesChange(e=>{o.value=e.filter(e=>e.chapterId===s.chapterId&&e.localPageIndex===s.localPageIndex)})},{immediate:!0});let l=null;e.watch(n,e=>{l&&(document.removeEventListener("mousedown",l),l=null),e&&(l=t=>{var a;const s=t.target;(null==(a=s.closest)?void 0:a.call(s,`[data-note-marker-zone="${e}"]`))||(n.value=null,r.value=null)},document.addEventListener("mousedown",l))}),e.onBeforeUnmount(()=>{l&&document.removeEventListener("mousedown",l)});const h=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.iconSize)??16}),d=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.highlightColor)??"rgba(245, 158, 11, 0.08)"});function c(e){const t=s.cssPageWidth/s.pdfPageWidth,a=s.cssPageHeight/s.pdfPageHeight,i=h.value,{left:o,top:r}=St({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:t,sy:a,cssPageWidth:s.cssPageWidth,iconSize:i}),l=function(e,t,a){let s=1/0,i=1/0,o=-1/0,r=-1/0;for(const n of e)s=Math.min(s,n.origin.x*t),i=Math.min(i,n.origin.y*a),o=Math.max(o,(n.origin.x+n.size.width)*t),r=Math.max(r,(n.origin.y+n.size.height)*a);return{left:s,top:i,width:o-s,height:r-i}}(e.rectsPdfCoord,t,a),d=n.value===e.noteId?72:0,c=Math.max(0,Math.min(l.left,o)-8),u=Math.max(0,Math.min(l.top,r)-8);return{zoneLeft:c,zoneTop:u,zoneW:Math.min(s.cssPageWidth,Math.max(l.left+l.width,o+i)+8)-c,zoneH:Math.max(l.top+l.height,r+i+6+d)+8-u,iconLeft:o,iconTop:r,sx:t,sy:a}}return(t,s)=>e.unref(i)&&o.value.length&&a.pdfPageWidth&&a.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",xt,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(o.value,t=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:t.noteId},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.rectsPdfCoord,(a,s)=>(e.openBlock(),e.createElementBlock("div",{key:`${t.noteId}-bg-${s}`,style:e.normalizeStyle({position:"absolute",left:a.origin.x*c(t).sx+"px",top:a.origin.y*c(t).sy+"px",width:a.size.width*c(t).sx+"px",height:a.size.height*c(t).sy+"px",background:d.value,borderRadius:"2px",pointerEvents:"auto"}),onMouseenter:e=>r.value=t.noteId},null,44,kt))),128)),r.value===t.noteId||n.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,"data-note-marker-zone":t.noteId,style:e.normalizeStyle({position:"absolute",left:`${c(t).zoneLeft}px`,top:`${c(t).zoneTop}px`,width:`${c(t).zoneW}px`,height:`${c(t).zoneH}px`,pointerEvents:"auto",zIndex:26}),onMouseenter:e=>r.value=t.noteId,onMouseleave:e=>n.value!==t.noteId&&(r.value=null)},[e.createElementVNode("button",{type:"button",title:"笔记",style:e.normalizeStyle({position:"absolute",left:c(t).iconLeft-c(t).zoneLeft+"px",top:c(t).iconTop-c(t).zoneTop+"px",width:`${h.value}px`,height:`${h.value}px`,border:"none",borderRadius:"50%",background:"#f59e0b",color:"#fff",cursor:"pointer",fontSize:"11px",padding:0}),onMousedown:s[0]||(s[0]=e.withModifiers(()=>{},["stop"])),onClick:e.withModifiers(e=>n.value=n.value===t.noteId?null:t.noteId,["stop"])}," 💬 ",44,$t),n.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:c(t).iconLeft-c(t).zoneLeft+"px",top:`${c(t).iconTop-c(t).zoneTop+h.value+4}px`,minWidth:"120px",padding:"6px",borderRadius:"8px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)",zIndex:30}),onMousedown:s[1]||(s[1]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",style:{display:"block",width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#334155",cursor:"pointer","text-align":"left"},onClick:e=>{return a=t,void(null==(s=i.value)||s.requestEditNote(a.noteId,a));var a,s}}," 编辑 ",8,Tt),e.createElementVNode("button",{type:"button",style:{display:"block",width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#dc2626",cursor:"pointer","text-align":"left"},onClick:e=>{var a,s;return s=t.noteId,null==(a=i.value)||a.requestDeleteNote(s),void(n.value=null)}}," 删除 ",8,Dt)],36)):e.createCommentVNode("",!0)],44,Lt)):e.createCommentVNode("",!0)],64))),128))])):e.createCommentVNode("",!0)}}),Nt={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none"}},Et=["title","onClick"],Ot=["onClick"],At=e.defineComponent({__name:"BookmarkMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(a){const s=a,{provides:i}=t.useCapability(Ae.id),o=e.ref([]),r=e.ref(null),n=e.ref(null);function l(){const e=i.value;e&&(o.value=e.listBookmarks().filter(e=>e.anchor.chapterId===s.chapterId&&e.anchor.localPageIndex===s.localPageIndex))}e.watch(i,e=>{if(e)return l(),e.onBookmarksChange(l)},{immediate:!0});let h=null;e.watch(r,e=>{h&&(document.removeEventListener("mousedown",h),h=null),e&&(h=e=>{var t;(null==(t=n.value)?void 0:t.contains(e.target))||(r.value=null)},document.addEventListener("mousedown",h))}),e.onBeforeUnmount(()=>{h&&document.removeEventListener("mousedown",h)});const d=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.iconSize)??16});function c(e){const{left:t,top:a}=function(e){var t;const a=s.cssPageWidth/s.pdfPageWidth,i=s.cssPageHeight/s.pdfPageHeight,o=(null==(t=e.anchor.rectsPdfCoord)?void 0:t.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord];return St({markerPdf:e.anchor.markerAnchor??{x:e.anchor.rectPdfCoord.origin.x+e.anchor.rectPdfCoord.size.width,y:e.anchor.rectPdfCoord.origin.y+e.anchor.rectPdfCoord.size.height},lineRects:o,sx:a,sy:i,cssPageWidth:s.cssPageWidth,iconSize:d.value})}(e);return{position:"absolute",left:`${Math.max(0,t-6)}px`,top:`${Math.max(0,a-6)}px`,width:`${d.value+12}px`,height:`${d.value+12}px`,pointerEvents:"auto",zIndex:20}}return(t,s)=>e.unref(i)&&o.value.length&&a.pdfPageWidth&&a.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Nt,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(o.value,t=>(e.openBlock(),e.createElementBlock("div",{key:t.id,style:e.normalizeStyle(c(t)),onMousedown:s[1]||(s[1]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",title:t.label,style:e.normalizeStyle({position:"absolute",left:"6px",top:"6px",width:`${d.value}px`,height:`${d.value}px`,border:"none",borderRadius:"4px",background:"#3b82f6",color:"#fff",cursor:"pointer",boxShadow:"0 2px 6px rgba(37, 99, 235, 0.35)",fontSize:"11px",padding:0}),onClick:e.withModifiers(e=>r.value=r.value===t.id?null:t.id,["stop"])}," 🔖 ",12,Et),r.value===t.id?(e.openBlock(),e.createElementBlock("div",{key:0,ref_for:!0,ref_key:"deleteMenuRef",ref:n,style:{position:"absolute",left:"6px",top:"-36px",zIndex:30,pointerEvents:"auto",minWidth:"88px",padding:"4px",borderRadius:"6px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)"},onClick:s[0]||(s[0]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",style:{width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#dc2626",cursor:"pointer","text-align":"left"},onClick:e=>async function(e){const t=i.value;t&&await t.requestRemoveBookmark(e)&&(r.value=null)}(t.id)}," 删除书签 ",8,Ot)],512)):e.createCommentVNode("",!0)],36))),128))])):e.createCommentVNode("",!0)}});function Gt(e){return e.chapterId}function Vt(e,t){e.wait(t,()=>{})}const _t=e.defineComponent({__name:"ChapterPageSurface",props:{item:{},features:{},showNoteMarkers:{type:Boolean},showBookmarkMarkers:{type:Boolean},showRedactionLayer:{type:Boolean},noteMarkerUi:{},bookmarkMarkerUi:{},buildSelectionMenu:{type:Function},createNote:{},annotationSelectionMenu:{},redactionSelectionMenu:{},renderPageOverlay:{type:Function}},setup(a){const s=a,i=e.computed(()=>Gt(s.item));!function(a){const{provides:s}=t.useCapability(o.DocumentManagerPlugin.id);e.watch([s,a],([e,t])=>{e&&t&&e.isDocumentOpen(t)&&e.setActiveDocument(t)},{immediate:!0})}(i);const{provides:r}=t.useCapability(o.DocumentManagerPlugin.id),{provides:n}=t.useCapability(h.SelectionPlugin.id),l=e.computed(()=>{var e,t;return null==(t=null==(e=r.value)?void 0:e.getDocument(i.value))?void 0:t.pages[s.item.localPageIndex]});function d(t,a){const i=s.createNote.value;if(i)return s=>{var o;const r={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(o=s.placement)?void 0:o.suggestTop)?-40:s.rect.size.height+8};return e.h("div",s.menuWrapperProps,[e.h("div",{style:r},e.h("button",{type:"button",style:{padding:"6px 10px",fontSize:"12px",border:"1px solid #e2e8f0",borderRadius:"6px",background:"#fff",cursor:"pointer"},onClick:()=>{if(!n.value)return;const e=n.value.getHighlightRectsForPage(t.localPageIndex,a);Vt(n.value.getSelectedText(a),a=>{var s,o,r;i((s=t,o=e,r=a.join("\n"),{chapterId:s.chapterId,localPageIndex:s.localPageIndex,globalPageIndex:s.globalPageIndex,globalPageNumber:s.globalPageNumber,rectsPdfCoord:o,selectedText:r}))})}},"添加附注"))])}}const c=e.computed(()=>{const e=s.buildSelectionMenu,t={item:s.item,defaultMenu:d(s.item,i.value),createNote:s.createNote.value};if(e){const a=e(t);if(a)return a}return t.defaultMenu}),u=e.computed(()=>{var e;return null==(e=s.renderPageOverlay)?void 0:e.call(s,s.item)});return(t,s)=>a.item.isPlaceholder?e.createCommentVNode("",!0):(e.openBlock(),e.createBlock(e.unref(b.GlobalPointerProvider),{key:0,"document-id":i.value},{default:e.withCtx(()=>[e.createVNode(e.unref(P.Rotate),{"document-id":i.value,"page-index":a.item.localPageIndex,style:{backgroundColor:"#fff"}},{default:e.withCtx(()=>[e.createVNode(e.unref(b.PagePointerProvider),{"document-id":i.value,"page-index":a.item.localPageIndex},{default:e.withCtx(()=>[e.createVNode(e.unref(ht),{"chapter-id":i.value,"local-page-index":a.item.localPageIndex},null,8,["chapter-id","local-page-index"]),e.createVNode(e.unref(w.SelectionLayer),{"document-id":i.value,"page-index":a.item.localPageIndex,"selection-menu":c.value},null,8,["document-id","page-index","selection-menu"]),a.showRedactionLayer?(e.openBlock(),e.createBlock(e.unref(C.RedactionLayer),{key:0,"document-id":i.value,"page-index":a.item.localPageIndex,"selection-menu":a.redactionSelectionMenu},null,8,["document-id","page-index","selection-menu"])):e.createCommentVNode("",!0),e.createVNode(e.unref(y.AnnotationLayer),{"document-id":i.value,"page-index":a.item.localPageIndex,"selection-menu":a.annotationSelectionMenu},null,8,["document-id","page-index","selection-menu"]),a.showBookmarkMarkers&&l.value?(e.openBlock(),e.createBlock(At,{key:1,"chapter-id":i.value,"local-page-index":a.item.localPageIndex,"pdf-page-width":l.value.size.width,"pdf-page-height":l.value.size.height,"css-page-width":a.item.width,"css-page-height":a.item.height,ui:a.bookmarkMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),u.value?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(u.value),{key:2})):e.createCommentVNode("",!0),a.showNoteMarkers&&l.value?(e.openBlock(),e.createBlock(zt,{key:3,"chapter-id":i.value,"local-page-index":a.item.localPageIndex,"pdf-page-width":l.value.size.width,"pdf-page-height":l.value.size.height,"css-page-width":a.item.width,"css-page-height":a.item.height,ui:a.noteMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),e.renderSlot(t.$slots,"default")]),_:3},8,["document-id","page-index"])]),_:3},8,["document-id","page-index"])]),_:3},8,["document-id"]))}}),Rt=e.defineComponent({__name:"HoverBookmarkLayer",props:{item:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},hoverUi:{}},setup(a){const s=a,i=e.computed(()=>Gt(s.item)),{provides:o}=t.useCapability(h.SelectionPlugin.id),{provides:r}=t.useCapability(Ae.id),n=e.ref(null),l=e.ref(null),d=e.ref(null),c=e.ref(null),u=e.computed(()=>{var e;return(null==(e=s.hoverUi)?void 0:e.iconSize)??16}),p=e.computed(()=>c.value??d.value);let g=null,f=0;function m(){const e=o.value;if(!e)return;const t=e.forDocument(i.value).getState().geometry[s.item.localPageIndex];t&&(l.value=t)}e.watch([o,i,()=>s.item.localPageIndex],([e])=>{if(null==g||g(),g=null,cancelAnimationFrame(f),l.value=null,!e)return;const t=e.forDocument(i.value);g=t.onSelectionChange(m);let a=!1;const o=()=>{if(!a){try{if(m(),t.getState().geometry[s.item.localPageIndex])return}catch{}f=requestAnimationFrame(o)}};return o(),()=>{a=!0,cancelAnimationFrame(f),null==g||g(),g=null}},{immediate:!0});let v=null;e.watch([l,()=>s.pdfPageWidth,c,o],()=>{v&&(document.removeEventListener("mousemove",v),v=null),l.value&&s.pdfPageWidth&&(v=e=>{if(c.value)return;const t=o.value;if(t)try{if(t.forDocument(i.value).getState().selecting)return void(d.value=null)}catch{}const a=n.value;if(!a)return;const r=a.getBoundingClientRect();if(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom)return void(d.value=null);const u=function(e,t){const a=h.glyphAt(e,t);if(a<0)return null;const s=h.expandToLineBoundary(e,a);if(!s)return null;const i=h.rectsWithinSlice(e,s.from,s.to);return 0===i.length?null:{lineRects:i,charFrom:s.from,charTo:s.to}}(l.value,{x:(e.clientX-r.left)/(s.cssPageWidth/s.pdfPageWidth),y:(e.clientY-r.top)/(s.cssPageHeight/s.pdfPageHeight)});d.value=(null==u?void 0:u.lineRects)??null},document.addEventListener("mousemove",v))},{immediate:!0}),e.onBeforeUnmount(()=>{v&&document.removeEventListener("mousemove",v),cancelAnimationFrame(f),null==g||g()});const b=e.computed(()=>{const e=p.value;return(null==e?void 0:e.length)?Ee(s.item.chapterId,s.item.localPageIndex,e,{globalPageIndex:s.item.globalPageIndex,globalPageNumber:s.item.globalPageNumber}):null}),P=e.computed(()=>{const e=b.value,t=r.value;return!(!e||!t)&&t.listBookmarks().some(t=>Ne(t.anchor,e))});function w(){const e=r.value,t=b.value;e&&t&&!P.value&&(e.addBookmark({label:`书签 ${(new Date).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}`,anchor:t}),d.value=null,c.value=null)}const y=e.computed(()=>{const e=p.value,t=null==e?void 0:e[e.length-1];if(!t||!s.pdfPageWidth)return null;const a=s.cssPageWidth/s.pdfPageWidth,i=s.cssPageHeight/s.pdfPageHeight,o=u.value;return{iconLeft:Math.min((t.origin.x+t.size.width)*a+6,Math.max(0,s.cssPageWidth-o-2)),iconTop:t.origin.y*i+(t.size.height*i-o)/2,zoneLeft:Math.max(0,(t.origin.x+t.size.width)*a-4),zoneTop:Math.max(0,t.origin.y*i-4),size:o}});return(t,s)=>{var i;return e.unref(r)&&a.pdfPageWidth&&a.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"rootRef",ref:n,style:{position:"absolute",inset:"0",zIndex:14,pointerEvents:"none"}},[y.value&&p.value&&!P.value?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:`${y.value.zoneLeft}px`,top:`${y.value.zoneTop}px`,width:`${y.value.size+20}px`,height:`${((null==(i=p.value[p.value.length-1])?void 0:i.size.height)??0)*(a.cssPageHeight/a.pdfPageHeight)+y.value.size+12}px`,pointerEvents:"auto"}),onMouseenter:s[0]||(s[0]=e=>c.value=p.value),onMouseleave:s[1]||(s[1]=e=>c.value=null)},[e.createElementVNode("button",{type:"button",title:"添加书签",style:e.normalizeStyle({position:"absolute",left:y.value.iconLeft-y.value.zoneLeft+"px",top:y.value.iconTop-y.value.zoneTop+"px",width:`${y.value.size}px`,height:`${y.value.size}px`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"#3b82f6",color:"#fff",border:"none",borderRadius:"4px",boxShadow:"0 2px 8px rgba(37, 99, 235, 0.45)",fontSize:"12px",padding:0}),onClick:e.withModifiers(w,["stop"])}," 🔖 ",4)],36)):e.createCommentVNode("",!0)],512)):e.createCommentVNode("",!0)}}}),Bt={key:0,width:"24",height:"24",viewBox:"0 0 28 28",fill:"none","aria-hidden":""},Ut={key:0,x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#fde047"},Ft={key:1,d:"M6 22h16",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},qt={key:2,d:"M6 22c2-2 3-2 5 0s3 2 5 0 3-2 5 0",stroke:"#dc2626","stroke-width":"2","stroke-linecap":"round",fill:"none"},Wt={key:3,d:"M5 14h18",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},Ht={key:1,width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},jt=e.defineComponent({__name:"SelectionToolbarIcons",props:{kind:{}},setup:t=>(a,s)=>"note"!==t.kind?(e.openBlock(),e.createElementBlock("svg",Bt,["highlight"===t.kind?(e.openBlock(),e.createElementBlock("rect",Ut)):e.createCommentVNode("",!0),s[0]||(s[0]=e.createElementVNode("text",{x:"14",y:"19","text-anchor":"middle","font-size":"15","font-weight":"700","font-family":"system-ui, -apple-system, sans-serif",fill:"#0f172a"}," A ",-1)),"underline"===t.kind?(e.openBlock(),e.createElementBlock("path",Ft)):"squiggly"===t.kind?(e.openBlock(),e.createElementBlock("path",qt)):"strikeout"===t.kind?(e.openBlock(),e.createElementBlock("path",Wt)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("svg",Ht,[...s[1]||(s[1]=[e.createElementVNode("path",{d:"M8 3h8l4 4v14H8V3z",fill:"#fef3c7",stroke:"#d97706","stroke-width":"1.2","stroke-linejoin":"round"},null,-1),e.createElementVNode("path",{d:"M16 3v4h4",stroke:"#d97706","stroke-width":"1.2"},null,-1),e.createElementVNode("path",{d:"M10 12h6M10 16h4",stroke:"#92400e","stroke-width":"1.2","stroke-linecap":"round"},null,-1)])]))}),Zt=["title","aria-label","onMouseenter","onClick"],Yt=["title","onMouseenter","onClick"],Kt={style:{"font-size":"11px","font-weight":"600"}},Xt=e.defineComponent({__name:"SelectionToolbarCard",props:{placementAbove:{type:Boolean},anchorHeight:{},hiddenBuiltinActions:{},extraActions:{}},emits:["action"],setup(t,{emit:a}){const s=t,i=a,o=[{id:"highlight",label:"高亮背景"},{id:"underline",label:"下划线"},{id:"squiggly",label:"波浪线"},{id:"strikeout",label:"删除线"},{id:"note",label:"添加笔记"}],r=e.computed(()=>new Set(s.hiddenBuiltinActions??[])),n=e.computed(()=>o.filter(e=>"note"!==e.id&&!r.value.has(e.id))),l=e.computed(()=>!r.value.has("note")),h=e.computed(()=>[...s.extraActions??[]].sort((e,t)=>(e.order??0)-(t.order??0))),d=e.ref(null),c=e.computed(()=>({position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:s.placementAbove?void 0:`${s.anchorHeight+10}px`,bottom:s.placementAbove?`${s.anchorHeight+10}px`:void 0,display:"flex",alignItems:"center",gap:"2px",padding:"4px 6px",borderRadius:"12px",background:"rgba(255, 255, 255, 0.96)",border:"1px solid rgba(15, 23, 42, 0.06)",boxShadow:"0 2px 8px rgba(15, 23, 42, 0.08), 0 12px 32px rgba(15, 23, 42, 0.1)",backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)"}));function u(e,t=!1){return{display:"flex",alignItems:"center",justifyContent:"center",width:"32px",height:"32px",padding:0,margin:0,border:"none",borderRadius:"8px",background:d.value===e?t?"#fffbeb":"#f1f5f9":"transparent",color:t?"#b45309":"#334155",cursor:"pointer",flexShrink:0,WebkitAppearance:"none",appearance:"none"}}const p={width:"1px",height:"20px",margin:"0 4px",background:"rgba(15, 23, 42, 0.1)",flexShrink:0};return(t,a)=>(e.openBlock(),e.createElementBlock("div",{role:"toolbar","aria-label":"选区工具",style:e.normalizeStyle(c.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,"aria-label":t.label,style:e.normalizeStyle(u(t.id)),onMouseenter:e=>d.value=t.id,onMouseleave:a[0]||(a[0]=e=>d.value=null),onClick:e=>i("action",t.id)},[e.createVNode(jt,{kind:t.id},null,8,["kind"])],44,Zt))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(h.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,style:e.normalizeStyle(u(t.id)),onMouseenter:e=>d.value=t.id,onMouseleave:a[1]||(a[1]=e=>d.value=null),onClick:e=>i("action",t.id)},[e.createElementVNode("span",Kt,e.toDisplayString(t.label.slice(0,2)),1)],44,Yt))),128)),l.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("span",{style:p,"aria-hidden":""}),e.createElementVNode("button",{type:"button",title:"添加笔记","aria-label":"添加笔记",style:e.normalizeStyle(u("note",!0)),onMouseenter:a[2]||(a[2]=e=>d.value="note"),onMouseleave:a[3]||(a[3]=e=>d.value=null),onClick:a[4]||(a[4]=e=>i("action","note"))},[e.createVNode(jt,{kind:"note"})],36)],64)):e.createCommentVNode("",!0)],4))}}),Qt={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"},Jt=e.defineComponent({__name:"PdfChapterViewport",props:{className:{},features:{},buildSelectionMenu:{},annotationSelectionMenu:{},redactionSelectionMenu:{},showNoteMarkers:{type:Boolean,default:!0},showBookmarkMarkers:{type:Boolean,default:!0},showRedactionLayer:{type:Boolean,default:!1},renderPageOverlay:{},onExtraSelectionAction:{}},setup(s){const i=s,r=e.computed(()=>i.features),{hostRef:n}=Je(r),l=function(){const{registry:a}=t.useRegistry();return e.computed(()=>{var e,t,s;const i=null==(s=null==(t=null==(e=a.value)?void 0:e.getPlugin(pe.id))?void 0:t.provides)?void 0:s.call(t);return i?e=>i.createNoteFromSelection(e):null})}(),d=function(){const{registry:a}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=a.value)?void 0:e.getPlugin(pe.id))})}(),c=function(){const{registry:a}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=a.value)?void 0:e.getPlugin(Ae.id))})}(),u=e.computed(()=>{var e,t;return i.showNoteMarkers&&d.value&&!1!==(null==(t=null==(e=i.features)?void 0:e.notes)?void 0:t.enabled)}),p=e.computed(()=>{var e,t;return i.showBookmarkMarkers&&c.value&&!1!==(null==(t=null==(e=i.features)?void 0:e.bookmarks)?void 0:t.enabled)}),g=e.computed(()=>{var e,t;return c.value&&!1!==(null==(t=null==(e=i.features)?void 0:e.bookmarks)?void 0:t.enabled)}),f=function(s,i){const o=e.computed(()=>{var e;return null==(e=s())?void 0:e.selectionToolbar}),r=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=s())?void 0:e.markup)?void 0:t.enabled)}),n=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=s())?void 0:e.notes)?void 0:t.enabled)}),{provides:l}=t.useCapability(h.SelectionPlugin.id),{provides:d}=t.useCapability(a.AnnotationPlugin.id),{provides:c}=t.useCapability(pe.id);return e.computed(()=>{var t,a,h;if(!1!==(null==(t=o.value)?void 0:t.enabled)&&(r.value||n.value||(null==(h=null==(a=o.value)?void 0:a.extraActions)?void 0:h.length)))return t=>{const a=Gt(t.item);return h=>{var u,p,g;return e.h("div",h.menuWrapperProps,e.h(Xt,{placementAbove:!!(null==(u=h.placement)?void 0:u.suggestTop),anchorHeight:h.rect.size.height,hiddenBuiltinActions:null==(p=o.value)?void 0:p.hiddenBuiltinActions,extraActions:null==(g=o.value)?void 0:g.extraActions,onAction:e=>{var o,h,u;if("highlight"!==e&&"underline"!==e&&"squiggly"!==e&&"strikeout"!==e){if("note"===e){if(!l.value||!c.value||!n.value)return;const e=l.value.getHighlightRectsForPage(t.item.localPageIndex,a);return void Vt(l.value.getSelectedText(a),a=>{var s;null==(s=c.value)||s.requestCreateFromSelection({chapterId:t.item.chapterId,localPageIndex:t.item.localPageIndex,globalPageIndex:t.item.globalPageIndex,globalPageNumber:t.item.globalPageNumber,rectsPdfCoord:e,selectedText:a.join("\n")})})}null==(o=null==i?void 0:i.onExtraAction)||o.call(i,e,t)}else{if(!l.value||!d.value||!r.value)return;T(a,Qt[e],d.value,l.value,null==(u=null==(h=s())?void 0:h.markup)?void 0:u.styles)}}}))}}})}(()=>i.features,{onExtraAction:i.onExtraSelectionAction}),m=e.computed(()=>{if(i.buildSelectionMenu||f.value)return e=>{const t=f.value?f.value(e):e.defaultMenu;return i.buildSelectionMenu?i.buildSelectionMenu({...e,defaultMenu:t}):t}}),{provides:v}=t.useCapability(o.DocumentManagerPlugin.id);function b(t){var a;const s=[];if(g.value){const a=function(t){var a,s,o,r;const n=Gt(t),l=null==(s=null==(a=v.value)?void 0:a.getDocument(n))?void 0:s.pages[t.localPageIndex];return t.isPlaceholder||!l?null:e.h(Rt,{item:t,pdfPageWidth:l.size.width,pdfPageHeight:l.size.height,cssPageWidth:t.width,cssPageHeight:t.height,hoverUi:null==(r=null==(o=i.features)?void 0:o.bookmarks)?void 0:r.hover})}(t);a&&s.push(a)}const o=null==(a=i.renderPageOverlay)?void 0:a.call(i,t);if(o&&s.push(o),s.length)return e.h("div",s)}return(t,a)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"hostRef",ref:n,class:e.normalizeClass(s.className),style:e.normalizeStyle(s.className?void 0:e.unref(S))},[e.createVNode(e.unref(lt),{class:e.normalizeClass(s.className)},{page:e.withCtx(({item:t})=>{var a,i,o,r;return[e.createVNode(_t,{item:t,features:s.features,"show-note-markers":u.value,"show-bookmark-markers":p.value,"show-redaction-layer":s.showRedactionLayer,"note-marker-ui":null==(i=null==(a=s.features)?void 0:a.notes)?void 0:i.marker,"bookmark-marker-ui":null==(r=null==(o=s.features)?void 0:o.bookmarks)?void 0:r.marker,"build-selection-menu":m.value,"create-note":e.unref(l),"annotation-selection-menu":s.annotationSelectionMenu,"redaction-selection-menu":s.redactionSelectionMenu,"render-page-overlay":b},null,8,["item","features","show-note-markers","show-bookmark-markers","show-redaction-layer","note-marker-ui","bookmark-marker-ui","build-selection-menu","create-note","annotation-selection-menu","redaction-selection-menu"])]}),_:1},8,["class"]),e.renderSlot(t.$slots,"default")],6))}}),ea=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{},onExtraSelectionAction:{type:Function}},setup(a){const s=a,i=e.computed(()=>function(e){if(e.options)return Ye(e.options);if(!e.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const t=z(e.features),{plugins:a}=We({...e.editorOptions,features:t});return{plugins:a,features:t,editorOptions:{...e.editorOptions,features:t}}}({engine:s.engine,options:s.options,editorOptions:s.editorOptions,features:s.features}));return(s,o)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(a.className),style:e.normalizeStyle(a.className?void 0:e.unref(S))},[e.createVNode(e.unref(t.EmbedPDF),{engine:a.engine,plugins:i.value.plugins},{default:e.withCtx(({pluginsReady:t})=>[t?(e.openBlock(),e.createBlock(Jt,{key:0,class:e.normalizeClass(a.viewportClassName),features:i.value.features,"on-extra-selection-action":a.onExtraSelectionAction},null,8,["class","features","on-extra-selection-action"])):e.createCommentVNode("",!0),t?e.renderSlot(s.$slots,"default",{key:1}):e.createCommentVNode("",!0)]),_:3},8,["engine","plugins"])],6))}}),ta={class:"chapter-tree-row"},aa=["aria-expanded"],sa={key:1,class:"chapter-tree-toggle-spacer","aria-hidden":""},ia={class:"chapter-tree-label"},oa={class:"chapter-tree-meta"},ra={key:0},na=(e,t)=>{const a=e.__vccOpts||e;for(const[s,i]of t)a[s]=i;return a},la=na(e.defineComponent({__name:"ChapterTreeItem",props:{node:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup(t){const a={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"},s=t,i=e.computed(()=>s.node.children??[]),o=e.computed(()=>i.value.length>0),r=e.ref(s.depth<1),n=e.computed(()=>s.activeChapterId===s.node.id),l=e.computed(()=>s.chapterStatus[s.node.id]??"idle"),h=e.computed(()=>!o.value);return(s,d)=>(e.openBlock(),e.createElementBlock("li",null,[e.createElementVNode("div",ta,[o.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"chapter-tree-toggle","aria-expanded":r.value,onClick:d[0]||(d[0]=e=>r.value=!r.value)},e.toDisplayString(r.value?"▼":"▶"),9,aa)):(e.openBlock(),e.createElementBlock("span",sa)),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["chapter-tree-btn",{"chapter-tree-btn-active":n.value}]),onClick:d[1]||(d[1]=e=>s.$emit("select",t.node.id))},[e.createElementVNode("div",ia,e.toDisplayString(t.node.title),1),e.createElementVNode("div",oa,[e.createElementVNode("span",null," 第 "+e.toDisplayString(t.node.startPage)+e.toDisplayString(t.node.endPage!==t.node.startPage?`–${t.node.endPage}`:"")+" 页 ",1),h.value?(e.openBlock(),e.createElementBlock("span",ra,e.toDisplayString(a[l.value]),1)):e.createCommentVNode("",!0)])],2)]),o.value&&r.value?(e.openBlock(),e.createBlock(ha,{key:0,nodes:i.value,depth:t.depth+1,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:d[2]||(d[2]=e=>s.$emit("select",e))},null,8,["nodes","depth","active-chapter-id","chapter-status"])):e.createCommentVNode("",!0)]))}}),[["__scopeId","data-v-315bbf7a"]]),ha=na(e.defineComponent({__name:"ChapterTreeList",props:{nodes:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup:t=>(a,s)=>(e.openBlock(),e.createElementBlock("ul",{class:"chapter-tree-list",style:e.normalizeStyle({marginLeft:t.depth>0?"12px":"0"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.nodes,i=>(e.openBlock(),e.createBlock(la,{key:i.id,node:i,depth:t.depth,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:s[0]||(s[0]=e=>a.$emit("select",e))},null,8,["node","depth","active-chapter-id","chapter-status"]))),128))],4))}),[["__scopeId","data-v-eb742e4f"]]),da={class:"chapter-tree"},ca={class:"chapter-tree-nav","aria-label":"章节目录"},ua=na(e.defineComponent({__name:"ChapterTreePanel",props:{tree:{},activeChapterId:{}},emits:["active-chapter-change"],setup(a,{emit:s}){const i=a,o=s,{provides:r}=t.useCapability(K.id),{provides:n}=t.useCapability(R.id),l=e.ref({});function h(){if(!n.value)return;const e={},t=a=>{var s;for(const i of a)e[i.id]=n.value.getChapterStatus(i.id),(null==(s=i.children)?void 0:s.length)&&t(i.children)};t(i.tree),l.value=e}e.watch([n,()=>i.tree],h,{immediate:!0});let d=null;function c(e){var t;o("active-chapter-change",e),null==(t=r.value)||t.scrollToChapter(e)}return e.watch(n,e=>{null==d||d(),d=e?e.onChapterStatusChange(h):null},{immediate:!0}),e.onBeforeUnmount(()=>null==d?void 0:d()),(t,s)=>(e.openBlock(),e.createElementBlock("aside",da,[s[0]||(s[0]=e.createElementVNode("h2",{class:"chapter-tree-title"},"章节目录",-1)),e.createElementVNode("nav",ca,[e.createVNode(ha,{nodes:a.tree,depth:0,"active-chapter-id":a.activeChapterId,"chapter-status":l.value,onSelect:c},null,8,["nodes","active-chapter-id","chapter-status"])])]))}}),[["__scopeId","data-v-d7a0838d"]]),pa=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{}},setup:t=>(t,a)=>(e.openBlock(),e.createBlock(e.unref(ea),e.normalizeProps(e.guardReactiveProps(t.$props)),null,16))});const ga={kind:"first-wins"};function fa(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}class ma{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}}function va(e,t=ga){const a=function(e,t=ga){const a=new Map;for(const i of e.chapters){const[e,t]=i.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(i):a.set(s,[i])}}const s=new Map;for(const[i,o]of a)s.set(i,fa(i,o,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((e,t)=>e-t),o=[];let r=0;for(const n of i){const e=a.get(n),t=s.get(e);if(!t)continue;const[i]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-i);o.push({globalPageIndex:r++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new ma(o)}const ba=class e extends i.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=i.createBehaviorEmitter(),this.manifestChange$=i.createEmitter(),this.overlapStrategy=ga,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(o.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ga,this.setManifestInternal(e.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,i]=s.globalPageRange,[o,r]=s.localPageRange;if(e>i&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${i}]`),o>r&&t.push(`${s.chapterId}: invalid localPageRange [${o},${r}]`),i-e!==r-o&&t.push(`${s.chapterId}: page-count mismatch (global ${i-e+1} vs local ${r-o+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>i)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)i.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=va(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const n of s){const e=i.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<i.length&&o.add(t)}const r=new Set;for(const n of o)r.add(i[n]);for(const n of r){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=i.find(e=>s.has(e));if(e&&this.documentManager.provides().isDocumentOpen(e)){this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,i),i}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(e){var t;this.updateStatus(e.chapterId,"loading"),this.chapterLastUsed.set(e.chapterId,Date.now());const a=e.encrypted&&(null==(t=this.passwordProvider)?void 0:t.getCachedPassword)?this.passwordProvider.getCachedPassword(e.chapterId):null,s=await this.resolvePdfPayload(e),i=this.documentManager.provides(),o="url"in s?i.openDocumentUrl({documentId:e.chapterId,url:s.url,name:e.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:e.chapterId,buffer:s.buffer,name:e.title,password:a??void 0,autoActivate:!1});return await new Promise(e=>o.wait(()=>e(),()=>e())),this.waitForTerminalStatus(e.chapterId)}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>{"loaded"!==e&&"error"!==e&&"password-required"!==e&&"closed"!==e||(s(),t(e))},s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)});a(this.chapterStatus.get(e)??"idle")})}async handleDocumentError(t,a,i){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const o=this.findChapter(t);if(!o)return;const r=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,r);let n=null;try{n=await this.passwordProvider.resolvePassword(o,r-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}if(!n)return void this.updateStatus(t,"password-required");this.updateStatus(t,"loading");this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})}closeChapter(e){const t=this.documentManager.provides();if(t.isDocumentOpen(e)){t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed"))}else this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};ba.id="chapter-manager";let Pa=ba;Object.defineProperty(exports,"EmbedPDF",{enumerable:!0,get:()=>t.EmbedPDF}),Object.defineProperty(exports,"useCapability",{enumerable:!0,get:()=>t.useCapability}),Object.defineProperty(exports,"usePdfiumEngine",{enumerable:!0,get:()=>M.usePdfiumEngine}),exports.CallbackPasswordProvider=N,exports.ChapterManagerPlugin=Pa,exports.ChapterPdfViewer=pa,exports.ChapterTreePanel=ua,exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=qe,exports.PdfChapterViewport=Jt,exports.applySelectionMarkup=T,exports.buildParagraphBookmarkAnchor=Ee,exports.createChapterViewerBundle=Ye,exports.createChapterViewerEditor=We,exports.createChapterViewerEditorOptions=function(e){const{features:t,...a}=Ze(je(e));return a},exports.createPdfChapterEditor=Ue;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),t=require("@embedpdf/core/vue"),a=require("@embedpdf/plugin-annotation"),s=require("@embedpdf/models"),r=require("@embedpdf/core"),i=require("@embedpdf/plugin-document-manager"),o=require("@embedpdf/plugin-interaction-manager"),n=require("@embedpdf/plugin-render"),l=require("@embedpdf/plugin-rotate"),h=require("@embedpdf/plugin-selection"),d=require("@embedpdf/plugin-history"),c=require("@embedpdf/plugin-redaction"),u=require("@embedpdf/plugin-form"),p=require("@embedpdf/plugin-stamp"),g=require("@embedpdf/plugin-signature"),f=require("@embedpdf/plugin-commands"),m=require("@embedpdf/plugin-i18n"),v=require("@embedpdf/plugin-ui"),b=require("@embedpdf/plugin-interaction-manager/vue"),P=require("@embedpdf/plugin-rotate/vue"),w=require("@embedpdf/plugin-selection/vue"),C=require("@embedpdf/plugin-annotation/vue"),I=require("@embedpdf/plugin-redaction/vue"),y=require("@embedpdf/plugin-render/vue"),M=require("@embedpdf/engines/vue"),S={position:"relative",height:"100%",width:"100%"},x={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:0},strikeout:{offsetY:0}},k={highlight:s.PdfAnnotationSubtype.HIGHLIGHT,underline:s.PdfAnnotationSubtype.UNDERLINE,squiggly:s.PdfAnnotationSubtype.SQUIGGLY,strikeout:s.PdfAnnotationSubtype.STRIKEOUT};function L(e,t){return 0===t?e:e.map(e=>({origin:{x:e.origin.x,y:e.origin.y+t},size:{...e.size}}))}function $(e){let t=1/0,a=1/0,s=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.origin.x),a=Math.min(a,i.origin.y),s=Math.max(s,i.origin.x+i.size.width),r=Math.max(r,i.origin.y+i.size.height);return{origin:{x:t,y:a},size:{width:s-t,height:r-a}}}function T(e,t,r,i,o){const n=r.forDocument(e),l=i.forDocument(e);if(!n||!l)return!1;const h="highlight"===t?"highlight":"underline"===t?"underline":"squiggly"===t?"squiggly":"strikeout",d=r.getTool(h);if(!d)return!1;const c=d.defaults,u={...x[g=t],...null==(f=o)?void 0:f[g]},p=l.getFormattedSelection();var g,f;if(0===p.length)return!1;n.setLocked({type:a.LockModeType.Exclude,categories:["markup","shape"]});for(const a of p){const e=s.uuidV4(),r=u.color??c.color??c.strokeColor,i=u.opacity??c.opacity,o=u.thickness??c.strokeWidth,l=u.offsetY??0,h="underline"===t||"squiggly"===t||"strikeout"===t?L(a.segmentRects,l):a.segmentRects,d="underline"===t||"squiggly"===t||"strikeout"===t?$(h):a.rect;n.createAnnotation(a.pageIndex,{id:e,created:new Date,flags:["print"],type:k[t],..."highlight"===t?{blendMode:s.PdfBlendMode.Multiply}:{},strokeColor:r,opacity:i,...null!=o?{strokeWidth:o}:{},pageIndex:a.pageIndex,rect:d,segmentRects:h})}return l.clear(),!0}function D(e,t){const a=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...a,enabled:!1!==(null==a?void 0:a.enabled)}}function z(e){const t=D(null==e?void 0:e.markup,{enabled:!0}),a=D(null==e?void 0:e.bookmarks,{enabled:!0}),s=D(null==e?void 0:e.notes,{enabled:!0});return{markup:t,bookmarks:a,notes:s,zoom:D(null==e?void 0:e.zoom,{enabled:!0,min:.5,max:3,initial:1}),selectionToolbar:D(void 0===(null==e?void 0:e.selectionToolbar)?!1!==t.enabled||!1!==s.enabled:e.selectionToolbar,{enabled:!0})}}class N{constructor(e){this.cb=e}resolvePassword(e,t){return this.cb(e,t)}}const O="chapter-manager",E={id:O,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}},G={kind:"first-wins"};function A(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let V=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const _=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=G,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??G,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=G){const a=function(e,t=G){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,A(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new V(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};_.id="chapter-manager";let R=_;const B={manifest:E,create:e=>new R(O,e),reducer:e=>e,initialState:{}},F="chapter-scroll",U={id:F,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}},q={kind:"first-wins"};function H(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let W=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const j=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=q,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??q,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=q){const a=function(e,t=q){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,H(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new W(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};j.id="chapter-manager";let Z=j;function Y(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}const J=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,Y),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Z.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||this.refreshLayout()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,a)=>this.scrollToGlobalPdfPoint(e,t,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};J.id="chapter-scroll";let K=J;const X={manifest:U,create:e=>new K(F,e),reducer:e=>e,initialState:{}},Q="note",ee={id:Q,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}},te={kind:"first-wins"};function ae(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let se=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const re=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=te,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??te,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=te){const a=function(e,t=te){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,ae(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new se(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};re.id="chapter-manager";let ie=re;const oe={kind:"first-wins"};function ne(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let le=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const he=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=oe,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??oe,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=oe){const a=function(e,t=oe){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,ne(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new le(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};he.id="chapter-manager";let de=he;function ce(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}const ue=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,ce),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(de.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||this.refreshLayout()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,a)=>this.scrollToGlobalPdfPoint(e,t,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};ue.id="chapter-scroll";let pe=ue;const ge=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=r.createBehaviorEmitter([]),this.noteActivated$=r.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(pe.id),this.chapterManager=this.registry.getPlugin(ie.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(e.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(a=>a.chapterId===e&&a.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,a;const s=this.notes.get(e);s&&(null==(a=(t=this.config.callbacks).onActivateNote)||a.call(t,e,s),this.noteActivated$.emit({noteId:e,anchor:s}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[a,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(a);for(const a of t)a.chapterId===e&&this.notes.set(a.noteId,a);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:me(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:t,complete:async e=>{const a={...t,noteId:e};this.registerNote(a)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const a=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let r=null;try{r=await s(a)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!r)return null;const i={...a,noteId:r.noteId};return this.registerNote(i),i}async deleteNote(t){var a,s;if(this.notes.has(t)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,t))}catch(r){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",r)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,a){var s,r;const i=this.notes.get(t);if(!i)return;const o={...i,content:a};try{await(null==(r=(s=this.config.callbacks).onUpdateNote)?void 0:r.call(s,o))}catch(n){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",n)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const a=this.notes.get(e);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(t=this.documentManager.provides().getDocument(a.chapterId))?void 0:t.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),a=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{r(),a(null)},2500),r=t.onLayoutChange(t=>{const i=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);i&&(clearTimeout(s),r(),a(i))})})}};ge.id="note";let fe=ge;function me(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const ve={manifest:ee,create:e=>new fe(Q,e),reducer:e=>e,initialState:{}},be="paragraph-bookmark",Pe={id:be,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}},we={kind:"first-wins"};function Ce(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let Ie=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const ye=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=we,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??we,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=we){const a=function(e,t=we){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,Ce(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new Ie(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};ye.id="chapter-manager";let Me=ye;const Se={kind:"first-wins"};function xe(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let ke=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const Le=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Se,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Se,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Se){const a=function(e,t=Se){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,xe(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new ke(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};Le.id="chapter-manager";let $e=Le;function Te(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}const De=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,Te),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin($e.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||this.refreshLayout()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,a)=>this.scrollToGlobalPdfPoint(e,t,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};De.id="chapter-scroll";let ze=De;function Ne(e){if(0===e.length)throw new Error("unionRects: empty rects");let t=1/0,a=1/0,s=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.origin.x),a=Math.min(a,i.origin.y),s=Math.max(s,i.origin.x+i.size.width),r=Math.max(r,i.origin.y+i.size.height);return{origin:{x:t,y:a},size:{width:s-t,height:r-a}}}function Oe(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Ee(e,t){const a=e.origin.y,s=e.origin.y+e.size.height,r=t.origin.y,i=t.origin.y+t.size.height,o=Math.max(s,i)-Math.min(a,r);return o<=0?0:Math.max(0,Math.min(s,i)-Math.max(a,r))/o}function Ge(e,t){var a,s;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const r=(null==(a=e.rectsPdfCoord)?void 0:a.length)?e.rectsPdfCoord:[e.rectPdfCoord],i=(null==(s=t.rectsPdfCoord)?void 0:s.length)?t.rectsPdfCoord:[t.rectPdfCoord],o=e.markerAnchor??Oe(r),n=t.markerAnchor??Oe(i);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const l of r)for(const e of i){if(Ee(l,e)<.5)continue;const t=Math.max(l.origin.x,e.origin.x);if(Math.min(l.origin.x+l.size.width,e.origin.x+e.size.width)-t>.25*Math.min(l.size.width,e.size.width))return!0}return!1}function Ae(e,t,a,s){const r=a.length>0?a:[];if(0===r.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:e,localPageIndex:t,globalPageIndex:null==s?void 0:s.globalPageIndex,globalPageNumber:null==s?void 0:s.globalPageNumber,rectPdfCoord:Ne(r),rectsPdfCoord:r,markerAnchor:Oe(r)}}const Ve=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.change$=r.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(ze.id),this.chapterManager=this.registry.getPlugin(Me.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(t){var a;if(this.config=t,null==(a=t.callbacks)?void 0:a.load)try{const e=await t.callbacks.load();for(const t of e)this.entries.set(t.id,t);this.change$.emit(this.list())}catch(s){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:e=>this.addBookmark(e),removeBookmark:e=>this.removeBookmark(e),updateBookmark:(e,t)=>this.updateBookmark(e,t),listBookmarks:()=>this.list(),getBookmark:e=>this.entries.get(e)??null,scrollToBookmark:e=>this.scrollToBookmark(e),requestRemoveBookmark:e=>this.requestRemoveBookmark(e),listBookmarksForChapter:e=>this.listBookmarksForChapter(e),replaceBookmarksForChapter:(e,t)=>this.replaceBookmarksForChapter(e,t),onBookmarksChange:this.change$.on}}addBookmark(e){for(const s of this.entries.values())if(Ge(s.anchor,e.anchor))return s;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,a),this.notifyAndPersist(),a}removeBookmark(e){var t,a,s;this.entries.delete(e)&&(this.notifyAndPersist(),null==(s=null==(a=null==(t=this.config)?void 0:t.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,e))}async requestRemoveBookmark(t){var a,s;const r=this.entries.get(t);if(!r)return!1;const i=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(i)try{if(!(await i(r)))return!1}catch(o){return this.logger.error(e.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const a=this.entries.get(e);a&&(this.entries.set(e,{...a,...t}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((e,t)=>e.createdAt-t.createdAt)}listBookmarksForChapter(e){return this.list().filter(t=>t.anchor.chapterId===e)}replaceBookmarksForChapter(e,t){for(const[a,s]of this.entries.entries())s.anchor.chapterId===e&&this.entries.delete(a);for(const a of t)a.anchor.chapterId===e&&this.entries.set(a.id,a);this.notifyAndPersist()}notifyAndPersist(){var t,a;const s=this.list();this.change$.emit(s),(null==(a=null==(t=this.config)?void 0:t.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(t=>this.logger.error(e.id,"Persist","persist callback rejected",t))}async scrollToBookmark(e){const t=this.entries.get(e);if(!t)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(t.anchor.chapterId);let s=t.anchor.globalPageIndex;if(void 0===s){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;s=e.globalPageIndex}const r=function(e){if(e.markerAnchor)return e.markerAnchor.y;const t=e.rectPdfCoord;return t.origin.y+t.size.height}(t.anchor);await async function(e,t,a){e.scrollToGlobalPageIndex(t),await function(e,t,a=2500){const s=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{i(),s(null)},a),i=e.onLayoutChange(e=>{const a=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);a&&(clearTimeout(r),i(),s(a))})})}(e,t),e.scrollToGlobalPdfPoint(t,a,{marginTop:80})}(a,s,r)}};Ve.id="paragraph-bookmark";let _e=Ve;const Re={manifest:Pe,create:e=>new _e(be,e),reducer:e=>e,initialState:{}},Be={"annotation-toolbar":{id:"annotation-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"],show:["overflow-annotation-tools"]},md:{minWidth:640,hide:["overflow-annotation-tools"],show:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"]}}},permanent:!1,categories:["annotation"],items:[{type:"spacer",id:"spacer-3",flex:!0},{type:"group",id:"annotation-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-ink",commandId:"annotation:add-ink",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-ink-highlighter",commandId:"annotation:add-ink-highlighter",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-text",commandId:"annotation:add-text",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"add-insert-text",commandId:"annotation:add-insert-text",variant:"icon",categories:["annotation","annotation-markup","annotation-insert-text"]},{type:"command-button",id:"add-replace-text",commandId:"annotation:add-replace-text",variant:"icon",categories:["annotation","annotation-markup","annotation-replace-text"]},{type:"command-button",id:"add-comment",commandId:"annotation:add-comment",variant:"icon",categories:["annotation","annotation-comment-tool"]},{type:"command-button",id:"add-callout",commandId:"annotation:add-callout",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"overflow-annotation-tools",commandId:"annotation:overflow-tools",variant:"icon",categories:["annotation","annotation-overflow"]},{type:"divider",id:"annotation-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"annotation-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-4",flex:!0}]},"shapes-toolbar":{id:"shapes-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-polygon","add-polyline"],show:["overflow-shapes-tools"]},md:{minWidth:640,hide:["overflow-shapes-tools"],show:["add-polygon","add-polyline"]}}},permanent:!1,categories:["annotation","annotation-shape"],items:[{type:"spacer",id:"spacer-5",flex:!0},{type:"group",id:"shapes-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rectangle",commandId:"annotation:add-rectangle",variant:"icon",categories:["annotation","annotation-shape","annotation-rectangle"]},{type:"command-button",id:"add-circle",commandId:"annotation:add-circle",variant:"icon",categories:["annotation","annotation-shape","annotation-circle"]},{type:"command-button",id:"add-line",commandId:"annotation:add-line",variant:"icon",categories:["annotation","annotation-shape","annotation-line"]},{type:"command-button",id:"add-arrow",commandId:"annotation:add-arrow",variant:"icon",categories:["annotation","annotation-shape","annotation-arrow"]},{type:"command-button",id:"add-polygon",commandId:"annotation:add-polygon",variant:"icon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command-button",id:"add-polyline",commandId:"annotation:add-polyline",variant:"icon",categories:["annotation","annotation-shape","annotation-polyline"]},{type:"command-button",id:"overflow-shapes-tools",commandId:"annotation:overflow-shapes",variant:"icon",categories:["annotation","annotation-shape","annotation-overflow"]},{type:"divider",id:"shapes-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"shapes-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-6",flex:!0}]},"form-toolbar":{id:"form-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-form-select","add-form-listbox"],show:["overflow-forms-tools"]},md:{minWidth:640,hide:["overflow-forms-tools"],show:["add-form-select","add-form-listbox"]}}},permanent:!1,categories:["form"],items:[{type:"spacer",id:"spacer-form-1",flex:!0},{type:"group",id:"form-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-form-textfield",commandId:"form:add-textfield",variant:"icon",categories:["form","form-textfield"]},{type:"command-button",id:"add-form-checkbox",commandId:"form:add-checkbox",variant:"icon",categories:["form","form-checkbox"]},{type:"command-button",id:"add-form-radio",commandId:"form:add-radio",variant:"icon",categories:["form","form-radio"]},{type:"command-button",id:"add-form-select",commandId:"form:add-select",variant:"icon",categories:["form","form-select"]},{type:"command-button",id:"add-form-listbox",commandId:"form:add-listbox",variant:"icon",categories:["form","form-listbox"]},{type:"command-button",id:"overflow-forms-tools",commandId:"form:overflow-tools",variant:"icon",categories:["form","form-overflow"]},{type:"divider",id:"form-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"command-button",id:"toggle-form-fill-mode",commandId:"form:toggle-fill-mode",variant:"icon",categories:["form","form-fill-mode"]},{type:"divider",id:"form-tools-divider-2",orientation:"vertical"},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-form-2",flex:!0}]},"insert-toolbar":{id:"insert-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["insert"],items:[{type:"spacer",id:"spacer-insert-1",flex:!0},{type:"group",id:"insert-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rubber-stamp",commandId:"insert:add-rubber-stamp",variant:"icon",categories:["insert","insert-rubber-stamp"]},{type:"command-button",id:"add-signature",commandId:"insert:add-signature",variant:"icon",categories:["insert","insert-signature"]},{type:"command-button",id:"add-image",commandId:"insert:add-image",variant:"icon",categories:["insert","insert-image"]},{type:"divider",id:"insert-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"insert-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-insert-2",flex:!0}]},"redaction-toolbar":{id:"redaction-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["redaction"],items:[{type:"spacer",id:"spacer-7",flex:!0},{type:"group",id:"redaction-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"redact",commandId:"redaction:redact",variant:"icon",categories:["redaction","redaction-combined"]},{type:"divider",id:"redaction-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-redaction-panel",commandId:"panel:toggle-redaction",variant:"icon",categories:["panel","panel-redaction"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"redaction-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-8",flex:!0}]}};class Fe{constructor(){this.specs=[]}register(e){if(this.specs.some(t=>t.id===e.id))throw new Error(`OperationRegistry: duplicate operation id "${e.id}"`);this.specs.push(e)}registerAll(e){for(const t of e)t&&this.register(t)}list(){return this.specs}buildToolbars(){const e=structuredClone(Be);for(const t of this.specs){const a=e[t.toolbarSlot];if(!a)continue;const s={type:"command-button",id:t.id,commandId:t.commandId,variant:"icon",...t.icon?{icon:t.icon}:{},...t.i18nKey?{labelKey:t.i18nKey}:{},...t.label?{label:t.label}:{},categories:t.categories??[]};a.items=Ue(a.items,s,t.position)}return e}}function Ue(e,t,a){return(null==a?void 0:a.after)||(null==a?void 0:a.before)?function(e,t,a){const s=e=>{const r=[];for(const i of e)"group"!==i.type?a.before&&i.id===a.before?r.push(t,i):(r.push(i),a.after&&i.id===a.after&&r.push(t)):r.push({...i,items:s(i.items)});return r};return s(e)}(e,t,a):(s=t,e.map(e=>"group"===e.type?{...e,items:[...e.items,s]}:e));var s}const qe={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function He(e){var t,s,b,P,w,C;const I=e.toolbar??{},y=I.enabledModes??["view","annotate","shapes","insert","form","redact"],M=y.length>0,{schema:S,operationRegistry:x}=function(e={}){var t,a,s,r,i,o;const n=new Set(e.enabledModes??["view","annotate","shapes","insert","form","redact"]),l=new Fe;(null==(t=e.customOperations)?void 0:t.length)&&l.registerAll(e.customOperations);const h=l.buildToolbars(),d={};for(const u of n){if("view"===u)continue;const e=qe[u];h[e]&&(d[e]=h[e])}const c=function(e){if(0===e.size)return null;const t=(e,t,a)=>({type:"command-button",id:`${e}-mode`,commandId:a,variant:"text",label:t,categories:["mode",e]});return{id:"chapter-editor-main-toolbar",position:{placement:"top",slot:"main",order:0},permanent:!0,items:[{type:"spacer",id:"main-spacer-left",flex:!0},{type:"group",id:"mode-group",alignment:"start",gap:2,items:[...e.has("view")?[t("view","View","mode:view")]:[],...e.has("annotate")?[t("annotate","Annotate","mode:annotate")]:[],...e.has("shapes")?[t("shapes","Shapes","mode:shapes")]:[],...e.has("insert")?[t("insert","Insert","mode:insert")]:[],...e.has("form")?[t("form","Form","mode:form")]:[],...e.has("redact")?[t("redact","Redact","mode:redact")]:[]]},{type:"spacer",id:"main-spacer-right",flex:!0}]}}(n);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(a=e.extend)?void 0:a.toolbars)&&Object.assign(d,e.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(s=e.extend)?void 0:s.menus)??{},sidebars:(null==(r=e.extend)?void 0:r.sidebars)??{},modals:(null==(i=e.extend)?void 0:i.modals)??{},selectionMenus:(null==(o=e.extend)?void 0:o.selectionMenus)??{}},operationRegistry:l}}({...I,enabledModes:y}),k={...M?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:e,documentId:t})=>{var s,r,i,o;const n=null==(s=e.getPlugin("ui"))?void 0:s.provides(),l=null==(r=e.getPlugin("interaction-manager"))?void 0:r.provides();n&&l&&(null==(i=l.forDocument(t))||i.activateDefaultMode(),n.forDocument(t).closeToolbarSlot("top","secondary"),null==(o=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||o.provides().forDocument(t).setLocked(e.getPluginConfig(a.ANNOTATION_PLUGIN_ID).locked??{type:a.LockModeType.None}))},active:({state:e,documentId:t})=>!v.isToolbarOpen(e.plugins,t,"top","secondary")},"mode:annotate":{id:"mode:annotate",label:"Annotate",categories:["mode","mode-annotate","annotation"],action:({registry:e,documentId:t})=>{var s,r;const i=null==(s=e.getPlugin("ui"))?void 0:s.provides();i&&(i.setActiveToolbar("top","secondary","annotation-toolbar",t),null==(r=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(t).setLocked({type:a.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","annotation-toolbar")},"mode:shapes":{id:"mode:shapes",label:"Shapes",categories:["mode","mode-shapes","annotation"],action:({registry:e,documentId:t})=>{var s,r;const i=null==(s=e.getPlugin("ui"))?void 0:s.provides();i&&(i.setActiveToolbar("top","secondary","shapes-toolbar",t),null==(r=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(t).setLocked({type:a.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","shapes-toolbar")},"mode:insert":{id:"mode:insert",label:"Insert",categories:["mode","mode-insert","insert"],action:({registry:e,documentId:t})=>{var s,r;const i=null==(s=e.getPlugin("ui"))?void 0:s.provides();i&&(i.setActiveToolbar("top","secondary","insert-toolbar",t),null==(r=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(t).setLocked({type:a.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","insert-toolbar")},"mode:form":{id:"mode:form",label:"Form",categories:["mode","mode-form","form"],action:({registry:e,documentId:t})=>{var s,r;const i=null==(s=e.getPlugin("ui"))?void 0:s.provides();i&&(i.setActiveToolbar("top","secondary","form-toolbar",t),null==(r=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(t).setLocked({type:a.LockModeType.None}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","form-toolbar")},"mode:redact":{id:"mode:redact",label:"Redact",categories:["mode","mode-redact","redaction"],action:({registry:e,documentId:t})=>{var s,r;const i=null==(s=e.getPlugin("ui"))?void 0:s.provides();i&&(i.setActiveToolbar("top","secondary","redaction-toolbar",t),null==(r=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(t).setLocked({type:a.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","redaction-toolbar")}}:{},...M?We(x.list()):{},...e.commands??{}},L=[r.createPluginRegistration(i.DocumentManagerPluginPackage,{initialDocuments:[]}),r.createPluginRegistration(B,{manifest:e.manifest,overlapStrategy:e.overlapStrategy,passwordProvider:e.passwordProvider,chapterPdfLoader:e.chapterPdfLoader,prefetchChapters:e.prefetchChapters,unloadTimeoutMs:e.unloadTimeoutMs}),r.createPluginRegistration(X,{placeholderPageHeight:e.placeholderPageHeight,placeholderPageWidth:e.placeholderPageWidth}),r.createPluginRegistration(o.InteractionManagerPluginPackage),r.createPluginRegistration(n.RenderPluginPackage),r.createPluginRegistration(l.RotatePluginPackage),r.createPluginRegistration(h.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),r.createPluginRegistration(d.HistoryPluginPackage),r.createPluginRegistration(a.AnnotationPluginPackage),r.createPluginRegistration(c.RedactionPluginPackage),r.createPluginRegistration(u.FormPluginPackage),r.createPluginRegistration(p.StampPluginPackage,!1===e.loadDefaultStampLibrary?{manifests:[]}:void 0),r.createPluginRegistration(g.SignaturePluginPackage),...Object.keys(k).length>0?[r.createPluginRegistration(f.CommandsPluginPackage,{commands:k})]:[],...M?[r.createPluginRegistration(m.I18nPluginPackage),r.createPluginRegistration(v.UIPluginPackage,{schema:S})]:[]];return e.notes&&L.push(r.createPluginRegistration(ve,{callbacks:e.notes.callbacks,ui:null==(s=null==(t=e.features)?void 0:t.notes)?void 0:s.marker})),e.bookmarks&&L.push(r.createPluginRegistration(Re,{callbacks:e.bookmarks.callbacks,ui:null==(P=null==(b=e.features)?void 0:b.bookmarks)?void 0:P.marker,hover:null==(C=null==(w=e.features)?void 0:w.bookmarks)?void 0:C.hover})),{plugins:L,uiSchema:S,operationRegistry:x}}function We(e){const t={};for(const a of e)a.handler&&(t[a.commandId]={id:a.commandId,labelKey:a.i18nKey,label:a.label,icon:a.icon,categories:a.categories,action:({documentId:e})=>{var t;null==(t=a.handler)||t.call(a,{documentId:e,chapterId:e})}});return t}const je=z();function Ze(e){return He({...e,toolbar:e.toolbar??{enabledModes:[]},features:z(e.features)})}const Ye={overlapStrategy:{kind:"first-wins"},passwordProvider:new N(async()=>null),prefetchChapters:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};function Je(e){return"callbacks"in e.notes?{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,notes:e.notes.callbacks,bookmarks:e.bookmarks.callbacks}:e}function Ke(e){return{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,...Ye,notes:{callbacks:e.notes},bookmarks:{callbacks:e.bookmarks},features:z(e.features)}}function Xe(e){const t=Ke(Je(e)),{plugins:a}=Ze(t);return{plugins:a,features:t.features,editorOptions:t}}function Qe(e,t=.5,a=3){return Math.min(a,Math.max(t,e))}function et(e,t,a){return Math.min(a,Math.max(t,e))}const tt={chapters:[]};function at(a){const s=e.ref(null),{provides:o}=t.useCapability(R.id),n=e.computed(()=>{var e;return(null==(e=o.value)?void 0:e.getManifest())??tt}),l=e.computed(()=>{var e;return null==(e=a.value)?void 0:e.zoom}),{scale:h,setScale:d,zoomEnabled:c,minZoom:u,maxZoom:p}=function(a,s){var o;const n=e.isRef(a)?a:e.computed(()=>a),{registry:l}=t.useRegistry(),{provides:h}=t.useCapability(i.DocumentManagerPlugin.id),{provides:d}=t.useCapability(R.id),c=e.ref((null==(o=s.value)?void 0:o.initial)??1),u=e.ref(c.value),p=()=>{var e;return(null==(e=s.value)?void 0:e.min)??.5},g=()=>{var e;return(null==(e=s.value)?void 0:e.max)??3},f=()=>{var e;return null==(e=s.value)?void 0:e.pageWidth};function m(e){const t=Qe(e,p(),g());u.value=t,c.value=t,function(e,t,a,s=.5,i=3){const o=null==e?void 0:e.getStore();if(!o)return;const n=Qe(a,s,i);o.dispatchToCore(r.setDefaultScale(n));for(const l of t.chapters)o.getState().core.documents[l.chapterId]&&o.dispatchToCore(r.setScale(n,l.chapterId))}(l.value,n.value,t,p(),g())}function v(e){f()?function(e){const t=f();if(!t||!h.value)return;const a=h.value.getDocument(e);a&&m(function(e,t,a=0){var s;const r=e.pages[a];return(null==(s=null==r?void 0:r.size)?void 0:s.width)?t/r.size.width:1}(a,t))}(e):m(u.value)}return e.watch([l,()=>{var e;return null==(e=s.value)?void 0:e.initial},()=>{var e;return null==(e=s.value)?void 0:e.pageWidth}],()=>{var e;l.value&&(f()||m((null==(e=s.value)?void 0:e.initial)??1))},{immediate:!0}),e.watch([d,n,()=>{var e;return null==(e=s.value)?void 0:e.pageWidth}],()=>{const e=d.value;if(e){for(const t of n.value.chapters)"loaded"===e.getChapterStatus(t.chapterId)&&v(t.chapterId);return e.onChapterStatusChange(e=>{"loaded"===e.status&&v(e.chapterId)})}},{immediate:!0}),{scale:c,setScale:m,zoomEnabled:()=>{var e;return!1!==(null==(e=s.value)?void 0:e.enabled)},minZoom:p,maxZoom:g}}(n,l);return function(t,a){let s=null;e.watch([t,a],()=>{null==s||s();const e=a.value;s=function(e,t){if(!e||!1===t.enabled)return()=>{};let a=null,s=null,r=0;const i=()=>{const s=e.querySelector("[data-chapter-scroll-viewport]");return!!s&&(null==a||a(),a=function({container:e,getScale:t,setScale:a,minZoom:s=.5,maxZoom:r=3}){let i=0,o=1,n=null,l=1,h=1;const d=e=>{(e.ctrlKey||e.metaKey)&&(e.preventDefault(),null===n?(h=t(),l=1):clearTimeout(n),l*=1-.01*e.deltaY,l=et(l,.1,10),a(et(h*l,s,r)),n=setTimeout(()=>{n=null},120))},c=new Map,u=e=>{if(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size){const[e,a]=[...c.values()];i=Math.hypot(a.x-e.x,a.y-e.y),o=t()}},p=e=>{if(c.has(e.pointerId)&&(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size&&i>0)){e.preventDefault();const[t,n]=[...c.values()],l=Math.hypot(n.x-t.x,n.y-t.y);a(et(o*(l/i),s,r))}},g=e=>{c.delete(e.pointerId),c.size<2&&(i=0)};return e.addEventListener("wheel",d,{passive:!1}),e.addEventListener("pointerdown",u),e.addEventListener("pointermove",p,{passive:!1}),e.addEventListener("pointerup",g),e.addEventListener("pointercancel",g),()=>{e.removeEventListener("wheel",d),e.removeEventListener("pointerdown",u),e.removeEventListener("pointermove",p),e.removeEventListener("pointerup",g),e.removeEventListener("pointercancel",g),n&&clearTimeout(n)}}({container:s,getScale:t.getScale,setScale:t.setScale,minZoom:t.minZoom,maxZoom:t.maxZoom}),!0)};return i()||(s=new MutationObserver(()=>{i()&&(null==s||s.disconnect(),s=null)}),s.observe(e,{childList:!0,subtree:!0}),r=requestAnimationFrame(()=>i())),()=>{r&&cancelAnimationFrame(r),null==s||s.disconnect(),null==a||a()}}(t.value??null,{enabled:e.enabled,getScale:e.getScale,setScale:e.setScale,minZoom:e.minZoom,maxZoom:e.maxZoom})},{deep:!0,flush:"post"}),e.onBeforeUnmount(()=>null==s?void 0:s())}(s,e.computed(()=>({enabled:c(),getScale:()=>h.value,setScale:d,minZoom:u(),maxZoom:p()}))),{hostRef:s,scale:h,setScale:d,zoomEnabled:c}}const st={kind:"first-wins"};function rt(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let it=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const ot=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=st,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??st,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=st){const a=function(e,t=st){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,rt(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new it(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};ot.id="chapter-manager";let nt=ot;function lt(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}const ht=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,lt),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(nt.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||this.refreshLayout()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,a)=>this.scrollToGlobalPdfPoint(e,t,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};ht.id="chapter-scroll";let dt=ht;const ct=["data-global-page-index","data-chapter-id","data-local-page-index"],ut=(e=>{const t=e.__vccOpts||e;for(const[a,s]of[["__scopeId","data-v-8a737137"]])t[a]=s;return t})(e.defineComponent({__name:"ChapterScroller",props:{class:{},style:{}},setup(a){const{provides:s}=t.useCapability(dt.id),r=e.ref(null),i=e.ref(null);let o=null;const n=()=>{null==o||o(),o=null,s.value&&(s.value.registerViewport(r.value),o=s.value.onLayoutChange(e=>{i.value=e}))};return e.onMounted(n),e.onBeforeUnmount(()=>{var e;null==o||o(),null==(e=s.value)||e.registerViewport(null)}),e.watch(s,n),(t,a)=>{var s,o,n;return e.openBlock(),e.createElementBlock("div",{ref_key:"containerRef",ref:r,"data-chapter-scroll-viewport":"",class:e.normalizeClass(t.$props.class),style:e.normalizeStyle({overflow:"auto",position:"relative",width:"100%",height:"100%",...t.$props.style})},[e.createElementVNode("div",{style:e.normalizeStyle({position:"relative",width:`${(null==(s=i.value)?void 0:s.totalWidth)??0}px`,height:`${(null==(o=i.value)?void 0:o.totalHeight)??0}px`,margin:"0 auto"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList((null==(n=i.value)?void 0:n.items)??[],s=>(e.openBlock(),e.createElementBlock("div",{key:s.globalPageIndex,"data-global-page-index":s.globalPageIndex,"data-chapter-id":s.chapterId,"data-local-page-index":s.localPageIndex,style:e.normalizeStyle({position:"absolute",top:`${s.offsetTop}px`,left:"50%",transform:"translateX(-50%)",width:`${s.width}px`,height:`${s.height}px`,backgroundColor:s.isPlaceholder?"#f3f4f6":"#fff",boxShadow:"0 1px 4px rgba(0,0,0,0.08)"})},[s.isPlaceholder?e.renderSlot(t.$slots,"placeholder",{key:0,item:s},()=>[a[0]||(a[0]=e.createElementVNode("div",{class:"chapter-scroll-placeholder"},"Loading chapter…",-1))],!0):e.renderSlot(t.$slots,"page",{key:1,item:s},void 0,!0)],12,ct))),128))],4)],6)}}})),pt=e.defineComponent({__name:"ChapterRenderLayer",props:{chapterId:{},localPageIndex:{},scale:{},dpr:{},class:{}},setup:t=>(a,s)=>(e.openBlock(),e.createBlock(e.unref(y.RenderLayer),{"document-id":t.chapterId,"page-index":t.localPageIndex,scale:t.scale,dpr:t.dpr,class:e.normalizeClass(t.class),style:{pointerEvents:"none"}},null,8,["document-id","page-index","scale","dpr","class"]))}),gt={kind:"first-wins"};function ft(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let mt=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const vt=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=gt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??gt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=gt){const a=function(e,t=gt){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,ft(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new mt(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};vt.id="chapter-manager";let bt=vt;const Pt={kind:"first-wins"};function wt(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}class Ct{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}}const It=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Pt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Pt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Pt){const a=function(e,t=Pt){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,wt(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new Ct(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};It.id="chapter-manager";let yt=It;function Mt(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}const St=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,Mt),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(yt.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||this.refreshLayout()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,a)=>this.scrollToGlobalPdfPoint(e,t,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};St.id="chapter-scroll";let xt=St;const kt=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=r.createBehaviorEmitter([]),this.noteActivated$=r.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(xt.id),this.chapterManager=this.registry.getPlugin(bt.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(e.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(a=>a.chapterId===e&&a.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,a;const s=this.notes.get(e);s&&(null==(a=(t=this.config.callbacks).onActivateNote)||a.call(t,e,s),this.noteActivated$.emit({noteId:e,anchor:s}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[a,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(a);for(const a of t)a.chapterId===e&&this.notes.set(a.noteId,a);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:$t(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:t,complete:async e=>{const a={...t,noteId:e};this.registerNote(a)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const a=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let r=null;try{r=await s(a)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!r)return null;const i={...a,noteId:r.noteId};return this.registerNote(i),i}async deleteNote(t){var a,s;if(this.notes.has(t)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,t))}catch(r){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",r)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,a){var s,r;const i=this.notes.get(t);if(!i)return;const o={...i,content:a};try{await(null==(r=(s=this.config.callbacks).onUpdateNote)?void 0:r.call(s,o))}catch(n){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",n)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const a=this.notes.get(e);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(t=this.documentManager.provides().getDocument(a.chapterId))?void 0:t.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),a=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{r(),a(null)},2500),r=t.onLayoutChange(t=>{const i=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);i&&(clearTimeout(s),r(),a(i))})})}};kt.id="note";let Lt=kt;function $t(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Tt(e){const{markerPdf:t,lineRects:a,sx:s,sy:r,cssPageWidth:i,iconSize:o,gapPx:n=6}=e,l=(null==a?void 0:a.length)?a[a.length-1]:void 0;let h,d;l?(h=(l.origin.x+l.size.width)*s+n,d=l.origin.y*r+(l.size.height*r-o)/2):(h=t.x*s-o/2,d=t.y*r-o-n);const c=Math.max(0,i-o-2);return h>c&&(h=c),d<0&&(d=0),{left:h,top:d}}const Dt={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none",zIndex:25}},zt=["onMouseenter"],Nt=["data-note-marker-zone","onMouseenter","onMouseleave"],Ot=["onClick"],Et=["onClick"],Gt=["onClick"],At=e.defineComponent({__name:"NoteMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(a){const s=a,{provides:r}=t.useCapability(Lt.id),i=e.ref([]),o=e.ref(null),n=e.ref(null);e.watch(r,e=>{if(e)return e.onNotesChange(e=>{i.value=e.filter(e=>e.chapterId===s.chapterId&&e.localPageIndex===s.localPageIndex)})},{immediate:!0});let l=null;e.watch(n,e=>{l&&(document.removeEventListener("mousedown",l),l=null),e&&(l=t=>{var a;const s=t.target;(null==(a=s.closest)?void 0:a.call(s,`[data-note-marker-zone="${e}"]`))||(n.value=null,o.value=null)},document.addEventListener("mousedown",l))}),e.onBeforeUnmount(()=>{l&&document.removeEventListener("mousedown",l)});const h=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.iconSize)??16}),d=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.highlightColor)??"rgba(245, 158, 11, 0.08)"});function c(e){const t=s.cssPageWidth/s.pdfPageWidth,a=s.cssPageHeight/s.pdfPageHeight,r=h.value,{left:i,top:o}=Tt({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:t,sy:a,cssPageWidth:s.cssPageWidth,iconSize:r}),l=function(e,t,a){let s=1/0,r=1/0,i=-1/0,o=-1/0;for(const n of e)s=Math.min(s,n.origin.x*t),r=Math.min(r,n.origin.y*a),i=Math.max(i,(n.origin.x+n.size.width)*t),o=Math.max(o,(n.origin.y+n.size.height)*a);return{left:s,top:r,width:i-s,height:o-r}}(e.rectsPdfCoord,t,a),d=n.value===e.noteId?72:0,c=Math.max(0,Math.min(l.left,i)-8),u=Math.max(0,Math.min(l.top,o)-8);return{zoneLeft:c,zoneTop:u,zoneW:Math.min(s.cssPageWidth,Math.max(l.left+l.width,i+r)+8)-c,zoneH:Math.max(l.top+l.height,o+r+6+d)+8-u,iconLeft:i,iconTop:o,sx:t,sy:a}}return(t,s)=>e.unref(r)&&i.value.length&&a.pdfPageWidth&&a.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Dt,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,t=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:t.noteId},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.rectsPdfCoord,(a,s)=>(e.openBlock(),e.createElementBlock("div",{key:`${t.noteId}-bg-${s}`,style:e.normalizeStyle({position:"absolute",left:a.origin.x*c(t).sx+"px",top:a.origin.y*c(t).sy+"px",width:a.size.width*c(t).sx+"px",height:a.size.height*c(t).sy+"px",background:d.value,borderRadius:"2px",pointerEvents:"auto"}),onMouseenter:e=>o.value=t.noteId},null,44,zt))),128)),o.value===t.noteId||n.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,"data-note-marker-zone":t.noteId,style:e.normalizeStyle({position:"absolute",left:`${c(t).zoneLeft}px`,top:`${c(t).zoneTop}px`,width:`${c(t).zoneW}px`,height:`${c(t).zoneH}px`,pointerEvents:"auto",zIndex:26}),onMouseenter:e=>o.value=t.noteId,onMouseleave:e=>n.value!==t.noteId&&(o.value=null)},[e.createElementVNode("button",{type:"button",title:"笔记",style:e.normalizeStyle({position:"absolute",left:c(t).iconLeft-c(t).zoneLeft+"px",top:c(t).iconTop-c(t).zoneTop+"px",width:`${h.value}px`,height:`${h.value}px`,border:"none",borderRadius:"50%",background:"#f59e0b",color:"#fff",cursor:"pointer",fontSize:"11px",padding:0}),onMousedown:s[0]||(s[0]=e.withModifiers(()=>{},["stop"])),onClick:e.withModifiers(e=>n.value=n.value===t.noteId?null:t.noteId,["stop"])}," 💬 ",44,Ot),n.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:c(t).iconLeft-c(t).zoneLeft+"px",top:`${c(t).iconTop-c(t).zoneTop+h.value+4}px`,minWidth:"120px",padding:"6px",borderRadius:"8px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)",zIndex:30}),onMousedown:s[1]||(s[1]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",style:{display:"block",width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#334155",cursor:"pointer","text-align":"left"},onClick:e=>{return a=t,void(null==(s=r.value)||s.requestEditNote(a.noteId,a));var a,s}}," 编辑 ",8,Et),e.createElementVNode("button",{type:"button",style:{display:"block",width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#dc2626",cursor:"pointer","text-align":"left"},onClick:e=>{var a,s;return s=t.noteId,null==(a=r.value)||a.requestDeleteNote(s),void(n.value=null)}}," 删除 ",8,Gt)],36)):e.createCommentVNode("",!0)],44,Nt)):e.createCommentVNode("",!0)],64))),128))])):e.createCommentVNode("",!0)}}),Vt={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none"}},_t=["title","onClick"],Rt=["onClick"],Bt=e.defineComponent({__name:"BookmarkMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(a){const s=a,{provides:r}=t.useCapability(_e.id),i=e.ref([]),o=e.ref(null),n=e.ref(null);function l(){const e=r.value;e&&(i.value=e.listBookmarks().filter(e=>e.anchor.chapterId===s.chapterId&&e.anchor.localPageIndex===s.localPageIndex))}e.watch(r,e=>{if(e)return l(),e.onBookmarksChange(l)},{immediate:!0});let h=null;e.watch(o,e=>{h&&(document.removeEventListener("mousedown",h),h=null),e&&(h=e=>{var t;(null==(t=n.value)?void 0:t.contains(e.target))||(o.value=null)},document.addEventListener("mousedown",h))}),e.onBeforeUnmount(()=>{h&&document.removeEventListener("mousedown",h)});const d=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.iconSize)??16});function c(e){const{left:t,top:a}=function(e){var t;const a=s.cssPageWidth/s.pdfPageWidth,r=s.cssPageHeight/s.pdfPageHeight,i=(null==(t=e.anchor.rectsPdfCoord)?void 0:t.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord];return Tt({markerPdf:e.anchor.markerAnchor??{x:e.anchor.rectPdfCoord.origin.x+e.anchor.rectPdfCoord.size.width,y:e.anchor.rectPdfCoord.origin.y+e.anchor.rectPdfCoord.size.height},lineRects:i,sx:a,sy:r,cssPageWidth:s.cssPageWidth,iconSize:d.value})}(e);return{position:"absolute",left:`${Math.max(0,t-6)}px`,top:`${Math.max(0,a-6)}px`,width:`${d.value+12}px`,height:`${d.value+12}px`,pointerEvents:"auto",zIndex:20}}return(t,s)=>e.unref(r)&&i.value.length&&a.pdfPageWidth&&a.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Vt,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,t=>(e.openBlock(),e.createElementBlock("div",{key:t.id,style:e.normalizeStyle(c(t)),onMousedown:s[1]||(s[1]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",title:t.label,style:e.normalizeStyle({position:"absolute",left:"6px",top:"6px",width:`${d.value}px`,height:`${d.value}px`,border:"none",borderRadius:"4px",background:"#3b82f6",color:"#fff",cursor:"pointer",boxShadow:"0 2px 6px rgba(37, 99, 235, 0.35)",fontSize:"11px",padding:0}),onClick:e.withModifiers(e=>o.value=o.value===t.id?null:t.id,["stop"])}," 🔖 ",12,_t),o.value===t.id?(e.openBlock(),e.createElementBlock("div",{key:0,ref_for:!0,ref_key:"deleteMenuRef",ref:n,style:{position:"absolute",left:"6px",top:"-36px",zIndex:30,pointerEvents:"auto",minWidth:"88px",padding:"4px",borderRadius:"6px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)"},onClick:s[0]||(s[0]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",style:{width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#dc2626",cursor:"pointer","text-align":"left"},onClick:e=>async function(e){const t=r.value;t&&await t.requestRemoveBookmark(e)&&(o.value=null)}(t.id)}," 删除书签 ",8,Rt)],512)):e.createCommentVNode("",!0)],36))),128))])):e.createCommentVNode("",!0)}});function Ft(e){return e.chapterId}function Ut(e,t){e.wait(t,()=>{})}const qt=e.defineComponent({__name:"ChapterPageSurface",props:{item:{},features:{},showNoteMarkers:{type:Boolean},showBookmarkMarkers:{type:Boolean},showRedactionLayer:{type:Boolean},noteMarkerUi:{},bookmarkMarkerUi:{},buildSelectionMenu:{type:Function},createNote:{},annotationSelectionMenu:{},redactionSelectionMenu:{},renderPageOverlay:{type:Function}},setup(a){const s=a,r=e.computed(()=>Ft(s.item));!function(a){const{provides:s}=t.useCapability(i.DocumentManagerPlugin.id);e.watch([s,a],([e,t])=>{e&&t&&e.isDocumentOpen(t)&&e.setActiveDocument(t)},{immediate:!0})}(r);const{provides:o}=t.useCapability(i.DocumentManagerPlugin.id),{provides:n}=t.useCapability(h.SelectionPlugin.id),l=e.computed(()=>{var e,t;return null==(t=null==(e=o.value)?void 0:e.getDocument(r.value))?void 0:t.pages[s.item.localPageIndex]});function d(t,a){const r=s.createNote.value;if(r)return s=>{var i;const o={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(i=s.placement)?void 0:i.suggestTop)?-40:s.rect.size.height+8};return e.h("div",s.menuWrapperProps,[e.h("div",{style:o},e.h("button",{type:"button",style:{padding:"6px 10px",fontSize:"12px",border:"1px solid #e2e8f0",borderRadius:"6px",background:"#fff",cursor:"pointer"},onClick:()=>{if(!n.value)return;const e=n.value.getHighlightRectsForPage(t.localPageIndex,a);Ut(n.value.getSelectedText(a),a=>{var s,i,o;r((s=t,i=e,o=a.join("\n"),{chapterId:s.chapterId,localPageIndex:s.localPageIndex,globalPageIndex:s.globalPageIndex,globalPageNumber:s.globalPageNumber,rectsPdfCoord:i,selectedText:o}))})}},"添加附注"))])}}const c=e.computed(()=>{const e=s.buildSelectionMenu,t={item:s.item,defaultMenu:d(s.item,r.value),createNote:s.createNote.value};if(e){const a=e(t);if(a)return a}return t.defaultMenu}),u=e.computed(()=>{var e;return null==(e=s.renderPageOverlay)?void 0:e.call(s,s.item)});return(t,s)=>a.item.isPlaceholder?e.createCommentVNode("",!0):(e.openBlock(),e.createBlock(e.unref(b.GlobalPointerProvider),{key:0,"document-id":r.value},{default:e.withCtx(()=>[e.createVNode(e.unref(P.Rotate),{"document-id":r.value,"page-index":a.item.localPageIndex,style:{backgroundColor:"#fff"}},{default:e.withCtx(()=>[e.createVNode(e.unref(b.PagePointerProvider),{"document-id":r.value,"page-index":a.item.localPageIndex},{default:e.withCtx(()=>[e.createVNode(e.unref(pt),{"chapter-id":r.value,"local-page-index":a.item.localPageIndex},null,8,["chapter-id","local-page-index"]),e.createVNode(e.unref(w.SelectionLayer),{"document-id":r.value,"page-index":a.item.localPageIndex,"selection-menu":c.value},null,8,["document-id","page-index","selection-menu"]),a.showRedactionLayer?(e.openBlock(),e.createBlock(e.unref(I.RedactionLayer),{key:0,"document-id":r.value,"page-index":a.item.localPageIndex,"selection-menu":a.redactionSelectionMenu},null,8,["document-id","page-index","selection-menu"])):e.createCommentVNode("",!0),e.createVNode(e.unref(C.AnnotationLayer),{"document-id":r.value,"page-index":a.item.localPageIndex,"selection-menu":a.annotationSelectionMenu},null,8,["document-id","page-index","selection-menu"]),a.showBookmarkMarkers&&l.value?(e.openBlock(),e.createBlock(Bt,{key:1,"chapter-id":r.value,"local-page-index":a.item.localPageIndex,"pdf-page-width":l.value.size.width,"pdf-page-height":l.value.size.height,"css-page-width":a.item.width,"css-page-height":a.item.height,ui:a.bookmarkMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),u.value?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(u.value),{key:2})):e.createCommentVNode("",!0),a.showNoteMarkers&&l.value?(e.openBlock(),e.createBlock(At,{key:3,"chapter-id":r.value,"local-page-index":a.item.localPageIndex,"pdf-page-width":l.value.size.width,"pdf-page-height":l.value.size.height,"css-page-width":a.item.width,"css-page-height":a.item.height,ui:a.noteMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),e.renderSlot(t.$slots,"default")]),_:3},8,["document-id","page-index"])]),_:3},8,["document-id","page-index"])]),_:3},8,["document-id"]))}}),Ht=e.defineComponent({__name:"HoverBookmarkLayer",props:{item:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},hoverUi:{}},setup(a){const s=a,r=e.computed(()=>Ft(s.item)),{provides:i}=t.useCapability(h.SelectionPlugin.id),{provides:o}=t.useCapability(_e.id),n=e.ref(null),l=e.ref(null),d=e.ref(null),c=e.ref(null),u=e.computed(()=>{var e;return(null==(e=s.hoverUi)?void 0:e.iconSize)??16}),p=e.computed(()=>c.value??d.value);let g=null,f=0;function m(){const e=i.value;if(!e)return;const t=e.forDocument(r.value).getState().geometry[s.item.localPageIndex];t&&(l.value=t)}e.watch([i,r,()=>s.item.localPageIndex],([e])=>{if(null==g||g(),g=null,cancelAnimationFrame(f),l.value=null,!e)return;const t=e.forDocument(r.value);g=t.onSelectionChange(m);let a=!1;const i=()=>{if(!a){try{if(m(),t.getState().geometry[s.item.localPageIndex])return}catch{}f=requestAnimationFrame(i)}};return i(),()=>{a=!0,cancelAnimationFrame(f),null==g||g(),g=null}},{immediate:!0});let v=null;e.watch([l,()=>s.pdfPageWidth,c,i],()=>{v&&(document.removeEventListener("mousemove",v),v=null),l.value&&s.pdfPageWidth&&(v=e=>{if(c.value)return;const t=i.value;if(t)try{if(t.forDocument(r.value).getState().selecting)return void(d.value=null)}catch{}const a=n.value;if(!a)return;const o=a.getBoundingClientRect();if(e.clientX<o.left||e.clientX>o.right||e.clientY<o.top||e.clientY>o.bottom)return void(d.value=null);const u=function(e,t){const a=h.glyphAt(e,t);if(a<0)return null;const s=h.expandToLineBoundary(e,a);if(!s)return null;const r=h.rectsWithinSlice(e,s.from,s.to);return 0===r.length?null:{lineRects:r,charFrom:s.from,charTo:s.to}}(l.value,{x:(e.clientX-o.left)/(s.cssPageWidth/s.pdfPageWidth),y:(e.clientY-o.top)/(s.cssPageHeight/s.pdfPageHeight)});d.value=(null==u?void 0:u.lineRects)??null},document.addEventListener("mousemove",v))},{immediate:!0}),e.onBeforeUnmount(()=>{v&&document.removeEventListener("mousemove",v),cancelAnimationFrame(f),null==g||g()});const b=e.computed(()=>{const e=p.value;return(null==e?void 0:e.length)?Ae(s.item.chapterId,s.item.localPageIndex,e,{globalPageIndex:s.item.globalPageIndex,globalPageNumber:s.item.globalPageNumber}):null}),P=e.computed(()=>{const e=b.value,t=o.value;return!(!e||!t)&&t.listBookmarks().some(t=>Ge(t.anchor,e))});function w(){const e=o.value,t=b.value;e&&t&&!P.value&&(e.addBookmark({label:`书签 ${(new Date).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}`,anchor:t}),d.value=null,c.value=null)}const C=e.computed(()=>{const e=p.value,t=null==e?void 0:e[e.length-1];if(!t||!s.pdfPageWidth)return null;const a=s.cssPageWidth/s.pdfPageWidth,r=s.cssPageHeight/s.pdfPageHeight,i=u.value;return{iconLeft:Math.min((t.origin.x+t.size.width)*a+6,Math.max(0,s.cssPageWidth-i-2)),iconTop:t.origin.y*r+(t.size.height*r-i)/2,zoneLeft:Math.max(0,(t.origin.x+t.size.width)*a-4),zoneTop:Math.max(0,t.origin.y*r-4),size:i}});return(t,s)=>{var r;return e.unref(o)&&a.pdfPageWidth&&a.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"rootRef",ref:n,style:{position:"absolute",inset:"0",zIndex:14,pointerEvents:"none"}},[C.value&&p.value&&!P.value?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:`${C.value.zoneLeft}px`,top:`${C.value.zoneTop}px`,width:`${C.value.size+20}px`,height:`${((null==(r=p.value[p.value.length-1])?void 0:r.size.height)??0)*(a.cssPageHeight/a.pdfPageHeight)+C.value.size+12}px`,pointerEvents:"auto"}),onMouseenter:s[0]||(s[0]=e=>c.value=p.value),onMouseleave:s[1]||(s[1]=e=>c.value=null)},[e.createElementVNode("button",{type:"button",title:"添加书签",style:e.normalizeStyle({position:"absolute",left:C.value.iconLeft-C.value.zoneLeft+"px",top:C.value.iconTop-C.value.zoneTop+"px",width:`${C.value.size}px`,height:`${C.value.size}px`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"#3b82f6",color:"#fff",border:"none",borderRadius:"4px",boxShadow:"0 2px 8px rgba(37, 99, 235, 0.45)",fontSize:"12px",padding:0}),onClick:e.withModifiers(w,["stop"])}," 🔖 ",4)],36)):e.createCommentVNode("",!0)],512)):e.createCommentVNode("",!0)}}}),Wt={key:0,width:"24",height:"24",viewBox:"0 0 28 28",fill:"none","aria-hidden":""},jt={key:0,x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#fde047"},Zt={key:1,d:"M6 22h16",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},Yt={key:2,d:"M6 22c2-2 3-2 5 0s3 2 5 0 3-2 5 0",stroke:"#dc2626","stroke-width":"2","stroke-linecap":"round",fill:"none"},Jt={key:3,d:"M5 14h18",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},Kt={key:1,width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},Xt=e.defineComponent({__name:"SelectionToolbarIcons",props:{kind:{}},setup:t=>(a,s)=>"note"!==t.kind?(e.openBlock(),e.createElementBlock("svg",Wt,["highlight"===t.kind?(e.openBlock(),e.createElementBlock("rect",jt)):e.createCommentVNode("",!0),s[0]||(s[0]=e.createElementVNode("text",{x:"14",y:"19","text-anchor":"middle","font-size":"15","font-weight":"700","font-family":"system-ui, -apple-system, sans-serif",fill:"#0f172a"}," A ",-1)),"underline"===t.kind?(e.openBlock(),e.createElementBlock("path",Zt)):"squiggly"===t.kind?(e.openBlock(),e.createElementBlock("path",Yt)):"strikeout"===t.kind?(e.openBlock(),e.createElementBlock("path",Jt)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("svg",Kt,[...s[1]||(s[1]=[e.createElementVNode("path",{d:"M8 3h8l4 4v14H8V3z",fill:"#fef3c7",stroke:"#d97706","stroke-width":"1.2","stroke-linejoin":"round"},null,-1),e.createElementVNode("path",{d:"M16 3v4h4",stroke:"#d97706","stroke-width":"1.2"},null,-1),e.createElementVNode("path",{d:"M10 12h6M10 16h4",stroke:"#92400e","stroke-width":"1.2","stroke-linecap":"round"},null,-1)])]))}),Qt=["title","aria-label","onMouseenter","onClick"],ea=["title","onMouseenter","onClick"],ta={style:{"font-size":"11px","font-weight":"600"}},aa=e.defineComponent({__name:"SelectionToolbarCard",props:{placementAbove:{type:Boolean},anchorHeight:{},hiddenBuiltinActions:{},extraActions:{}},emits:["action"],setup(t,{emit:a}){const s=t,r=a,i=[{id:"highlight",label:"高亮背景"},{id:"underline",label:"下划线"},{id:"squiggly",label:"波浪线"},{id:"strikeout",label:"删除线"},{id:"note",label:"添加笔记"}],o=e.computed(()=>new Set(s.hiddenBuiltinActions??[])),n=e.computed(()=>i.filter(e=>"note"!==e.id&&!o.value.has(e.id))),l=e.computed(()=>!o.value.has("note")),h=e.computed(()=>[...s.extraActions??[]].sort((e,t)=>(e.order??0)-(t.order??0))),d=e.ref(null),c=e.computed(()=>({position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:s.placementAbove?void 0:`${s.anchorHeight+10}px`,bottom:s.placementAbove?`${s.anchorHeight+10}px`:void 0,display:"flex",alignItems:"center",gap:"2px",padding:"4px 6px",borderRadius:"12px",background:"rgba(255, 255, 255, 0.96)",border:"1px solid rgba(15, 23, 42, 0.06)",boxShadow:"0 2px 8px rgba(15, 23, 42, 0.08), 0 12px 32px rgba(15, 23, 42, 0.1)",backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)"}));function u(e,t=!1){return{display:"flex",alignItems:"center",justifyContent:"center",width:"32px",height:"32px",padding:0,margin:0,border:"none",borderRadius:"8px",background:d.value===e?t?"#fffbeb":"#f1f5f9":"transparent",color:t?"#b45309":"#334155",cursor:"pointer",flexShrink:0,WebkitAppearance:"none",appearance:"none"}}const p={width:"1px",height:"20px",margin:"0 4px",background:"rgba(15, 23, 42, 0.1)",flexShrink:0};return(t,a)=>(e.openBlock(),e.createElementBlock("div",{role:"toolbar","aria-label":"选区工具",style:e.normalizeStyle(c.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,"aria-label":t.label,style:e.normalizeStyle(u(t.id)),onMouseenter:e=>d.value=t.id,onMouseleave:a[0]||(a[0]=e=>d.value=null),onClick:e=>r("action",t.id)},[e.createVNode(Xt,{kind:t.id},null,8,["kind"])],44,Qt))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(h.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,style:e.normalizeStyle(u(t.id)),onMouseenter:e=>d.value=t.id,onMouseleave:a[1]||(a[1]=e=>d.value=null),onClick:e=>r("action",t.id)},[e.createElementVNode("span",ta,e.toDisplayString(t.label.slice(0,2)),1)],44,ea))),128)),l.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("span",{style:p,"aria-hidden":""}),e.createElementVNode("button",{type:"button",title:"添加笔记","aria-label":"添加笔记",style:e.normalizeStyle(u("note",!0)),onMouseenter:a[2]||(a[2]=e=>d.value="note"),onMouseleave:a[3]||(a[3]=e=>d.value=null),onClick:a[4]||(a[4]=e=>r("action","note"))},[e.createVNode(Xt,{kind:"note"})],36)],64)):e.createCommentVNode("",!0)],4))}}),sa={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"},ra=e.defineComponent({__name:"PdfChapterViewport",props:{className:{},features:{},buildSelectionMenu:{},annotationSelectionMenu:{},redactionSelectionMenu:{},showNoteMarkers:{type:Boolean,default:!0},showBookmarkMarkers:{type:Boolean,default:!0},showRedactionLayer:{type:Boolean,default:!1},renderPageOverlay:{},onExtraSelectionAction:{}},setup(s){const r=s,o=e.computed(()=>r.features),{hostRef:n}=at(o),l=function(){const{registry:a}=t.useRegistry();return e.computed(()=>{var e,t,s;const r=null==(s=null==(t=null==(e=a.value)?void 0:e.getPlugin(fe.id))?void 0:t.provides)?void 0:s.call(t);return r?e=>r.createNoteFromSelection(e):null})}(),d=function(){const{registry:a}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=a.value)?void 0:e.getPlugin(fe.id))})}(),c=function(){const{registry:a}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=a.value)?void 0:e.getPlugin(_e.id))})}(),u=e.computed(()=>{var e,t;return r.showNoteMarkers&&d.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.notes)?void 0:t.enabled)}),p=e.computed(()=>{var e,t;return r.showBookmarkMarkers&&c.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.bookmarks)?void 0:t.enabled)}),g=e.computed(()=>{var e,t;return c.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.bookmarks)?void 0:t.enabled)}),f=function(s,r){const i=e.computed(()=>{var e;return null==(e=s())?void 0:e.selectionToolbar}),o=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=s())?void 0:e.markup)?void 0:t.enabled)}),n=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=s())?void 0:e.notes)?void 0:t.enabled)}),{provides:l}=t.useCapability(h.SelectionPlugin.id),{provides:d}=t.useCapability(a.AnnotationPlugin.id),{provides:c}=t.useCapability(fe.id);return e.computed(()=>{var t,a,h;if(!1!==(null==(t=i.value)?void 0:t.enabled)&&(o.value||n.value||(null==(h=null==(a=i.value)?void 0:a.extraActions)?void 0:h.length)))return t=>{const a=Ft(t.item);return h=>{var u,p,g;return e.h("div",h.menuWrapperProps,e.h(aa,{placementAbove:!!(null==(u=h.placement)?void 0:u.suggestTop),anchorHeight:h.rect.size.height,hiddenBuiltinActions:null==(p=i.value)?void 0:p.hiddenBuiltinActions,extraActions:null==(g=i.value)?void 0:g.extraActions,onAction:e=>{var i,h,u;if("highlight"!==e&&"underline"!==e&&"squiggly"!==e&&"strikeout"!==e){if("note"===e){if(!l.value||!c.value||!n.value)return;const e=l.value.getHighlightRectsForPage(t.item.localPageIndex,a);return void Ut(l.value.getSelectedText(a),a=>{var s;null==(s=c.value)||s.requestCreateFromSelection({chapterId:t.item.chapterId,localPageIndex:t.item.localPageIndex,globalPageIndex:t.item.globalPageIndex,globalPageNumber:t.item.globalPageNumber,rectsPdfCoord:e,selectedText:a.join("\n")})})}null==(i=null==r?void 0:r.onExtraAction)||i.call(r,e,t)}else{if(!l.value||!d.value||!o.value)return;T(a,sa[e],d.value,l.value,null==(u=null==(h=s())?void 0:h.markup)?void 0:u.styles)}}}))}}})}(()=>r.features,{onExtraAction:r.onExtraSelectionAction}),m=e.computed(()=>{if(r.buildSelectionMenu||f.value)return e=>{const t=f.value?f.value(e):e.defaultMenu;return r.buildSelectionMenu?r.buildSelectionMenu({...e,defaultMenu:t}):t}}),{provides:v}=t.useCapability(i.DocumentManagerPlugin.id);function b(t){var a;const s=[];if(g.value){const a=function(t){var a,s,i,o;const n=Ft(t),l=null==(s=null==(a=v.value)?void 0:a.getDocument(n))?void 0:s.pages[t.localPageIndex];return t.isPlaceholder||!l?null:e.h(Ht,{item:t,pdfPageWidth:l.size.width,pdfPageHeight:l.size.height,cssPageWidth:t.width,cssPageHeight:t.height,hoverUi:null==(o=null==(i=r.features)?void 0:i.bookmarks)?void 0:o.hover})}(t);a&&s.push(a)}const i=null==(a=r.renderPageOverlay)?void 0:a.call(r,t);if(i&&s.push(i),s.length)return e.h("div",s)}return(t,a)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"hostRef",ref:n,class:e.normalizeClass(s.className),style:e.normalizeStyle(s.className?void 0:e.unref(S))},[e.createVNode(e.unref(ut),{class:e.normalizeClass(s.className)},{page:e.withCtx(({item:t})=>{var a,r,i,o;return[e.createVNode(qt,{item:t,features:s.features,"show-note-markers":u.value,"show-bookmark-markers":p.value,"show-redaction-layer":s.showRedactionLayer,"note-marker-ui":null==(r=null==(a=s.features)?void 0:a.notes)?void 0:r.marker,"bookmark-marker-ui":null==(o=null==(i=s.features)?void 0:i.bookmarks)?void 0:o.marker,"build-selection-menu":m.value,"create-note":e.unref(l),"annotation-selection-menu":s.annotationSelectionMenu,"redaction-selection-menu":s.redactionSelectionMenu,"render-page-overlay":b},null,8,["item","features","show-note-markers","show-bookmark-markers","show-redaction-layer","note-marker-ui","bookmark-marker-ui","build-selection-menu","create-note","annotation-selection-menu","redaction-selection-menu"])]}),_:1},8,["class"]),e.renderSlot(t.$slots,"default")],6))}}),ia={key:0,style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,width:"100%"}},oa=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{},onExtraSelectionAction:{type:Function}},setup(a){const s=a,r=e.computed(()=>function(e){if(e.options)return Xe(e.options);if(!e.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const t=z(e.features),{plugins:a}=Ze({...e.editorOptions,features:t});return{plugins:a,features:t,editorOptions:{...e.editorOptions,features:t}}}({engine:s.engine,options:s.options,editorOptions:s.editorOptions,features:s.features}));return(s,i)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(a.className),style:e.normalizeStyle(a.className?void 0:e.unref(S))},[e.createVNode(e.unref(t.EmbedPDF),{engine:a.engine,plugins:r.value.plugins},{default:e.withCtx(({pluginsReady:t})=>[t?(e.openBlock(),e.createElementBlock("div",ia,[e.renderSlot(s.$slots,"prepend"),e.createVNode(ra,{class:e.normalizeClass(a.viewportClassName),style:{flex:1,minHeight:0},features:r.value.features,"on-extra-selection-action":a.onExtraSelectionAction},null,8,["class","features","on-extra-selection-action"]),e.renderSlot(s.$slots,"default")])):e.createCommentVNode("",!0)]),_:3},8,["engine","plugins"])],6))}}),na={class:"chapter-tree-row"},la=["aria-expanded"],ha={key:1,class:"chapter-tree-toggle-spacer","aria-hidden":""},da={class:"chapter-tree-label"},ca={class:"chapter-tree-meta"},ua={key:0},pa=(e,t)=>{const a=e.__vccOpts||e;for(const[s,r]of t)a[s]=r;return a},ga=pa(e.defineComponent({__name:"ChapterTreeItem",props:{node:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup(t){const a={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"},s=t,r=e.computed(()=>s.node.children??[]),i=e.computed(()=>r.value.length>0),o=e.ref(s.depth<1),n=e.computed(()=>s.activeChapterId===s.node.id),l=e.computed(()=>s.chapterStatus[s.node.id]??"idle"),h=e.computed(()=>!i.value);return(s,d)=>(e.openBlock(),e.createElementBlock("li",null,[e.createElementVNode("div",na,[i.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"chapter-tree-toggle","aria-expanded":o.value,onClick:d[0]||(d[0]=e=>o.value=!o.value)},e.toDisplayString(o.value?"▼":"▶"),9,la)):(e.openBlock(),e.createElementBlock("span",ha)),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["chapter-tree-btn",{"chapter-tree-btn-active":n.value}]),onClick:d[1]||(d[1]=e=>s.$emit("select",t.node.id))},[e.createElementVNode("div",da,e.toDisplayString(t.node.title),1),e.createElementVNode("div",ca,[e.createElementVNode("span",null," 第 "+e.toDisplayString(t.node.startPage)+e.toDisplayString(t.node.endPage!==t.node.startPage?`–${t.node.endPage}`:"")+" 页 ",1),h.value?(e.openBlock(),e.createElementBlock("span",ua,e.toDisplayString(a[l.value]),1)):e.createCommentVNode("",!0)])],2)]),i.value&&o.value?(e.openBlock(),e.createBlock(fa,{key:0,nodes:r.value,depth:t.depth+1,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:d[2]||(d[2]=e=>s.$emit("select",e))},null,8,["nodes","depth","active-chapter-id","chapter-status"])):e.createCommentVNode("",!0)]))}}),[["__scopeId","data-v-315bbf7a"]]),fa=pa(e.defineComponent({__name:"ChapterTreeList",props:{nodes:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup:t=>(a,s)=>(e.openBlock(),e.createElementBlock("ul",{class:"chapter-tree-list",style:e.normalizeStyle({marginLeft:t.depth>0?"12px":"0"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.nodes,r=>(e.openBlock(),e.createBlock(ga,{key:r.id,node:r,depth:t.depth,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:s[0]||(s[0]=e=>a.$emit("select",e))},null,8,["node","depth","active-chapter-id","chapter-status"]))),128))],4))}),[["__scopeId","data-v-eb742e4f"]]),ma={class:"chapter-tree"},va={class:"chapter-tree-nav","aria-label":"章节目录"},ba=pa(e.defineComponent({__name:"ChapterTreePanel",props:{tree:{},activeChapterId:{}},emits:["active-chapter-change"],setup(a,{emit:s}){const r=a,i=s,{provides:o}=t.useCapability(K.id),{provides:n}=t.useCapability(R.id),l=e.ref({});function h(){if(!n.value)return;const e={},t=a=>{var s;for(const r of a)e[r.id]=n.value.getChapterStatus(r.id),(null==(s=r.children)?void 0:s.length)&&t(r.children)};t(r.tree),l.value=e}e.watch([n,()=>r.tree],h,{immediate:!0});let d=null;function c(e){var t;i("active-chapter-change",e),null==(t=o.value)||t.scrollToChapter(e)}return e.watch(n,e=>{null==d||d(),d=e?e.onChapterStatusChange(h):null},{immediate:!0}),e.onBeforeUnmount(()=>null==d?void 0:d()),(t,s)=>(e.openBlock(),e.createElementBlock("aside",ma,[s[0]||(s[0]=e.createElementVNode("h2",{class:"chapter-tree-title"},"章节目录",-1)),e.createElementVNode("nav",va,[e.createVNode(fa,{nodes:a.tree,depth:0,"active-chapter-id":a.activeChapterId,"chapter-status":l.value,onSelect:c},null,8,["nodes","active-chapter-id","chapter-status"])])]))}}),[["__scopeId","data-v-d7a0838d"]]),Pa=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{}},setup:t=>(t,a)=>(e.openBlock(),e.createBlock(e.unref(oa),e.normalizeProps(e.guardReactiveProps(t.$props)),e.createSlots({default:e.withCtx(()=>[e.renderSlot(t.$slots,"default")]),_:2},[t.$slots.prepend?{name:"prepend",fn:e.withCtx(()=>[e.renderSlot(t.$slots,"prepend")]),key:"0"}:void 0]),1040))});const wa={kind:"first-wins"};function Ca(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}class Ia{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}}function ya(e,t=wa){const a=function(e,t=wa){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,Ca(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new Ia(i)}const Ma=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=wa,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??wa,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=ya(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));if(e&&this.documentManager.provides().isDocumentOpen(e)){this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}if(!n)return void this.updateStatus(t,"password-required");this.updateStatus(t,"loading");this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})}closeChapter(e){const t=this.documentManager.provides();if(t.isDocumentOpen(e)){t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed"))}else this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};Ma.id="chapter-manager";let Sa=Ma;const xa={kind:"first-wins"};function ka(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let La=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const $a=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=xa,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??xa,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=xa){const a=function(e,t=xa){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,ka(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new La(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};$a.id="chapter-manager";let Ta=$a;const Da={kind:"first-wins"};function za(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}class Na{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}}const Oa=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Da,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Da,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Da){const a=function(e,t=Da){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,za(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new Na(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};Oa.id="chapter-manager";let Ea=Oa;function Ga(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}(class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,Ga),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ea.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||this.refreshLayout()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,a)=>this.scrollToGlobalPdfPoint(e,t,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}}).id="chapter-scroll";const Aa={kind:"first-wins"};function Va(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let _a=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const Ra=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Aa,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Aa,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Aa){const a=function(e,t=Aa){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,Va(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new _a(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};Ra.id="chapter-manager";let Ba=Ra;const Fa={kind:"first-wins"};function Ua(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let qa=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const Ha=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Fa,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Fa,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Fa){const a=function(e,t=Fa){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,Ua(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new qa(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};Ha.id="chapter-manager";let Wa=Ha;function ja(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}const Za=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,ja),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Wa.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||this.refreshLayout()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,a)=>this.scrollToGlobalPdfPoint(e,t,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};Za.id="chapter-scroll";let Ya=Za;const Ja=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=r.createBehaviorEmitter([]),this.noteActivated$=r.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(Ya.id),this.chapterManager=this.registry.getPlugin(Ba.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(e.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(a=>a.chapterId===e&&a.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,a;const s=this.notes.get(e);s&&(null==(a=(t=this.config.callbacks).onActivateNote)||a.call(t,e,s),this.noteActivated$.emit({noteId:e,anchor:s}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[a,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(a);for(const a of t)a.chapterId===e&&this.notes.set(a.noteId,a);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:Xa(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:t,complete:async e=>{const a={...t,noteId:e};this.registerNote(a)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const a=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let r=null;try{r=await s(a)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!r)return null;const i={...a,noteId:r.noteId};return this.registerNote(i),i}async deleteNote(t){var a,s;if(this.notes.has(t)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,t))}catch(r){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",r)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,a){var s,r;const i=this.notes.get(t);if(!i)return;const o={...i,content:a};try{await(null==(r=(s=this.config.callbacks).onUpdateNote)?void 0:r.call(s,o))}catch(n){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",n)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const a=this.notes.get(e);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(t=this.documentManager.provides().getDocument(a.chapterId))?void 0:t.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),a=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{r(),a(null)},2500),r=t.onLayoutChange(t=>{const i=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);i&&(clearTimeout(s),r(),a(i))})})}};Ja.id="note";let Ka=Ja;function Xa(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const Qa={kind:"first-wins"};function es(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let ts=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const as=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Qa,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Qa,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Qa){const a=function(e,t=Qa){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,es(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new ts(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};as.id="chapter-manager";let ss=as;const rs={kind:"first-wins"};function is(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}class os{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}}const ns=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=rs,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??rs,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=rs){const a=function(e,t=rs){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,is(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new os(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};ns.id="chapter-manager";let ls=ns;function hs(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}const ds=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,hs),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ls.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||this.refreshLayout()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,a)=>this.scrollToGlobalPdfPoint(e,t,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};ds.id="chapter-scroll";let cs=ds;function us(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function ps(e,t){const a=e.origin.y,s=e.origin.y+e.size.height,r=t.origin.y,i=t.origin.y+t.size.height,o=Math.max(s,i)-Math.min(a,r);return o<=0?0:Math.max(0,Math.min(s,i)-Math.max(a,r))/o}function gs(e,t){var a,s;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const r=(null==(a=e.rectsPdfCoord)?void 0:a.length)?e.rectsPdfCoord:[e.rectPdfCoord],i=(null==(s=t.rectsPdfCoord)?void 0:s.length)?t.rectsPdfCoord:[t.rectPdfCoord],o=e.markerAnchor??us(r),n=t.markerAnchor??us(i);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const l of r)for(const e of i){if(ps(l,e)<.5)continue;const t=Math.max(l.origin.x,e.origin.x);if(Math.min(l.origin.x+l.size.width,e.origin.x+e.size.width)-t>.25*Math.min(l.size.width,e.size.width))return!0}return!1}const fs=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.change$=r.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(cs.id),this.chapterManager=this.registry.getPlugin(ss.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(t){var a;if(this.config=t,null==(a=t.callbacks)?void 0:a.load)try{const e=await t.callbacks.load();for(const t of e)this.entries.set(t.id,t);this.change$.emit(this.list())}catch(s){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:e=>this.addBookmark(e),removeBookmark:e=>this.removeBookmark(e),updateBookmark:(e,t)=>this.updateBookmark(e,t),listBookmarks:()=>this.list(),getBookmark:e=>this.entries.get(e)??null,scrollToBookmark:e=>this.scrollToBookmark(e),requestRemoveBookmark:e=>this.requestRemoveBookmark(e),listBookmarksForChapter:e=>this.listBookmarksForChapter(e),replaceBookmarksForChapter:(e,t)=>this.replaceBookmarksForChapter(e,t),onBookmarksChange:this.change$.on}}addBookmark(e){for(const s of this.entries.values())if(gs(s.anchor,e.anchor))return s;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,a),this.notifyAndPersist(),a}removeBookmark(e){var t,a,s;this.entries.delete(e)&&(this.notifyAndPersist(),null==(s=null==(a=null==(t=this.config)?void 0:t.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,e))}async requestRemoveBookmark(t){var a,s;const r=this.entries.get(t);if(!r)return!1;const i=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(i)try{if(!(await i(r)))return!1}catch(o){return this.logger.error(e.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const a=this.entries.get(e);a&&(this.entries.set(e,{...a,...t}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((e,t)=>e.createdAt-t.createdAt)}listBookmarksForChapter(e){return this.list().filter(t=>t.anchor.chapterId===e)}replaceBookmarksForChapter(e,t){for(const[a,s]of this.entries.entries())s.anchor.chapterId===e&&this.entries.delete(a);for(const a of t)a.anchor.chapterId===e&&this.entries.set(a.id,a);this.notifyAndPersist()}notifyAndPersist(){var t,a;const s=this.list();this.change$.emit(s),(null==(a=null==(t=this.config)?void 0:t.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(t=>this.logger.error(e.id,"Persist","persist callback rejected",t))}async scrollToBookmark(e){const t=this.entries.get(e);if(!t)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(t.anchor.chapterId);let s=t.anchor.globalPageIndex;if(void 0===s){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;s=e.globalPageIndex}const r=function(e){if(e.markerAnchor)return e.markerAnchor.y;const t=e.rectPdfCoord;return t.origin.y+t.size.height}(t.anchor);await async function(e,t,a){e.scrollToGlobalPageIndex(t),await function(e,t,a=2500){const s=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{i(),s(null)},a),i=e.onLayoutChange(e=>{const a=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);a&&(clearTimeout(r),i(),s(a))})})}(e,t),e.scrollToGlobalPdfPoint(t,a,{marginTop:80})}(a,s,r)}};fs.id="paragraph-bookmark";let ms=fs;function vs(e,t){const a=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...a,enabled:!1!==(null==a?void 0:a.enabled)}}s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT,function(){const e=vs(void 0,{enabled:!0}),t=vs(void 0,{enabled:!0}),a=vs(void 0,{enabled:!0});vs(void 0,{enabled:!0,min:.5,max:3,initial:1}),vs(!1!==e.enabled||!1!==a.enabled,{enabled:!0})}();function bs(e){const t=new Uint8Array(e);let a="";for(let s=0;s<t.length;s++)a+=String.fromCharCode(t[s]);return btoa(a)}function Ps(e){return{bookmarks:!1!==(null==e?void 0:e.bookmarks),notes:!1!==(null==e?void 0:e.notes),markup:!1!==(null==e?void 0:e.markup)}}function ws(e){var t,s,r,i;return{annotation:null==(t=e.getPlugin(a.AnnotationPlugin.id))?void 0:t.provides(),note:null==(s=e.getPlugin(Ka.id))?void 0:s.provides(),bookmark:null==(r=e.getPlugin(ms.id))?void 0:r.provides(),chapterManager:null==(i=e.getPlugin(Ta.id))?void 0:i.provides()}}async function Cs(e,t,a){if(!a||!e)return;const s=await e.ensureChapterLoaded(t);if("loaded"!==s)throw new Error(`章节 ${t} 未加载成功(${s}),无法导入/导出划线`)}async function Is(e,t,a){const s=Ps(a),{annotation:r,note:i,bookmark:o,chapterManager:n}=ws(e),l={chapterId:t};if(s.bookmarks){if(!o)throw new Error("paragraph-bookmark 插件未注册");l.bookmarks=o.listBookmarksForChapter(t)}if(s.notes){if(!i)throw new Error("note 插件未注册");l.notes=i.listNotesForChapter(t)}if(s.markup){if(!r)throw new Error("annotation 插件未注册");await Cs(n,t,!1!==(null==a?void 0:a.ensureChapterLoaded));const e=await(h=r.forDocument(t).exportAnnotations(),new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))}));l.markup=function(e){return e.map(e=>{if(!(e.ctx&&"data"in e.ctx&&e.ctx.data instanceof ArrayBuffer))return{annotation:e.annotation};const t=e.ctx;return{annotation:e.annotation,ctx:{dataBase64:bs(t.data),mimeType:t.mimeType}}})}(e)}var h;return l}async function ys(e,t,a){const s=Ps(a),r=(null==a?void 0:a.mode)??"replace",{annotation:i,note:o,bookmark:n,chapterManager:l}=ws(e),h=t.chapterId;if(s.bookmarks&&t.bookmarks){if(!n)throw new Error("paragraph-bookmark 插件未注册");if("replace"===r)n.replaceBookmarksForChapter(h,t.bookmarks);else for(const e of t.bookmarks)n.addBookmark(e)}if(s.notes&&t.notes){if(!o)throw new Error("note 插件未注册");if("replace"===r)o.replaceNotesForChapter(h,t.notes);else for(const e of t.notes)o.registerNote(e)}if(s.markup&&t.markup){if(!i)throw new Error("annotation 插件未注册");await Cs(l,h,!1!==(null==a?void 0:a.ensureChapterLoaded));const e=i.forDocument(h),s=function(e){return e.map(e=>{var t;if(!(null==(t=e.ctx)?void 0:t.dataBase64))return{annotation:e.annotation};const a=function(e){const t=atob(e),a=new Uint8Array(t.length);for(let s=0;s<t.length;s++)a[s]=t.charCodeAt(s);return a.buffer}(e.ctx.dataBase64);return{annotation:e.annotation,ctx:{data:a,...e.ctx.mimeType?{mimeType:e.ctx.mimeType}:{}}}})}(t.markup);"replace"===r&&e.deleteAllAnnotations(),e.importAnnotations(s)}(null==a?void 0:a.persistNotes)&&o&&await a.persistNotes(o.listAllNotes()),(null==a?void 0:a.persistBookmarks)&&n&&await a.persistBookmarks(n.listBookmarks())}function Ms(e){return JSON.stringify(e,null,2)}function Ss(e){return JSON.stringify(e,null,2)}function xs(e,t){const a=new Blob([t],{type:"application/json;charset=utf-8"}),s=URL.createObjectURL(a),r=document.createElement("a");r.href=s,r.download=e,r.click(),URL.revokeObjectURL(s)}Object.defineProperty(exports,"EmbedPDF",{enumerable:!0,get:()=>t.EmbedPDF}),Object.defineProperty(exports,"useCapability",{enumerable:!0,get:()=>t.useCapability}),Object.defineProperty(exports,"useRegistry",{enumerable:!0,get:()=>t.useRegistry}),Object.defineProperty(exports,"usePdfiumEngine",{enumerable:!0,get:()=>M.usePdfiumEngine}),exports.CHAPTER_ANNOTATIONS_ARCHIVE_VERSION=1,exports.CallbackPasswordProvider=N,exports.ChapterManagerPlugin=Sa,exports.ChapterPdfViewer=Pa,exports.ChapterTreePanel=ba,exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=je,exports.PdfChapterViewport=ra,exports.applySelectionMarkup=T,exports.buildParagraphBookmarkAnchor=Ae,exports.chapterAnnotationsArchiveToJson=Ms,exports.chapterAnnotationsSnapshotToJson=Ss,exports.createChapterViewerBundle=Xe,exports.createChapterViewerEditor=Ze,exports.createChapterViewerEditorOptions=function(e){const{features:t,...a}=Ke(Je(e));return a},exports.createPdfChapterEditor=He,exports.downloadChapterAnnotationsArchive=function(e,t="chapter-annotations.json"){xs(t,Ms(e))},exports.downloadChapterAnnotationsSnapshot=function(e,t){xs(t??`chapter-annotations-${e.chapterId}.json`,Ss(e))},exports.downloadJsonFile=xs,exports.exportAllChapterAnnotations=async function(e,t,a){const s={};for(const r of t.chapters){const t=await Is(e,r.chapterId,a),{chapterId:i,...o}=t;s[r.chapterId]=o}return{version:1,exportedAt:(new Date).toISOString(),chapters:s}},exports.exportChapterAnnotations=Is,exports.importChapterAnnotations=ys,exports.importChapterAnnotationsArchive=async function(e,t,a){if(1!==t.version)throw new Error(`不支持的归档版本 ${t.version},当前为 1`);for(const[s,r]of Object.entries(t.chapters))await ys(e,{chapterId:s,...r},a)},exports.parseChapterAnnotationsArchiveJson=function(e){const t=JSON.parse(e);if(!t||"object"!=typeof t||!t.chapters)throw new Error("无效的章节标注 JSON");return t},exports.parseChapterAnnotationsSnapshotJson=function(e){const t=JSON.parse(e);if(!(null==t?void 0:t.chapterId))throw new Error("无效的章节标注 JSON:缺少 chapterId");return t};
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|