@aceshooting/lyra-ui 30.1.0 → 30.2.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/CHANGELOG.md +21 -0
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
- package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
- package/dist/components/charts/chart/chart-prepared-data.d.ts +3 -1
- package/dist/components/charts/chart/chart-prepared-data.js +1 -1
- package/dist/components/charts/chart/chart.class.js +2 -2
- package/dist/components/charts/chart/lite-chart.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.d.ts +1 -1
- package/dist/components/forms/checkbox/checkbox.class.js +2 -2
- package/dist/components/forms/combobox/option.class.d.ts +1 -1
- package/dist/components/forms/combobox/option.class.js +2 -2
- package/dist/components/forms/radio/radio.class.d.ts +1 -1
- package/dist/components/forms/radio/radio.class.js +1 -1
- package/dist/components/forms/switch/switch.class.d.ts +1 -1
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/media/map/map-anchor-controller.js +1 -1
- package/dist/components/media/map/map.class.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer-loader.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.d.ts +11 -11
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
- package/dist/internal/accessible-text-controller.js +1 -1
- package/dist/internal/anchored-overlay-runtime.js +1 -1
- package/dist/internal/default-label-forwarding.js +1 -0
- package/dist/internal/hierarchy-summary-source.js +1 -0
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/positioner.d.ts +8 -0
- package/dist/internal/positioner.js +1 -1
- package/llms/components/lr-map.md +7 -6
- package/llms/components/lr-pptx-viewer.md +9 -5
- package/llms/index.md +1 -1
- package/llms/peers.md +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEngine3dLoader}from"../../../internal/engine-3d-loader.js";import{webgl2Available}from"../../../internal/engine-3d.js";import{tag}from"../../../internal/prefix.js";const modelEngineLoader=createEngine3dLoader({entry:"model",tag:tag("model-viewer"),load:()=>import("@aceshooting/lyra-3d/model")}),modelEngineEnvironment={available:document=>webgl2Available(()=>document.createElement("canvas"))};export{modelEngineEnvironment,modelEngineLoader};
|
|
1
|
+
import{createEngine3dLoader}from"../../../internal/engine-3d-loader.js";import{webgl2Available}from"../../../internal/engine-3d.js";import{tag}from"../../../internal/prefix.js";const modelEngineLoader=createEngine3dLoader({entry:"model",tag:tag("model-viewer"),load:()=>import("@aceshooting/lyra-3d/model")}),modelEngineEnvironment={available:document=>webgl2Available(()=>document.createElement("canvas"))};function supportsAsyncModelData(engine){return"setDataAsync"in engine&&typeof engine.setDataAsync=="function"}export{modelEngineEnvironment,modelEngineLoader,supportsAsyncModelData};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{ifDefined}from"lit/directives/if-defined.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{safeDownloadHref}from"../../../internal/safe-url.js";import{isAbortError,isResourceLimitError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{engine3dFailureReason}from"../../../internal/engine-3d.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{modelEngineEnvironment,modelEngineLoader}from"./model-viewer-loader.js";import{MODEL_SOURCE_MAX_BYTES,DEFAULT_MODEL_CAMERA,readModelSource,resolveModelFormat,snapshotModelCamera}from"./model-viewer-source.js";import{styles}from"./model-viewer.styles.js";import{LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_download,LYRA_DEFAULT_engine3dContextLost,LYRA_DEFAULT_engine3dSoftwareRendering,LYRA_DEFAULT_engine3dUnavailable,LYRA_DEFAULT_engine3dUnsupported,LYRA_DEFAULT_retry,LYRA_DEFAULT_zoomIn,LYRA_DEFAULT_zoomOut}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_modelViewerAlternative,LYRA_DEFAULT_modelViewerEmpty,LYRA_DEFAULT_modelViewerFit,LYRA_DEFAULT_modelViewerInstructions,LYRA_DEFAULT_modelViewerInvalid,LYRA_DEFAULT_modelViewerLabel,LYRA_DEFAULT_modelViewerProgress,LYRA_DEFAULT_modelViewerReady,LYRA_DEFAULT_modelViewerRotateDown,LYRA_DEFAULT_modelViewerRotateLeft,LYRA_DEFAULT_modelViewerRotateRight,LYRA_DEFAULT_modelViewerRotateUp,LYRA_DEFAULT_modelViewerUnsupportedFormat}from"../../../internal/default-strings/viewers.generated.js";const KEY_ACTIONS=Object.freeze({ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down","+":"in","=":"in","-":"out",Home:"fit"});class LyraModelViewer extends LyraElement{constructor(){super(...arguments),this._src="",this._name="",this._mimeType="",this._format="auto",this.authoredCamera=!1,this.alt="",this.target="_blank",this.rel="",this.status="idle",this.message="",this.software=!1,this.loaded=0,this.total=null,this.generation=0,this.observers=[],this.mediaCleanup=[],this.announcements=new ViewerAnnouncementController(this),this.descriptions=new HostDescriptionController(this,()=>this.viewport,()=>{const instructions=this.renderRoot.querySelector('[part="instructions"]');return instructions?[instructions]:[]})}static{this.defaultStrings={...super.defaultStrings,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,download:LYRA_DEFAULT_download,engine3dContextLost:LYRA_DEFAULT_engine3dContextLost,engine3dSoftwareRendering:LYRA_DEFAULT_engine3dSoftwareRendering,engine3dUnavailable:LYRA_DEFAULT_engine3dUnavailable,engine3dUnsupported:LYRA_DEFAULT_engine3dUnsupported,loadingDocument:LYRA_DEFAULT_loadingDocument,modelViewerAlternative:LYRA_DEFAULT_modelViewerAlternative,modelViewerEmpty:LYRA_DEFAULT_modelViewerEmpty,modelViewerFit:LYRA_DEFAULT_modelViewerFit,modelViewerInstructions:LYRA_DEFAULT_modelViewerInstructions,modelViewerInvalid:LYRA_DEFAULT_modelViewerInvalid,modelViewerLabel:LYRA_DEFAULT_modelViewerLabel,modelViewerProgress:LYRA_DEFAULT_modelViewerProgress,modelViewerReady:LYRA_DEFAULT_modelViewerReady,modelViewerRotateDown:LYRA_DEFAULT_modelViewerRotateDown,modelViewerRotateLeft:LYRA_DEFAULT_modelViewerRotateLeft,modelViewerRotateRight:LYRA_DEFAULT_modelViewerRotateRight,modelViewerRotateUp:LYRA_DEFAULT_modelViewerRotateUp,modelViewerUnsupportedFormat:LYRA_DEFAULT_modelViewerUnsupportedFormat,retry:LYRA_DEFAULT_retry,zoomIn:LYRA_DEFAULT_zoomIn,zoomOut:LYRA_DEFAULT_zoomOut}}static{this.styles=[LyraElement.styles,styles]}get src(){return this._src}set src(value){const next=typeof value=="string"?value:"",old=this._src;next!==old&&(this.retire(),this._src=next,this.requestUpdate("src",old))}get name(){return this._name}set name(value){const next=typeof value=="string"?value:"",old=this._name;next!==old&&(this.retire(),this._name=next,this.requestUpdate("name",old))}get mimeType(){return this._mimeType}set mimeType(value){const next=typeof value=="string"?value:"",old=this._mimeType;next!==old&&(this.retire(),this._mimeType=next,this.requestUpdate("mimeType",old))}get format(){return this._format}set format(value){const next=value??"auto",old=this._format;next!==old&&(this.retire(),this._format=next,this.requestUpdate("format",old))}get camera(){return this._camera}set camera(value){const next=value==null?void 0:snapshotModelCamera(value),old=this._camera;this._camera=next,this.authoredCamera=next!==void 0;try{next?this.engine?.setCamera(next):this.status==="ready"&&this.fit()}catch(error){this.fail("invalid","error",error)}this.requestUpdate("camera",old)}get viewport(){return this.renderRoot?.querySelector('[part="viewport"]')??null}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.retire(),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.retire(),this.announcements.adopted(),this.descriptions.adopted(),this.isConnected&&this.scheduleAfterUpdate(()=>{this.load()})}updated(changed){super.updated(changed),this.announcements.transition("model",this.status,this.statusText(),this.status==="error"?"assertive":this.status==="ready"||this.status==="empty"||this.status==="loading"||this.status==="context-lost"?"polite":void 0),["src","name","mimeType","format"].some(key=>changed.has(key))&&this.scheduleAfterUpdate(()=>{this.load()})}retire(){this.generation++,this.controller?.abort(),this.controller=void 0;for(const observer of this.observers)observer.disconnect();this.observers=[];for(const cleanup of this.mediaCleanup)cleanup();this.mediaCleanup=[];const engine=this.engine;this.engine=void 0;try{engine?.dispose()}catch{}this.viewport?.replaceChildren(),this.status="idle",this.message="",this.software=!1,this.loaded=0,this.total=null}fail(message,reason,error){this.retire(),this.status="error",this.message=message,this.emit("lr-engine-fallback",{from:"webgl",to:"list",reason}),this.emit("lr-render-error",{error:error??new Error("Model engine unavailable")})}async load(){if(this.retire(),!this.src||!this.isConnected)return;const owner=this.ownerDocument,view=owner.defaultView,container=this.viewport;if(!view||!container)return;const generation=this.generation,controller=new view.AbortController;this.controller=controller;const current=()=>generation===this.generation&&!controller.signal.aborted&&this.isConnected&&this.ownerDocument===owner;if(this.src.length>MODEL_SOURCE_MAX_BYTES){this.fail("tooLarge","error");return}const format=resolveModelFormat(this.format,this.name,this.mimeType,this.src);if(!format){this.fail("unsupportedFormat","unsupported");return}if(!resolveOwnerFetchTarget(this,this.src)){this.fail("urlNotAllowed","error");return}if(!modelEngineEnvironment.available(owner)){this.fail("engineUnsupported","unsupported");return}this.status="loading";let candidate=null;try{const bytes=await readModelSource(this,this.src,controller.signal,current,(loaded,total)=>{current()&&(total!==this.total||loaded===total||loaded-this.loaded>=1048576)&&(this.loaded=loaded,this.total=total)});if(!current())return;if(candidate=await modelEngineLoader.create(),!current()){candidate?.dispose();return}if(!candidate){this.fail("engineUnavailable","unavailable");return}const engine=candidate;if(this.engine=engine,typeof engine.fit!="function"){this.fail("engineUnavailable","unavailable");return}engine.setStyle(this.engineStyle());let parsed=!1,contextLost=!1;const publishParsedView=()=>{!current()||contextLost||!parsed||(this.status=engine.positionOf?.(0)===null?"empty":"ready",this.message="",this.status==="ready"&&!this.authoredCamera&&this.fit())};if(await engine.mount(container,{hover:()=>{},pick:()=>{},camera:value=>{current()&&this.status==="ready"&&this.acceptCamera(value,!0)},progress:(loaded,total)=>{if(!(!current()||parsed||!Number.isFinite(loaded)||!Number.isFinite(total)||total<0||loaded<total))try{parsed=!0,publishParsedView(),current()&&this.emit("lr-load",{format})}catch(error){current()&&this.fail("invalid","error",error)}},lost:reason=>{if(current())if(reason==="context-lost"){if(contextLost)return;contextLost=!0,this.status="context-lost",this.message="contextLost",this.emit("lr-engine-fallback",{from:"webgl",to:"list",reason})}else this.fail("invalid","error")},rendering:info=>{current()&&(this.software=info.software)},restored:()=>{if(!(!current()||!contextLost))try{contextLost=!1,this.message="",parsed?publishParsedView():this.status="loading",current()&&this.refreshEngine()}catch(error){current()&&this.fail("invalid","error",error)}}}),!current()){this.engine===engine&&(this.engine=void 0,engine.dispose());return}if(container.querySelectorAll("canvas").forEach(canvas=>{canvas.setAttribute("aria-hidden","true"),canvas.removeAttribute("tabindex")}),this.authoredCamera&&this.camera&&engine.setCamera(this.camera),this.watchEnvironment(current),this.refreshEngine(),!current())return;engine.setData({bytes,format},generation)}catch(error){if(!current()||isAbortError(error))return;const reason=engine3dFailureReason(error);this.fail(isResourceLimitError(error)?"tooLarge":reason==="unsupported"?"engineUnsupported":"invalid",reason,error)}}engineStyle(){const view=this.ownerDocument.defaultView,computed=view.getComputedStyle(this),canvas=this.ownerDocument.createElement("canvas");canvas.width=canvas.height=1;const context=canvas.getContext("2d",{willReadFrequently:!0}),color=token=>{const resolved=resolveCanvasColor(this,`var(${token})`,computed.color);if(!context)return resolved;context.clearRect(0,0,1,1),context.fillStyle=resolved,context.fillRect(0,0,1,1);const rgba=context.getImageData(0,0,1,1).data;return`rgba(${rgba[0]}, ${rgba[1]}, ${rgba[2]}, ${rgba[3]/255})`};return{background:color("--lr-color-surface"),foreground:color("--lr-color-text"),muted:color("--lr-color-text-quiet"),accent:color("--lr-color-brand"),focus:color("--lr-focus-ring-color"),palette:[color("--lr-color-brand")],fontFamily:computed.fontFamily,fontSize:finiteRange(Number.parseFloat(computed.fontSize),14,1,128),pointSize:8,lineWidth:1,devicePixelRatio:finiteRange(view.devicePixelRatio,1,.25,4),reducedMotion:view.matchMedia("(prefers-reduced-motion: reduce)").matches,forcedColors:view.matchMedia("(forced-colors: active)").matches}}refreshEngine(){if(!(!this.engine||!this.isConnected))try{this.engine.setStyle(this.engineStyle());const box=this.viewport?.getBoundingClientRect();box&&this.engine.resize(Math.max(1,box.width),Math.max(1,box.height))}catch(error){this.fail("invalid","error",error)}}watchEnvironment(current){const view=this.ownerDocument.defaultView,refresh=()=>{current()&&this.refreshEngine()},resize=new view.ResizeObserver(refresh);resize.observe(this.viewport),this.observers.push(resize);const mutation=new view.MutationObserver(refresh);let ancestor=this;for(;ancestor;){mutation.observe(ancestor,{attributes:!0});const root=ancestor.getRootNode();ancestor=ancestor.parentElement??(root instanceof view.ShadowRoot?root.host:null)}this.observers.push(mutation);for(const query of["(prefers-reduced-motion: reduce)","(forced-colors: active)","(prefers-color-scheme: dark)"]){const media=view.matchMedia(query);media.addEventListener("change",refresh),this.mediaCleanup.push(()=>media.removeEventListener("change",refresh))}}acceptCamera(value,emit){let next;try{next=snapshotModelCamera(value)}catch{return}const old=this._camera;this._camera=next,this.requestUpdate("camera",old),emit&&(this.authoredCamera=!0,this.emit("lr-camera-change",{camera:next}))}fit(){if(this.engine&&this.status==="ready")try{this.acceptCamera(this.engine.fit?.(),!1)}catch(error){this.fail("invalid","error",error)}}retry(){this.retire(),this.scheduleAfterUpdate(()=>{this.load()})}move(action){if(!this.engine||this.status!=="ready")return;if(action==="fit"){const generation=this.generation;this.fit(),generation===this.generation&&this.status==="ready"&&this.camera&&this.emit("lr-camera-change",{camera:this.camera});return}const current=this.camera??DEFAULT_MODEL_CAMERA,horizontal=this.effectiveDirection==="rtl"?-1:1,next=snapshotModelCamera({...current,yaw:current.yaw+(action==="left"?-.1*horizontal:action==="right"?.1*horizontal:0),pitch:current.pitch+(action==="up"?.1:action==="down"?-.1:0),distance:current.distance*(action==="in"?.8:action==="out"?1.25:1)});try{this.engine.setCamera(next),this.acceptCamera(next,!0)}catch(error){this.fail("invalid","error",error)}}keydown(event){if(event.altKey||event.ctrlKey||event.metaKey||event.isComposing||event.currentTarget!==event.target||this.closest("[inert]"))return;const action=Object.hasOwn(KEY_ACTIONS,event.key)?KEY_ACTIONS[event.key]:void 0;!action||this.status!=="ready"||(event.preventDefault(),this.move(action))}statusText(){switch(this.message){case"tooLarge":return this.localize("documentPreviewResourceTooLarge");case"urlNotAllowed":return this.localize("documentPreviewUrlNotAllowed");case"unsupportedFormat":return this.localize("modelViewerUnsupportedFormat");case"invalid":return this.localize("modelViewerInvalid");case"engineUnsupported":return this.localize("engine3dUnsupported");case"engineUnavailable":return this.localize("engine3dUnavailable");case"contextLost":return this.localize("engine3dContextLost");default:break}if(this.status==="ready")return this.localize("modelViewerReady");if(this.status==="empty")return this.localize("modelViewerEmpty");if(this.status==="loading"){if(this.total===null)return this.localize("loadingDocument");const number=getNumberFormat(this.effectiveLocale);return this.localize("modelViewerProgress",void 0,{loaded:number.format(this.loaded),total:number.format(this.total)})}return this.localize("documentPreviewEmpty",void 0,{type:this.localize("modelViewerLabel")})}render(){const label=hostAriaLabel(this)??(this.name||this.localize("modelViewerLabel")),ready=this.status==="ready",href=this.src.length<=MODEL_SOURCE_MAX_BYTES?safeDownloadHref(this.src,this.ownerDocument?.defaultView?.URL??URL):null,controls=[["left",this.localize("modelViewerRotateLeft")],["right",this.localize("modelViewerRotateRight")],["up",this.localize("modelViewerRotateUp")],["down",this.localize("modelViewerRotateDown")],["in",this.localize("zoomIn")],["out",this.localize("zoomOut")],["fit",this.localize("modelViewerFit")]];return html`<section part="base" role="region" aria-label=${label}>
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{ifDefined}from"lit/directives/if-defined.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{safeDownloadHref}from"../../../internal/safe-url.js";import{isAbortError,isResourceLimitError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{engine3dFailureReason}from"../../../internal/engine-3d.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{modelEngineEnvironment,modelEngineLoader,supportsAsyncModelData}from"./model-viewer-loader.js";import{MODEL_SOURCE_MAX_BYTES,DEFAULT_MODEL_CAMERA,readModelSource,resolveModelFormat,snapshotModelCamera}from"./model-viewer-source.js";import{styles}from"./model-viewer.styles.js";import{LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_download,LYRA_DEFAULT_engine3dContextLost,LYRA_DEFAULT_engine3dSoftwareRendering,LYRA_DEFAULT_engine3dUnavailable,LYRA_DEFAULT_engine3dUnsupported,LYRA_DEFAULT_retry,LYRA_DEFAULT_zoomIn,LYRA_DEFAULT_zoomOut}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_modelViewerAlternative,LYRA_DEFAULT_modelViewerEmpty,LYRA_DEFAULT_modelViewerFit,LYRA_DEFAULT_modelViewerInstructions,LYRA_DEFAULT_modelViewerInvalid,LYRA_DEFAULT_modelViewerLabel,LYRA_DEFAULT_modelViewerProgress,LYRA_DEFAULT_modelViewerReady,LYRA_DEFAULT_modelViewerRotateDown,LYRA_DEFAULT_modelViewerRotateLeft,LYRA_DEFAULT_modelViewerRotateRight,LYRA_DEFAULT_modelViewerRotateUp,LYRA_DEFAULT_modelViewerUnsupportedFormat}from"../../../internal/default-strings/viewers.generated.js";const KEY_ACTIONS=Object.freeze({ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down","+":"in","=":"in","-":"out",Home:"fit"});class LyraModelViewer extends LyraElement{constructor(){super(...arguments),this._src="",this._name="",this._mimeType="",this._format="auto",this.authoredCamera=!1,this.alt="",this.target="_blank",this.rel="",this.status="idle",this.message="",this.software=!1,this.loaded=0,this.total=null,this.generation=0,this.observers=[],this.mediaCleanup=[],this.announcements=new ViewerAnnouncementController(this),this.descriptions=new HostDescriptionController(this,()=>this.viewport,()=>{const instructions=this.renderRoot.querySelector('[part="instructions"]');return instructions?[instructions]:[]})}static{this.defaultStrings={...super.defaultStrings,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,download:LYRA_DEFAULT_download,engine3dContextLost:LYRA_DEFAULT_engine3dContextLost,engine3dSoftwareRendering:LYRA_DEFAULT_engine3dSoftwareRendering,engine3dUnavailable:LYRA_DEFAULT_engine3dUnavailable,engine3dUnsupported:LYRA_DEFAULT_engine3dUnsupported,loadingDocument:LYRA_DEFAULT_loadingDocument,modelViewerAlternative:LYRA_DEFAULT_modelViewerAlternative,modelViewerEmpty:LYRA_DEFAULT_modelViewerEmpty,modelViewerFit:LYRA_DEFAULT_modelViewerFit,modelViewerInstructions:LYRA_DEFAULT_modelViewerInstructions,modelViewerInvalid:LYRA_DEFAULT_modelViewerInvalid,modelViewerLabel:LYRA_DEFAULT_modelViewerLabel,modelViewerProgress:LYRA_DEFAULT_modelViewerProgress,modelViewerReady:LYRA_DEFAULT_modelViewerReady,modelViewerRotateDown:LYRA_DEFAULT_modelViewerRotateDown,modelViewerRotateLeft:LYRA_DEFAULT_modelViewerRotateLeft,modelViewerRotateRight:LYRA_DEFAULT_modelViewerRotateRight,modelViewerRotateUp:LYRA_DEFAULT_modelViewerRotateUp,modelViewerUnsupportedFormat:LYRA_DEFAULT_modelViewerUnsupportedFormat,retry:LYRA_DEFAULT_retry,zoomIn:LYRA_DEFAULT_zoomIn,zoomOut:LYRA_DEFAULT_zoomOut}}static{this.styles=[LyraElement.styles,styles]}get src(){return this._src}set src(value){const next=typeof value=="string"?value:"",old=this._src;next!==old&&(this.retire(),this._src=next,this.requestUpdate("src",old))}get name(){return this._name}set name(value){const next=typeof value=="string"?value:"",old=this._name;next!==old&&(this.retire(),this._name=next,this.requestUpdate("name",old))}get mimeType(){return this._mimeType}set mimeType(value){const next=typeof value=="string"?value:"",old=this._mimeType;next!==old&&(this.retire(),this._mimeType=next,this.requestUpdate("mimeType",old))}get format(){return this._format}set format(value){const next=value??"auto",old=this._format;next!==old&&(this.retire(),this._format=next,this.requestUpdate("format",old))}get camera(){return this._camera}set camera(value){const next=value==null?void 0:snapshotModelCamera(value),old=this._camera;this._camera=next,this.authoredCamera=next!==void 0;try{next?this.engine?.setCamera(next):this.status==="ready"&&this.fit()}catch(error){this.fail("invalid","error",error)}this.requestUpdate("camera",old)}get viewport(){return this.renderRoot?.querySelector('[part="viewport"]')??null}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.retire(),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.retire(),this.announcements.adopted(),this.descriptions.adopted(),this.isConnected&&this.scheduleAfterUpdate(()=>{this.load()})}updated(changed){super.updated(changed),this.announcements.transition("model",this.status,this.statusText(),this.status==="error"?"assertive":this.status==="ready"||this.status==="empty"||this.status==="loading"||this.status==="context-lost"?"polite":void 0),["src","name","mimeType","format"].some(key=>changed.has(key))&&this.scheduleAfterUpdate(()=>{this.load()})}retire(){this.generation++,this.controller?.abort(),this.controller=void 0;for(const observer of this.observers)observer.disconnect();this.observers=[];for(const cleanup of this.mediaCleanup)cleanup();this.mediaCleanup=[];const engine=this.engine;this.engine=void 0;try{engine?.dispose()}catch{}this.viewport?.replaceChildren(),this.status="idle",this.message="",this.software=!1,this.loaded=0,this.total=null}fail(message,reason,error){this.retire(),this.status="error",this.message=message,this.emit("lr-engine-fallback",{from:"webgl",to:"list",reason}),this.emit("lr-render-error",{error:error??new Error("Model engine unavailable")})}async load(){if(this.retire(),!this.src||!this.isConnected)return;const owner=this.ownerDocument,view=owner.defaultView,container=this.viewport;if(!view||!container)return;const generation=this.generation,controller=new view.AbortController;this.controller=controller;const current=()=>generation===this.generation&&!controller.signal.aborted&&this.isConnected&&this.ownerDocument===owner;if(this.src.length>MODEL_SOURCE_MAX_BYTES){this.fail("tooLarge","error");return}const format=resolveModelFormat(this.format,this.name,this.mimeType,this.src);if(!format){this.fail("unsupportedFormat","unsupported");return}if(!resolveOwnerFetchTarget(this,this.src)){this.fail("urlNotAllowed","error");return}if(!modelEngineEnvironment.available(owner)){this.fail("engineUnsupported","unsupported");return}this.status="loading";let candidate=null;try{const bytes=await readModelSource(this,this.src,controller.signal,current,(loaded,total)=>{current()&&(total!==this.total||loaded===total||loaded-this.loaded>=1048576)&&(this.loaded=loaded,this.total=total)});if(!current())return;if(candidate=await modelEngineLoader.create(),!current()){candidate?.dispose();return}if(!candidate){this.fail("engineUnavailable","unavailable");return}const engine=candidate;if(this.engine=engine,typeof engine.fit!="function"){this.fail("engineUnavailable","unavailable");return}engine.setStyle(this.engineStyle());let parsed=!1,contextLost=!1;const publishParsedView=()=>{!current()||contextLost||!parsed||(this.status=engine.positionOf?.(0)===null?"empty":"ready",this.message="",this.status==="ready"&&!this.authoredCamera&&this.fit())};if(await engine.mount(container,{hover:()=>{},pick:()=>{},camera:value=>{current()&&this.status==="ready"&&this.acceptCamera(value,!0)},progress:(loaded,total)=>{if(!(!current()||parsed||!Number.isFinite(loaded)||!Number.isFinite(total)||total<0||loaded<total))try{parsed=!0,publishParsedView(),current()&&this.emit("lr-load",{format})}catch(error){current()&&this.fail("invalid","error",error)}},lost:reason=>{if(current())if(reason==="context-lost"){if(contextLost)return;contextLost=!0,this.status="context-lost",this.message="contextLost",this.emit("lr-engine-fallback",{from:"webgl",to:"list",reason})}else this.fail("invalid","error")},rendering:info=>{current()&&(this.software=info.software)},restored:()=>{if(!(!current()||!contextLost))try{contextLost=!1,this.message="",parsed?publishParsedView():this.status="loading",current()&&this.refreshEngine()}catch(error){current()&&this.fail("invalid","error",error)}}}),!current()){this.engine===engine&&(this.engine=void 0,engine.dispose());return}if(container.querySelectorAll("canvas").forEach(canvas=>{canvas.setAttribute("aria-hidden","true"),canvas.removeAttribute("tabindex")}),this.authoredCamera&&this.camera&&engine.setCamera(this.camera),this.watchEnvironment(current),this.refreshEngine(),!current())return;if(supportsAsyncModelData(engine)){if(await engine.setDataAsync({bytes,format},generation,{signal:controller.signal}),!current())return}else engine.setData({bytes,format},generation)}catch(error){if(!current()||isAbortError(error))return;const reason=engine3dFailureReason(error);this.fail(isResourceLimitError(error)?"tooLarge":reason==="unsupported"?"engineUnsupported":"invalid",reason,error)}}engineStyle(){const view=this.ownerDocument.defaultView,computed=view.getComputedStyle(this),canvas=this.ownerDocument.createElement("canvas");canvas.width=canvas.height=1;const context=canvas.getContext("2d",{willReadFrequently:!0}),color=token=>{const resolved=resolveCanvasColor(this,`var(${token})`,computed.color);if(!context)return resolved;context.clearRect(0,0,1,1),context.fillStyle=resolved,context.fillRect(0,0,1,1);const rgba=context.getImageData(0,0,1,1).data;return`rgba(${rgba[0]}, ${rgba[1]}, ${rgba[2]}, ${rgba[3]/255})`};return{background:color("--lr-color-surface"),foreground:color("--lr-color-text"),muted:color("--lr-color-text-quiet"),accent:color("--lr-color-brand"),focus:color("--lr-focus-ring-color"),palette:[color("--lr-color-brand")],fontFamily:computed.fontFamily,fontSize:finiteRange(Number.parseFloat(computed.fontSize),14,1,128),pointSize:8,lineWidth:1,devicePixelRatio:finiteRange(view.devicePixelRatio,1,.25,4),reducedMotion:view.matchMedia("(prefers-reduced-motion: reduce)").matches,forcedColors:view.matchMedia("(forced-colors: active)").matches}}refreshEngine(){if(!(!this.engine||!this.isConnected))try{this.engine.setStyle(this.engineStyle());const box=this.viewport?.getBoundingClientRect();box&&this.engine.resize(Math.max(1,box.width),Math.max(1,box.height))}catch(error){this.fail("invalid","error",error)}}watchEnvironment(current){const view=this.ownerDocument.defaultView,refresh=()=>{current()&&this.refreshEngine()},resize=new view.ResizeObserver(refresh);resize.observe(this.viewport),this.observers.push(resize);const mutation=new view.MutationObserver(refresh);let ancestor=this;for(;ancestor;){mutation.observe(ancestor,{attributes:!0});const root=ancestor.getRootNode();ancestor=ancestor.parentElement??(root instanceof view.ShadowRoot?root.host:null)}this.observers.push(mutation);for(const query of["(prefers-reduced-motion: reduce)","(forced-colors: active)","(prefers-color-scheme: dark)"]){const media=view.matchMedia(query);media.addEventListener("change",refresh),this.mediaCleanup.push(()=>media.removeEventListener("change",refresh))}}acceptCamera(value,emit){let next;try{next=snapshotModelCamera(value)}catch{return}const old=this._camera;this._camera=next,this.requestUpdate("camera",old),emit&&(this.authoredCamera=!0,this.emit("lr-camera-change",{camera:next}))}fit(){if(this.engine&&this.status==="ready")try{this.acceptCamera(this.engine.fit?.(),!1)}catch(error){this.fail("invalid","error",error)}}retry(){this.retire(),this.scheduleAfterUpdate(()=>{this.load()})}move(action){if(!this.engine||this.status!=="ready")return;if(action==="fit"){const generation=this.generation;this.fit(),generation===this.generation&&this.status==="ready"&&this.camera&&this.emit("lr-camera-change",{camera:this.camera});return}const current=this.camera??DEFAULT_MODEL_CAMERA,horizontal=this.effectiveDirection==="rtl"?-1:1,next=snapshotModelCamera({...current,yaw:current.yaw+(action==="left"?-.1*horizontal:action==="right"?.1*horizontal:0),pitch:current.pitch+(action==="up"?.1:action==="down"?-.1:0),distance:current.distance*(action==="in"?.8:action==="out"?1.25:1)});try{this.engine.setCamera(next),this.acceptCamera(next,!0)}catch(error){this.fail("invalid","error",error)}}keydown(event){if(event.altKey||event.ctrlKey||event.metaKey||event.isComposing||event.currentTarget!==event.target||this.closest("[inert]"))return;const action=Object.hasOwn(KEY_ACTIONS,event.key)?KEY_ACTIONS[event.key]:void 0;!action||this.status!=="ready"||(event.preventDefault(),this.move(action))}statusText(){switch(this.message){case"tooLarge":return this.localize("documentPreviewResourceTooLarge");case"urlNotAllowed":return this.localize("documentPreviewUrlNotAllowed");case"unsupportedFormat":return this.localize("modelViewerUnsupportedFormat");case"invalid":return this.localize("modelViewerInvalid");case"engineUnsupported":return this.localize("engine3dUnsupported");case"engineUnavailable":return this.localize("engine3dUnavailable");case"contextLost":return this.localize("engine3dContextLost");default:break}if(this.status==="ready")return this.localize("modelViewerReady");if(this.status==="empty")return this.localize("modelViewerEmpty");if(this.status==="loading"){if(this.total===null)return this.localize("loadingDocument");const number=getNumberFormat(this.effectiveLocale);return this.localize("modelViewerProgress",void 0,{loaded:number.format(this.loaded),total:number.format(this.total)})}return this.localize("documentPreviewEmpty",void 0,{type:this.localize("modelViewerLabel")})}render(){const label=hostAriaLabel(this)??(this.name||this.localize("modelViewerLabel")),ready=this.status==="ready",href=this.src.length<=MODEL_SOURCE_MAX_BYTES?safeDownloadHref(this.src,this.ownerDocument?.defaultView?.URL??URL):null,controls=[["left",this.localize("modelViewerRotateLeft")],["right",this.localize("modelViewerRotateRight")],["up",this.localize("modelViewerRotateUp")],["down",this.localize("modelViewerRotateDown")],["in",this.localize("zoomIn")],["out",this.localize("zoomOut")],["fit",this.localize("modelViewerFit")]];return html`<section part="base" role="region" aria-label=${label}>
|
|
2
2
|
<div part="viewport" role="group" aria-label=${label} aria-busy=${String(this.status==="loading")} tabindex=${ready?"0":"-1"} ?data-ready=${ready} ?hidden=${this.status==="idle"||this.status==="empty"||this.status==="error"} @keydown=${this.keydown}></div>
|
|
3
3
|
<div part="toolbar">${controls.map(([action,label2])=>html`<button part="control" type="button" ?disabled=${!ready} @click=${()=>this.move(action)}>${label2}</button>`)}</div>
|
|
4
4
|
<p part="instructions">${this.localize("modelViewerInstructions")}</p>
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import{type LyraSearchChangeDetail,type LyraTextViewerTargetEventMap}from'../../../internal/text-viewer-target.js';import type{AnchorResultDetail,LyraAnchor,LyraAnchorKind,TextSelectDetail}from'../document-viewer/anchors.js';import type{LyraViewerDiagnosticEventDetail}from'../viewer-diagnostics.js';import type{LyraPageViewerSnapshot,LyraPageViewerStateChangeDetail,PageThumbnailRenderHandle}from'../page-rail/page-rail.class.js';export type{LyraViewerDiagnostic,LyraViewerDiagnosticCode,LyraViewerDiagnosticEventDetail,LyraViewerDiagnosticSeverity,}from'../viewer-diagnostics.js';export interface LyraPptxViewerEventMap extends LyraTextViewerTargetEventMap{'lr-load':CustomEvent<{slideCount:number;}>;'lr-slide-change':CustomEvent<{index:number;count:number;}>;'lr-render-error':CustomEvent<{error:unknown;}>;'lr-search-change':CustomEvent<LyraSearchChangeDetail>;'lr-anchor-result':CustomEvent<AnchorResultDetail>;'lr-text-select':CustomEvent<TextSelectDetail>;'lr-viewer-diagnostic':CustomEvent<LyraViewerDiagnosticEventDetail>;'lr-page-viewer-state-change':CustomEvent<LyraPageViewerStateChangeDetail>;}declare class LyraPptxViewerBase extends LyraElement<LyraPptxViewerEventMap>{}declare const LyraPptxViewer_base:Omit<typeof LyraPptxViewerBase,'prototype'> &(new(...args:ConstructorParameters<typeof LyraPptxViewerBase>)=>InstanceType<typeof LyraPptxViewerBase> &import("../../../lyra.js").LyraTextViewerTarget&import("../../../internal/text-viewer-target.js").TextViewerTargetHooks&{renderAnchorLiveRegion():unknown;});
|
|
2
2
|
/**
|
|
3
|
-
* Best-effort client-side PPTX viewer
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
3
|
+
* Best-effort client-side PPTX viewer with optional `@aiden0z/pptx-renderer`.
|
|
4
|
+
* An always-visible fidelity notice covers unrendered animations, equations, embedded OLE
|
|
5
|
+
* objects, notes, and several advanced effects.
|
|
6
|
+
* Remote bytes and measured ZIP expansion are bounded before renderer parsing. Peers lacking
|
|
7
|
+
* complete, safely bounded ZIP limits fail closed.
|
|
8
|
+
* Slides and thumbnails block external images, picture fills, audio, video, and posters linked
|
|
9
|
+
* by the presentation. Embedded package media remains; linked media is omitted or gets a placeholder.
|
|
10
|
+
* Click-driven hyperlinks are unchanged.
|
|
11
|
+
* `text-quote` searches all slides, preferring `prefix`/`suffix` matches; `page` navigates one-based slides.
|
|
12
|
+
* Lyra assigns no slide fragment IDs. Fragments require exact DOM IDs in mounted renderer output;
|
|
13
|
+
* these IDs are unstable. Use `page`/`goToSlide()` or `text-quote`.
|
|
14
14
|
*
|
|
15
15
|
* @customElement lr-pptx-viewer
|
|
16
16
|
* @event lr-load - Fired after a presentation opens. `detail: { slideCount }`.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{adaptPptxViewer,getPptxRenderer}from"./pptx-loader.js";import{assertPptxArchiveWithinLimits}from"./pptx-resource-guard.js";import{styles}from"./pptx-viewer.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{textQuoteContextScore}from"../document-viewer/anchors.js";import{PageViewerSnapshotController}from"../page-rail/page-viewer-snapshot.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{renderViewerPagerButton,viewerPagerStyles}from"../viewer-pager.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_pptxViewerFidelityNotice,LYRA_DEFAULT_pptxViewerLabel,LYRA_DEFAULT_pptxViewerMissingLibrary,LYRA_DEFAULT_pptxViewerNextSlide,LYRA_DEFAULT_pptxViewerPreviousSlide,LYRA_DEFAULT_pptxViewerRenderError,LYRA_DEFAULT_pptxViewerSlideOf}from"../../../internal/default-strings/viewers.generated.js";const MAX_PPTX_SEARCH_MATCHES=1e4,MAX_PPTX_THUMBNAIL_WIDTH=2048;class LyraPptxViewerBase extends LyraElement{}class LyraPptxViewer extends TextViewerTarget(LyraPptxViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.page=1,this.maxHeight="",this.phase="idle",this.errorMessage="",this.slideCount=0,this.currentSlideIndex=0,this.loadRenderer=getPptxRenderer,this.generation=0,this.announcements=new ViewerAnnouncementController(this),this.pptxSearchQuery="",this.lastSearchLocale="",this.pptxSearchMatches=[],this.pendingSearchResetEvent=!1,this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1,this.pptxSearchGeneration=0,this.pageViewerState=new PageViewerSnapshotController,this.anchorKinds=["text-quote","fragment","page"],this.onViewerEvent=event=>{if(event.kind==="slide-change"){this.commitSlide(event.index);return}this.reportPeerDiagnostic(event.code,event.cause,{page:event.page,nodeId:event.nodeId},event.fatal)},this.focusedPagerPart=null,this.detached=new DeferredTeardown(()=>this.releaseDetachedPresentation())}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,loading:LYRA_DEFAULT_loading,pptxViewerFidelityNotice:LYRA_DEFAULT_pptxViewerFidelityNotice,pptxViewerLabel:LYRA_DEFAULT_pptxViewerLabel,pptxViewerMissingLibrary:LYRA_DEFAULT_pptxViewerMissingLibrary,pptxViewerNextSlide:LYRA_DEFAULT_pptxViewerNextSlide,pptxViewerPreviousSlide:LYRA_DEFAULT_pptxViewerPreviousSlide,pptxViewerRenderError:LYRA_DEFAULT_pptxViewerRenderError,pptxViewerSlideOf:LYRA_DEFAULT_pptxViewerSlideOf}}static{this.styles=[LyraElement.styles,styles,viewerPagerStyles,srOnly,viewerLoadingStyles]}async search(query2){const generation=++this.pptxSearchGeneration,viewer=this.viewer,boundedQuery=boundedViewerSearchQuery(query2,this.effectiveLocale);if(this.pptxSearchQuery=query2,this.lastSearchLocale=this.effectiveLocale,this.disposeSearchHighlight(),viewer?.clearSearchHighlights(),!boundedQuery.accepted)return this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!1,this.pptxSearchActiveIndex=-1,this.emitPptxSearchChange(),0;if(!viewer||!boundedQuery.needle)return this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1,this.emitPptxSearchChange(),0;try{const raw=viewer.searchText(query2.trim(),{matchCase:!1});if(generation!==this.pptxSearchGeneration||viewer!==this.viewer)return this.pptxSearchMatches.length;const normalized=this.normalizeSearchResults(raw,viewer.slideCount);return this.pptxSearchMatches=normalized.matches,this.pptxSearchMatchCountExact=normalized.matchCountExact,this.pptxSearchActiveIndex=this.pptxSearchMatches.length>0?0:-1,this.emitPptxSearchChange(),this.pptxSearchActiveIndex>=0&&await this.focusPptxSearchMatch(this.pptxSearchActiveIndex,generation,viewer),this.pptxSearchMatches.length}catch(cause){return generation!==this.pptxSearchGeneration||viewer!==this.viewer||(this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!1,this.pptxSearchActiveIndex=-1,this.reportPeerDiagnostic("pptx-search-error",cause),this.emitPptxSearchChange()),0}}async searchNext(){const viewer=this.viewer;if(!viewer||this.pptxSearchMatches.length===0)return!1;const generation=++this.pptxSearchGeneration;return this.pptxSearchActiveIndex=(this.pptxSearchActiveIndex+1)%this.pptxSearchMatches.length,this.emitPptxSearchChange(),await this.focusPptxSearchMatch(this.pptxSearchActiveIndex,generation,viewer),generation===this.pptxSearchGeneration}async searchPrevious(){const viewer=this.viewer;if(!viewer||this.pptxSearchMatches.length===0)return!1;const generation=++this.pptxSearchGeneration;return this.pptxSearchActiveIndex=(this.pptxSearchActiveIndex-1+this.pptxSearchMatches.length)%this.pptxSearchMatches.length,this.emitPptxSearchChange(),await this.focusPptxSearchMatch(this.pptxSearchActiveIndex,generation,viewer),generation===this.pptxSearchGeneration}clearSearch(){this.pptxSearchGeneration++,this.pptxSearchQuery="",this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1,this.disposeSearchHighlight(),this.viewer?.clearSearchHighlights(),this.emitPptxSearchChange()}get pageViewerSnapshot(){return this.pageViewerState.value}set pageViewerSnapshot(_value){}textContentRoot(){return this.renderRoot.querySelector('[part="container"]')??this.renderRoot.querySelector('[part="base"]')}async applyAnchor(anchor){const viewer=this.viewer;if(anchor.kind==="page"){const index=anchor.page-1;return!viewer||!Number.isInteger(anchor.page)||index<0||index>=this.slideCount?!1:(await this.goToSlide(index),viewer===this.viewer&&this.currentSlideIndex===index)}if(anchor.kind==="text-quote"&&viewer){const slideIndex=this.slideForTextQuote(viewer,anchor);if(slideIndex>=0&&slideIndex!==this.currentSlideIndex){if(await this.goToSlide(slideIndex),viewer!==this.viewer||this.currentSlideIndex!==slideIndex)return!1;await this.updateComplete}}return this.applyMountedAnchor(anchor)}applyMountedAnchor(anchor){return Object.getPrototypeOf(LyraPptxViewer.prototype).applyAnchor.call(this,anchor)}slideForTextQuote(viewer,anchor){const quote=anchor.quote.trim(),bounded=boundedViewerSearchQuery(quote,this.effectiveLocale);if(!bounded.accepted||!bounded.needle)return-1;let matches;try{matches=this.normalizeSearchResults(viewer.searchText(quote,{matchCase:!1}),viewer.slideCount).matches}catch(cause){return this.reportPeerDiagnostic("pptx-search-error",cause),-1}let best,bestScore=-1;for(const match of matches){const score=textQuoteContextScore(match.text,match.matchStart,match.matchEnd,anchor.prefix,anchor.suffix);score>bestScore&&(best=match,bestScore=score)}return best?.slideIndex??-1}keepPagerFocus(){const part=this.focusedPagerPart;this.focusedPagerPart=null;const twin=part==="previous-button"?"next-button":part==="next-button"?"previous-button":void 0,root=this.shadowRoot;!twin||!root||root.querySelector(`[part="${part}"]`)?.disabled&&root.querySelector(`[part="${twin}"]:not(:disabled)`)?.focus()}updated(changed){if(super.updated(changed),this.keepPagerFocus(),this.announcements.transition("load",this.phase,this.phase==="error"?this.errorMessage:this.localize("loading")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.mount()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitPptxSearchChange()),changed.has("page")&&this.viewer&&this.page-1!==this.currentSlideIndex){const page=this.page;this.scheduleAfterUpdate(()=>{this.page===page&&this.goToSlide(page-1)},"page-navigation")}const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.pptxSearchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.pptxSearchQuery)},"search")}}willUpdate(changed){super.willUpdate(changed);const active=shadowFocusTarget(this);this.focusedPagerPart=active?.localName==="button"&&!active.disabled?active.getAttribute("part"):null,changed.has("src")&&(this.pendingSearchResetEvent||=this.hasPptxSearchState(),this.resetPptxSearchState()),(changed.has("page")||changed.has("slideCount"))&&(this.page=finiteInteger(this.page,1,1,Math.max(1,this.slideCount)))}connectedCallback(){super.connectedCallback(),this.announcements.connect();const moved=this.detached.cancel();this.hasUpdated&&this.src&&!moved&&this.scheduleAfterUpdate(()=>{this.mount()})}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedPresentation(){this.teardown(),this.phase="idle",this.slideCount=0,this.currentSlideIndex=0,this.page=1,this.pageViewerState.reset()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}async goToSlide(index){const viewer=this.viewer;if(!viewer||!Number.isSafeInteger(index)||index<0||index>=viewer.slideCount)return;const generation=this.generation;try{await viewer.goToSlide(index)}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation||viewer!==this.viewer)return;this.teardown(),this.phase="error",this.slideCount=0,this.currentSlideIndex=0,this.page=1,this.errorMessage=this.localize("pptxViewerRenderError"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}viewer===this.viewer&&viewer.currentSlideIndex!==this.currentSlideIndex&&this.commitSlide(viewer.currentSlideIndex)}async renderPageThumbnailToContainer(page,container,options){const viewer=this.viewer,generation=this.generation,width=options?.width??96;if(!viewer||!Number.isSafeInteger(page)||page<1||page>viewer.slideCount||!Number.isFinite(width)||width<=0||width>MAX_PPTX_THUMBNAIL_WIDTH)return!1;const previousChildren=[...container.childNodes],restorePreviousChildren=()=>{container.replaceChildren(...previousChildren)};let handle;try{handle=viewer.renderThumbnailToContainer(page-1,container,{width})}catch{return restorePreviousChildren(),!1}if(!handle)return restorePreviousChildren(),!1;try{await handle.ready}catch{return handle.dispose(),restorePreviousChildren(),!1}if(generation!==this.generation||viewer!==this.viewer||!container.isConnected)return handle.dispose(),restorePreviousChildren(),!1;for(const child of previousChildren)child.parentNode===container&&child.remove();return handle}isValidSlideIndex(index){return Number.isSafeInteger(index)&&index>=0&&index<this.slideCount}commitSlide(index){if(!this.isValidSlideIndex(index))return;const changed=index!==this.currentSlideIndex;this.currentSlideIndex=index,this.page=index+1,this.publishPageViewerSnapshot("ready",this.slideCount),changed&&this.emit("lr-slide-change",{index,count:this.slideCount})}publishPageViewerSnapshot(status,pageCount){const snapshot=this.pageViewerState.publish(status,finiteInteger(this.page,1,1,Math.max(1,pageCount)),finiteInteger(pageCount,0,0,Number.MAX_SAFE_INTEGER));snapshot&&this.isConnected&&this.emit("lr-page-viewer-state-change",{snapshot})}teardown(){const shouldEmitSearchReset=this.hasPptxSearchState();this.generation++,this.viewerUnsubscribe?.(),this.viewerUnsubscribe=void 0,this.viewer?.destroy(),this.viewer=void 0,this.resetPptxSearchState(),shouldEmitSearchReset&&this.emitPptxSearchChange()}hasPptxSearchState(){return this.pptxSearchQuery!==""||this.pptxSearchMatches.length>0||!this.pptxSearchMatchCountExact||this.pptxSearchActiveIndex!==-1}resetPptxSearchState(){this.pptxSearchGeneration++,this.disposeSearchHighlight(),this.viewer?.clearSearchHighlights(),this.pptxSearchQuery="",this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1}normalizeSearchResults(value,slideCount){if(!Array.isArray(value))throw new TypeError("PPTX search returned a non-array result.");const matches=[],work=new ViewerSearchWorkBudget;let matchCountExact=!0;for(const candidate of value){if(!work.consume("")){matchCountExact=!1;break}if(!candidate||typeof candidate!="object")continue;const result=candidate;if(!(!Number.isSafeInteger(result.slideIndex)||result.slideIndex<0||result.slideIndex>=slideCount||typeof result.nodeId!="string"||typeof result.text!="string"||!Number.isSafeInteger(result.matchStart)||!Number.isSafeInteger(result.matchEnd)||result.matchStart<0||result.matchEnd<result.matchStart||result.matchEnd>result.text.length)){if(!work.consume(result.nodeId)||!work.consume(result.text)){matchCountExact=!1;break}if(matches.length===MAX_PPTX_SEARCH_MATCHES){matchCountExact=!1;break}matches.push(candidate)}}return{matches,matchCountExact:matchCountExact&&work.complete}}async focusPptxSearchMatch(index,generation,viewer){const match=this.pptxSearchMatches[index];if(match){this.disposeSearchHighlight(),viewer.clearSearchHighlights();try{if(await viewer.goToSlide(match.slideIndex),generation!==this.pptxSearchGeneration||viewer!==this.viewer)return;const highlight=await viewer.highlightSearchResult(match,{scrollIntoView:!1});if(generation!==this.pptxSearchGeneration||viewer!==this.viewer){highlight?.dispose();return}this.searchHighlight=highlight??void 0}catch(cause){generation===this.pptxSearchGeneration&&viewer===this.viewer&&this.reportPeerDiagnostic("pptx-search-error",cause,{page:match.slideIndex+1})}}}disposeSearchHighlight(){this.searchHighlight?.dispose(),this.searchHighlight=void 0}emitPptxSearchChange(){this.emit("lr-search-change",{query:this.pptxSearchQuery,matchCount:this.pptxSearchMatches.length,matchCountExact:this.pptxSearchMatchCountExact,activeIndex:this.pptxSearchActiveIndex})}reportPeerDiagnostic(code,cause,location={},fatal=!1){this.emit("lr-viewer-diagnostic",{diagnostic:Object.freeze({code,severity:"error",fatal,source:"pptx-renderer",cause,...location})}),fatal&&(this.teardown(),this.phase="error",this.slideCount=0,this.currentSlideIndex=0,this.page=1,this.errorMessage=this.localize("pptxViewerRenderError"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error:cause}))}async mount(){this.teardown(),this.pageViewerState.advance();const signal=this.beginAbortableLoad(),generation=this.generation;if(this.slideCount=0,this.currentSlideIndex=0,this.page=1,!this.src){this.phase="idle",this.publishPageViewerSnapshot("idle",0);return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.phase="error",this.errorMessage=error.message,this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}this.phase="loading",this.publishPageViewerSnapshot("loading",0);let module,response;try{[module,response]=await Promise.all([this.loadRenderer(),fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0)])}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.phase="error",this.errorMessage=this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}if(!this.isConnected||generation!==this.generation)return;if(!module||!response.ok){response.body?.cancel().catch(()=>{});const error=new LyraUserFacingError(this.localize(module?"documentPreviewFailedToLoad":"pptxViewerMissingLibrary"));this.phase="error",this.errorMessage=error.message,this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}let buffer;try{if(buffer=await readResponseArrayBuffer(response),!this.isConnected||generation!==this.generation)return;await assertPptxArchiveWithinLimits(buffer,{signal})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.phase="error",this.errorMessage=this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}if(!(!this.isConnected||generation!==this.generation)&&(this.phase="mounted",await this.updateComplete,!(!this.isConnected||generation!==this.generation||!this.containerEl)))try{const openedViewer=await module.PptxViewer.open(buffer,this.containerEl,{zipLimits:module.RECOMMENDED_ZIP_LIMITS,listOptions:{windowed:!0}});if(!this.isConnected||generation!==this.generation){openedViewer.destroy();return}const viewer=adaptPptxViewer(openedViewer);if(!viewer)throw openedViewer.destroy(),new TypeError("The PPTX renderer did not expose the required viewer capabilities.");this.viewer=viewer,this.viewerUnsubscribe=viewer.subscribe(this.onViewerEvent),this.slideCount=viewer.slideCount,this.isValidSlideIndex(viewer.currentSlideIndex)&&(this.currentSlideIndex=viewer.currentSlideIndex,this.page=viewer.currentSlideIndex+1),this.publishPageViewerSnapshot("ready",viewer.slideCount),this.emit("lr-load",{slideCount:viewer.slideCount})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.phase="error",this.errorMessage=this.localize("pptxViewerRenderError"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error})}}renderBody(){return this.phase==="loading"?renderViewerLoading(this.localize("loading")):this.phase==="error"?html`<div part="error">${this.errorMessage}</div>`:this.phase!=="mounted"?nothing:html`
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{adaptPptxViewer,getPptxRenderer}from"./pptx-loader.js";import{assertPptxArchiveWithinLimits}from"./pptx-resource-guard.js";import{styles}from"./pptx-viewer.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{textQuoteContextScore}from"../document-viewer/anchors.js";import{PageViewerSnapshotController}from"../page-rail/page-viewer-snapshot.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{renderViewerPagerButton,viewerPagerStyles}from"../viewer-pager.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_pptxViewerFidelityNotice,LYRA_DEFAULT_pptxViewerLabel,LYRA_DEFAULT_pptxViewerMissingLibrary,LYRA_DEFAULT_pptxViewerNextSlide,LYRA_DEFAULT_pptxViewerPreviousSlide,LYRA_DEFAULT_pptxViewerRenderError,LYRA_DEFAULT_pptxViewerSlideOf}from"../../../internal/default-strings/viewers.generated.js";const MAX_PPTX_SEARCH_MATCHES=1e4,MAX_PPTX_THUMBNAIL_WIDTH=2048;class LyraPptxViewerBase extends LyraElement{}class LyraPptxViewer extends TextViewerTarget(LyraPptxViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.page=1,this.maxHeight="",this.phase="idle",this.errorMessage="",this.slideCount=0,this.currentSlideIndex=0,this.loadRenderer=getPptxRenderer,this.generation=0,this.announcements=new ViewerAnnouncementController(this),this.pptxSearchQuery="",this.lastSearchLocale="",this.pptxSearchMatches=[],this.pendingSearchResetEvent=!1,this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1,this.pptxSearchGeneration=0,this.pageViewerState=new PageViewerSnapshotController,this.anchorKinds=["text-quote","fragment","page"],this.onViewerEvent=event=>{if(event.kind==="slide-change"){this.commitSlide(event.index);return}this.reportPeerDiagnostic(event.code,event.cause,{page:event.page,nodeId:event.nodeId},event.fatal)},this.focusedPagerPart=null,this.detached=new DeferredTeardown(()=>this.releaseDetachedPresentation())}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,loading:LYRA_DEFAULT_loading,pptxViewerFidelityNotice:LYRA_DEFAULT_pptxViewerFidelityNotice,pptxViewerLabel:LYRA_DEFAULT_pptxViewerLabel,pptxViewerMissingLibrary:LYRA_DEFAULT_pptxViewerMissingLibrary,pptxViewerNextSlide:LYRA_DEFAULT_pptxViewerNextSlide,pptxViewerPreviousSlide:LYRA_DEFAULT_pptxViewerPreviousSlide,pptxViewerRenderError:LYRA_DEFAULT_pptxViewerRenderError,pptxViewerSlideOf:LYRA_DEFAULT_pptxViewerSlideOf}}static{this.styles=[LyraElement.styles,styles,viewerPagerStyles,srOnly,viewerLoadingStyles]}async search(query2){const generation=++this.pptxSearchGeneration,viewer=this.viewer,boundedQuery=boundedViewerSearchQuery(query2,this.effectiveLocale);if(this.pptxSearchQuery=query2,this.lastSearchLocale=this.effectiveLocale,this.disposeSearchHighlight(),viewer?.clearSearchHighlights(),!boundedQuery.accepted)return this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!1,this.pptxSearchActiveIndex=-1,this.emitPptxSearchChange(),0;if(!viewer||!boundedQuery.needle)return this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1,this.emitPptxSearchChange(),0;try{const raw=viewer.searchText(query2.trim(),{matchCase:!1});if(generation!==this.pptxSearchGeneration||viewer!==this.viewer)return this.pptxSearchMatches.length;const normalized=this.normalizeSearchResults(raw,viewer.slideCount);return this.pptxSearchMatches=normalized.matches,this.pptxSearchMatchCountExact=normalized.matchCountExact,this.pptxSearchActiveIndex=this.pptxSearchMatches.length>0?0:-1,this.emitPptxSearchChange(),this.pptxSearchActiveIndex>=0&&await this.focusPptxSearchMatch(this.pptxSearchActiveIndex,generation,viewer),this.pptxSearchMatches.length}catch(cause){return generation!==this.pptxSearchGeneration||viewer!==this.viewer||(this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!1,this.pptxSearchActiveIndex=-1,this.reportPeerDiagnostic("pptx-search-error",cause),this.emitPptxSearchChange()),0}}async searchNext(){const viewer=this.viewer;if(!viewer||this.pptxSearchMatches.length===0)return!1;const generation=++this.pptxSearchGeneration;return this.pptxSearchActiveIndex=(this.pptxSearchActiveIndex+1)%this.pptxSearchMatches.length,this.emitPptxSearchChange(),await this.focusPptxSearchMatch(this.pptxSearchActiveIndex,generation,viewer),generation===this.pptxSearchGeneration}async searchPrevious(){const viewer=this.viewer;if(!viewer||this.pptxSearchMatches.length===0)return!1;const generation=++this.pptxSearchGeneration;return this.pptxSearchActiveIndex=(this.pptxSearchActiveIndex-1+this.pptxSearchMatches.length)%this.pptxSearchMatches.length,this.emitPptxSearchChange(),await this.focusPptxSearchMatch(this.pptxSearchActiveIndex,generation,viewer),generation===this.pptxSearchGeneration}clearSearch(){this.pptxSearchGeneration++,this.pptxSearchQuery="",this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1,this.disposeSearchHighlight(),this.viewer?.clearSearchHighlights(),this.emitPptxSearchChange()}get pageViewerSnapshot(){return this.pageViewerState.value}set pageViewerSnapshot(_value){}textContentRoot(){return this.renderRoot.querySelector('[part="container"]')??this.renderRoot.querySelector('[part="base"]')}async applyAnchor(anchor){const viewer=this.viewer;if(anchor.kind==="page"){const index=anchor.page-1;return!viewer||!Number.isInteger(anchor.page)||index<0||index>=this.slideCount?!1:(await this.goToSlide(index),viewer===this.viewer&&this.currentSlideIndex===index)}if(anchor.kind==="text-quote"&&viewer){const slideIndex=this.slideForTextQuote(viewer,anchor);if(slideIndex>=0&&slideIndex!==this.currentSlideIndex){if(await this.goToSlide(slideIndex),viewer!==this.viewer||this.currentSlideIndex!==slideIndex)return!1;await this.updateComplete}}return this.applyMountedAnchor(anchor)}applyMountedAnchor(anchor){return Object.getPrototypeOf(LyraPptxViewer.prototype).applyAnchor.call(this,anchor)}slideForTextQuote(viewer,anchor){const quote=anchor.quote.trim(),bounded=boundedViewerSearchQuery(quote,this.effectiveLocale);if(!bounded.accepted||!bounded.needle)return-1;let matches;try{matches=this.normalizeSearchResults(viewer.searchText(quote,{matchCase:!1}),viewer.slideCount).matches}catch(cause){return this.reportPeerDiagnostic("pptx-search-error",cause),-1}let best,bestScore=-1;for(const match of matches){const score=textQuoteContextScore(match.text,match.matchStart,match.matchEnd,anchor.prefix,anchor.suffix);score>bestScore&&(best=match,bestScore=score)}return best?.slideIndex??-1}keepPagerFocus(){const part=this.focusedPagerPart;this.focusedPagerPart=null;const twin=part==="previous-button"?"next-button":part==="next-button"?"previous-button":void 0,root=this.shadowRoot;!twin||!root||root.querySelector(`[part="${part}"]`)?.disabled&&root.querySelector(`[part="${twin}"]:not(:disabled)`)?.focus()}updated(changed){if(super.updated(changed),this.keepPagerFocus(),this.announcements.transition("load",this.phase,this.phase==="error"?this.errorMessage:this.localize("loading")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.mount()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitPptxSearchChange()),changed.has("page")&&this.viewer&&this.page-1!==this.currentSlideIndex){const page=this.page;this.scheduleAfterUpdate(()=>{this.page===page&&this.goToSlide(page-1)},"page-navigation")}const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.pptxSearchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.pptxSearchQuery)},"search")}}willUpdate(changed){super.willUpdate(changed);const active=shadowFocusTarget(this);this.focusedPagerPart=active?.localName==="button"&&!active.disabled?active.getAttribute("part"):null,changed.has("src")&&(this.pendingSearchResetEvent||=this.hasPptxSearchState(),this.resetPptxSearchState()),(changed.has("page")||changed.has("slideCount"))&&(this.page=finiteInteger(this.page,1,1,Math.max(1,this.slideCount)))}connectedCallback(){super.connectedCallback(),this.announcements.connect();const moved=this.detached.cancel();this.hasUpdated&&this.src&&!moved&&this.scheduleAfterUpdate(()=>{this.mount()})}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedPresentation(){this.teardown(),this.phase="idle",this.slideCount=0,this.currentSlideIndex=0,this.page=1,this.pageViewerState.reset()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}async goToSlide(index){const viewer=this.viewer;if(!viewer||!Number.isSafeInteger(index)||index<0||index>=viewer.slideCount)return;const generation=this.generation;try{await viewer.goToSlide(index)}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation||viewer!==this.viewer)return;this.teardown(),this.phase="error",this.slideCount=0,this.currentSlideIndex=0,this.page=1,this.errorMessage=this.localize("pptxViewerRenderError"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}viewer===this.viewer&&viewer.currentSlideIndex!==this.currentSlideIndex&&this.commitSlide(viewer.currentSlideIndex)}async renderPageThumbnailToContainer(page,container,options){const viewer=this.viewer,generation=this.generation,width=options?.width??96;if(!viewer||!Number.isSafeInteger(page)||page<1||page>viewer.slideCount||!Number.isFinite(width)||width<=0||width>MAX_PPTX_THUMBNAIL_WIDTH)return!1;const previousChildren=[...container.childNodes],restorePreviousChildren=()=>{container.replaceChildren(...previousChildren)};let handle;try{handle=viewer.renderThumbnailToContainer(page-1,container,{width})}catch{return restorePreviousChildren(),!1}if(!handle)return restorePreviousChildren(),!1;try{await handle.ready}catch{return handle.dispose(),restorePreviousChildren(),!1}if(generation!==this.generation||viewer!==this.viewer||!container.isConnected)return handle.dispose(),restorePreviousChildren(),!1;for(const child of previousChildren)child.parentNode===container&&child.remove();return handle}isValidSlideIndex(index){return Number.isSafeInteger(index)&&index>=0&&index<this.slideCount}commitSlide(index){if(!this.isValidSlideIndex(index))return;const changed=index!==this.currentSlideIndex;this.currentSlideIndex=index,this.page=index+1,this.publishPageViewerSnapshot("ready",this.slideCount),changed&&this.emit("lr-slide-change",{index,count:this.slideCount})}publishPageViewerSnapshot(status,pageCount){const snapshot=this.pageViewerState.publish(status,finiteInteger(this.page,1,1,Math.max(1,pageCount)),finiteInteger(pageCount,0,0,Number.MAX_SAFE_INTEGER));snapshot&&this.isConnected&&this.emit("lr-page-viewer-state-change",{snapshot})}teardown(){const shouldEmitSearchReset=this.hasPptxSearchState();this.generation++,this.viewerUnsubscribe?.(),this.viewerUnsubscribe=void 0,this.viewer?.destroy(),this.viewer=void 0,this.resetPptxSearchState(),shouldEmitSearchReset&&this.emitPptxSearchChange()}hasPptxSearchState(){return this.pptxSearchQuery!==""||this.pptxSearchMatches.length>0||!this.pptxSearchMatchCountExact||this.pptxSearchActiveIndex!==-1}resetPptxSearchState(){this.pptxSearchGeneration++,this.disposeSearchHighlight(),this.viewer?.clearSearchHighlights(),this.pptxSearchQuery="",this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1}normalizeSearchResults(value,slideCount){if(!Array.isArray(value))throw new TypeError("PPTX search returned a non-array result.");const matches=[],work=new ViewerSearchWorkBudget;let matchCountExact=!0;for(const candidate of value){if(!work.consume("")){matchCountExact=!1;break}if(!candidate||typeof candidate!="object")continue;const result=candidate;if(!(!Number.isSafeInteger(result.slideIndex)||result.slideIndex<0||result.slideIndex>=slideCount||typeof result.nodeId!="string"||typeof result.text!="string"||!Number.isSafeInteger(result.matchStart)||!Number.isSafeInteger(result.matchEnd)||result.matchStart<0||result.matchEnd<result.matchStart||result.matchEnd>result.text.length)){if(!work.consume(result.nodeId)||!work.consume(result.text)){matchCountExact=!1;break}if(matches.length===MAX_PPTX_SEARCH_MATCHES){matchCountExact=!1;break}matches.push(candidate)}}return{matches,matchCountExact:matchCountExact&&work.complete}}async focusPptxSearchMatch(index,generation,viewer){const match=this.pptxSearchMatches[index];if(match){this.disposeSearchHighlight(),viewer.clearSearchHighlights();try{if(await viewer.goToSlide(match.slideIndex),generation!==this.pptxSearchGeneration||viewer!==this.viewer)return;const highlight=await viewer.highlightSearchResult(match,{scrollIntoView:!1});if(generation!==this.pptxSearchGeneration||viewer!==this.viewer){highlight?.dispose();return}this.searchHighlight=highlight??void 0}catch(cause){generation===this.pptxSearchGeneration&&viewer===this.viewer&&this.reportPeerDiagnostic("pptx-search-error",cause,{page:match.slideIndex+1})}}}disposeSearchHighlight(){this.searchHighlight?.dispose(),this.searchHighlight=void 0}emitPptxSearchChange(){this.emit("lr-search-change",{query:this.pptxSearchQuery,matchCount:this.pptxSearchMatches.length,matchCountExact:this.pptxSearchMatchCountExact,activeIndex:this.pptxSearchActiveIndex})}reportPeerDiagnostic(code,cause,location={},fatal=!1){this.emit("lr-viewer-diagnostic",{diagnostic:Object.freeze({code,severity:"error",fatal,source:"pptx-renderer",cause,...location})}),fatal&&(this.teardown(),this.phase="error",this.slideCount=0,this.currentSlideIndex=0,this.page=1,this.errorMessage=this.localize("pptxViewerRenderError"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error:cause}))}async mount(){this.teardown(),this.pageViewerState.advance();const signal=this.beginAbortableLoad(),generation=this.generation;if(this.slideCount=0,this.currentSlideIndex=0,this.page=1,!this.src){this.phase="idle",this.publishPageViewerSnapshot("idle",0);return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.phase="error",this.errorMessage=error.message,this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}this.phase="loading",this.publishPageViewerSnapshot("loading",0);let module,response;try{[module,response]=await Promise.all([this.loadRenderer(),fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0)])}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.phase="error",this.errorMessage=this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}if(!this.isConnected||generation!==this.generation)return;if(!module||!response.ok){response.body?.cancel().catch(()=>{});const error=new LyraUserFacingError(this.localize(module?"documentPreviewFailedToLoad":"pptxViewerMissingLibrary"));this.phase="error",this.errorMessage=error.message,this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}let buffer;try{if(buffer=await readResponseArrayBuffer(response),!this.isConnected||generation!==this.generation)return;await assertPptxArchiveWithinLimits(buffer,{signal})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.phase="error",this.errorMessage=this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}if(!(!this.isConnected||generation!==this.generation)&&(this.phase="mounted",await this.updateComplete,!(!this.isConnected||generation!==this.generation||!this.containerEl)))try{const openedViewer=await module.PptxViewer.open(buffer,this.containerEl,{externalMedia:"block",zipLimits:module.RECOMMENDED_ZIP_LIMITS,listOptions:{windowed:!0}});if(!this.isConnected||generation!==this.generation){openedViewer.destroy();return}const viewer=adaptPptxViewer(openedViewer);if(!viewer)throw openedViewer.destroy(),new TypeError("The PPTX renderer did not expose the required viewer capabilities.");this.viewer=viewer,this.viewerUnsubscribe=viewer.subscribe(this.onViewerEvent),this.slideCount=viewer.slideCount,this.isValidSlideIndex(viewer.currentSlideIndex)&&(this.currentSlideIndex=viewer.currentSlideIndex,this.page=viewer.currentSlideIndex+1),this.publishPageViewerSnapshot("ready",viewer.slideCount),this.emit("lr-load",{slideCount:viewer.slideCount})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.phase="error",this.errorMessage=this.localize("pptxViewerRenderError"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error})}}renderBody(){return this.phase==="loading"?renderViewerLoading(this.localize("loading")):this.phase==="error"?html`<div part="error">${this.errorMessage}</div>`:this.phase!=="mounted"?nothing:html`
|
|
2
2
|
<div part="nav" ?hidden=${this.slideCount<=1}>
|
|
3
3
|
${renderViewerPagerButton("previous",this.localize("pptxViewerPreviousSlide"),this.currentSlideIndex<=0,()=>{this.goToSlide(this.currentSlideIndex-1)})}
|
|
4
4
|
<span part="slide-count">${this.localize("pptxViewerSlideOf",void 0,{current:getNumberFormat(this.effectiveLocale).format(this.currentSlideIndex+1),total:getNumberFormat(this.effectiveLocale).format(this.slideCount)})}</span>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{releaseAccessibleTextAncestors,accessibleTextRecordsMatter,bindAccessibleTextObserver,composedAccessibilityText,releaseAccessibleTextReferences}from"./accessibility-visibility.js";import{assignedSlotOf}from"./composed-tree.js";import{CustomElementUpgradeObserver}from"./custom-element-upgrade-observer.js";import{OwnedFrame,OwnedTimeout}from"./owned-timer.js";class AccessibleTextController{constructor(host,slots,onChange,extraAttributes=[],enabled=!0,trackReferences=!1,observeAncestors=!0){this.host=host,this.slots=slots,this.onChange=onChange,this.extraAttributes=extraAttributes,this.enabled=enabled,this.upgrades=new CustomElementUpgradeObserver(()=>this.changed()),this.active=!1,this.preserveNextBinding=!1,this.drainedRecords=!1,this.onSlotChange=event=>{const slot=event.composedPath().find(target=>target.localName==="slot"&&target.getRootNode()===this.slotRoot);!slot||!this.slots.includes(slot.name)||this.changed()},this.ancestors={releases:[],get enabled(){return typeof observeAncestors=="function"?observeAncestors():observeAncestors},changed:records=>{this.drainingAncestors?this.drainingAncestors.push(...records):this.changed(records)}},trackReferences&&(this.references={releases:[],changed:()=>this.changed()}),this.visibilityFrame=new OwnedFrame(host),this.visibilityTimer=new OwnedTimeout(host),host.addController(this)}hostConnected(){this.active=!0,this.enabled&&(this.bindSlotRoot(),this.rebuild())}hostUpdated(){const preserveBinding=this.preserveNextBinding;if(this.preserveNextBinding=!1,this.active&&this.enabled){const observer=this.observer,pending=observer?.takeRecords()??[],relevant=observer&&pending.length>0&&this.recordsMatter(pending)&&accessibleTextRecordsMatter(observer,pending),previousRoot=this.slotRoot;this.bindSlotRoot()
|
|
1
|
+
import{releaseAccessibleTextAncestors,accessibleTextRecordsMatter,bindAccessibleTextObserver,composedAccessibilityText,releaseAccessibleTextReferences}from"./accessibility-visibility.js";import{assignedSlotOf}from"./composed-tree.js";import{CustomElementUpgradeObserver}from"./custom-element-upgrade-observer.js";import{OwnedFrame,OwnedTimeout}from"./owned-timer.js";class AccessibleTextController{constructor(host,slots,onChange,extraAttributes=[],enabled=!0,trackReferences=!1,observeAncestors=!0){this.host=host,this.slots=slots,this.onChange=onChange,this.extraAttributes=extraAttributes,this.enabled=enabled,this.upgrades=new CustomElementUpgradeObserver(()=>this.changed()),this.active=!1,this.preserveNextBinding=!1,this.drainedRecords=!1,this.onSlotChange=event=>{const slot=event.composedPath().find(target=>target.localName==="slot"&&target.getRootNode()===this.slotRoot);!slot||!this.slots.includes(slot.name)||this.changed()},this.ancestors={releases:[],get enabled(){return typeof observeAncestors=="function"?observeAncestors():observeAncestors},changed:records=>{this.drainingAncestors?this.drainingAncestors.push(...records):this.changed(records)}},trackReferences&&(this.references={releases:[],changed:()=>this.changed()}),this.visibilityFrame=new OwnedFrame(host),this.visibilityTimer=new OwnedTimeout(host),host.addController(this)}hostConnected(){this.active=!0,this.enabled&&(this.bindSlotRoot(),this.rebuild())}hostUpdated(){const preserveBinding=this.preserveNextBinding;if(this.preserveNextBinding=!1,this.active&&this.enabled){const observer=this.observer,pending=observer?.takeRecords()??[],relevant=observer&&pending.length>0&&this.recordsMatter(pending)&&accessibleTextRecordsMatter(observer,pending),previousRoot=this.slotRoot;this.bindSlotRoot();let records=relevant?pending:[];(!preserveBinding||pending.length>0||this.drainedRecords||previousRoot!==this.slotRoot)&&(records=records.concat(this.bindObserver())),records.length&&queueMicrotask(()=>{this.active&&this.enabled&&this.observer===observer&&this.host.isConnected&&this.notify(records)})}}hostDisconnected(){this.active=!1,this.preserveNextBinding=!1,this.cancelVisibilityRefresh(),this.slotRoot?.removeEventListener("slotchange",this.onSlotChange),this.slotRoot=void 0,this.observer?.disconnect(),this.observer=void 0,this.upgrades.disconnect(),releaseAccessibleTextAncestors(this.ancestors),this.references&&releaseAccessibleTextReferences(this.references)}adopted(){this.active&&this.enabled&&this.rebuild()}setEnabled(enabled){this.enabled!==enabled&&(this.enabled=enabled,this.active&&(enabled?(this.bindSlotRoot(),this.rebuild()):(this.cancelVisibilityRefresh(),this.slotRoot?.removeEventListener("slotchange",this.onSlotChange),this.slotRoot=void 0,this.observer?.disconnect(),this.observer=void 0,this.upgrades.disconnect(),releaseAccessibleTextAncestors(this.ancestors),this.references&&releaseAccessibleTextReferences(this.references))))}bind(){const pending=this.bindObserver();pending.length&&this.active&&this.enabled&&this.notify(pending)}bindObserver(){const pending=this.takeAncestorRecords();return bindAccessibleTextObserver(this.observer,this.host,this.extraAttributes,this.upgrades,this.references,this.ancestors),this.drainedRecords=!1,pending}preserveBindingForNextUpdate(){this.preserveNextBinding=!0}takeAncestorRecords(){if(this.drainingAncestors||!this.active||!this.enabled)return[];const records=[];this.drainingAncestors=records;try{for(const release of[...this.ancestors.releases])release.flush()}finally{this.drainingAncestors=void 0}return records}takeRecords(){const ancestorRecords=this.takeAncestorRecords(),records=[...this.observer?.takeRecords()??[],...ancestorRecords];return ancestorRecords.length&&this.notify(ancestorRecords),records.length>0&&(this.drainedRecords=!0),records}hasDrainedRecords(){return this.drainedRecords}text(){const root=this.host.shadowRoot,slots=root?[...root.querySelectorAll("slot")].filter(slot=>this.slots.includes(slot.name)):[],nodes=slots.length?slots.flatMap(slot=>[...slot.assignedNodes({flatten:!0})]):[...this.host.childNodes].filter(node=>node.nodeType!==1||this.slots.includes(node.getAttribute("slot")??""));return composedAccessibilityText(nodes)}hasContent(){return this.text().trim().length>0}rebuild(){this.cancelVisibilityRefresh(),this.observer?.disconnect(),this.upgrades.disconnect(),releaseAccessibleTextAncestors(this.ancestors),this.references&&releaseAccessibleTextReferences(this.references);const Observer=this.host.ownerDocument.defaultView?.MutationObserver;this.observer=Observer?new Observer((records,observer)=>{this.observer===observer&&this.recordsMatter(records)&&accessibleTextRecordsMatter(observer,records)&&this.changed(records)}):void 0,this.bind()}bindSlotRoot(){const root=this.host.shadowRoot??void 0;this.slotRoot!==root&&(this.slotRoot?.removeEventListener("slotchange",this.onSlotChange),this.slotRoot=root,root?.addEventListener("slotchange",this.onSlotChange))}recordsMatter(records){if(this.slots.length===0)return!0;const feedsSlot=start=>{const visited=new Set;let node=start;for(;node&&node!==this.host&&!visited.has(node);){if(visited.add(node),node.parentNode===this.host){const name=node.nodeType===1?node.getAttribute("slot")??"":"";return this.slots.includes(name)}node=assignedSlotOf(node)??node.parentNode??node.host??null}return!0};return records.some(record=>record.type==="attributes"&&record.attributeName==="slot"?!0:record.target===this.host&&record.type==="childList"?[...record.addedNodes,...record.removedNodes].some(node=>node.nodeType!==1?this.slots.includes(""):this.slots.includes(node.getAttribute("slot")??"")):feedsSlot(record.target))}changed(records=[]){!this.active||!this.enabled||!this.host.isConnected||(this.bind(),this.notify(records))}notify(records){this.onChange(records),records.some(record=>record.type==="attributes"&&["class","style","hidden"].includes(record.attributeName??""))&&(this.visibilityFrame.pending||this.visibilityTimer.pending||this.visibilityFrame.schedule(()=>{this.visibilityTimer.schedule(0,()=>{this.active&&this.enabled&&this.onChange([])})}))}cancelVisibilityRefresh(){this.visibilityFrame.cancel(),this.visibilityTimer.cancel()}}export{AccessibleTextController};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const defaultRuntimeLoader=()=>import("./positioner.js").then(runtime=>({place:runtime.placeAnchoredSurface,trackRect:runtime.trackRect,releaseTopLayer:runtime.releaseTopLayer}));let runtimeLoader=defaultRuntimeLoader,runtimePromise;function loadAnchoredOverlayRuntime(){if(runtimePromise)return runtimePromise;const pending=runtimeLoader().catch(error=>{throw runtimePromise===pending&&(runtimePromise=void 0),error});return runtimePromise=pending}const activePlacementByPopup=new WeakMap;function concealPendingPopup(popup,strategy){activePlacementByPopup.get(popup)?.(),popup.style.position=strategy??"fixed";const pending=[popup.style.visibility,popup.style.getPropertyPriority("visibility")];return popup.style.setProperty("visibility","hidden","important"),pending}function releasePendingPopup(popup,pending){const[value,priority]=pending;popup.style.visibility!=="hidden"||popup.style.getPropertyPriority("visibility")!=="important"||popup.style.setProperty("visibility",value,priority)}function deferredPlace(...args){const[anchor,popup,options={}]=args,pendingVisibility=concealPendingPopup(popup,options.strategy);let active=!0,cleanup,positioned=!1;const dispose=()=>{active&&(active=!1,activePlacementByPopup.delete(popup),cleanup?.(),releasePendingPopup(popup,pendingVisibility))};return activePlacementByPopup.set(popup,dispose),loadAnchoredOverlayRuntime().then(runtime=>{if(active)try{cleanup=runtime.place(anchor,popup,{...options,onPlaced:result=>{active&&(positioned||(positioned=!0,releasePendingPopup(popup,pendingVisibility)),options.onPlaced?.(result))}})}catch{}},()=>{}),dispose}function deferredPlaceReady(...args){const[anchor,popup,options={}]=args,pendingVisibility=concealPendingPopup(popup,options.strategy);let active=!0,cleanup,settle;const ready=new Promise(resolve=>{settle=resolve}),dispose=(()=>{active&&(active=!1,activePlacementByPopup.delete(popup),cleanup?.(),releasePendingPopup(popup,pendingVisibility),settle?.(!1))});return activePlacementByPopup.set(popup,dispose),loadAnchoredOverlayRuntime().then(runtime=>{if(active)try{cleanup=runtime.place(anchor,popup,{...options,onPlaced:result=>{active&&(settle&&(releasePendingPopup(popup,pendingVisibility),settle(!0),settle=void 0),options.onPlaced?.(result))}})}catch{settle?.(!1)}},()=>settle?.(!1)),dispose.ready=ready,dispose}async function waitForDeferredPlacement(current){let operation;for(;operation=current();){const positioned=await operation.ready;if(operation===current())return!!positioned}return!0}async function awaitPopupAnimations(host,popup,isCurrent){const ownerDocument=host.ownerDocument;if(!isCurrent())return!1;if(!host.isConnected)return!0;const view=ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),host.ownerDocument!==ownerDocument||!isCurrent())return!1;const animations=popup()?.getAnimations({subtree:!0})??[];return await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),host.ownerDocument===ownerDocument&&isCurrent()}async function settlePopupTransition(options){const{host,isCurrent}=options,ownerDocument=host.ownerDocument,current=()=>host.ownerDocument===ownerDocument&&isCurrent();await host.updateComplete,current()&&(options.waitForPosition&&(!await options.waitForPosition()||!current()||(await host.updateComplete,!current()))||await awaitPopupAnimations(host,options.popup,current)&&(options.conceal&&(options.conceal(),await host.updateComplete,!current())||options.onSettled()))}class PopupTransitionWaiters{#waiters=new Map;wait(event){return new Promise(resolve=>{const waiters=this.#waiters.get(event)??new Set;waiters.add(resolve),this.#waiters.set(event,waiters)})}resolve(event){const waiters=this.#waiters.get(event);if(waiters){this.#waiters.delete(event);for(const resolve of waiters)resolve()}}}function deferredTrackRect(...args){let active=!0,cleanup;return loadAnchoredOverlayRuntime().then(runtime=>{active&&(cleanup=runtime.trackRect(...args))}).catch(()=>{}),()=>{active=!1,cleanup?.(),cleanup=void 0}}function __setAnchoredOverlayRuntimeLoaderForTesting(loader){runtimeLoader=loader??defaultRuntimeLoader,runtimePromise=void 0}function topLayerPlacement(topLayer,strategy){return{strategy:topLayer?"fixed":strategy,topLayer}}function syncTopLayerRelease(popup,wasPromoted,topLayer,runtime){if(wasPromoted&&!topLayer){if(runtime)return runtime.releaseTopLayer?.(popup),topLayer;loadAnchoredOverlayRuntime().then(runtime2=>runtime2.releaseTopLayer?.(popup),()=>{})}return topLayer}export{PopupTransitionWaiters,__setAnchoredOverlayRuntimeLoaderForTesting,awaitPopupAnimations,deferredPlace,deferredPlaceReady,deferredTrackRect,loadAnchoredOverlayRuntime,settlePopupTransition,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement};
|
|
1
|
+
const defaultRuntimeLoader=()=>import("./positioner.js").then(runtime=>({place:runtime.placeAnchoredSurface,placeSession:runtime.placeAnchoredSurfaceSession,trackRect:runtime.trackRect,releaseTopLayer:runtime.releaseTopLayer}));let runtimeLoader=defaultRuntimeLoader,runtimePromise;function loadAnchoredOverlayRuntime(){if(runtimePromise)return runtimePromise;const pending=runtimeLoader().catch(error=>{throw runtimePromise===pending&&(runtimePromise=void 0),error});return runtimePromise=pending}const activePlacementByPopup=new WeakMap;function concealPendingPopup(popup,strategy){activePlacementByPopup.get(popup)?.(),popup.style.position=strategy??"fixed";const pending=[popup.style.visibility,popup.style.getPropertyPriority("visibility")];return popup.style.setProperty("visibility","hidden","important"),pending}function releasePendingPopup(popup,pending){const[value,priority]=pending;popup.style.visibility!=="hidden"||popup.style.getPropertyPriority("visibility")!=="important"||popup.style.setProperty("visibility",value,priority)}function deferredPlace(...args){const[anchor,popup,options={}]=args,pendingVisibility=concealPendingPopup(popup,options.strategy);let active=!0,cleanup,positioned=!1;const dispose=()=>{active&&(active=!1,activePlacementByPopup.delete(popup),cleanup?.(),releasePendingPopup(popup,pendingVisibility))};return activePlacementByPopup.set(popup,dispose),loadAnchoredOverlayRuntime().then(runtime=>{if(active)try{cleanup=runtime.place(anchor,popup,{...options,onPlaced:result=>{active&&(positioned||(positioned=!0,releasePendingPopup(popup,pendingVisibility)),options.onPlaced?.(result))}})}catch{}},()=>{}),dispose}function deferredPlaceReady(...args){const[anchor,popup,options={}]=args,pendingVisibility=concealPendingPopup(popup,options.strategy);let active=!0,cleanup,settle;const ready=new Promise(resolve=>{settle=resolve}),dispose=(()=>{active&&(active=!1,activePlacementByPopup.delete(popup),cleanup?.(),releasePendingPopup(popup,pendingVisibility),settle?.(!1))});return activePlacementByPopup.set(popup,dispose),loadAnchoredOverlayRuntime().then(runtime=>{if(active)try{cleanup=runtime.place(anchor,popup,{...options,onPlaced:result=>{active&&(settle&&(releasePendingPopup(popup,pendingVisibility),settle(!0),settle=void 0),options.onPlaced?.(result))}})}catch{settle?.(!1)}},()=>settle?.(!1)),dispose.ready=ready,dispose}function deferredPlaceSession(...args){const[anchor,popup,options={}]=args,pendingVisibility=concealPendingPopup(popup,options.strategy);let active=!0,suspended=!1,starting=!1,failed=!1,generation=0,runtime,cleanup,retained,settle;const ready=new Promise(resolve=>{settle=resolve}),finish=value=>{settle?.(value),settle=void 0},dispose=()=>{if(!active)return;active=!1,activePlacementByPopup.get(popup)===dispose&&activePlacementByPopup.delete(popup);const stop=cleanup;cleanup=void 0,retained=void 0,stop?.(),releasePendingPopup(popup,pendingVisibility),finish(!1)};activePlacementByPopup.set(popup,dispose);const start=(propagateFailure=!1)=>{if(!active||suspended||starting||failed||cleanup||!runtime)return;const installed=generation,capability=runtime.placeSession;starting=!0;try{const placementOptions={...options,onPlaced:result=>{!active||suspended||!capability&&installed!==generation||(settle&&(releasePendingPopup(popup,pendingVisibility),finish(!0)),options.onPlaced?.(result))}},next=capability?capability.call(runtime,anchor,popup,placementOptions):runtime.place(anchor,popup,placementOptions);if(!active){next();return}cleanup=next,retained=capability?next:void 0,(suspended||installed!==generation)&&(retained?retained.invalidate():(cleanup=void 0,next()))}catch(error){if(failed=!0,finish(!1),propagateFailure)throw error}finally{starting=!1}active&&!suspended&&installed!==generation&&(retained?retained.update():start(propagateFailure))},operation=Object.assign(dispose,{ready,isActive(){return active&&!failed&&(retained?.isActive()??!0)},invalidate(){if(active)if(suspended=!0,generation++,retained)retained.invalidate();else{const stop=cleanup;cleanup=void 0,stop?.()}},update(){active&&(suspended=!1,retained?retained.update():start(!0))}});return loadAnchoredOverlayRuntime().then(value=>{runtime=value,start()},()=>{failed=!0,finish(!1)}),operation}async function waitForDeferredPlacement(current){let operation;for(;operation=current();){const positioned=await operation.ready;if(operation===current())return!!positioned}return!0}async function awaitPopupAnimations(host,popup,isCurrent){const ownerDocument=host.ownerDocument;if(!isCurrent())return!1;if(!host.isConnected)return!0;const view=ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),host.ownerDocument!==ownerDocument||!isCurrent())return!1;const animations=popup()?.getAnimations({subtree:!0})??[];return await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),host.ownerDocument===ownerDocument&&isCurrent()}async function settlePopupTransition(options){const{host,isCurrent}=options,ownerDocument=host.ownerDocument,current=()=>host.ownerDocument===ownerDocument&&isCurrent();await host.updateComplete,current()&&(options.waitForPosition&&(!await options.waitForPosition()||!current()||(await host.updateComplete,!current()))||await awaitPopupAnimations(host,options.popup,current)&&(options.conceal&&(options.conceal(),await host.updateComplete,!current())||options.onSettled()))}class PopupTransitionWaiters{#waiters=new Map;wait(event){return new Promise(resolve=>{const waiters=this.#waiters.get(event)??new Set;waiters.add(resolve),this.#waiters.set(event,waiters)})}resolve(event){const waiters=this.#waiters.get(event);if(waiters){this.#waiters.delete(event);for(const resolve of waiters)resolve()}}}function deferredTrackRect(...args){let active=!0,cleanup;return loadAnchoredOverlayRuntime().then(runtime=>{active&&(cleanup=runtime.trackRect(...args))}).catch(()=>{}),()=>{active=!1,cleanup?.(),cleanup=void 0}}function __setAnchoredOverlayRuntimeLoaderForTesting(loader){runtimeLoader=loader??defaultRuntimeLoader,runtimePromise=void 0}function topLayerPlacement(topLayer,strategy){return{strategy:topLayer?"fixed":strategy,topLayer}}function syncTopLayerRelease(popup,wasPromoted,topLayer,runtime){if(wasPromoted&&!topLayer){if(runtime)return runtime.releaseTopLayer?.(popup),topLayer;loadAnchoredOverlayRuntime().then(runtime2=>runtime2.releaseTopLayer?.(popup),()=>{})}return topLayer}export{PopupTransitionWaiters,__setAnchoredOverlayRuntimeLoaderForTesting,awaitPopupAnimations,deferredPlace,deferredPlaceReady,deferredPlaceSession,deferredTrackRect,loadAnchoredOverlayRuntime,settlePopupTransition,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function isDefaultLabelNode(node){if(node.nodeType!==1)return!0;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}function defaultLabelForwardingSlots(host){return Array.from(host.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==host;)top=top.parentNode;return top.parentNode===host&&isDefaultLabelNode(top)})}export{defaultLabelForwardingSlots,isDefaultLabelNode};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{hierarchyField}from"./hierarchy-source-controller.js";function createHierarchySummarySource(host,source,options){return{get revision(){return source.revision},async project(request){const binding=options.captureBinding(),owner=host.ownerDocument,owned=()=>binding()&&host.ownerDocument===owner&&host.isConnected&&!request.signal.aborted,current=()=>{if(!owned())return!1;const revision=source.revision;return owned()&&revision===request.revision},check=()=>{if(!current())throw new Error(options.changedMessage)};check();const project=source.project;check();const result=await project.call(source,request);check();const rawSummary=result.summary;check();const summary=options.summary(rawSummary,check),validateRow=value=>options.row?options.row(value,check):value,view=result.rows;check();const count=view.count;check();const hasItemAt="itemAt"in view;check();const itemAt=hasItemAt?view.itemAt:void 0;check();let wrapped;if(typeof itemAt=="function"){const indexed=view;wrapped={count,itemAt(index){check();const method=indexed.itemAt;check();const value=method.call(indexed,index);return check(),validateRow(value)},keyAt(index){check();const method=indexed.keyAt;check();const value=method.call(indexed,index);return check(),value},indexOfKey(key){check();const method=indexed.indexOfKey;check();const value=method.call(indexed,key);return check(),value}}}else{const ranged=view;wrapped={count,async read(range){const active=()=>{if(check(),range.signal.aborted)throw new Error(options.rangeChangedMessage)};active();const method=ranged.read;active();const value=await method.call(ranged,range);return active(),options.range?options.range(value,range,active,validateRow):value},async indexOfKey(key,context){const active=()=>{if(check(),context.signal.aborted)throw new Error(options.navigationChangedMessage)};active();const method=ranged.indexOfKey;active();const value=await method.call(ranged,key,context);return active(),value}}}const state=result.state;check();const total=result.total;check(),options.total?.(summary,total);const focusIndex=result.focusIndex;return check(),options.accepted(wrapped,summary,current),{state,total,rows:wrapped,...focusIndex===void 0?{}:{focusIndex}}}}}function traceSourceSummary(value,check){const startMs=hierarchyField(value,"startMs");check();const endMs=hierarchyField(value,"endMs");if(check(),typeof startMs!="number"||typeof endMs!="number"||!Number.isFinite(startMs)||!Number.isFinite(endMs)||startMs<0||endMs<startMs||!Number.isFinite(endMs-startMs))throw new TypeError("Invalid trace extent");return{startMs,endMs}}function captureHierarchySourceEffects(host,control,binding){const epoch=control.epoch,owner=host.ownerDocument,projection=control.projection,{error,loading,rowError,rowsObserved}=control,bound=()=>host.isConnected&&host.ownerDocument===owner&&binding()&&control.epoch===epoch;return{epoch,error,loading,rowError,rowsObserved,bound,current:()=>bound()&&control.projection===projection&&control.error===error&&control.loading===loading&&control.rowError===rowError&&control.rowsObserved===rowsObserved}}export{captureHierarchySourceEffects,createHierarchySummarySource,traceSourceSummary};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="30.
|
|
1
|
+
const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="30.2.0";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
|
|
@@ -95,6 +95,14 @@ onPlaced?:(result:PlacementResult)=>void;}
|
|
|
95
95
|
* dimension/padding is negative; signed finite `offset` and `skidding` remain supported.
|
|
96
96
|
*/
|
|
97
97
|
export declare function place(anchor:Element|VirtualAnchor,popup:HTMLElement,opts?:PlaceOptions):()=>void;
|
|
98
|
+
/** A library-owned placement whose geometry can change without replacing its subscriptions.*/
|
|
99
|
+
export type AnchoredSurfaceSession=(()=>void)&{
|
|
100
|
+
/** False after disposal, including a current computation that failed closed.*/
|
|
101
|
+
isActive():boolean;
|
|
102
|
+
/** Immediately rejects pending geometry and pauses observer updates until `update()`.*/
|
|
103
|
+
invalidate():void;
|
|
104
|
+
/** Resumes placement from the current anchor rect with the existing options and observers.*/
|
|
105
|
+
update():void;};
|
|
98
106
|
/** {@link placeAnchoredSurface} options: the public `PlaceOptions` plus the library-internal
|
|
99
107
|
* top-layer switch, which public `place()` does not accept. */
|
|
100
108
|
export interface AnchoredSurfaceOptions extends PlaceOptions{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{computePosition,autoUpdate,getOverflowAncestors,arrow,flip,shift,offset,platform,size,hide}from"@floating-ui/dom";import{establishesFixedContainingBlock,findFixedContainingBlockAncestor,isNativeTopLayerElement}from"./fixed-containing-block.js";import{applyReferenceHidden,ancestorZoom,compensateAncestorZoom,hasTopLayerAncestor,isLibraryPromotedAndShowing,needsTopLayerEscape,promoteToTopLayer,stripStaleTopLayer}from"./top-layer-escape.js";import{finiteGeometry,PositionerGeometryError,validatedClientRect}from"./positioner-geometry.js";import{virtualAnchorFromRect}from"./positioner-geometry.js";import{releaseTopLayer}from"./top-layer-escape.js";const HOVER_BRIDGE_CORNERS=["top-left","top-right","bottom-right","bottom-left"],placementStyleOwners=new WeakMap;function hoverBridgeQuad(anchorRect,popupRect,placement){const side=placement.split("-")[0],onBlockAxis=side==="top"||side==="bottom",[first,second]=(onBlockAxis?anchorRect.top<popupRect.top:anchorRect.left<popupRect.left)?[anchorRect,popupRect]:[popupRect,anchorRect];return onBlockAxis?[[first.left,first.bottom],[first.right,first.bottom],[second.right,second.top],[second.left,second.top]]:[[first.right,first.top],[second.left,second.top],[second.left,second.bottom],[first.right,first.bottom]]}function styleMapFor(store,element){let values=store.get(element);return values||(values=new Map,store.set(element,values)),values}function readInlineStyle(element,property){return{value:element.style.getPropertyValue(property),priority:element.style.getPropertyPriority(property)}}function sameInlineStyle(left,right){return left.value===right.value&&left.priority===right.priority}function writeInlineStyle(element,property,value){element.style.removeProperty(property),value.value&&element.style.setProperty(property,value.value,value.priority)}function createPlacementSyncOwnershipController(){const syncedDimensions=new WeakMap;let nextPlacementGeneration=0;const isOlderThan=(update,current)=>update.placementGeneration<current.placementGeneration||update.placementGeneration===current.placementGeneration&&update.updateGeneration<current.updateGeneration;return{beginPlacement(){return{generation:++nextPlacementGeneration,nextUpdateGeneration:0}},beginUpdate(run){return{placementGeneration:run.generation,updateGeneration:++run.nextUpdateGeneration}},publish(popup,update,dimensions){const current=syncedDimensions.get(popup);current&&isOlderThan(update,current)||syncedDimensions.set(popup,{...dimensions,placementGeneration:update.placementGeneration,updateGeneration:update.updateGeneration})},release(popup,run){const dimensions=syncedDimensions.get(popup);if(!(dimensions&&dimensions.placementGeneration>run.generation)){for(const dimension of["width","height"]){const owned=dimensions?.[dimension];owned&&sameInlineStyle(readInlineStyle(popup,dimension),owned)&&writeInlineStyle(popup,dimension,{value:"",priority:""})}syncedDimensions.set(popup,{placementGeneration:run.generation,updateGeneration:Number.MAX_SAFE_INTEGER})}}}}const placementSyncOwnership=createPlacementSyncOwnershipController();function createPlacementStyleTransaction(){const writes=[],transaction={state:"open"};return{set(element,property,value,priority=""){if(transaction.state!=="open")return;const owners=styleMapFor(placementStyleOwners,element),previous=readInlineStyle(element,property),currentOwner=owners.get(property),write={transaction,element,property,previous,previousOwner:currentOwner&&sameInlineStyle(previous,currentOwner.written)?currentOwner:void 0,written:previous};writes.push(write),writeInlineStyle(element,property,{value,priority}),write.written=readInlineStyle(element,property),owners.set(property,write)},ownedValue(element,property){if(transaction.state!=="open")return;const owner=placementStyleOwners.get(element)?.get(property);if(owner?.transaction!==transaction)return;const current=readInlineStyle(element,property);return sameInlineStyle(current,owner.written)?current:void 0},commit(){if(transaction.state==="open"){transaction.state="committed";for(const write of writes){const owners=placementStyleOwners.get(write.element);owners?.get(write.property)===write&&owners.delete(write.property)}writes.length=0}},rollback(){if(transaction.state==="open"){transaction.state="rolled-back";for(const write of writes.reverse()){const owners=placementStyleOwners.get(write.element);if(owners?.get(write.property)!==write)continue;if(!sameInlineStyle(readInlineStyle(write.element,write.property),write.written)){owners.delete(write.property);continue}let previous=write.previous,previousOwner=write.previousOwner;for(;previousOwner?.transaction.state==="rolled-back";)previous=previousOwner.previous,previousOwner=previousOwner.previousOwner;writeInlineStyle(write.element,write.property,previous),previousOwner?.transaction.state==="open"?owners.set(write.property,previousOwner):owners.delete(write.property)}writes.length=0}}}}function writeHoverBridge(bridge,quad,styleTransaction){HOVER_BRIDGE_CORNERS.forEach((corner,index)=>{const[x,y]=quad[index];styleTransaction.set(bridge,`--lr-positioner-hover-bridge-${corner}-x`,`${x}px`),styleTransaction.set(bridge,`--lr-positioner-hover-bridge-${corner}-y`,`${y}px`)})}async function correctedGetOffsetParent(element,polyfill){const defaultOffsetParent=await platform.getOffsetParent(element,polyfill);if(!(element instanceof HTMLElement))return defaultOffsetParent;const view=element.ownerDocument.defaultView;if(!view)return defaultOffsetParent;if(isNativeTopLayerElement(element))return view;const position=view.getComputedStyle(element).position;if(position==="absolute")return findFixedContainingBlockAncestor(element,!0)??(Math.abs(ancestorZoom(element)-1)>1e-6?view:defaultOffsetParent);if(position!=="fixed")return defaultOffsetParent;const nearestContainingBlock=findFixedContainingBlockAncestor(element);return nearestContainingBlock||(defaultOffsetParent instanceof Element&&establishesFixedContainingBlock(defaultOffsetParent)?defaultOffsetParent:view)}function fixedInlineCoordinates(containingBlock){const probe=containingBlock.ownerDocument.createElement("span");probe.setAttribute("aria-hidden","true"),probe.style.cssText="all:initial!important;position:fixed!important;left:0!important;top:0!important;width:0!important;height:0!important;visibility:hidden!important";try{if((containingBlock.shadowRoot??containingBlock).appendChild(probe),probe.getClientRects().length===0)return;const origin=validatedClientRect(probe.getBoundingClientRect(),"place() fixed origin");probe.style.setProperty("width","100px","important"),probe.style.setProperty("height","100px","important");const size2=validatedClientRect(probe.getBoundingClientRect(),"place() fixed scale"),scale={x:size2.width/100,y:size2.height/100};return scale.x>0&&scale.y>0?{origin,scale}:void 0}finally{probe.remove()}}async function popupRectAtPosition(anchor,popup,strategy,x,y,placementPlatform=platform){const currentRect=validatedClientRect(popup.getBoundingClientRect(),"place() popup rect"),offsetParent=await correctedGetOffsetParent(popup),rect=await placementPlatform.convertOffsetParentRelativeRectToViewportRelativeRect({elements:{reference:anchor,floating:popup},rect:{x,y,width:0,height:0},offsetParent,strategy}),{x:left,y:top}=rect,{width,height}=currentRect;return validatedClientRect({x:left,y:top,width,height,left,top,right:left+width,bottom:top+height},"place() converted popup rect")}function validatePlaceNumericOptions(opts){["offset","skidding","flipPadding","shiftPadding","padding","autoSizePadding","arrowPadding"].forEach((name,index)=>{const value=opts[name];value!==void 0&&finiteGeometry(value,`place() ${name}`,index>1)})}function validateAnchorBeforeSetup(anchor){try{validatedClientRect(anchor.getBoundingClientRect(),"place() anchor rect")}catch(error){if(error instanceof PositionerGeometryError)throw error}}function place(anchor,popup,opts={}){return placeImpl(anchor,popup,opts)}const MAX_ESCAPE_RERUNS=2;function placeImpl(anchor,popup,opts,hooks){validatePlaceNumericOptions(opts),validateAnchorBeforeSetup(anchor);const placementRun=placementSyncOwnership.beginPlacement(popup),strategy=opts.strategy??"fixed";popup.style.position=strategy,popup.style.margin="0";const padding=opts.padding??8,sync=opts.sync,autoSize=opts.autoSize,hoverBridge=opts.hoverBridge;let disposed=!1,escapeReruns=0,stopAutoUpdate,stopResize,stopScroll,scrollFrame,updateGeneration=0;const openStyleTransactions=new Set,view=popup.ownerDocument.defaultView??window,visualViewport=view.visualViewport,updateFromVisualViewport=()=>update(),cancelScrollFrame=()=>{scrollFrame!==void 0&&(view.cancelAnimationFrame(scrollFrame),scrollFrame=void 0)},updateFromScroll=()=>{disposed||(updateGeneration++,scrollFrame===void 0&&(scrollFrame=view.requestAnimationFrame(()=>{scrollFrame=void 0,update()})))},dispose=()=>{if(!disposed){disposed=!0,updateGeneration++,cancelScrollFrame(),stopScroll?.(),stopResize?.(),stopAutoUpdate?.(),stopAutoUpdate=void 0,visualViewport?.removeEventListener("resize",updateFromVisualViewport);for(const transaction of[...openStyleTransactions].reverse())transaction.rollback();openStyleTransactions.clear()}};sync||placementSyncOwnership.release(popup,placementRun);const middlewareFor=(styleTransaction,isCurrent)=>[offset({mainAxis:opts.offset??4,crossAxis:opts.skidding??0}),sync?size({apply({rects,elements}){if(!isCurrent())return;const referenceWidth=finiteGeometry(rects.reference.width,"place() reference width",!0),referenceHeight=finiteGeometry(rects.reference.height,"place() reference height",!0);styleTransaction.set(elements.floating,"width",sync==="width"||sync==="both"?`${referenceWidth}px`:""),styleTransaction.set(elements.floating,"height",sync==="height"||sync==="both"?`${referenceHeight}px`:"")}}):void 0,opts.flip===!1?void 0:flip({boundary:opts.flipBoundary??opts.boundary,fallbackPlacements:opts.flipFallbackPlacements,fallbackStrategy:opts.flipFallbackStrategy==="initial-placement"?"initialPlacement":opts.flipFallbackStrategy==="best-fit"?"bestFit":void 0,padding:opts.flipPadding}),opts.shift===!1?void 0:shift({boundary:opts.shiftBoundary??opts.boundary,padding:opts.shiftPadding??padding,crossAxis:opts.shiftCrossAxis===!0}),opts.arrow?arrow({element:opts.arrow,padding:opts.arrowPadding??0}):void 0,size({boundary:opts.boundary,padding,apply({availableWidth,availableHeight,elements}){isCurrent()&&(autoSize!=="horizontal"&&autoSize!=="both"&&styleTransaction.set(elements.floating,"--lr-positioner-available-inline-size",`${Math.max(0,finiteGeometry(availableWidth,"place() available width"))}px`),autoSize!=="vertical"&&autoSize!=="both"&&styleTransaction.set(elements.floating,"--lr-positioner-available-block-size",`${Math.max(0,finiteGeometry(availableHeight,"place() available height"))}px`))}}),autoSize?size({boundary:opts.autoSizeBoundary??opts.boundary,padding:opts.autoSizePadding??0,apply({availableWidth,availableHeight,elements}){isCurrent()&&((autoSize==="horizontal"||autoSize==="both")&&styleTransaction.set(elements.floating,"--lr-positioner-available-inline-size",`${Math.max(0,finiteGeometry(availableWidth,"place() auto-size available width"))}px`),(autoSize==="vertical"||autoSize==="both")&&styleTransaction.set(elements.floating,"--lr-positioner-available-block-size",`${Math.max(0,finiteGeometry(availableHeight,"place() auto-size available height"))}px`))}}):void 0,...hooks?.middleware??[]].filter(entry=>entry!==void 0);function update(){if(disposed)return;cancelScrollFrame();const generation=++updateGeneration,isCurrent=()=>!disposed&&generation===updateGeneration;try{validatedClientRect(anchor.getBoundingClientRect(),"place() anchor rect")}catch{dispose();return}try{hooks?.beforeCompute()}catch{}const updateRun=placementSyncOwnership.beginUpdate(placementRun),styleTransaction=createPlacementStyleTransaction();openStyleTransactions.add(styleTransaction);const rollback=()=>{styleTransaction.rollback(),openStyleTransactions.delete(styleTransaction)};let resolvedOffsetParent;const offsetParents=new Map,recordingGetOffsetParent=async(element,polyfill)=>{let pending=polyfill?void 0:offsetParents.get(element);pending||(pending=correctedGetOffsetParent(element,polyfill),polyfill||offsetParents.set(element,pending));const result=await pending;return element===popup&&(resolvedOffsetParent=result),result};let inlineCoordinates,inlineOffsetParent;const placementPlatform={...platform,getOffsetParent:recordingGetOffsetParent,async getElementRects(data){const rects=await platform.getElementRects.call(this,data),parent=resolvedOffsetParent;if(inlineCoordinates=strategy==="fixed"&&parent instanceof HTMLElement&&!(parent instanceof HTMLSlotElement)&&getComputedStyle(parent).display==="inline"&&["","normal","1"].includes(getComputedStyle(popup).zoom||"")?fixedInlineCoordinates(parent):void 0,inlineOffsetParent=inlineCoordinates?parent:void 0,!inlineCoordinates||!inlineOffsetParent)return rects;const viewport=await platform.convertOffsetParentRelativeRectToViewportRelativeRect({elements:{reference:data.reference,floating:data.floating},rect:rects.reference,offsetParent:inlineOffsetParent,strategy}),{origin,scale}=inlineCoordinates;return{...rects,reference:{x:finiteGeometry((viewport.x-origin.left)/scale.x,"place() inline reference x"),y:finiteGeometry((viewport.y-origin.top)/scale.y,"place() inline reference y"),width:finiteGeometry(viewport.width/scale.x,"place() inline reference width"),height:finiteGeometry(viewport.height/scale.y,"place() inline reference height")}}},getScale(element){return inlineCoordinates&&element===inlineOffsetParent?inlineCoordinates.scale:platform.getScale(element)},convertOffsetParentRelativeRectToViewportRelativeRect(data){if(inlineCoordinates&&data.offsetParent===inlineOffsetParent&&data.strategy==="fixed"){const{origin,scale}=inlineCoordinates;return{x:origin.left+data.rect.x*scale.x,y:origin.top+data.rect.y*scale.y,width:data.rect.width*scale.x,height:data.rect.height*scale.y}}return platform.convertOffsetParentRelativeRectToViewportRelativeRect(data)}};computePosition(anchor,popup,{strategy,placement:opts.placement??"bottom-start",middleware:middlewareFor(styleTransaction,isCurrent),platform:placementPlatform}).then(async({x,y,placement,middlewareData})=>{if(!isCurrent()){rollback();return}let bridgeQuad;try{if(finiteGeometry(x,"place() resolved x"),finiteGeometry(y,"place() resolved y"),middlewareData.arrow?.x!==void 0&&finiteGeometry(middlewareData.arrow.x,"place() resolved arrow x"),middlewareData.arrow?.y!==void 0&&finiteGeometry(middlewareData.arrow.y,"place() resolved arrow y"),hooks&&escapeReruns<MAX_ESCAPE_RERUNS){const view2=popup.ownerDocument.defaultView??window;let rerun=!1;try{rerun=hooks.afterResolve(resolvedOffsetParent??view2,middlewareData)}catch{rerun=!1}if(rerun){escapeReruns++,rollback(),update();return}}if(escapeReruns=0,hoverBridge){const anchorRect=validatedClientRect(anchor.getBoundingClientRect(),"place() anchor rect"),placedPopupRect=await popupRectAtPosition(anchor,popup,strategy,x,y,placementPlatform);if(!isCurrent()){rollback();return}bridgeQuad=hoverBridgeQuad(anchorRect,placedPopupRect,placement)}if(!isCurrent()){rollback();return}styleTransaction.set(popup,"left",`${finiteGeometry(x,"place() resolved x")}px`),styleTransaction.set(popup,"top",`${finiteGeometry(y,"place() resolved y")}px`),hoverBridge&&bridgeQuad&&writeHoverBridge(hoverBridge,bridgeQuad,styleTransaction);const ownedSyncDimensions=sync?{width:styleTransaction.ownedValue(popup,"width"),height:styleTransaction.ownedValue(popup,"height")}:void 0;styleTransaction.commit(),openStyleTransactions.delete(styleTransaction),sync&&placementSyncOwnership.publish(popup,updateRun,ownedSyncDimensions??{})}catch{isCurrent()?dispose():rollback();return}opts.onPlaced?.({placement,arrow:middlewareData.arrow})},()=>{isCurrent()?dispose():rollback()})}const reference=anchor.nodeType===1?anchor:anchor.contextElement,scrollTargets=new Set([...reference?getOverflowAncestors(reference):[],...getOverflowAncestors(popup),...visualViewport?[visualViewport]:[]]);for(const target of scrollTargets)target.addEventListener("scroll",updateFromScroll,{passive:!0}),target.addEventListener("resize",cancelScrollFrame);stopScroll=()=>{for(const target of scrollTargets)target.removeEventListener("scroll",updateFromScroll),target.removeEventListener("resize",cancelScrollFrame)};const stop=autoUpdate(anchor,popup,()=>{scrollFrame===void 0&&update()},{elementResize:!1,ancestorScroll:!1});return disposed?(stop(),dispose):(stopAutoUpdate=stop,stopResize=observeElementResize(anchor,popup,update),visualViewport?.addEventListener("resize",updateFromVisualViewport),dispose)}function isWindowLike(value){return!(value instanceof Element)}function placeAnchoredSurface(anchor,popup,opts={}){validatePlaceNumericOptions(opts),validateAnchorBeforeSetup(anchor);const bridge=opts.hoverBridge,fixed=(opts.strategy??"fixed")==="fixed",escape=(element,eligible)=>{isLibraryPromotedAndShowing(element)||(eligible&&(opts.topLayer||needsTopLayerEscape(element))?promoteToTopLayer(element,popup):stripStaleTopLayer(element))},referenceHidden=hide({strategy:"referenceHidden"}),referenceElement=anchor instanceof Element?anchor:anchor.contextElement??null,referenceMeasurable=()=>referenceElement!==null&&!hasTopLayerAncestor(referenceElement);return bridge&&escape(bridge,!0),escape(popup,fixed),placeImpl(anchor,popup,opts,{beforeCompute(){bridge&&escape(bridge,!0),fixed&&compensateAncestorZoom(popup,null),bridge&&compensateAncestorZoom(bridge,null,popup)},middleware:[{name:referenceHidden.name,options:referenceHidden.options,fn:async state=>{if(!fixed||!referenceMeasurable())return{};const result=await referenceHidden.fn(state),offsets=result.data?.referenceHiddenOffsets,{width,height}=state.rects.reference;return!offsets||width>0&&height>0?result:{data:{...result.data,referenceHidden:offsets.top>0||offsets.right>0||offsets.bottom>0||offsets.left>0}}}}],afterResolve(offsetParent,data){return applyReferenceHidden(popup,data.hide?.referenceHidden===!0),fixed?isWindowLike(offsetParent)||isLibraryPromotedAndShowing(popup)?!1:promoteToTopLayer(popup):compensateAncestorZoom(popup,isWindowLike(offsetParent)?null:offsetParent)}})}function trackRect(target,onUpdate){const update=()=>onUpdate(target.getBoundingClientRect()),stopAutoUpdate=autoUpdate(target,target,update),visualViewport=target.ownerDocument.defaultView?.visualViewport,onVisualViewportChange=()=>update();return visualViewport?.addEventListener("resize",onVisualViewportChange),visualViewport?.addEventListener("scroll",onVisualViewportChange),()=>{stopAutoUpdate(),visualViewport?.removeEventListener("resize",onVisualViewportChange),visualViewport?.removeEventListener("scroll",onVisualViewportChange)}}function observeElementResize(anchor,popup,update){const view=popup.ownerDocument.defaultView;let active=!0,frame;const observer=view?.ResizeObserver?new view.ResizeObserver(()=>{!active||frame!==void 0||(frame=view.requestAnimationFrame(()=>{frame=void 0,active&&update()}))}):void 0,reference=anchor.nodeType===1?anchor:anchor.contextElement;return reference&&observer?.observe(reference),observer?.observe(popup),()=>{active=!1,observer?.disconnect(),frame!==void 0&&view?.cancelAnimationFrame(frame)}}export{createPlacementStyleTransaction,createPlacementSyncOwnershipController,place,placeAnchoredSurface,releaseTopLayer,trackRect,virtualAnchorFromRect};
|
|
1
|
+
import{computePosition,autoUpdate,getOverflowAncestors,arrow,flip,shift,offset,platform,size,hide}from"@floating-ui/dom";import{establishesFixedContainingBlock,findFixedContainingBlockAncestor,isNativeTopLayerElement}from"./fixed-containing-block.js";import{applyReferenceHidden,ancestorZoom,compensateAncestorZoom,hasTopLayerAncestor,isLibraryPromotedAndShowing,needsTopLayerEscape,promoteToTopLayer,stripStaleTopLayer}from"./top-layer-escape.js";import{finiteGeometry,PositionerGeometryError,validatedClientRect}from"./positioner-geometry.js";import{virtualAnchorFromRect}from"./positioner-geometry.js";import{releaseTopLayer}from"./top-layer-escape.js";const HOVER_BRIDGE_CORNERS=["top-left","top-right","bottom-right","bottom-left"],placementStyleOwners=new WeakMap;function hoverBridgeQuad(anchorRect,popupRect,placement){const side=placement.split("-")[0],onBlockAxis=side==="top"||side==="bottom",[first,second]=(onBlockAxis?anchorRect.top<popupRect.top:anchorRect.left<popupRect.left)?[anchorRect,popupRect]:[popupRect,anchorRect];return onBlockAxis?[[first.left,first.bottom],[first.right,first.bottom],[second.right,second.top],[second.left,second.top]]:[[first.right,first.top],[second.left,second.top],[second.left,second.bottom],[first.right,first.bottom]]}function styleMapFor(store,element){let values=store.get(element);return values||(values=new Map,store.set(element,values)),values}function readInlineStyle(element,property){return{value:element.style.getPropertyValue(property),priority:element.style.getPropertyPriority(property)}}function sameInlineStyle(left,right){return left.value===right.value&&left.priority===right.priority}function writeInlineStyle(element,property,value){element.style.removeProperty(property),value.value&&element.style.setProperty(property,value.value,value.priority)}function createPlacementSyncOwnershipController(){const syncedDimensions=new WeakMap;let nextPlacementGeneration=0;const isOlderThan=(update,current)=>update.placementGeneration<current.placementGeneration||update.placementGeneration===current.placementGeneration&&update.updateGeneration<current.updateGeneration;return{beginPlacement(){return{generation:++nextPlacementGeneration,nextUpdateGeneration:0}},beginUpdate(run){return{placementGeneration:run.generation,updateGeneration:++run.nextUpdateGeneration}},publish(popup,update,dimensions){const current=syncedDimensions.get(popup);current&&isOlderThan(update,current)||syncedDimensions.set(popup,{...dimensions,placementGeneration:update.placementGeneration,updateGeneration:update.updateGeneration})},release(popup,run){const dimensions=syncedDimensions.get(popup);if(!(dimensions&&dimensions.placementGeneration>run.generation)){for(const dimension of["width","height"]){const owned=dimensions?.[dimension];owned&&sameInlineStyle(readInlineStyle(popup,dimension),owned)&&writeInlineStyle(popup,dimension,{value:"",priority:""})}syncedDimensions.set(popup,{placementGeneration:run.generation,updateGeneration:Number.MAX_SAFE_INTEGER})}}}}const placementSyncOwnership=createPlacementSyncOwnershipController();function createPlacementStyleTransaction(){const writes=[],transaction={state:"open"};return{set(element,property,value,priority=""){if(transaction.state!=="open")return;const owners=styleMapFor(placementStyleOwners,element),previous=readInlineStyle(element,property),currentOwner=owners.get(property),write={transaction,element,property,previous,previousOwner:currentOwner&&sameInlineStyle(previous,currentOwner.written)?currentOwner:void 0,written:previous};writes.push(write),writeInlineStyle(element,property,{value,priority}),write.written=readInlineStyle(element,property),owners.set(property,write)},ownedValue(element,property){if(transaction.state!=="open")return;const owner=placementStyleOwners.get(element)?.get(property);if(owner?.transaction!==transaction)return;const current=readInlineStyle(element,property);return sameInlineStyle(current,owner.written)?current:void 0},commit(){if(transaction.state==="open"){transaction.state="committed";for(const write of writes){const owners=placementStyleOwners.get(write.element);owners?.get(write.property)===write&&owners.delete(write.property)}writes.length=0}},rollback(){if(transaction.state==="open"){transaction.state="rolled-back";for(const write of writes.reverse()){const owners=placementStyleOwners.get(write.element);if(owners?.get(write.property)!==write)continue;if(!sameInlineStyle(readInlineStyle(write.element,write.property),write.written)){owners.delete(write.property);continue}let previous=write.previous,previousOwner=write.previousOwner;for(;previousOwner?.transaction.state==="rolled-back";)previous=previousOwner.previous,previousOwner=previousOwner.previousOwner;writeInlineStyle(write.element,write.property,previous),previousOwner?.transaction.state==="open"?owners.set(write.property,previousOwner):owners.delete(write.property)}writes.length=0}}}}function writeHoverBridge(bridge,quad,styleTransaction){HOVER_BRIDGE_CORNERS.forEach((corner,index)=>{const[x,y]=quad[index];styleTransaction.set(bridge,`--lr-positioner-hover-bridge-${corner}-x`,`${x}px`),styleTransaction.set(bridge,`--lr-positioner-hover-bridge-${corner}-y`,`${y}px`)})}async function correctedGetOffsetParent(element,polyfill){const defaultOffsetParent=await platform.getOffsetParent(element,polyfill);if(!(element instanceof HTMLElement))return defaultOffsetParent;const view=element.ownerDocument.defaultView;if(!view)return defaultOffsetParent;if(isNativeTopLayerElement(element))return view;const position=view.getComputedStyle(element).position;if(position==="absolute")return findFixedContainingBlockAncestor(element,!0)??(Math.abs(ancestorZoom(element)-1)>1e-6?view:defaultOffsetParent);if(position!=="fixed")return defaultOffsetParent;const nearestContainingBlock=findFixedContainingBlockAncestor(element);return nearestContainingBlock||(defaultOffsetParent instanceof Element&&establishesFixedContainingBlock(defaultOffsetParent)?defaultOffsetParent:view)}function fixedInlineCoordinates(containingBlock){const probe=containingBlock.ownerDocument.createElement("span");probe.setAttribute("aria-hidden","true"),probe.style.cssText="all:initial!important;position:fixed!important;left:0!important;top:0!important;width:0!important;height:0!important;visibility:hidden!important";try{if((containingBlock.shadowRoot??containingBlock).appendChild(probe),probe.getClientRects().length===0)return;const origin=validatedClientRect(probe.getBoundingClientRect(),"place() fixed origin");probe.style.setProperty("width","100px","important"),probe.style.setProperty("height","100px","important");const size2=validatedClientRect(probe.getBoundingClientRect(),"place() fixed scale"),scale={x:size2.width/100,y:size2.height/100};return scale.x>0&&scale.y>0?{origin,scale}:void 0}finally{probe.remove()}}async function popupRectAtPosition(anchor,popup,strategy,x,y,placementPlatform=platform){const currentRect=validatedClientRect(popup.getBoundingClientRect(),"place() popup rect"),offsetParent=await correctedGetOffsetParent(popup),rect=await placementPlatform.convertOffsetParentRelativeRectToViewportRelativeRect({elements:{reference:anchor,floating:popup},rect:{x,y,width:0,height:0},offsetParent,strategy}),{x:left,y:top}=rect,{width,height}=currentRect;return validatedClientRect({x:left,y:top,width,height,left,top,right:left+width,bottom:top+height},"place() converted popup rect")}function validatePlaceNumericOptions(opts){["offset","skidding","flipPadding","shiftPadding","padding","autoSizePadding","arrowPadding"].forEach((name,index)=>{const value=opts[name];value!==void 0&&finiteGeometry(value,`place() ${name}`,index>1)})}function validateAnchorBeforeSetup(anchor){try{validatedClientRect(anchor.getBoundingClientRect(),"place() anchor rect")}catch(error){if(error instanceof PositionerGeometryError)throw error}}function place(anchor,popup,opts={}){return placeImpl(anchor,popup,opts)}const MAX_ESCAPE_RERUNS=2;function placeImpl(anchor,popup,opts,hooks){validatePlaceNumericOptions(opts),validateAnchorBeforeSetup(anchor);const placementRun=placementSyncOwnership.beginPlacement(popup),strategy=opts.strategy??"fixed";popup.style.position=strategy,popup.style.margin="0";const padding=opts.padding??8,sync=opts.sync,autoSize=opts.autoSize,hoverBridge=opts.hoverBridge;let disposed=!1,suspended=!1,escapeReruns=0,stopAutoUpdate,stopResize,stopScroll,scrollFrame,updateGeneration=0;const openStyleTransactions=new Set,view=popup.ownerDocument.defaultView??window,visualViewport=view.visualViewport,updateFromVisualViewport=()=>update(),cancelScrollFrame=()=>{scrollFrame!==void 0&&(view.cancelAnimationFrame(scrollFrame),scrollFrame=void 0)},updateFromScroll=()=>{disposed||suspended||(updateGeneration++,scrollFrame===void 0&&(scrollFrame=view.requestAnimationFrame(()=>{scrollFrame=void 0,update()})))},dispose=()=>{if(!disposed){disposed=!0,updateGeneration++,cancelScrollFrame(),stopScroll?.(),stopResize?.(),stopAutoUpdate?.(),stopAutoUpdate=void 0,visualViewport?.removeEventListener("resize",updateFromVisualViewport);for(const transaction of[...openStyleTransactions].reverse())transaction.rollback();openStyleTransactions.clear()}},session=Object.assign(dispose,{isActive(){return!disposed},invalidate(){if(!(disposed||suspended)){suspended=!0,updateGeneration++,cancelScrollFrame();for(const transaction of[...openStyleTransactions].reverse())transaction.rollback();openStyleTransactions.clear()}},update(){disposed||(suspended=!1,update())}});sync||placementSyncOwnership.release(popup,placementRun);const middlewareFor=(styleTransaction,isCurrent)=>[offset({mainAxis:opts.offset??4,crossAxis:opts.skidding??0}),sync?size({apply({rects,elements}){if(!isCurrent())return;const referenceWidth=finiteGeometry(rects.reference.width,"place() reference width",!0),referenceHeight=finiteGeometry(rects.reference.height,"place() reference height",!0);styleTransaction.set(elements.floating,"width",sync==="width"||sync==="both"?`${referenceWidth}px`:""),styleTransaction.set(elements.floating,"height",sync==="height"||sync==="both"?`${referenceHeight}px`:"")}}):void 0,opts.flip===!1?void 0:flip({boundary:opts.flipBoundary??opts.boundary,fallbackPlacements:opts.flipFallbackPlacements,fallbackStrategy:opts.flipFallbackStrategy==="initial-placement"?"initialPlacement":opts.flipFallbackStrategy==="best-fit"?"bestFit":void 0,padding:opts.flipPadding}),opts.shift===!1?void 0:shift({boundary:opts.shiftBoundary??opts.boundary,padding:opts.shiftPadding??padding,crossAxis:opts.shiftCrossAxis===!0}),opts.arrow?arrow({element:opts.arrow,padding:opts.arrowPadding??0}):void 0,size({boundary:opts.boundary,padding,apply({availableWidth,availableHeight,elements}){isCurrent()&&(autoSize!=="horizontal"&&autoSize!=="both"&&styleTransaction.set(elements.floating,"--lr-positioner-available-inline-size",`${Math.max(0,finiteGeometry(availableWidth,"place() available width"))}px`),autoSize!=="vertical"&&autoSize!=="both"&&styleTransaction.set(elements.floating,"--lr-positioner-available-block-size",`${Math.max(0,finiteGeometry(availableHeight,"place() available height"))}px`))}}),autoSize?size({boundary:opts.autoSizeBoundary??opts.boundary,padding:opts.autoSizePadding??0,apply({availableWidth,availableHeight,elements}){isCurrent()&&((autoSize==="horizontal"||autoSize==="both")&&styleTransaction.set(elements.floating,"--lr-positioner-available-inline-size",`${Math.max(0,finiteGeometry(availableWidth,"place() auto-size available width"))}px`),(autoSize==="vertical"||autoSize==="both")&&styleTransaction.set(elements.floating,"--lr-positioner-available-block-size",`${Math.max(0,finiteGeometry(availableHeight,"place() auto-size available height"))}px`))}}):void 0,...hooks?.middleware??[]].filter(entry=>entry!==void 0);function update(){if(disposed||suspended)return;cancelScrollFrame();const generation=++updateGeneration,isCurrent=()=>!disposed&&!suspended&&generation===updateGeneration;try{validatedClientRect(anchor.getBoundingClientRect(),"place() anchor rect")}catch{dispose();return}if(!isCurrent())return;try{hooks?.beforeCompute()}catch{}if(!isCurrent())return;const updateRun=placementSyncOwnership.beginUpdate(placementRun),styleTransaction=createPlacementStyleTransaction();openStyleTransactions.add(styleTransaction);const rollback=()=>{styleTransaction.rollback(),openStyleTransactions.delete(styleTransaction)};let resolvedOffsetParent;const offsetParents=new Map,recordingGetOffsetParent=async(element,polyfill)=>{let pending=polyfill?void 0:offsetParents.get(element);pending||(pending=correctedGetOffsetParent(element,polyfill),polyfill||offsetParents.set(element,pending));const result=await pending;return element===popup&&(resolvedOffsetParent=result),result};let inlineCoordinates,inlineOffsetParent;const placementPlatform={...platform,getOffsetParent:recordingGetOffsetParent,async getElementRects(data){const rects=await platform.getElementRects.call(this,data),parent=resolvedOffsetParent;if(inlineCoordinates=strategy==="fixed"&&parent instanceof HTMLElement&&!(parent instanceof HTMLSlotElement)&&getComputedStyle(parent).display==="inline"&&["","normal","1"].includes(getComputedStyle(popup).zoom||"")?fixedInlineCoordinates(parent):void 0,inlineOffsetParent=inlineCoordinates?parent:void 0,!inlineCoordinates||!inlineOffsetParent)return rects;const viewport=await platform.convertOffsetParentRelativeRectToViewportRelativeRect({elements:{reference:data.reference,floating:data.floating},rect:rects.reference,offsetParent:inlineOffsetParent,strategy}),{origin,scale}=inlineCoordinates;return{...rects,reference:{x:finiteGeometry((viewport.x-origin.left)/scale.x,"place() inline reference x"),y:finiteGeometry((viewport.y-origin.top)/scale.y,"place() inline reference y"),width:finiteGeometry(viewport.width/scale.x,"place() inline reference width"),height:finiteGeometry(viewport.height/scale.y,"place() inline reference height")}}},getScale(element){return inlineCoordinates&&element===inlineOffsetParent?inlineCoordinates.scale:platform.getScale(element)},convertOffsetParentRelativeRectToViewportRelativeRect(data){if(inlineCoordinates&&data.offsetParent===inlineOffsetParent&&data.strategy==="fixed"){const{origin,scale}=inlineCoordinates;return{x:origin.left+data.rect.x*scale.x,y:origin.top+data.rect.y*scale.y,width:data.rect.width*scale.x,height:data.rect.height*scale.y}}return platform.convertOffsetParentRelativeRectToViewportRelativeRect(data)}};computePosition(anchor,popup,{strategy,placement:opts.placement??"bottom-start",middleware:middlewareFor(styleTransaction,isCurrent),platform:placementPlatform}).then(async({x,y,placement,middlewareData})=>{if(!isCurrent()){rollback();return}let bridgeQuad;try{if(finiteGeometry(x,"place() resolved x"),finiteGeometry(y,"place() resolved y"),middlewareData.arrow?.x!==void 0&&finiteGeometry(middlewareData.arrow.x,"place() resolved arrow x"),middlewareData.arrow?.y!==void 0&&finiteGeometry(middlewareData.arrow.y,"place() resolved arrow y"),hooks&&escapeReruns<MAX_ESCAPE_RERUNS){const view2=popup.ownerDocument.defaultView??window;let rerun=!1;try{rerun=hooks.afterResolve(resolvedOffsetParent??view2,middlewareData)}catch{rerun=!1}if(rerun){escapeReruns++,rollback(),update();return}}if(escapeReruns=0,hoverBridge){const anchorRect=validatedClientRect(anchor.getBoundingClientRect(),"place() anchor rect"),placedPopupRect=await popupRectAtPosition(anchor,popup,strategy,x,y,placementPlatform);if(!isCurrent()){rollback();return}bridgeQuad=hoverBridgeQuad(anchorRect,placedPopupRect,placement)}if(!isCurrent()){rollback();return}styleTransaction.set(popup,"left",`${finiteGeometry(x,"place() resolved x")}px`),styleTransaction.set(popup,"top",`${finiteGeometry(y,"place() resolved y")}px`),hoverBridge&&bridgeQuad&&writeHoverBridge(hoverBridge,bridgeQuad,styleTransaction);const ownedSyncDimensions=sync?{width:styleTransaction.ownedValue(popup,"width"),height:styleTransaction.ownedValue(popup,"height")}:void 0;styleTransaction.commit(),openStyleTransactions.delete(styleTransaction),sync&&placementSyncOwnership.publish(popup,updateRun,ownedSyncDimensions??{})}catch{isCurrent()?dispose():rollback();return}opts.onPlaced?.({placement,arrow:middlewareData.arrow})},()=>{isCurrent()?dispose():rollback()})}const reference=anchor.nodeType===1?anchor:anchor.contextElement,scrollTargets=new Set([...reference?getOverflowAncestors(reference):[],...getOverflowAncestors(popup),...visualViewport?[visualViewport]:[]]);for(const target of scrollTargets)target.addEventListener("scroll",updateFromScroll,{passive:!0}),target.addEventListener("resize",cancelScrollFrame);stopScroll=()=>{for(const target of scrollTargets)target.removeEventListener("scroll",updateFromScroll),target.removeEventListener("resize",cancelScrollFrame)};const stop=autoUpdate(anchor,popup,()=>{scrollFrame===void 0&&update()},{elementResize:!1,ancestorScroll:!1});return disposed?(stop(),session):(stopAutoUpdate=stop,stopResize=observeElementResize(anchor,popup,update),visualViewport?.addEventListener("resize",updateFromVisualViewport),session)}function isWindowLike(value){return!(value instanceof Element)}function placeAnchoredSurface(anchor,popup,opts={}){return placeAnchoredSurfaceSession(anchor,popup,opts)}function placeAnchoredSurfaceSession(anchor,popup,opts={}){validatePlaceNumericOptions(opts),validateAnchorBeforeSetup(anchor);const bridge=opts.hoverBridge,fixed=(opts.strategy??"fixed")==="fixed",escape=(element,eligible)=>{isLibraryPromotedAndShowing(element)||(eligible&&(opts.topLayer||needsTopLayerEscape(element))?promoteToTopLayer(element,popup):stripStaleTopLayer(element))},referenceHidden=hide({strategy:"referenceHidden"}),referenceElement=anchor instanceof Element?anchor:anchor.contextElement??null,referenceMeasurable=()=>referenceElement!==null&&!hasTopLayerAncestor(referenceElement);return bridge&&escape(bridge,!0),escape(popup,fixed),placeImpl(anchor,popup,opts,{beforeCompute(){bridge&&escape(bridge,!0),fixed&&compensateAncestorZoom(popup,null),bridge&&compensateAncestorZoom(bridge,null,popup)},middleware:[{name:referenceHidden.name,options:referenceHidden.options,fn:async state=>{if(!fixed||!referenceMeasurable())return{};const result=await referenceHidden.fn(state),offsets=result.data?.referenceHiddenOffsets,{width,height}=state.rects.reference;return!offsets||width>0&&height>0?result:{data:{...result.data,referenceHidden:offsets.top>0||offsets.right>0||offsets.bottom>0||offsets.left>0}}}}],afterResolve(offsetParent,data){return applyReferenceHidden(popup,data.hide?.referenceHidden===!0),fixed?isWindowLike(offsetParent)||isLibraryPromotedAndShowing(popup)?!1:promoteToTopLayer(popup):compensateAncestorZoom(popup,isWindowLike(offsetParent)?null:offsetParent)}})}function trackRect(target,onUpdate){const update=()=>onUpdate(target.getBoundingClientRect()),stopAutoUpdate=autoUpdate(target,target,update),visualViewport=target.ownerDocument.defaultView?.visualViewport,onVisualViewportChange=()=>update();return visualViewport?.addEventListener("resize",onVisualViewportChange),visualViewport?.addEventListener("scroll",onVisualViewportChange),()=>{stopAutoUpdate(),visualViewport?.removeEventListener("resize",onVisualViewportChange),visualViewport?.removeEventListener("scroll",onVisualViewportChange)}}function observeElementResize(anchor,popup,update){const view=popup.ownerDocument.defaultView;let active=!0,frame;const observer=view?.ResizeObserver?new view.ResizeObserver(()=>{!active||frame!==void 0||(frame=view.requestAnimationFrame(()=>{frame=void 0,active&&update()}))}):void 0,reference=anchor.nodeType===1?anchor:anchor.contextElement;return reference&&observer?.observe(reference),observer?.observe(popup),()=>{active=!1,observer?.disconnect(),frame!==void 0&&view?.cancelAnimationFrame(frame)}}export{createPlacementStyleTransaction,createPlacementSyncOwnershipController,place,placeAnchoredSurface,placeAnchoredSurfaceSession,releaseTopLayer,trackRect,virtualAnchorFromRect};
|
|
@@ -63,12 +63,13 @@ style, await `whenIdle()` for the current resource and rendering work. Observe
|
|
|
63
63
|
rejection when replacing styles or disconnecting; a returned `true` from a synchronous command
|
|
64
64
|
means admission, not asynchronous completion.
|
|
65
65
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
66
|
+
URL `mapStyle` replacements and new objects on the modular peer use `setStyle(style, { diff: false })`.
|
|
67
|
+
Readiness waits for the replacement's committed `style.load` before capturing its catalog and
|
|
68
|
+
restoring owned layers, images and style overrides. Superseding an unfinished replacement also
|
|
69
|
+
rebuilds the style. This trades style diffs for reliable completion, including unchanged URL
|
|
70
|
+
responses and structurally equal new modular objects. Reassigning the exact same object is a no-op.
|
|
71
|
+
Loaded native MapLibre styles retain synchronous inline diffs. The live peer determines behavior;
|
|
72
|
+
`engine` changes apply after reconnect. Map and camera identity are preserved.
|
|
72
73
|
|
|
73
74
|
**On-demand runtimes:** optional `lr-map` features load their code on first use, so a bundler that
|
|
74
75
|
splits chunks keeps them out of the initial bundle. Drawing and vertex editing load when `drawMode`
|
|
@@ -103,11 +103,15 @@ wants that deferred too can instead import
|
|
|
103
103
|
same registration lazily and exports `PPTX_VIEWER_TAG` (`'lr-pptx-viewer'`) as a stable reference to
|
|
104
104
|
the tag it eventually registers.
|
|
105
105
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
`documentPreviewResourceTooLarge` message
|
|
109
|
-
|
|
110
|
-
|
|
106
|
+
Before the renderer opens an archive, remote resources are capped at 25 MB and measured ZIP
|
|
107
|
+
expansion at 256 MB. Exceeding either replaces the presentation with the localized
|
|
108
|
+
`documentPreviewResourceTooLarge` message. The optional peer must expose complete recommended
|
|
109
|
+
ZIP limits within Lyra's safety ceilings; missing, malformed, or more-permissive limits make it
|
|
110
|
+
unavailable and the viewer fails closed.
|
|
111
|
+
|
|
112
|
+
Initial rendering, slide navigation, and thumbnails block presentation-linked external images,
|
|
113
|
+
background and shape/text picture fills, audio, video, and posters. Embedded package media remains
|
|
114
|
+
available; linked media is omitted or replaced by a placeholder. Click-driven hyperlinks are unchanged.
|
|
111
115
|
|
|
112
116
|
The peer instance is immediately wrapped in a validated `PptxViewerAdapter`; the component observes
|
|
113
117
|
only readonly slide metadata, complete-model search/navigation/highlight/thumbnail capabilities and
|
package/llms/index.md
CHANGED
|
@@ -241,7 +241,7 @@ Optional peers: `llms/peers.md`. Safe `wa-*`/`sl-*` migration: `llms/migration.m
|
|
|
241
241
|
- `lr-calendar-viewer` · lr-calendar-viewer.js · `stable` since `4.0.0` — Parses `.ics` calendars with the optional `ical.js` peer and renders each VEVENT as plain text, preserving summaries, DATE/DATE-TIME...
|
|
242
242
|
- `lr-archive-viewer` · lr-archive-viewer.js · `stable` since `4.0.0` — Lists names and declared uncompressed sizes in a ZIP archive without rendering entry contents or loading an archive parser.
|
|
243
243
|
- `lr-ebook-viewer` · lr-ebook-viewer.js · `stable` since `4.0.0` — Renders an EPUB with the optional `epubjs` peer.
|
|
244
|
-
- `lr-pptx-viewer` · lr-pptx-viewer.js · `stable` since `4.0.0` — Best-effort client-side PPTX viewer
|
|
244
|
+
- `lr-pptx-viewer` · lr-pptx-viewer.js · `stable` since `4.0.0` — Best-effort client-side PPTX viewer with optional `@aiden0z/pptx-renderer`.
|
|
245
245
|
- `lr-svg-viewer` · lr-svg-viewer.js · `stable` since `4.0.0` — Fetches and safely renders an inline SVG document.
|
|
246
246
|
- `lr-html-viewer` · lr-html-viewer.js · `stable` since `4.0.0` — Fetches and safely renders an inline HTML document.
|
|
247
247
|
- `lr-dataset-viewer` · lr-dataset-viewer.js · `stable` since `4.0.0` — Fetches delimited text and renders a virtualized, accessible data table: a `role="table"` container with a sticky `role="row"` header...
|
package/llms/peers.md
CHANGED
|
@@ -40,7 +40,7 @@ for the page.
|
|
|
40
40
|
| `@aceshooting/lyra-3d` | `^1.0.0` | `lr-chart-3d`, `lr-embedding-explorer`, `lr-graph`, `lr-image-viewer`, `lr-knowledge-graph-explorer`, `lr-model-viewer`, `lr-video` |
|
|
41
41
|
| `@aceshooting/lyra-flags` | `^2.3.1` | _(loaded by a shared internal module)_ |
|
|
42
42
|
| `@aceshooting/lyra-map` | `^1.3.0` | `lr-geojson-viewer`, `lr-map` |
|
|
43
|
-
| `@aceshooting/lyra-translations` | `^30.
|
|
43
|
+
| `@aceshooting/lyra-translations` | `^30.2.0` | _(not referenced by any component)_ |
|
|
44
44
|
| `@aiden0z/pptx-renderer` | `^1.4.0` | `lr-pptx-viewer` |
|
|
45
45
|
| `@sgratzl/chartjs-chart-boxplot` | `^4.0.0` | `lr-box-plot` |
|
|
46
46
|
| `chart.js` | `^4.0.1` | `lr-bar-chart`, `lr-box-plot`, `lr-bubble-chart`, `lr-chart`, `lr-doughnut-chart`, `lr-histogram`, `lr-line-chart`, `lr-pie-chart`, `lr-polar-area-chart`, `lr-radar-chart`, `lr-scatter-chart` |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aceshooting/lyra-ui",
|
|
3
|
-
"version": "30.
|
|
3
|
+
"version": "30.2.0",
|
|
4
4
|
"description": "Free, independent Lit web components: an open-source alternative to Shoelace and Web Awesome with accessible forms, dashboards, charts, and agent UI.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"web-components",
|
|
@@ -2631,7 +2631,7 @@
|
|
|
2631
2631
|
"@aceshooting/lyra-3d": "^1.0.0",
|
|
2632
2632
|
"@aceshooting/lyra-flags": "^2.3.1",
|
|
2633
2633
|
"@aceshooting/lyra-map": "^1.3.0",
|
|
2634
|
-
"@aceshooting/lyra-translations": "^30.
|
|
2634
|
+
"@aceshooting/lyra-translations": "^30.2.0",
|
|
2635
2635
|
"@aiden0z/pptx-renderer": "^1.4.0",
|
|
2636
2636
|
"@sgratzl/chartjs-chart-boxplot": "^4.0.0",
|
|
2637
2637
|
"chart.js": "^4.0.1",
|
|
@@ -2760,9 +2760,9 @@
|
|
|
2760
2760
|
}
|
|
2761
2761
|
},
|
|
2762
2762
|
"devDependencies": {
|
|
2763
|
-
"@aceshooting/lyra-3d": "1.
|
|
2763
|
+
"@aceshooting/lyra-3d": "1.1.0",
|
|
2764
2764
|
"@aceshooting/lyra-flags": "^2.3.1",
|
|
2765
|
-
"@aceshooting/lyra-map": "1.3.
|
|
2765
|
+
"@aceshooting/lyra-map": "1.3.1",
|
|
2766
2766
|
"@aiden0z/pptx-renderer": "^1.4.0",
|
|
2767
2767
|
"@codecov/bundle-analyzer": "^2.0.1",
|
|
2768
2768
|
"@custom-elements-manifest/analyzer": "^0.11.0",
|
|
@@ -2806,7 +2806,7 @@
|
|
|
2806
2806
|
"katex": "^0.19.1",
|
|
2807
2807
|
"libphonenumber-js": "^1.13.15",
|
|
2808
2808
|
"mammoth": "^1.13.0",
|
|
2809
|
-
"maplibre-gl": "^6.
|
|
2809
|
+
"maplibre-gl": "^6.16.0",
|
|
2810
2810
|
"marked": "^18.1.1",
|
|
2811
2811
|
"oxc-parser": "^0.155.0",
|
|
2812
2812
|
"papaparse": "^5.7.0",
|
|
@@ -2881,7 +2881,7 @@
|
|
|
2881
2881
|
"check:testing-event-registry": "node scripts/build-testing-event-registry.mjs --check",
|
|
2882
2882
|
"registration-graph": "node scripts/generate-registration-graph.mjs",
|
|
2883
2883
|
"check:registration-graph": "node scripts/generate-registration-graph.mjs --check",
|
|
2884
|
-
"test:registration-graph": "node scripts/generate-registration-graph.test.mjs",
|
|
2884
|
+
"test:registration-graph": "node scripts/generate-registration-graph.test.mjs && node --test scripts/lib/runtime-module-edges.test.mjs",
|
|
2885
2885
|
"check:composed-child-contracts": "node scripts/check-composed-child-contracts.mjs",
|
|
2886
2886
|
"test:composed-child-contracts": "node scripts/check-composed-child-contracts.test.mjs",
|
|
2887
2887
|
"component-quality": "node scripts/generate-component-quality.mjs --write --measure-gzip",
|