@aceshooting/lyra-ui 24.2.0 → 25.1.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.
Files changed (137) hide show
  1. package/CHANGELOG.md +38 -26
  2. package/README.md +21 -18
  3. package/custom-elements.json +1 -1
  4. package/design-tokens.json +1 -1
  5. package/dist/components/agent-tools/activity-feed/activity-feed.styles.js +1 -1
  6. package/dist/components/agent-tools/task-list/task-list.styles.js +1 -1
  7. package/dist/components/agent-tools/thinking-panel/thinking-panel.styles.js +1 -1
  8. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  9. package/dist/components/conversation/code-block/code-block.styles.js +1 -1
  10. package/dist/components/conversation/code-block/shiki-dark-theme.js +1 -1
  11. package/dist/components/conversation/markdown/markdown.styles.js +1 -1
  12. package/dist/components/conversation/model-select/model-select.class.js +2 -1
  13. package/dist/components/conversation/model-select/model-select.styles.js +1 -1
  14. package/dist/components/conversation/selection-toolbar/selection-toolbar.styles.js +1 -1
  15. package/dist/components/conversation/voice-picker/voice-picker.class.js +2 -1
  16. package/dist/components/conversation/voice-picker/voice-picker.styles.js +1 -1
  17. package/dist/components/data/data-grid/data-grid.class.d.ts +7 -1
  18. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  19. package/dist/components/data/document-library/document-library.class.js +1 -1
  20. package/dist/components/data/table/table.styles.js +1 -1
  21. package/dist/components/forms/color-picker/color-picker.class.js +2 -1
  22. package/dist/components/forms/color-picker/color-picker.styles.js +1 -1
  23. package/dist/components/forms/combobox/combobox.class.d.ts +5 -2
  24. package/dist/components/forms/combobox/combobox.class.js +2 -1
  25. package/dist/components/forms/combobox/combobox.styles.js +1 -1
  26. package/dist/components/forms/date-picker/date-input.class.d.ts +3 -0
  27. package/dist/components/forms/date-picker/date-input.class.js +2 -1
  28. package/dist/components/forms/date-picker/date-input.styles.js +1 -1
  29. package/dist/components/forms/input/time-input.class.js +2 -1
  30. package/dist/components/forms/input/time-input.styles.js +1 -1
  31. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +2 -1
  32. package/dist/components/forms/locale-picker/locale-picker.class.js +2 -1
  33. package/dist/components/forms/locale-picker/locale-picker.styles.js +1 -1
  34. package/dist/components/forms/otp-input/otp-input.class.js +1 -1
  35. package/dist/components/forms/select/select.class.js +2 -1
  36. package/dist/components/forms/select/select.styles.js +1 -1
  37. package/dist/components/forms/swatch-picker/swatch-picker.class.d.ts +6 -1
  38. package/dist/components/forms/swatch-picker/swatch-picker.class.js +1 -1
  39. package/dist/components/layout/app-rail/app-rail.styles.js +1 -1
  40. package/dist/components/layout/menu/menu.styles.js +1 -1
  41. package/dist/components/layout/menubar/menubar.styles.js +1 -1
  42. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +2 -2
  43. package/dist/components/layout/navigation-menu-item/navigation-menu-item.styles.js +1 -1
  44. package/dist/components/layout/scroller/scroller.styles.js +1 -1
  45. package/dist/components/layout/virtual-list/virtual-list.class.d.ts +5 -0
  46. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  47. package/dist/components/media/av-player/av-player.styles.js +1 -1
  48. package/dist/components/media/image-viewer/image-viewer.styles.js +1 -1
  49. package/dist/components/media/map/map.class.d.ts +5 -2
  50. package/dist/components/media/map/map.class.js +4 -3
  51. package/dist/components/media/map/map.styles.js +1 -1
  52. package/dist/components/overlays/dialog/dialog.class.d.ts +1 -1
  53. package/dist/components/overlays/dialog/dialog.class.js +2 -1
  54. package/dist/components/overlays/dialog/dialog.styles.js +1 -1
  55. package/dist/components/overlays/overlay/overlay.styles.d.ts +1 -1
  56. package/dist/components/overlays/overlay/overlay.styles.js +1 -1
  57. package/dist/components/overlays/overlay/popover-glass.styles.d.ts +1 -0
  58. package/dist/components/overlays/overlay/popover-glass.styles.js +1 -0
  59. package/dist/components/overlays/overlay/popover.class.js +1 -1
  60. package/dist/components/retrieval/knowledge-base/knowledge-base.class.js +1 -1
  61. package/dist/components/retrieval/source-list/source-list.styles.js +1 -1
  62. package/dist/components/utility/export-button/export-button.class.d.ts +1 -1
  63. package/dist/components/utility/export-button/export-button.class.js +2 -1
  64. package/dist/components/utility/export-button/export-button.styles.js +1 -1
  65. package/dist/components/utility/mention-popover/mention-popover.class.d.ts +1 -1
  66. package/dist/components/utility/mention-popover/mention-popover.class.js +2 -1
  67. package/dist/components/utility/mention-popover/mention-popover.styles.js +1 -1
  68. package/dist/components/utility/tour/tour.class.d.ts +6 -4
  69. package/dist/components/utility/tour/tour.class.js +1 -1
  70. package/dist/components/viewers/document-compare/document-compare.styles.js +1 -1
  71. package/dist/components/viewers/document-preview/document-preview.class.js +1 -1
  72. package/dist/framework-types.d.ts +1 -1
  73. package/dist/internal/glass-independent-root.styles.d.ts +2 -0
  74. package/dist/internal/glass-independent-root.styles.js +1 -0
  75. package/dist/internal/glass-scroll-layer.d.ts +1 -1
  76. package/dist/internal/glass-scroll-layer.js +1 -1
  77. package/dist/internal/glass-scroll-layer.styles.d.ts +2 -0
  78. package/dist/internal/glass-scroll-layer.styles.js +1 -0
  79. package/dist/internal/glass-surface.styles.d.ts +0 -2
  80. package/dist/internal/glass-surface.styles.js +1 -1
  81. package/dist/internal/native-modal-carrier.js +2 -2
  82. package/dist/internal/package-metadata.d.ts +1 -1
  83. package/dist/internal/package-metadata.js +1 -1
  84. package/dist/internal/sizes.styles.js +1 -1
  85. package/dist/internal/specialist-tokens.styles.js +1 -1
  86. package/dist/internal/theme-token-types.d.ts +16 -0
  87. package/dist/internal/tokens/palette.styles.js +1 -1
  88. package/dist/internal/tokens.styles.js +1 -1
  89. package/dist/looks/material.css +1 -1
  90. package/dist/styles/design-tokens.css +1 -1
  91. package/dist/styles/tokens-root.css +1 -1
  92. package/dist/surfaces/glass.css +1 -1
  93. package/dist/theme/gemstones.d.ts +7 -0
  94. package/dist/theme/gemstones.js +1 -1
  95. package/dist/theme/looks/material.d.ts +1 -1
  96. package/dist/theme/looks/material.js +1 -1
  97. package/dist/theme/startup-resolution.d.ts +1 -0
  98. package/dist/theme/startup-resolution.js +1 -0
  99. package/dist/theme/style-ownership.js +1 -1
  100. package/dist/theme/theme-bootstrap.js +1 -1
  101. package/dist/theme/theme.d.ts +6 -21
  102. package/dist/theme/theme.js +1 -1
  103. package/dist/theme.css +1 -1
  104. package/llms/components/lr-combobox.md +3 -2
  105. package/llms/components/lr-date-input.md +1 -1
  106. package/llms/components/lr-date-picker.md +6 -0
  107. package/llms/components/lr-dialog.md +3 -0
  108. package/llms/components/lr-export-button.md +2 -0
  109. package/llms/components/lr-icon.md +1 -1
  110. package/llms/components/lr-locale-picker.md +7 -1
  111. package/llms/components/lr-map.md +7 -0
  112. package/llms/components/lr-mention-popover.md +3 -0
  113. package/llms/components/lr-model-select.md +3 -0
  114. package/llms/components/lr-navigation-menu.md +3 -0
  115. package/llms/components/lr-otp-input.md +3 -1
  116. package/llms/components/lr-select.md +3 -0
  117. package/llms/components/lr-swatch-picker.md +17 -5
  118. package/llms/components/lr-tour.md +4 -2
  119. package/llms/components/lr-voice-picker.md +3 -0
  120. package/llms/shared/native-styles-and-utilities.md +40 -0
  121. package/llms/shared/styles-and-tokens.md +193 -93
  122. package/llms/shared.md +232 -93
  123. package/llms/tokens.md +82 -82
  124. package/package.json +1 -1
  125. package/vscode-css-data.json +1 -1
  126. package/web-types.json +1 -1
  127. package/dist/components/agent-tools/run-events.js +0 -1
  128. package/dist/components/agent-tools/tool-param-form/tool-param-types.js +0 -1
  129. package/dist/components/forms/emoji-picker/emoji-types.js +0 -1
  130. package/dist/components/layout/dashboard-grid/layout-types.js +0 -1
  131. package/dist/components/layout/details/accordion-types.js +0 -1
  132. package/dist/components/viewers/viewer-diagnostics.js +0 -1
  133. package/dist/internal/localization-types.js +0 -1
  134. package/dist/internal/node-type-style.js +0 -1
  135. package/dist/internal/picker-value.js +0 -1
  136. package/dist/internal/shared-unions.js +0 -1
  137. package/dist/internal/stream-phase.js +0 -1
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{maxCssTime}from"../../../internal/css-motion-time.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{styles}from"./mention-popover.styles.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_mentionResultCount,LYRA_DEFAULT_mentionResultPosition,LYRA_DEFAULT_mentionSuggestions,LYRA_DEFAULT_noMatches}from"../../../internal/default-strings.generated.js";function isTextControl(el){const view=el.ownerDocument.defaultView;return view?el instanceof view.HTMLTextAreaElement?!0:el instanceof view.HTMLInputElement&&(el.type==="text"||el.type==="search"):!1}function isTextareaAnchor(el){const view=el.ownerDocument.defaultView;return!!(view&&el instanceof view.HTMLTextAreaElement)}const MIRROR_CSS_PROPS=["box-sizing","width","padding-top","padding-right","padding-bottom","padding-left","border-top-width","border-right-width","border-bottom-width","border-left-width","border-style","font-family","font-size","font-style","font-variant","font-weight","font-stretch","letter-spacing","word-spacing","line-height","text-align","text-indent","text-transform","tab-size","direction"];function caretClientRect(el){const owner=el.ownerDocument,view=owner.defaultView;if(!view)return null;const elRect=el.getBoundingClientRect();if(elRect.width===0||elRect.height===0)return null;const computed=view.getComputedStyle(el),mirror=owner.createElement("div");mirror.style.position="absolute",mirror.style.visibility="hidden",mirror.style.top="0",mirror.style.left="-9999px",mirror.style.whiteSpace=el instanceof view.HTMLTextAreaElement?"pre-wrap":"pre",mirror.style.overflowWrap="break-word";for(const prop of MIRROR_CSS_PROPS)mirror.style.setProperty(prop,computed.getPropertyValue(prop));const index=el.selectionStart??el.value.length;mirror.append(owner.createTextNode(el.value.slice(0,index)));const marker=owner.createElement("span");marker.textContent=el.value.slice(index)||"​",mirror.appendChild(marker),owner.body.appendChild(mirror);const mirrorRect=mirror.getBoundingClientRect(),markerRect=marker.getBoundingClientRect();mirror.remove();const lineHeight=parseFloat(computed.lineHeight)||markerRect.height||16;return new view.DOMRect(elRect.left+(markerRect.left-mirrorRect.left)-el.scrollLeft,elRect.top+(markerRect.top-mirrorRect.top)-el.scrollTop,1,lineHeight)}class LyraMentionPopover extends LyraElement{constructor(){super(...arguments),this._textareaFocusSessionGeneration=0,this._items=Object.freeze([]),this.query="",this.open=!1,this.filter=null,this.activeIndex=0,this.listboxHidden=!0,this.listboxHideToken=0,this._listId=nextId("mention-popover-listbox"),this.virtualAnchor=null,this._isFirstUpdate=!0,this._silentClose=!1,this._ownsFocus=!1,this._focusTransferGeneration=0,this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index)||index<0)return;const item=this.filteredItems[index];item&&this.commit(item)},this.onListboxKeyDown=e=>{e.defaultPrevented||!this._ownsFocus||this.handleKeyDown(e)&&this.open&&this.focusActiveOption()}}static{this.defaultStrings={...super.defaultStrings,mentionResultCount:LYRA_DEFAULT_mentionResultCount,mentionResultPosition:LYRA_DEFAULT_mentionResultPosition,mentionSuggestions:LYRA_DEFAULT_mentionSuggestions,noMatches:LYRA_DEFAULT_noMatches}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={items:{attribute:!1,noAccessor:!0}}}requestUpdate(name,oldValue,options){(name==="open"||name==="anchor"||name==="query"||name==="items"||name==="filter")&&this.hasTextareaFocusSession()&&(this._textareaFocusSessionGeneration+=1),super.requestUpdate(name,oldValue,options)}hasTextareaFocusSession(){const relationshipControl=this.anchorRelationship?.control;return this.anchor!==void 0&&isTextareaAnchor(this.anchor)||relationshipControl!==void 0&&isTextareaAnchor(relationshipControl)}get items(){return this._items}set items(next){const previous=this._items,source=Array.isArray(next)?next:[];this._items=Object.freeze(source.map(item=>Object.freeze({...item}))),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.announceResultState()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,changed.has("open")&&this.open&&(this.listboxHidden=!1),this._ownsFocus&&!this.fallbackFocusIsStillOwned()&&(this._ownsFocus=!1,this._focusOwnerPredicate=void 0),(changed.has("query")||changed.has("items")||changed.has("filter"))&&(this.activeIndex=0);const candidatesChanged=changed.has("query")||changed.has("items")||changed.has("filter");this._ownsFocus&&changed.has("open")&&!this.open?(this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0):this._ownsFocus&&this.open&&candidatesChanged&&this.filteredItems.length===0&&(this.anchor?.isConnected?this.restoreAnchorFocus():this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0}),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),this._ownsFocus&&changed.has("anchor")&&this.anchorRelationship?.control!==this.anchor&&this.detachAnchorRelationship()}updated(changed){if(super.updated(changed),changed.has("open"))if(this.open)this.reposition();else{this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.settleListboxHidden();const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),!this._isFirstUpdate&&!this._silentClose&&queueMicrotask(()=>this.emit("lr-mention-close")),this._silentClose=!1}else this.open&&(changed.has("anchor")||changed.has("query"))&&this.reposition();if(changed.has("activeIndex")||changed.has("query")||changed.has("items")||changed.has("filter")){const active=this.renderRoot.querySelector('[part="option"][data-active]');active?.scrollIntoView({block:"nearest"}),this._ownsFocus&&(!active&&this.anchor?.isConnected?this.restoreFocus():this.restoreFocus(!0))}this.syncAnchorRelationship(),this.open?this.announceResultState():this.resetResultAnnouncements()}disconnectedCallback(){this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.announcementSink?.release(),this.announcementSink=void 0,this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.listboxHideToken++,this.listboxHidden=!0,this.open=!1}adoptedCallback(){super.adoptedCallback(),this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.syncAnnouncementSink(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),this.open=!1}syncAnnouncementSink(){this.announcementSink?.element?.ownerDocument!==this.ownerDocument&&(this.announcementSink?.release(),this.announcementSink=this.isConnected?acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}):void 0)}resetResultAnnouncements(){this.announcedResultCount=void 0,this.announcedResultPosition=void 0}announceResultState(){if(!this.open||!this.announcementSink)return;const rows=this.filteredItems,resultState=rows.length===0?this.localize("noMatches"):this.localize("mentionResultCount",void 0,{count:rows.length}),index=this.clampedIndex(rows),position=index<0?void 0:this.localize("mentionResultPosition",void 0,{current:index+1,total:rows.length});if(this._isFirstUpdate){this.announcedResultCount=resultState,this.announcedResultPosition=position;return}if(resultState!==this.announcedResultCount&&(this.announcementSink.announce(resultState),this.announcedResultCount=resultState),position===void 0){this.announcedResultPosition=void 0;return}position!==this.announcedResultPosition&&(this.announcementSink.announce(position),this.announcedResultPosition=position)}snapshotAttribute(control,name){return{present:control.hasAttribute(name),value:control.getAttribute(name)}}restoreAttribute(control,name,snapshot){snapshot.present?control.setAttribute(name,snapshot.value??""):control.removeAttribute(name)}captureAnchorCaret(relationship=this.anchorRelationship){if(!relationship||!isTextareaAnchor(relationship.control))return;const{control}=relationship;relationship.selectionStart=control.selectionStart,relationship.selectionEnd=control.selectionEnd,relationship.selectionDirection=control.selectionDirection}restoreRelationshipFocus(relationship){const{control}=relationship;if(control.isConnected)try{control.focus({preventScroll:!0}),isTextareaAnchor(control)&&relationship.selectionStart!==null&&relationship.selectionStart!==void 0&&relationship.selectionEnd!==null&&relationship.selectionEnd!==void 0&&control.setSelectionRange(relationship.selectionStart,relationship.selectionEnd,relationship.selectionDirection??void 0)}catch{}}restoreAnchorFocus(){const relationship=this.anchorRelationship;if(relationship){this.restoreRelationshipFocus(relationship);return}const anchor=this.anchor;if(anchor?.isConnected)try{anchor.focus({preventScroll:!0})}catch{}}attachAnchorRelationship(control){const reflected=control,textarea=isTextareaAnchor(control),attributes=new Map((textarea?["role","aria-expanded","aria-haspopup","aria-autocomplete","aria-controls","aria-activedescendant"]:["role","aria-expanded","aria-haspopup","aria-controls","aria-activedescendant"]).map(name=>[name,this.snapshotAttribute(control,name)])),activeElement="ariaActiveDescendantElement"in control?reflected.ariaActiveDescendantElement??null:void 0,controlsElements="ariaControlsElements"in control?reflected.ariaControlsElements??null:void 0,capturedTextareaActiveElement=textarea&&attributes.get("aria-activedescendant")?.present&&attributes.get("aria-activedescendant")?.value===""?activeElement??void 0:void 0,capturedTextareaControlsElements=textarea&&attributes.get("aria-controls")?.present&&attributes.get("aria-controls")?.value===""&&controlsElements?.length?controlsElements:void 0,relationship={control,attributes,activeElement:textarea?capturedTextareaActiveElement:activeElement,controlsElements:textarea?capturedTextareaControlsElements:controlsElements,selectionStart:textarea?control.selectionStart:void 0,selectionEnd:textarea?control.selectionEnd:void 0,selectionDirection:textarea?control.selectionDirection:void 0};return this.anchorRelationship=relationship,relationship}detachAnchorRelationship(){const relationship=this.anchorRelationship;if(!relationship)return;if(this.anchorRelationship=void 0,this._ownsFocus&&(this.restoreRelationshipFocus(relationship),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),!isTextareaAnchor(relationship.control)){const reflected2=relationship.control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=relationship.controlsElements}catch{}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);return}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);const reflected=relationship.control;if(relationship.activeElement!==void 0)try{reflected.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected.ariaControlsElements=relationship.controlsElements}catch{}}syncAnchorRelationship(){const next=this.open&&this.anchor&&isTextControl(this.anchor)?this.anchor:void 0;if(this.anchorRelationship?.control!==next&&this.detachAnchorRelationship(),!next)return;const relationship=this.anchorRelationship??this.attachAnchorRelationship(next),control=relationship.control;if(isTextareaAnchor(control)){control.removeAttribute("role"),control.removeAttribute("aria-expanded"),control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant");const reflected2=control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=null}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=null}catch{}control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant"),control.setAttribute("aria-haspopup","listbox"),control.setAttribute("aria-autocomplete","list");return}relationship.attributes.get("role")?.present||control.setAttribute("role","combobox"),control.setAttribute("aria-expanded","true"),control.setAttribute("aria-haspopup","listbox");const listbox=this.renderRoot.querySelector('[part="listbox"]'),reflected=control;if(listbox&&"ariaControlsElements"in control)try{control.removeAttribute("aria-controls"),reflected.ariaControlsElements=[listbox],reflected.ariaControlsElements?.[0]!==listbox&&(reflected.ariaControlsElements=[this],reflected.ariaControlsElements?.[0]!==this&&control.removeAttribute("aria-controls"))}catch{control.removeAttribute("aria-controls")}else control.removeAttribute("aria-controls");control.removeAttribute("aria-activedescendant"),this.syncActiveDescendant(control)}get filteredItems(){const locale=this.effectiveLocale,q=(this.query??"").trim().toLocaleLowerCase(locale);return this.items.filter(item=>typeof item.label!="string"||item.label.trim().length===0?!1:q?this.filter?this.filter(item,q):item.label.toLocaleLowerCase(locale).includes(q)||(typeof item.description=="string"?item.description:"").toLocaleLowerCase(locale).includes(q):!0)}get activeDescendantId(){if(!this.open)return null;const idx=this.clampedIndex(this.filteredItems);return idx>=0?this.rowId(idx):null}get activeDescendantElement(){const id=this.activeDescendantId,escape=this.ownerDocument.defaultView?.CSS.escape;return id&&escape?this.renderRoot.querySelector(`#${escape(id)}`):null}syncActiveDescendant(_control){if(isTextareaAnchor(_control)||(_control.removeAttribute("aria-activedescendant"),!("ariaActiveDescendantElement"in _control)))return!1;const active=this.activeDescendantElement;try{const reflected=_control;reflected.ariaActiveDescendantElement=active;const accepted=reflected.ariaActiveDescendantElement===active;return accepted||(reflected.ariaActiveDescendantElement=null,_control.removeAttribute("aria-activedescendant")),accepted}catch{return _control.removeAttribute("aria-activedescendant"),!1}}async focusActiveOption(options={}){const ownsFocus=options.ownsFocus??(this._ownsFocus?this._focusOwnerPredicate:void 0);if(!this.open||!this.isConnected||!this.activeDescendantElement||!this.callFocusOwner(ownsFocus))return!1;const generation=++this._focusTransferGeneration,textareaSession=this.anchor!==void 0&&isTextareaAnchor(this.anchor),textareaSessionGeneration=this._textareaFocusSessionGeneration,snapshot={ownerDocument:this.ownerDocument,anchor:this.anchor,items:this.items,query:this.query,filter:this.filter,activeIndex:this.activeIndex};if(await this.updateComplete,await this.cleanup?.ready===!1||generation!==this._focusTransferGeneration||textareaSession&&textareaSessionGeneration!==this._textareaFocusSessionGeneration||!this.isConnected||!this.open||this.ownerDocument!==snapshot.ownerDocument||this.anchor!==snapshot.anchor||this.items!==snapshot.items||this.query!==snapshot.query||this.filter!==snapshot.filter||this.activeIndex!==snapshot.activeIndex||!this.callFocusOwner(ownsFocus))return!1;const active=this.activeDescendantElement;return!active?.isConnected||!this.callFocusOwner(ownsFocus)||(this.captureAnchorCaret(),active.focus({preventScroll:!0}),activeElementIn(this.shadowRoot)!==active)?!1:(this._focusOwnerPredicate=ownsFocus,this._ownsFocus=!0,!0)}async restoreFocus(waitForPlacement=!1){if(waitForPlacement){if(await this.cleanup?.ready===!1||!this._ownsFocus||!this.open)return;if(this.hasTextareaFocusSession()&&!this.fallbackFocusIsStillOwned()){this._ownsFocus=!1,this._focusOwnerPredicate=void 0;return}}const active=this.renderRoot.querySelector('[part="option"][data-active]');active?active.focus({preventScroll:!0}):this.anchor?.isConnected?(this.renderRoot.querySelector('[part="listbox"]')?.setAttribute("tabindex","-1"),this.restoreAnchorFocus(),this.scheduleAfterUpdate(()=>{this._ownsFocus=!1,this._focusOwnerPredicate=void 0})):this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0})}callFocusOwner(predicate){try{return predicate?.()??!0}catch{return!1}}fallbackFocusIsStillOwned(){return this.callFocusOwner(this._focusOwnerPredicate)&&activeElementIn(this.shadowRoot)!==null}get listboxId(){return this._listId}handleKeyDown(e){if(!this.open||e.isComposing||e.keyCode===229)return!1;const rows=this.filteredItems;switch(e.key){case"ArrowDown":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),1),!0):!1;case"ArrowUp":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),-1),!0):!1;case"Enter":case"Tab":{const idx=this.clampedIndex(rows);return idx<0?!1:(e.preventDefault(),this.commit(rows[idx]),!0)}case"Escape":return e.preventDefault(),this.open=!1,!0;default:return!1}}clampedIndex(rows){const count=rows.length;if(!count)return-1;const clamped=Math.min(Math.max(this.activeIndex,0),count-1);if(!rows[clamped]?.disabled)return clamped;for(let forward=clamped+1;forward<count;forward+=1)if(!rows[forward]?.disabled)return forward;for(let backward=clamped-1;backward>=0;backward-=1)if(!rows[backward]?.disabled)return backward;return-1}stepEnabledIndex(rows,from,direction){const count=rows.length;if(!count)return 0;let index=Math.min(Math.max(from+direction,0),count-1);for(let steps=0;steps<count;steps+=1){if(!rows[index]?.disabled)return index;if(index+=direction,index<0||index>=count)break}return from>=0&&from<count&&!rows[from]?.disabled?from:this.activeIndex}rowId(index){return`${this._listId}-opt-${index}`}commit(item){if(item.disabled)return;const index=this.items.indexOf(item);if(index<0)return;const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),this.emit("lr-mention-select",Object.freeze({suggestionId:item.suggestionId,index,label:item.label})),this._silentClose=!0,this.open=!1}reposition(){this.cleanup?.(),this.cleanup=void 0;const anchorEl=this.resolveAnchorElement(),popup=this.renderRoot.querySelector('[part="listbox"]');if(anchorEl&&popup){const placement=place(anchorEl,popup,{placement:"bottom-start",strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});this.cleanup=placement,placement.ready.then(positioned=>{positioned||this.cleanup!==placement||!this.open||(this._silentClose=!0,this.open=!1)})}}async settleListboxHidden(){const token=++this.listboxHideToken;if(await this.updateComplete,token!==this.listboxHideToken||this.open)return;const listbox=this.renderRoot.querySelector('[part="listbox"]'),view=this.ownerDocument.defaultView;if(listbox&&view&&!prefersReducedMotion(this)){const computed=view.getComputedStyle(listbox),durationMs=maxCssTime(computed.transitionDuration)+maxCssTime(computed.transitionDelay);if(durationMs>0&&(await new Promise(resolve=>{let settled=!1,timeout;const finish=()=>{settled||(settled=!0,timeout!==void 0&&view.clearTimeout(timeout),listbox.removeEventListener("transitionend",onEnd),listbox.removeEventListener("transitioncancel",onEnd),resolve())},onEnd=event=>{event.target===listbox&&finish()};listbox.addEventListener("transitionend",onEnd),listbox.addEventListener("transitioncancel",onEnd),timeout=view.setTimeout(finish,durationMs+50)}),token!==this.listboxHideToken||this.open))return}this.listboxHidden=!0}resolveAnchorElement(){const anchor=this.anchor;if(!anchor)return null;if(isTextControl(anchor)){const rect=caretClientRect(anchor);if(rect){const owner=anchor.ownerDocument;this.virtualAnchor&&this.virtualAnchor.ownerDocument!==owner&&(this.virtualAnchor.remove(),this.virtualAnchor=null);const virtual=this.virtualAnchor??(this.virtualAnchor=owner.createElement("div"));return virtual.style.position="fixed",virtual.style.left=`${rect.left}px`,virtual.style.top=`${rect.top}px`,virtual.style.width="0",virtual.style.height=`${rect.height}px`,virtual.style.pointerEvents="none",virtual.isConnected||owner.body.appendChild(virtual),virtual}}return anchor}get effectiveEmptyText(){return this.emptyText===void 0?this.localize("noMatches"):this.emptyText}get effectiveLabel(){return hostAriaLabel(this)??(this.label===void 0?this.localize("mentionSuggestions"):this.label)}renderRow(item,index,activeId){const id=this.rowId(index),active=id===activeId;return html`
1
+ import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{maxCssTime}from"../../../internal/css-motion-time.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{styles}from"./mention-popover.styles.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_mentionResultCount,LYRA_DEFAULT_mentionResultPosition,LYRA_DEFAULT_mentionSuggestions,LYRA_DEFAULT_noMatches}from"../../../internal/default-strings.generated.js";function isTextControl(el){const view=el.ownerDocument.defaultView;return view?el instanceof view.HTMLTextAreaElement?!0:el instanceof view.HTMLInputElement&&(el.type==="text"||el.type==="search"):!1}function isTextareaAnchor(el){const view=el.ownerDocument.defaultView;return!!(view&&el instanceof view.HTMLTextAreaElement)}const MIRROR_CSS_PROPS=["box-sizing","width","padding-top","padding-right","padding-bottom","padding-left","border-top-width","border-right-width","border-bottom-width","border-left-width","border-style","font-family","font-size","font-style","font-variant","font-weight","font-stretch","letter-spacing","word-spacing","line-height","text-align","text-indent","text-transform","tab-size","direction"];function caretClientRect(el){const owner=el.ownerDocument,view=owner.defaultView;if(!view)return null;const elRect=el.getBoundingClientRect();if(elRect.width===0||elRect.height===0)return null;const computed=view.getComputedStyle(el),mirror=owner.createElement("div");mirror.style.position="absolute",mirror.style.visibility="hidden",mirror.style.top="0",mirror.style.left="-9999px",mirror.style.whiteSpace=el instanceof view.HTMLTextAreaElement?"pre-wrap":"pre",mirror.style.overflowWrap="break-word";for(const prop of MIRROR_CSS_PROPS)mirror.style.setProperty(prop,computed.getPropertyValue(prop));const index=el.selectionStart??el.value.length;mirror.append(owner.createTextNode(el.value.slice(0,index)));const marker=owner.createElement("span");marker.textContent=el.value.slice(index)||"​",mirror.appendChild(marker),owner.body.appendChild(mirror);const mirrorRect=mirror.getBoundingClientRect(),markerRect=marker.getBoundingClientRect();mirror.remove();const lineHeight=parseFloat(computed.lineHeight)||markerRect.height||16;return new view.DOMRect(elRect.left+(markerRect.left-mirrorRect.left)-el.scrollLeft,elRect.top+(markerRect.top-mirrorRect.top)-el.scrollTop,1,lineHeight)}class LyraMentionPopover extends LyraElement{static{this.defaultStrings={...super.defaultStrings,mentionResultCount:LYRA_DEFAULT_mentionResultCount,mentionResultPosition:LYRA_DEFAULT_mentionResultPosition,mentionSuggestions:LYRA_DEFAULT_mentionSuggestions,noMatches:LYRA_DEFAULT_noMatches}}constructor(){super(),this._textareaFocusSessionGeneration=0,this._items=Object.freeze([]),this.query="",this.open=!1,this.filter=null,this.activeIndex=0,this.listboxHidden=!0,this.listboxHideToken=0,this._listId=nextId("mention-popover-listbox"),this.virtualAnchor=null,this._isFirstUpdate=!0,this._silentClose=!1,this._ownsFocus=!1,this._focusTransferGeneration=0,this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index)||index<0)return;const item=this.filteredItems[index];item&&this.commit(item)},this.onListboxKeyDown=e=>{e.defaultPrevented||!this._ownsFocus||this.handleKeyDown(e)&&this.open&&this.focusActiveOption()},new GlassScrollLayer(this,'[part="listbox"]',()=>this.open)}static{this.styles=[LyraElement.styles,styles]}static{this.properties={items:{attribute:!1,noAccessor:!0}}}requestUpdate(name,oldValue,options){(name==="open"||name==="anchor"||name==="query"||name==="items"||name==="filter")&&this.hasTextareaFocusSession()&&(this._textareaFocusSessionGeneration+=1),super.requestUpdate(name,oldValue,options)}hasTextareaFocusSession(){const relationshipControl=this.anchorRelationship?.control;return this.anchor!==void 0&&isTextareaAnchor(this.anchor)||relationshipControl!==void 0&&isTextareaAnchor(relationshipControl)}get items(){return this._items}set items(next){const previous=this._items,source=Array.isArray(next)?next:[];this._items=Object.freeze(source.map(item=>Object.freeze({...item}))),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.announceResultState()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,changed.has("open")&&this.open&&(this.listboxHidden=!1),this._ownsFocus&&!this.fallbackFocusIsStillOwned()&&(this._ownsFocus=!1,this._focusOwnerPredicate=void 0),(changed.has("query")||changed.has("items")||changed.has("filter"))&&(this.activeIndex=0);const candidatesChanged=changed.has("query")||changed.has("items")||changed.has("filter");this._ownsFocus&&changed.has("open")&&!this.open?(this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0):this._ownsFocus&&this.open&&candidatesChanged&&this.filteredItems.length===0&&(this.anchor?.isConnected?this.restoreAnchorFocus():this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0}),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),this._ownsFocus&&changed.has("anchor")&&this.anchorRelationship?.control!==this.anchor&&this.detachAnchorRelationship()}updated(changed){if(super.updated(changed),changed.has("open"))if(this.open)this.reposition();else{this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.settleListboxHidden();const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),!this._isFirstUpdate&&!this._silentClose&&queueMicrotask(()=>this.emit("lr-mention-close")),this._silentClose=!1}else this.open&&(changed.has("anchor")||changed.has("query"))&&this.reposition();if(changed.has("activeIndex")||changed.has("query")||changed.has("items")||changed.has("filter")){const active=this.renderRoot.querySelector('[part="option"][data-active]');active?.scrollIntoView({block:"nearest"}),this._ownsFocus&&(!active&&this.anchor?.isConnected?this.restoreFocus():this.restoreFocus(!0))}this.syncAnchorRelationship(),this.open?this.announceResultState():this.resetResultAnnouncements()}disconnectedCallback(){this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.announcementSink?.release(),this.announcementSink=void 0,this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.listboxHideToken++,this.listboxHidden=!0,this.open=!1}adoptedCallback(){super.adoptedCallback(),this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.syncAnnouncementSink(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),this.open=!1}syncAnnouncementSink(){this.announcementSink?.element?.ownerDocument!==this.ownerDocument&&(this.announcementSink?.release(),this.announcementSink=this.isConnected?acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}):void 0)}resetResultAnnouncements(){this.announcedResultCount=void 0,this.announcedResultPosition=void 0}announceResultState(){if(!this.open||!this.announcementSink)return;const rows=this.filteredItems,resultState=rows.length===0?this.localize("noMatches"):this.localize("mentionResultCount",void 0,{count:rows.length}),index=this.clampedIndex(rows),position=index<0?void 0:this.localize("mentionResultPosition",void 0,{current:index+1,total:rows.length});if(this._isFirstUpdate){this.announcedResultCount=resultState,this.announcedResultPosition=position;return}if(resultState!==this.announcedResultCount&&(this.announcementSink.announce(resultState),this.announcedResultCount=resultState),position===void 0){this.announcedResultPosition=void 0;return}position!==this.announcedResultPosition&&(this.announcementSink.announce(position),this.announcedResultPosition=position)}snapshotAttribute(control,name){return{present:control.hasAttribute(name),value:control.getAttribute(name)}}restoreAttribute(control,name,snapshot){snapshot.present?control.setAttribute(name,snapshot.value??""):control.removeAttribute(name)}captureAnchorCaret(relationship=this.anchorRelationship){if(!relationship||!isTextareaAnchor(relationship.control))return;const{control}=relationship;relationship.selectionStart=control.selectionStart,relationship.selectionEnd=control.selectionEnd,relationship.selectionDirection=control.selectionDirection}restoreRelationshipFocus(relationship){const{control}=relationship;if(control.isConnected)try{control.focus({preventScroll:!0}),isTextareaAnchor(control)&&relationship.selectionStart!==null&&relationship.selectionStart!==void 0&&relationship.selectionEnd!==null&&relationship.selectionEnd!==void 0&&control.setSelectionRange(relationship.selectionStart,relationship.selectionEnd,relationship.selectionDirection??void 0)}catch{}}restoreAnchorFocus(){const relationship=this.anchorRelationship;if(relationship){this.restoreRelationshipFocus(relationship);return}const anchor=this.anchor;if(anchor?.isConnected)try{anchor.focus({preventScroll:!0})}catch{}}attachAnchorRelationship(control){const reflected=control,textarea=isTextareaAnchor(control),attributes=new Map((textarea?["role","aria-expanded","aria-haspopup","aria-autocomplete","aria-controls","aria-activedescendant"]:["role","aria-expanded","aria-haspopup","aria-controls","aria-activedescendant"]).map(name=>[name,this.snapshotAttribute(control,name)])),activeElement="ariaActiveDescendantElement"in control?reflected.ariaActiveDescendantElement??null:void 0,controlsElements="ariaControlsElements"in control?reflected.ariaControlsElements??null:void 0,capturedTextareaActiveElement=textarea&&attributes.get("aria-activedescendant")?.present&&attributes.get("aria-activedescendant")?.value===""?activeElement??void 0:void 0,capturedTextareaControlsElements=textarea&&attributes.get("aria-controls")?.present&&attributes.get("aria-controls")?.value===""&&controlsElements?.length?controlsElements:void 0,relationship={control,attributes,activeElement:textarea?capturedTextareaActiveElement:activeElement,controlsElements:textarea?capturedTextareaControlsElements:controlsElements,selectionStart:textarea?control.selectionStart:void 0,selectionEnd:textarea?control.selectionEnd:void 0,selectionDirection:textarea?control.selectionDirection:void 0};return this.anchorRelationship=relationship,relationship}detachAnchorRelationship(){const relationship=this.anchorRelationship;if(!relationship)return;if(this.anchorRelationship=void 0,this._ownsFocus&&(this.restoreRelationshipFocus(relationship),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),!isTextareaAnchor(relationship.control)){const reflected2=relationship.control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=relationship.controlsElements}catch{}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);return}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);const reflected=relationship.control;if(relationship.activeElement!==void 0)try{reflected.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected.ariaControlsElements=relationship.controlsElements}catch{}}syncAnchorRelationship(){const next=this.open&&this.anchor&&isTextControl(this.anchor)?this.anchor:void 0;if(this.anchorRelationship?.control!==next&&this.detachAnchorRelationship(),!next)return;const relationship=this.anchorRelationship??this.attachAnchorRelationship(next),control=relationship.control;if(isTextareaAnchor(control)){control.removeAttribute("role"),control.removeAttribute("aria-expanded"),control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant");const reflected2=control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=null}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=null}catch{}control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant"),control.setAttribute("aria-haspopup","listbox"),control.setAttribute("aria-autocomplete","list");return}relationship.attributes.get("role")?.present||control.setAttribute("role","combobox"),control.setAttribute("aria-expanded","true"),control.setAttribute("aria-haspopup","listbox");const listbox=this.renderRoot.querySelector('[part="listbox"]'),reflected=control;if(listbox&&"ariaControlsElements"in control)try{control.removeAttribute("aria-controls"),reflected.ariaControlsElements=[listbox],reflected.ariaControlsElements?.[0]!==listbox&&(reflected.ariaControlsElements=[this],reflected.ariaControlsElements?.[0]!==this&&control.removeAttribute("aria-controls"))}catch{control.removeAttribute("aria-controls")}else control.removeAttribute("aria-controls");control.removeAttribute("aria-activedescendant"),this.syncActiveDescendant(control)}get filteredItems(){const locale=this.effectiveLocale,q=(this.query??"").trim().toLocaleLowerCase(locale);return this.items.filter(item=>typeof item.label!="string"||item.label.trim().length===0?!1:q?this.filter?this.filter(item,q):item.label.toLocaleLowerCase(locale).includes(q)||(typeof item.description=="string"?item.description:"").toLocaleLowerCase(locale).includes(q):!0)}get activeDescendantId(){if(!this.open)return null;const idx=this.clampedIndex(this.filteredItems);return idx>=0?this.rowId(idx):null}get activeDescendantElement(){const id=this.activeDescendantId,escape=this.ownerDocument.defaultView?.CSS.escape;return id&&escape?this.renderRoot.querySelector(`#${escape(id)}`):null}syncActiveDescendant(_control){if(isTextareaAnchor(_control)||(_control.removeAttribute("aria-activedescendant"),!("ariaActiveDescendantElement"in _control)))return!1;const active=this.activeDescendantElement;try{const reflected=_control;reflected.ariaActiveDescendantElement=active;const accepted=reflected.ariaActiveDescendantElement===active;return accepted||(reflected.ariaActiveDescendantElement=null,_control.removeAttribute("aria-activedescendant")),accepted}catch{return _control.removeAttribute("aria-activedescendant"),!1}}async focusActiveOption(options={}){const ownsFocus=options.ownsFocus??(this._ownsFocus?this._focusOwnerPredicate:void 0);if(!this.open||!this.isConnected||!this.activeDescendantElement||!this.callFocusOwner(ownsFocus))return!1;const generation=++this._focusTransferGeneration,textareaSession=this.anchor!==void 0&&isTextareaAnchor(this.anchor),textareaSessionGeneration=this._textareaFocusSessionGeneration,snapshot={ownerDocument:this.ownerDocument,anchor:this.anchor,items:this.items,query:this.query,filter:this.filter,activeIndex:this.activeIndex};if(await this.updateComplete,await this.cleanup?.ready===!1||generation!==this._focusTransferGeneration||textareaSession&&textareaSessionGeneration!==this._textareaFocusSessionGeneration||!this.isConnected||!this.open||this.ownerDocument!==snapshot.ownerDocument||this.anchor!==snapshot.anchor||this.items!==snapshot.items||this.query!==snapshot.query||this.filter!==snapshot.filter||this.activeIndex!==snapshot.activeIndex||!this.callFocusOwner(ownsFocus))return!1;const active=this.activeDescendantElement;return!active?.isConnected||!this.callFocusOwner(ownsFocus)||(this.captureAnchorCaret(),active.focus({preventScroll:!0}),activeElementIn(this.shadowRoot)!==active)?!1:(this._focusOwnerPredicate=ownsFocus,this._ownsFocus=!0,!0)}async restoreFocus(waitForPlacement=!1){if(waitForPlacement){if(await this.cleanup?.ready===!1||!this._ownsFocus||!this.open)return;if(this.hasTextareaFocusSession()&&!this.fallbackFocusIsStillOwned()){this._ownsFocus=!1,this._focusOwnerPredicate=void 0;return}}const active=this.renderRoot.querySelector('[part="option"][data-active]');active?active.focus({preventScroll:!0}):this.anchor?.isConnected?(this.renderRoot.querySelector('[part="listbox"]')?.setAttribute("tabindex","-1"),this.restoreAnchorFocus(),this.scheduleAfterUpdate(()=>{this._ownsFocus=!1,this._focusOwnerPredicate=void 0})):this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0})}callFocusOwner(predicate){try{return predicate?.()??!0}catch{return!1}}fallbackFocusIsStillOwned(){return this.callFocusOwner(this._focusOwnerPredicate)&&activeElementIn(this.shadowRoot)!==null}get listboxId(){return this._listId}handleKeyDown(e){if(!this.open||e.isComposing||e.keyCode===229)return!1;const rows=this.filteredItems;switch(e.key){case"ArrowDown":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),1),!0):!1;case"ArrowUp":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),-1),!0):!1;case"Enter":case"Tab":{const idx=this.clampedIndex(rows);return idx<0?!1:(e.preventDefault(),this.commit(rows[idx]),!0)}case"Escape":return e.preventDefault(),this.open=!1,!0;default:return!1}}clampedIndex(rows){const count=rows.length;if(!count)return-1;const clamped=Math.min(Math.max(this.activeIndex,0),count-1);if(!rows[clamped]?.disabled)return clamped;for(let forward=clamped+1;forward<count;forward+=1)if(!rows[forward]?.disabled)return forward;for(let backward=clamped-1;backward>=0;backward-=1)if(!rows[backward]?.disabled)return backward;return-1}stepEnabledIndex(rows,from,direction){const count=rows.length;if(!count)return 0;let index=Math.min(Math.max(from+direction,0),count-1);for(let steps=0;steps<count;steps+=1){if(!rows[index]?.disabled)return index;if(index+=direction,index<0||index>=count)break}return from>=0&&from<count&&!rows[from]?.disabled?from:this.activeIndex}rowId(index){return`${this._listId}-opt-${index}`}commit(item){if(item.disabled)return;const index=this.items.indexOf(item);if(index<0)return;const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),this.emit("lr-mention-select",Object.freeze({suggestionId:item.suggestionId,index,label:item.label})),this._silentClose=!0,this.open=!1}reposition(){this.cleanup?.(),this.cleanup=void 0;const anchorEl=this.resolveAnchorElement(),popup=this.renderRoot.querySelector('[part="listbox"]');if(anchorEl&&popup){const placement=place(anchorEl,popup,{placement:"bottom-start",strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});this.cleanup=placement,placement.ready.then(positioned=>{positioned||this.cleanup!==placement||!this.open||(this._silentClose=!0,this.open=!1)})}}async settleListboxHidden(){const token=++this.listboxHideToken;if(await this.updateComplete,token!==this.listboxHideToken||this.open)return;const listbox=this.renderRoot.querySelector('[part="listbox"]'),view=this.ownerDocument.defaultView;if(listbox&&view&&!prefersReducedMotion(this)){const computed=view.getComputedStyle(listbox),durationMs=maxCssTime(computed.transitionDuration)+maxCssTime(computed.transitionDelay);if(durationMs>0&&(await new Promise(resolve=>{let settled=!1,timeout;const finish=()=>{settled||(settled=!0,timeout!==void 0&&view.clearTimeout(timeout),listbox.removeEventListener("transitionend",onEnd),listbox.removeEventListener("transitioncancel",onEnd),resolve())},onEnd=event=>{event.target===listbox&&finish()};listbox.addEventListener("transitionend",onEnd),listbox.addEventListener("transitioncancel",onEnd),timeout=view.setTimeout(finish,durationMs+50)}),token!==this.listboxHideToken||this.open))return}this.listboxHidden=!0}resolveAnchorElement(){const anchor=this.anchor;if(!anchor)return null;if(isTextControl(anchor)){const rect=caretClientRect(anchor);if(rect){const owner=anchor.ownerDocument;this.virtualAnchor&&this.virtualAnchor.ownerDocument!==owner&&(this.virtualAnchor.remove(),this.virtualAnchor=null);const virtual=this.virtualAnchor??(this.virtualAnchor=owner.createElement("div"));return virtual.style.position="fixed",virtual.style.left=`${rect.left}px`,virtual.style.top=`${rect.top}px`,virtual.style.width="0",virtual.style.height=`${rect.height}px`,virtual.style.pointerEvents="none",virtual.isConnected||owner.body.appendChild(virtual),virtual}}return anchor}get effectiveEmptyText(){return this.emptyText===void 0?this.localize("noMatches"):this.emptyText}get effectiveLabel(){return hostAriaLabel(this)??(this.label===void 0?this.localize("mentionSuggestions"):this.label)}renderRow(item,index,activeId){const id=this.rowId(index),active=id===activeId;return html`
2
2
  <div
3
3
  part="option"
4
4
  id=${id}
@@ -28,6 +28,7 @@ import{__decorate}from"tslib";import{maxCssTime}from"../../../internal/css-motio
28
28
  @click=${this.onListboxClick}
29
29
  @keydown=${this.onListboxKeyDown}
30
30
  >
31
+ <span class="glass-scroll-layer" aria-hidden="true"></span>
31
32
  ${rows.length===0?html`<div part="empty" role="option" aria-selected="false" aria-disabled="true">${this.effectiveEmptyText}</div>`:rows.map((item,i)=>this.renderRow(item,i,activeId))}
32
33
  </div>
33
34
  `}}__decorate([property({attribute:!1})],LyraMentionPopover.prototype,"anchor",void 0),__decorate([property()],LyraMentionPopover.prototype,"query",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraMentionPopover.prototype,"open",void 0),__decorate([property({attribute:!1})],LyraMentionPopover.prototype,"filter",void 0),__decorate([property({attribute:"empty-text"})],LyraMentionPopover.prototype,"emptyText",void 0),__decorate([property()],LyraMentionPopover.prototype,"label",void 0),__decorate([state()],LyraMentionPopover.prototype,"activeIndex",void 0),__decorate([state()],LyraMentionPopover.prototype,"listboxHidden",void 0),__decorate([state()],LyraMentionPopover.prototype,"_ownsFocus",void 0);export{LyraMentionPopover};
@@ -1 +1 @@
1
- import{css}from"lit";import{overlaySurface,overlaySurfaceControlEdge}from"../../../internal/overlay-surface.styles.js";const styles=css` :host { display: contents; } [part='listbox'][hidden] { display: none; } [part='listbox'] { position: fixed; z-index: var(--lr-layer-dropdown); box-sizing: border-box; max-block-size: min(var(--lr-size-16rem), var(--lr-positioner-available-block-size, var(--lr-size-16rem))); overflow-y: auto; overflow-x: clip; inline-size: max-content; min-inline-size: min(var(--lr-popover-viewport-clamp), var(--lr-size-14rem), var(--lr-positioner-available-inline-size, 100vw)); max-inline-size: min(var(--lr-popover-viewport-clamp), var(--lr-size-24rem), var(--lr-positioner-available-inline-size, 100vw)); padding: var(--lr-space-xs); ${overlaySurface} ${overlaySurfaceControlEdge} box-shadow: var(--lr-overlay-shadow-anchored, var(--lr-shadow-m)); visibility: hidden; opacity: 0; transform: translateY(var(--lr-size-neg-0-25rem)); transition: opacity var(--lr-transition-fast), transform var(--lr-transition-fast), visibility 0s linear var(--lr-transition-fast); } :host([open]) [part='listbox'] { visibility: visible; opacity: 1; transform: translateY(0); transition-delay: 0s, 0s, 0s; } @media (prefers-reduced-motion: reduce) { [part='listbox'] { transition: none !important; } } [part='option'] { display: flex; align-items: center; gap: var(--lr-space-xs); inline-size: 100%; min-block-size: var(--lr-icon-button-size); padding: var(--lr-space-xs) var(--lr-space-s); border-radius: var(--lr-radius); cursor: pointer; } [part='option']:where(:not([aria-disabled='true'])):hover, [part='option'][data-active] { background: var(--lr-mention-popover-option-active-bg, var(--lr-color-brand-quiet)); } [part='option']:where(:not([aria-disabled='true'])):active { background: color-mix( in oklab, var(--lr-mention-popover-option-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part='option'][aria-selected='true'] { color: var(--lr-mention-popover-option-active-color, var(--lr-color-brand)); } [part='option'][aria-disabled='true'] { cursor: default; opacity: var(--lr-mention-popover-option-disabled-opacity, 0.5); } [part='option-icon'] { flex: 0 0 auto; line-height: var(--lr-line-height-1-4); } [part='option-label'] { display: flex; flex-direction: column; min-inline-size: 0; line-height: var(--lr-line-height-1-4); } [part='option-label'] span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part='option-description'] { font-size: var(--lr-font-size-xs); color: var(--lr-color-text-quiet); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part='option']:where(:not([aria-disabled='true'])):hover [part='option-description'], [part='option'][data-active] [part='option-description'] { color: var(--lr-color-text); } [part='empty'] { padding: var(--lr-space-s) var(--lr-space-m); color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-md-sm); overflow-wrap: anywhere; } `;export{styles};
1
+ import{css}from"lit";import{glassSurface}from"../../../internal/glass-surface.styles.js";import{glassScrollLayerStyles}from"../../../internal/glass-scroll-layer.styles.js";import{glassIndependentRootStyles}from"../../../internal/glass-independent-root.styles.js";import{overlaySurface,overlaySurfaceControlEdge}from"../../../internal/overlay-surface.styles.js";const styles=css` :host { display: contents; } [part='listbox'][hidden] { display: none; } [part='listbox'] { position: fixed; z-index: var(--lr-layer-dropdown); box-sizing: border-box; max-block-size: min(var(--lr-size-16rem), var(--lr-positioner-available-block-size, var(--lr-size-16rem))); overflow-y: auto; overflow-x: clip; inline-size: max-content; min-inline-size: min(var(--lr-popover-viewport-clamp), var(--lr-size-14rem), var(--lr-positioner-available-inline-size, 100vw)); max-inline-size: min(var(--lr-popover-viewport-clamp), var(--lr-size-24rem), var(--lr-positioner-available-inline-size, 100vw)); padding: var(--lr-space-xs); ${overlaySurface} ${overlaySurfaceControlEdge} box-shadow: var(--lr-overlay-shadow-anchored, var(--lr-shadow-m)); visibility: hidden; opacity: 0; transform: translateY(var(--lr-size-neg-0-25rem)); transition: opacity var(--lr-transition-fast), transform var(--lr-transition-fast), visibility 0s linear var(--lr-transition-fast); } :host([open]) [part='listbox'] { visibility: visible; opacity: 1; transform: translateY(0); transition-delay: 0s, 0s, 0s; } @media (prefers-reduced-motion: reduce) { [part='listbox'] { transition: none !important; } } [part='option'] { display: flex; align-items: center; gap: var(--lr-space-xs); inline-size: 100%; min-block-size: var(--lr-icon-button-size); padding: var(--lr-space-xs) var(--lr-space-s); border-radius: var(--lr-radius); cursor: pointer; } [part='option']:where(:not([aria-disabled='true'])):hover, [part='option'][data-active] { background: var(--lr-mention-popover-option-active-bg, var(--lr-color-brand-quiet)); } [part='option']:where(:not([aria-disabled='true'])):active { background: color-mix( in oklab, var(--lr-mention-popover-option-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part='option'][aria-selected='true'] { color: var(--lr-mention-popover-option-active-color, var(--lr-color-brand)); } [part='option'][aria-disabled='true'] { cursor: default; opacity: var(--lr-mention-popover-option-disabled-opacity, 0.5); } [part='option-icon'] { flex: 0 0 auto; line-height: var(--lr-line-height-1-4); } [part='option-label'] { display: flex; flex-direction: column; min-inline-size: 0; line-height: var(--lr-line-height-1-4); } [part='option-label'] span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part='option-description'] { font-size: var(--lr-font-size-xs); color: var(--lr-color-text-quiet); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part='option']:where(:not([aria-disabled='true'])):hover [part='option-description'], [part='option'][data-active] [part='option-description'] { color: var(--lr-color-text); } [part='empty'] { padding: var(--lr-space-s) var(--lr-space-m); color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-md-sm); overflow-wrap: anywhere; } ${glassScrollLayerStyles} ${glassIndependentRootStyles} ${glassSurface('[part="listbox"]',css`var(--lr-overlay-surface, var(--_lr-overlay-surface, var(--lr-color-surface-container-high)))`,void 0,!0)} `;export{styles};
@@ -46,10 +46,11 @@ readonly hidePrevious?:boolean;}
46
46
  * Reason a tour ended, forwarded as `lr-tour-end` detail.reason.
47
47
  * `'completed'`/`'skip'`/`'escape'` are emitted by the tour's own built-in dismiss triggers;
48
48
  * `'unmount'` is emitted when the tour is removed from the DOM while still open by something
49
- * other than its own `end()` (mirrors `lr-dialog`'s identical `'unmount'` case); any other
50
- * string is whatever a caller passes to `end()` directly.
49
+ * other than its own `end()` (mirrors `lr-dialog`'s identical `'unmount'` case);
50
+ * `'unavailable'` is emitted when deferred placement fails and the hidden panel cannot remain open;
51
+ * any other string is whatever a caller passes to `end()` directly.
51
52
  */
52
- export type LyraTourEndReason='completed'|'skip'|'escape'|'api'|'unmount'|(string&Record<never,never>);export interface LyraTourEventMap{'lr-tour-start':CustomEvent<{readonly index:number;}>;
53
+ export type LyraTourEndReason='completed'|'skip'|'escape'|'api'|'unmount'|'unavailable'|(string&Record<never,never>);export interface LyraTourEventMap{'lr-tour-start':CustomEvent<{readonly index:number;}>;
53
54
  /** Cancelable proposal to move to another step, fired before `activeIndex` changes. */
54
55
  'lr-tour-step-change-request':CustomEvent<{readonly index:number;readonly previousIndex:number;readonly step:Readonly<LyraTourStep>;readonly via:'next'|'back'|'goto';}>;'lr-tour-end-request':CustomEvent<{reason:LyraTourEndReason;}>;'lr-tour-end':CustomEvent<{reason:LyraTourEndReason;}>;'lr-tour-target-missing':CustomEvent<{readonly index:number;readonly step:Readonly<LyraTourStep>;}>;}
55
56
  /**
@@ -121,7 +122,8 @@ export type LyraTourEndReason='completed'|'skip'|'escape'|'api'|'unmount'|(strin
121
122
  * @event lr-tour-end-request - Cancelable proposal before an ordinary tour end. `detail: { reason }`.
122
123
  * Preventing it keeps the tour open. Removal from the document does not request permission.
123
124
  * @event lr-tour-end - Non-cancelable notification after the tour closes. `detail: { reason }`.
124
- * Forced removal emits reason `unmount` without a request because it cannot be vetoed.
125
+ * Forced removal emits reason `unmount`; unavailable deferred placement emits `unavailable`.
126
+ * Neither requests permission because the closure cannot be vetoed.
125
127
  * @event lr-tour-target-missing - The active step's `target` did not resolve to a connected
126
128
  * element. `detail: { index, step }`. Not cancelable -- informational. The tour does not
127
129
  * auto-end; it renders that step's popover unanchored (viewport-centered, no spotlight cutout)
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{DeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{activateOverlay,collectFocusableElements,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{nextId,hasRealContent}from"../../../internal/a11y.js";import{deferredPlaceReady as place,deferredTrackRect as trackRect}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteInteger,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{needsTopLayerEscape,promoteToTopLayer,releaseTopLayer}from"../../../internal/top-layer-escape.js";import{styles}from"./tour.styles.js";import{resolveCssLength}from"../../../internal/css-length.js";import{LYRA_DEFAULT_next,LYRA_DEFAULT_previous,LYRA_DEFAULT_tourDone,LYRA_DEFAULT_tourSkip,LYRA_DEFAULT_tourStepOf}from"../../../internal/default-strings.generated.js";const DEFAULT_DISTANCE=12,DEFAULT_SPOTLIGHT_PADDING=4,MAX_TOUR_STEPS=256,MAX_STEP_ID_LENGTH=256,MAX_TARGET_SELECTOR_LENGTH=8192,MAX_HEADING_LENGTH=4096,MAX_CONTENT_LENGTH=65536,MAX_STEP_SPOTLIGHT_PADDING=1e4,SPOTLIGHT_PADDING_LENGTH=/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:px|rem|em|vw|vh)$/i,spotlightPaddingConverter={fromAttribute:value=>{if(value===null)return value;const trimmed=value.trim();return SPOTLIGHT_PADDING_LENGTH.test(trimmed)?trimmed:Number(value)}},TOUR_PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function keyholeClipPath(x,y,width,height){const right=x+width,bottom=y+height;return`polygon(evenodd, 0% 0%, 100% 0%, 100% 100%, 0% 100%, 0% 0%, ${x}px ${y}px, ${x}px ${bottom}px, ${right}px ${bottom}px, ${right}px ${y}px, ${x}px ${y}px, 0% 0%)`}function isElementNode(value){return typeof value=="object"&&value!==null&&value.nodeType===1&&typeof value.localName=="string"&&typeof value.matches=="function"}function isPlainRecord(value){if(typeof value!="object"||value===null)return!1;try{if(Array.isArray(value))return!1;const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function ownDataValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function safeArrayLength(value){try{if(!Array.isArray(value))return 0;const descriptor=Object.getOwnPropertyDescriptor(value,"length"),length=descriptor&&"value"in descriptor?descriptor.value:0;return typeof length=="number"&&Number.isFinite(length)?Math.min(MAX_TOUR_STEPS,Math.max(0,Math.floor(length))):0}catch{return 0}}function arrayItem(value,index){try{if(!Array.isArray(value))return;const descriptor=Object.getOwnPropertyDescriptor(value,String(index));return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function boundedString(value,maxLength){return typeof value=="string"?value.slice(0,maxLength):void 0}function normalizeTourTarget(value){if(typeof value=="string"){const selector=value.slice(0,MAX_TARGET_SELECTOR_LENGTH);return selector||void 0}if(typeof value=="function")return value;try{return isHtmlElement(value)?value:void 0}catch{return}}function snapshotTourSteps(value){const normalized=[],length=safeArrayLength(value);for(let index=0;index<length;index+=1){const candidate=arrayItem(value,index);if(!isPlainRecord(candidate))continue;const stepId=boundedString(ownDataValue(candidate,"stepId"),MAX_STEP_ID_LENGTH),target=normalizeTourTarget(ownDataValue(candidate,"target")),heading=boundedString(ownDataValue(candidate,"heading"),MAX_HEADING_LENGTH);if(!stepId||stepId!==stepId.trim()||!target||heading===void 0)continue;const content=boundedString(ownDataValue(candidate,"content"),MAX_CONTENT_LENGTH),rawPlacement=ownDataValue(candidate,"placement"),placement=TOUR_PLACEMENTS.has(rawPlacement)?rawPlacement:void 0,rawPadding=ownDataValue(candidate,"spotlightPadding"),spotlightPadding=typeof rawPadding=="number"&&Number.isFinite(rawPadding)?finiteRange(rawPadding,DEFAULT_SPOTLIGHT_PADDING,0,MAX_STEP_SPOTLIGHT_PADDING):void 0,rawInteractive=ownDataValue(candidate,"interactiveTarget"),interactiveTarget=typeof rawInteractive=="boolean"?rawInteractive:void 0,rawHidePrevious=ownDataValue(candidate,"hidePrevious"),hidePrevious=typeof rawHidePrevious=="boolean"?rawHidePrevious:void 0;normalized.push(Object.freeze({stepId,target,heading,...content!==void 0?{content}:{},...placement!==void 0?{placement}:{},...spotlightPadding!==void 0?{spotlightPadding}:{},...interactiveTarget!==void 0?{interactiveTarget}:{},...hidePrevious!==void 0?{hidePrevious}:{}}))}return Object.freeze(normalized)}class LyraTour extends LyraElement{constructor(){super(...arguments),this.open=!1,this._steps=Object.freeze([]),this.activeIndex=0,this.placement="bottom",this.distance=DEFAULT_DISTANCE,this.spotlightPadding=DEFAULT_SPOTLIGHT_PADDING,this.lightDismiss=!1,this.withoutProgress=!1,this.accessibleLabel=null,this.unanchored=!1,this.hasSlotContent=!1,this.spotlightPositioned=!1,this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlay?.isTopmost()&&this.end("escape")},onUnexpectedClose:()=>{this.end("escape"),this.open&&this.nativeModal.show()}}),this.activeTargetSnapshot=null,this.focusReturnTarget=null,this.deferredFocusReturn=new DeferredFocusReturn,this.maskId=nextId("tour-mask"),this.headingId=nextId("tour-heading"),this.bodyId=nextId("tour-body"),this.progressTextId=nextId("tour-progress-text"),this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onDefaultSlotChange=e=>{this.hasSlotContent=hasRealContent(e.target.assignedNodes({flatten:!0}))},this.onInteractiveScopeKeyDown=event=>{if(event.key!=="Tab"||event.defaultPrevented||!this.open||!this.overlay?.isTopmost())return;const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;const target=this.interactiveKeyboardTarget;if(!target)return;const panelFocusable=collectFocusableElements(popover),targetFocusable=collectFocusableElements(target);if(panelFocusable.length===0&&targetFocusable.length===0){event.preventDefault(),popover.focus();return}const active=deepActiveElement(this.ownerDocument),panelIndex=panelFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),targetIndex=targetFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),destination=panelIndex>=0?event.shiftKey&&panelIndex===0?targetFocusable.at(-1)??panelFocusable.at(-1):!event.shiftKey&&panelIndex===panelFocusable.length-1?targetFocusable[0]??panelFocusable[0]:void 0:targetIndex>=0?event.shiftKey&&targetIndex===0?panelFocusable.at(-1)??targetFocusable.at(-1):!event.shiftKey&&targetIndex===targetFocusable.length-1?panelFocusable[0]??targetFocusable[0]:void 0:active===popover&&!event.shiftKey?void 0:event.shiftKey?targetFocusable.at(-1)??panelFocusable.at(-1):panelFocusable[0]??targetFocusable[0];destination&&(event.preventDefault(),destination.focus())},this.onPopoverKeyDown=event=>{if(event.defaultPrevented||this.ownsDirectionalKeys(event))return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";event.key===forwardKey?(event.preventDefault(),this.next()):event.key===backwardKey&&(event.preventDefault(),this.back())}}static{this.defaultStrings={...super.defaultStrings,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous,tourDone:LYRA_DEFAULT_tourDone,tourSkip:LYRA_DEFAULT_tourSkip,tourStepOf:LYRA_DEFAULT_tourStepOf}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}static{this.properties={steps:{attribute:!1,noAccessor:!0}}}get steps(){return this._steps}set steps(next){const previous=this._steps;this._steps=snapshotTourSteps(next),this.requestUpdate("steps",previous)}willUpdate(changed){if(super.willUpdate(changed),changed.has("activeIndex")||changed.has("steps")){const maxIndex=Math.max(0,this.steps.length-1),normalizedIndex=finiteInteger(this.activeIndex,0,0,maxIndex);normalizedIndex!==this.activeIndex&&(this.activeIndex=normalizedIndex)}if(this.hasUpdated||(this.hasSlotContent=hasRealContent(this.childNodes)),this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps"))){const interactive=!!this.steps[this.activeIndex]?.interactiveTarget;interactive&&this.nativeModal.hide(),this.nativeModal.prepare(!interactive)}if(this.open&&this.steps.length===0)this.open=!1,this.deactivateOverlayInternal();else if(changed.has("open"))if(this.open){this.deferredFocusReturn.cancel();const active=deepActiveElement(this.ownerDocument);this.focusReturnTarget=isHtmlElement(active)?active:null,this.activateOverlayInternal()}else this.deactivateOverlayInternal();if(this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps"))){const step=this.steps[this.activeIndex];this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1}this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps")||changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding"))&&(this.spotlightPositioned=!1)}updated(changed){super.updated(changed);const activationChanged=changed.has("open")||changed.has("activeIndex")||changed.has("steps"),geometryChanged=changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding");if(this.open&&(activationChanged||geometryChanged)){const preserveInteractiveTargetFocus=changed.has("steps")&&this.canPreserveInteractiveTargetFocus(),overlayChanged=this.activateOverlayInternal();this.nativeModal.show();const shouldFocus=changed.has("open")||changed.has("activeIndex")||overlayChanged||changed.has("steps")&&!preserveInteractiveTargetFocus,placement=this.activateStep({scroll:activationChanged,announceMissing:activationChanged});shouldFocus&&this.focusAfterPlacement(placement)}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.open&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlayInternal(),queueMicrotask(async()=>{if(!this.isConnected||!this.open)return;const step=this.steps[this.activeIndex];if(this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1,await this.updateComplete,!this.isConnected||!this.open)return;this.nativeModal.show();const placement=this.activateStep({scroll:!0,announceMissing:!0});this.focusAfterPlacement(placement)}))}disconnectedCallback(){super.disconnectedCallback(),this.disposePositioning(),this.nativeModal.hide(),this.overlay?.suspend(),this.deferredFocusReturn.cancel(),this.open&&queueMicrotask(()=>{!this.isConnected&&this.open&&(this.open=!1,this.emit("lr-tour-end",{reason:"unmount"}))})}start(index=0){this.steps.length!==0&&(this.activeIndex=this.clampIndex(index),this.open=!0,this.emit("lr-tour-start",Object.freeze({index:this.activeIndex})))}next(){const total=this.steps.length;if(total!==0){if(this.activeIndex>=total-1){this.end("completed");return}this.transitionTo(this.activeIndex+1,"next")}}back(){this.activeIndex<=0||this.transitionTo(this.activeIndex-1,"back")}goToStep(index){if(this.steps.length===0)return;const clamped=this.clampIndex(index);clamped!==this.activeIndex&&this.transitionTo(clamped,"goto")}skip(){this.end("skip")}end(reason="api"){!this.open||this.emit("lr-tour-end-request",{reason},{cancelable:!0}).defaultPrevented||(this.open=!1,this.emit("lr-tour-end",{reason}))}clampIndex(index){const total=this.steps.length;return total===0?0:finiteInteger(index,0,0,total-1)}transitionTo(index,via){const previousIndex=this.activeIndex,step=this.steps[index];!step||this.emit("lr-tour-step-change-request",Object.freeze({index,previousIndex,step,via}),{cancelable:!0}).defaultPrevented||(this.activeIndex=index)}resolveTarget(step){try{const{target}=step,resolved=typeof target=="string"?this.ownerDocument.querySelector(target):typeof target=="function"?target():target;return isHtmlElement(resolved)&&resolved.isConnected&&resolved.ownerDocument===this.ownerDocument?resolved:null}catch{return null}}canPreserveInteractiveTargetFocus(){const previousTarget=this.interactiveKeyboardTarget,step=this.steps[this.activeIndex];return!previousTarget?.isConnected||!step?.interactiveTarget?!1:this.activeTargetSnapshot===previousTarget&&composedContains(previousTarget,deepActiveElement(this.ownerDocument))}activateStep(options){this.disposePositioning();const step=this.steps[this.activeIndex];if(!step)return;this.escapeContainingBlock();const target=this.activeTargetSnapshot;if(!target?.isConnected){options.announceMissing&&this.emit("lr-tour-target-missing",Object.freeze({index:this.activeIndex,step}));return}const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;if(options.scroll){const reducedMotion=!target.ownerDocument.defaultView||prefersReducedMotion(this);target.scrollIntoView({block:"center",inline:"nearest",behavior:reducedMotion?"auto":"smooth"})}const placement=rtlAwarePlacement(step.placement??this.placement,this);this.placeCleanup=place(target,popover,{placement,offset:finiteNumber(this.distance,DEFAULT_DISTANCE),strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});const interactive=!!step.interactiveTarget;return interactive&&(this.interactiveKeyboardTarget=target,this.interactiveKeyboardDocument=target.ownerDocument,this.interactiveKeyboardDocument.addEventListener("keydown",this.onInteractiveScopeKeyDown,!0)),this.spotlightCleanup=trackRect(target,rect=>this.paintSpotlight(rect,this.spotlightPaddingPx(step),interactive)),this.placeCleanup}spotlightPaddingPx(step){const value=step.spotlightPadding??this.spotlightPadding,px=typeof value=="string"?resolveCssLength(value,{host:this})??Number.NaN:value;return finiteRange(px,DEFAULT_SPOTLIGHT_PADDING,0)}focusAfterPlacement(placement){if(!placement){this.overlay?.focusInitial();return}placement.ready.then(positioned=>{if(!(this.placeCleanup!==placement||!this.open||!this.isConnected)){if(positioned){this.overlay?.focusInitial();return}this.open=!1,this.deactivateOverlayInternal()}})}paintSpotlight(rect,padding,interactive){const x=rect.left-padding,y=rect.top-padding,width=Math.max(0,rect.width+padding*2),height=Math.max(0,rect.height+padding*2),backdrop=this.renderRoot.querySelector('[part="backdrop"]'),cutout=this.renderRoot.querySelector('[part="backdrop"] .cutout'),spotlight=this.renderRoot.querySelector('[part="spotlight"]');cutout&&(cutout.setAttribute("x",String(x)),cutout.setAttribute("y",String(y)),cutout.setAttribute("width",String(width)),cutout.setAttribute("height",String(height))),spotlight&&(spotlight.style.left=`${x}px`,spotlight.style.top=`${y}px`,spotlight.style.width=`${width}px`,spotlight.style.height=`${height}px`,spotlight.hidden=!1),backdrop&&(backdrop.style.clipPath=interactive?keyholeClipPath(x,y,width,height):""),this.spotlightPositioned=!0}resetSpotlightGeometry(){this.spotlightPositioned=!1;const cutout=this.renderRoot?.querySelector('[part="backdrop"] .cutout'),spotlight=this.renderRoot?.querySelector('[part="spotlight"]'),backdrop=this.renderRoot?.querySelector('[part="backdrop"]');cutout&&(cutout.setAttribute("x","0"),cutout.setAttribute("y","0"),cutout.setAttribute("width","0"),cutout.setAttribute("height","0")),spotlight&&(spotlight.hidden=!0,spotlight.style.removeProperty("left"),spotlight.style.removeProperty("top"),spotlight.style.removeProperty("width"),spotlight.style.removeProperty("height")),backdrop?.style.removeProperty("clip-path")}escapeContainingBlock(){if(!(!needsTopLayerEscape(this)||!promoteToTopLayer(this))&&!this.escapedInset){const previous=["top","right","bottom","left"].map(property2=>({property:property2,value:this.style.getPropertyValue(property2),priority:this.style.getPropertyPriority(property2)}));this.style.setProperty("inset","0"),this.escapedInset={previous,written:this.style.getPropertyValue("top")}}}releaseContainingBlockEscape(){releaseTopLayer(this);const inset=this.escapedInset;if(this.escapedInset=void 0,!!inset)for(const{property:property2,value,priority}of inset.previous)this.style.getPropertyValue(property2)!==inset.written||this.style.getPropertyPriority(property2)!==""||(this.style.removeProperty(property2),value&&this.style.setProperty(property2,value,priority))}disposePositioning(){this.placeCleanup?.(),this.placeCleanup=void 0,this.spotlightCleanup?.(),this.spotlightCleanup=void 0,this.resetSpotlightGeometry(),this.interactiveKeyboardDocument?.removeEventListener("keydown",this.onInteractiveScopeKeyDown,!0),this.interactiveKeyboardDocument=void 0,this.interactiveKeyboardTarget=void 0}activateOverlayInternal(){if(!this.isConnected)return!1;const interactive=!!this.steps[this.activeIndex]?.interactiveTarget;return this.overlay?.isActive()&&this.overlayInteractive===interactive?!1:(this.overlay?.isActive()&&(this.overlay.deactivate({restoreFocus:!1}),this.overlay=void 0),this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="popover"]')??null,onEscape:()=>this.end("escape"),onBackdrop:()=>this.end("skip"),preferredInitialFocus:()=>this.renderRoot.querySelector('[part="popover"]'),restoreFocusTo:()=>{const target=this.focusReturnTarget;return target?.isConnected&&target.ownerDocument===this.ownerDocument?target:null},modal:!interactive,trapFocus:!interactive,lockScroll:!0,suspendWhenUnrendered:!0}),this.overlayInteractive=interactive,!0)}deactivateOverlayInternal(){this.disposePositioning(),this.releaseContainingBlockEscape(),this.activeTargetSnapshot=null;const hadOverlay=this.overlay!==void 0;this.nativeModal.hide(),this.overlay?.deactivate(),this.overlay=void 0,this.overlayInteractive=void 0;const trigger=this.focusReturnTarget;this.focusReturnTarget=null,hadOverlay&&trigger&&this.isConnected&&this.deferredFocusReturn.schedule({host:this,candidates:()=>[trigger.isConnected&&trigger.ownerDocument===this.ownerDocument?trigger:null],isCurrent:()=>!this.open})}ownsDirectionalKeys(event){return event.composedPath().some(node=>isElementNode(node)&&node.matches('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="combobox"], [role="grid"], [role="gridcell"], [role="listbox"], [role="menu"], [role="menuitem"], [role="radio"], [role="radiogroup"], [role="scrollbar"], [role="slider"], [role="spinbutton"], [role="tab"], [role="tablist"], [role="tree"], [role="treeitem"]'))}formatProgressNumber(value){try{return getNumberFormat(this.effectiveLocale).format(value)}catch{return String(value)}}render(){const step=this.open?this.steps[this.activeIndex]:void 0;if(!step)return html``;const total=this.steps.length,isLastStep=this.activeIndex>=total-1,headingName=(step.heading??"").trim(),authoredName=this.accessibleLabel,useHeading=authoredName===null&&headingName.length>0,suppliedName=authoredName?.trim()??"",fallbackName=this.localize("tourStepOf",void 0,{current:this.formatProgressNumber(this.activeIndex+1),total:this.formatProgressNumber(total)}),panelName=authoredName===null?fallbackName:suppliedName,describedBy=[this.hasSlotContent||!!step.content?this.bodyId:"",this.withoutProgress?"":this.progressTextId].filter(id=>id.length>0).join(" ");return this.nativeModal.render(html`
1
+ import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{DeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{activateOverlay,collectFocusableElements,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{nextId,hasRealContent}from"../../../internal/a11y.js";import{deferredPlaceReady as place,deferredTrackRect as trackRect}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteInteger,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{needsTopLayerEscape,promoteToTopLayer,releaseTopLayer}from"../../../internal/top-layer-escape.js";import{styles}from"./tour.styles.js";import{resolveCssLength}from"../../../internal/css-length.js";import{LYRA_DEFAULT_next,LYRA_DEFAULT_previous,LYRA_DEFAULT_tourDone,LYRA_DEFAULT_tourSkip,LYRA_DEFAULT_tourStepOf}from"../../../internal/default-strings.generated.js";const DEFAULT_DISTANCE=12,DEFAULT_SPOTLIGHT_PADDING=4,MAX_TOUR_STEPS=256,MAX_STEP_ID_LENGTH=256,MAX_TARGET_SELECTOR_LENGTH=8192,MAX_HEADING_LENGTH=4096,MAX_CONTENT_LENGTH=65536,MAX_STEP_SPOTLIGHT_PADDING=1e4,SPOTLIGHT_PADDING_LENGTH=/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:px|rem|em|vw|vh)$/i,spotlightPaddingConverter={fromAttribute:value=>{if(value===null)return value;const trimmed=value.trim();return SPOTLIGHT_PADDING_LENGTH.test(trimmed)?trimmed:Number(value)}},TOUR_PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function keyholeClipPath(x,y,width,height){const right=x+width,bottom=y+height;return`polygon(evenodd, 0% 0%, 100% 0%, 100% 100%, 0% 100%, 0% 0%, ${x}px ${y}px, ${x}px ${bottom}px, ${right}px ${bottom}px, ${right}px ${y}px, ${x}px ${y}px, 0% 0%)`}function isElementNode(value){return typeof value=="object"&&value!==null&&value.nodeType===1&&typeof value.localName=="string"&&typeof value.matches=="function"}function isPlainRecord(value){if(typeof value!="object"||value===null)return!1;try{if(Array.isArray(value))return!1;const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function ownDataValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function safeArrayLength(value){try{if(!Array.isArray(value))return 0;const descriptor=Object.getOwnPropertyDescriptor(value,"length"),length=descriptor&&"value"in descriptor?descriptor.value:0;return typeof length=="number"&&Number.isFinite(length)?Math.min(MAX_TOUR_STEPS,Math.max(0,Math.floor(length))):0}catch{return 0}}function arrayItem(value,index){try{if(!Array.isArray(value))return;const descriptor=Object.getOwnPropertyDescriptor(value,String(index));return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function boundedString(value,maxLength){return typeof value=="string"?value.slice(0,maxLength):void 0}function normalizeTourTarget(value){if(typeof value=="string"){const selector=value.slice(0,MAX_TARGET_SELECTOR_LENGTH);return selector||void 0}if(typeof value=="function")return value;try{return isHtmlElement(value)?value:void 0}catch{return}}function snapshotTourSteps(value){const normalized=[],length=safeArrayLength(value);for(let index=0;index<length;index+=1){const candidate=arrayItem(value,index);if(!isPlainRecord(candidate))continue;const stepId=boundedString(ownDataValue(candidate,"stepId"),MAX_STEP_ID_LENGTH),target=normalizeTourTarget(ownDataValue(candidate,"target")),heading=boundedString(ownDataValue(candidate,"heading"),MAX_HEADING_LENGTH);if(!stepId||stepId!==stepId.trim()||!target||heading===void 0)continue;const content=boundedString(ownDataValue(candidate,"content"),MAX_CONTENT_LENGTH),rawPlacement=ownDataValue(candidate,"placement"),placement=TOUR_PLACEMENTS.has(rawPlacement)?rawPlacement:void 0,rawPadding=ownDataValue(candidate,"spotlightPadding"),spotlightPadding=typeof rawPadding=="number"&&Number.isFinite(rawPadding)?finiteRange(rawPadding,DEFAULT_SPOTLIGHT_PADDING,0,MAX_STEP_SPOTLIGHT_PADDING):void 0,rawInteractive=ownDataValue(candidate,"interactiveTarget"),interactiveTarget=typeof rawInteractive=="boolean"?rawInteractive:void 0,rawHidePrevious=ownDataValue(candidate,"hidePrevious"),hidePrevious=typeof rawHidePrevious=="boolean"?rawHidePrevious:void 0;normalized.push(Object.freeze({stepId,target,heading,...content!==void 0?{content}:{},...placement!==void 0?{placement}:{},...spotlightPadding!==void 0?{spotlightPadding}:{},...interactiveTarget!==void 0?{interactiveTarget}:{},...hidePrevious!==void 0?{hidePrevious}:{}}))}return Object.freeze(normalized)}class LyraTour extends LyraElement{constructor(){super(...arguments),this.open=!1,this._steps=Object.freeze([]),this.activeIndex=0,this.placement="bottom",this.distance=DEFAULT_DISTANCE,this.spotlightPadding=DEFAULT_SPOTLIGHT_PADDING,this.lightDismiss=!1,this.withoutProgress=!1,this.accessibleLabel=null,this.unanchored=!1,this.hasSlotContent=!1,this.spotlightPositioned=!1,this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlay?.isTopmost()&&this.end("escape")},onUnexpectedClose:()=>{this.end("escape"),this.open&&this.nativeModal.show()}}),this.activeTargetSnapshot=null,this.focusReturnTarget=null,this.deferredFocusReturn=new DeferredFocusReturn,this.maskId=nextId("tour-mask"),this.headingId=nextId("tour-heading"),this.bodyId=nextId("tour-body"),this.progressTextId=nextId("tour-progress-text"),this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onDefaultSlotChange=e=>{this.hasSlotContent=hasRealContent(e.target.assignedNodes({flatten:!0}))},this.onInteractiveScopeKeyDown=event=>{if(event.key!=="Tab"||event.defaultPrevented||!this.open||!this.overlay?.isTopmost())return;const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;const target=this.interactiveKeyboardTarget;if(!target)return;const panelFocusable=collectFocusableElements(popover),targetFocusable=collectFocusableElements(target);if(panelFocusable.length===0&&targetFocusable.length===0){event.preventDefault(),popover.focus();return}const active=deepActiveElement(this.ownerDocument),panelIndex=panelFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),targetIndex=targetFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),destination=panelIndex>=0?event.shiftKey&&panelIndex===0?targetFocusable.at(-1)??panelFocusable.at(-1):!event.shiftKey&&panelIndex===panelFocusable.length-1?targetFocusable[0]??panelFocusable[0]:void 0:targetIndex>=0?event.shiftKey&&targetIndex===0?panelFocusable.at(-1)??targetFocusable.at(-1):!event.shiftKey&&targetIndex===targetFocusable.length-1?panelFocusable[0]??targetFocusable[0]:void 0:active===popover&&!event.shiftKey?void 0:event.shiftKey?targetFocusable.at(-1)??panelFocusable.at(-1):panelFocusable[0]??targetFocusable[0];destination&&(event.preventDefault(),destination.focus())},this.onPopoverKeyDown=event=>{if(event.defaultPrevented||this.ownsDirectionalKeys(event))return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";event.key===forwardKey?(event.preventDefault(),this.next()):event.key===backwardKey&&(event.preventDefault(),this.back())}}static{this.defaultStrings={...super.defaultStrings,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous,tourDone:LYRA_DEFAULT_tourDone,tourSkip:LYRA_DEFAULT_tourSkip,tourStepOf:LYRA_DEFAULT_tourStepOf}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}static{this.properties={steps:{attribute:!1,noAccessor:!0}}}get steps(){return this._steps}set steps(next){const previous=this._steps;this._steps=snapshotTourSteps(next),this.requestUpdate("steps",previous)}willUpdate(changed){if(super.willUpdate(changed),changed.has("activeIndex")||changed.has("steps")){const maxIndex=Math.max(0,this.steps.length-1),normalizedIndex=finiteInteger(this.activeIndex,0,0,maxIndex);normalizedIndex!==this.activeIndex&&(this.activeIndex=normalizedIndex)}if(this.hasUpdated||(this.hasSlotContent=hasRealContent(this.childNodes)),this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps"))){const interactive=!!this.steps[this.activeIndex]?.interactiveTarget;interactive&&this.nativeModal.hide(),this.nativeModal.prepare(!interactive)}if(this.open&&this.steps.length===0)this.open=!1,this.deactivateOverlayInternal();else if(changed.has("open"))if(this.open){this.deferredFocusReturn.cancel();const active=deepActiveElement(this.ownerDocument);this.focusReturnTarget=isHtmlElement(active)?active:null,this.activateOverlayInternal()}else this.deactivateOverlayInternal();if(this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps"))){const step=this.steps[this.activeIndex];this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1}this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps")||changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding"))&&(this.spotlightPositioned=!1)}updated(changed){super.updated(changed);const activationChanged=changed.has("open")||changed.has("activeIndex")||changed.has("steps"),geometryChanged=changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding");if(this.open&&(activationChanged||geometryChanged)){const preserveInteractiveTargetFocus=changed.has("steps")&&this.canPreserveInteractiveTargetFocus(),overlayChanged=this.activateOverlayInternal();this.nativeModal.show();const shouldFocus=changed.has("open")||changed.has("activeIndex")||overlayChanged||changed.has("steps")&&!preserveInteractiveTargetFocus,placement=this.activateStep({scroll:activationChanged,announceMissing:activationChanged});shouldFocus&&this.focusAfterPlacement(placement)}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.open&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlayInternal(),queueMicrotask(async()=>{if(!this.isConnected||!this.open)return;const step=this.steps[this.activeIndex];if(this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1,await this.updateComplete,!this.isConnected||!this.open)return;this.nativeModal.show();const placement=this.activateStep({scroll:!0,announceMissing:!0});this.focusAfterPlacement(placement)}))}disconnectedCallback(){super.disconnectedCallback(),this.disposePositioning(),this.nativeModal.hide(),this.overlay?.suspend(),this.deferredFocusReturn.cancel(),this.open&&queueMicrotask(()=>{!this.isConnected&&this.open&&(this.open=!1,this.emit("lr-tour-end",{reason:"unmount"}))})}start(index=0){this.steps.length!==0&&(this.activeIndex=this.clampIndex(index),this.open=!0,this.emit("lr-tour-start",Object.freeze({index:this.activeIndex})))}next(){const total=this.steps.length;if(total!==0){if(this.activeIndex>=total-1){this.end("completed");return}this.transitionTo(this.activeIndex+1,"next")}}back(){this.activeIndex<=0||this.transitionTo(this.activeIndex-1,"back")}goToStep(index){if(this.steps.length===0)return;const clamped=this.clampIndex(index);clamped!==this.activeIndex&&this.transitionTo(clamped,"goto")}skip(){this.end("skip")}end(reason="api"){!this.open||this.emit("lr-tour-end-request",{reason},{cancelable:!0}).defaultPrevented||(this.open=!1,this.emit("lr-tour-end",{reason}))}clampIndex(index){const total=this.steps.length;return total===0?0:finiteInteger(index,0,0,total-1)}transitionTo(index,via){const previousIndex=this.activeIndex,step=this.steps[index];!step||this.emit("lr-tour-step-change-request",Object.freeze({index,previousIndex,step,via}),{cancelable:!0}).defaultPrevented||(this.activeIndex=index)}resolveTarget(step){try{const{target}=step,resolved=typeof target=="string"?this.ownerDocument.querySelector(target):typeof target=="function"?target():target;return isHtmlElement(resolved)&&resolved.isConnected&&resolved.ownerDocument===this.ownerDocument?resolved:null}catch{return null}}canPreserveInteractiveTargetFocus(){const previousTarget=this.interactiveKeyboardTarget,step=this.steps[this.activeIndex];return!previousTarget?.isConnected||!step?.interactiveTarget?!1:this.activeTargetSnapshot===previousTarget&&composedContains(previousTarget,deepActiveElement(this.ownerDocument))}activateStep(options){this.disposePositioning();const step=this.steps[this.activeIndex];if(!step)return;this.escapeContainingBlock();const target=this.activeTargetSnapshot;if(!target?.isConnected){options.announceMissing&&this.emit("lr-tour-target-missing",Object.freeze({index:this.activeIndex,step}));return}const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;if(options.scroll){const reducedMotion=!target.ownerDocument.defaultView||prefersReducedMotion(this);target.scrollIntoView({block:"center",inline:"nearest",behavior:reducedMotion?"auto":"smooth"})}const placement=rtlAwarePlacement(step.placement??this.placement,this);this.placeCleanup=place(target,popover,{placement,offset:finiteNumber(this.distance,DEFAULT_DISTANCE),strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});const interactive=!!step.interactiveTarget;return interactive&&(this.interactiveKeyboardTarget=target,this.interactiveKeyboardDocument=target.ownerDocument,this.interactiveKeyboardDocument.addEventListener("keydown",this.onInteractiveScopeKeyDown,!0)),this.spotlightCleanup=trackRect(target,rect=>this.paintSpotlight(rect,this.spotlightPaddingPx(step),interactive)),this.placeCleanup}spotlightPaddingPx(step){const value=step.spotlightPadding??this.spotlightPadding,px=typeof value=="string"?resolveCssLength(value,{host:this})??Number.NaN:value;return finiteRange(px,DEFAULT_SPOTLIGHT_PADDING,0)}focusAfterPlacement(placement){if(!placement){this.overlay?.focusInitial();return}placement.ready.then(positioned=>{if(!(this.placeCleanup!==placement||!this.open||!this.isConnected)){if(positioned){this.overlay?.focusInitial();return}this.open=!1,this.deactivateOverlayInternal(),this.emit("lr-tour-end",{reason:"unavailable"})}})}paintSpotlight(rect,padding,interactive){const x=rect.left-padding,y=rect.top-padding,width=Math.max(0,rect.width+padding*2),height=Math.max(0,rect.height+padding*2),backdrop=this.renderRoot.querySelector('[part="backdrop"]'),cutout=this.renderRoot.querySelector('[part="backdrop"] .cutout'),spotlight=this.renderRoot.querySelector('[part="spotlight"]');cutout&&(cutout.setAttribute("x",String(x)),cutout.setAttribute("y",String(y)),cutout.setAttribute("width",String(width)),cutout.setAttribute("height",String(height))),spotlight&&(spotlight.style.left=`${x}px`,spotlight.style.top=`${y}px`,spotlight.style.width=`${width}px`,spotlight.style.height=`${height}px`,spotlight.hidden=!1),backdrop&&(backdrop.style.clipPath=interactive?keyholeClipPath(x,y,width,height):""),this.spotlightPositioned=!0}resetSpotlightGeometry(){this.spotlightPositioned=!1;const cutout=this.renderRoot?.querySelector('[part="backdrop"] .cutout'),spotlight=this.renderRoot?.querySelector('[part="spotlight"]'),backdrop=this.renderRoot?.querySelector('[part="backdrop"]');cutout&&(cutout.setAttribute("x","0"),cutout.setAttribute("y","0"),cutout.setAttribute("width","0"),cutout.setAttribute("height","0")),spotlight&&(spotlight.hidden=!0,spotlight.style.removeProperty("left"),spotlight.style.removeProperty("top"),spotlight.style.removeProperty("width"),spotlight.style.removeProperty("height")),backdrop?.style.removeProperty("clip-path")}escapeContainingBlock(){if(!(!needsTopLayerEscape(this)||!promoteToTopLayer(this))&&!this.escapedInset){const previous=["top","right","bottom","left"].map(property2=>({property:property2,value:this.style.getPropertyValue(property2),priority:this.style.getPropertyPriority(property2)}));this.style.setProperty("inset","0"),this.escapedInset={previous,written:this.style.getPropertyValue("top")}}}releaseContainingBlockEscape(){releaseTopLayer(this);const inset=this.escapedInset;if(this.escapedInset=void 0,!!inset)for(const{property:property2,value,priority}of inset.previous)this.style.getPropertyValue(property2)!==inset.written||this.style.getPropertyPriority(property2)!==""||(this.style.removeProperty(property2),value&&this.style.setProperty(property2,value,priority))}disposePositioning(){this.placeCleanup?.(),this.placeCleanup=void 0,this.spotlightCleanup?.(),this.spotlightCleanup=void 0,this.resetSpotlightGeometry(),this.interactiveKeyboardDocument?.removeEventListener("keydown",this.onInteractiveScopeKeyDown,!0),this.interactiveKeyboardDocument=void 0,this.interactiveKeyboardTarget=void 0}activateOverlayInternal(){if(!this.isConnected)return!1;const interactive=!!this.steps[this.activeIndex]?.interactiveTarget;return this.overlay?.isActive()&&this.overlayInteractive===interactive?!1:(this.overlay?.isActive()&&(this.overlay.deactivate({restoreFocus:!1}),this.overlay=void 0),this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="popover"]')??null,onEscape:()=>this.end("escape"),onBackdrop:()=>this.end("skip"),preferredInitialFocus:()=>this.renderRoot.querySelector('[part="popover"]'),restoreFocusTo:()=>{const target=this.focusReturnTarget;return target?.isConnected&&target.ownerDocument===this.ownerDocument?target:null},modal:!interactive,trapFocus:!interactive,lockScroll:!0,suspendWhenUnrendered:!0}),this.overlayInteractive=interactive,!0)}deactivateOverlayInternal(){this.disposePositioning(),this.releaseContainingBlockEscape(),this.activeTargetSnapshot=null;const hadOverlay=this.overlay!==void 0;this.nativeModal.hide(),this.overlay?.deactivate(),this.overlay=void 0,this.overlayInteractive=void 0;const trigger=this.focusReturnTarget;this.focusReturnTarget=null,hadOverlay&&trigger&&this.isConnected&&this.deferredFocusReturn.schedule({host:this,candidates:()=>[trigger.isConnected&&trigger.ownerDocument===this.ownerDocument?trigger:null],isCurrent:()=>!this.open})}ownsDirectionalKeys(event){return event.composedPath().some(node=>isElementNode(node)&&node.matches('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="combobox"], [role="grid"], [role="gridcell"], [role="listbox"], [role="menu"], [role="menuitem"], [role="radio"], [role="radiogroup"], [role="scrollbar"], [role="slider"], [role="spinbutton"], [role="tab"], [role="tablist"], [role="tree"], [role="treeitem"]'))}formatProgressNumber(value){try{return getNumberFormat(this.effectiveLocale).format(value)}catch{return String(value)}}render(){const step=this.open?this.steps[this.activeIndex]:void 0;if(!step)return html``;const total=this.steps.length,isLastStep=this.activeIndex>=total-1,headingName=(step.heading??"").trim(),authoredName=this.accessibleLabel,useHeading=authoredName===null&&headingName.length>0,suppliedName=authoredName?.trim()??"",fallbackName=this.localize("tourStepOf",void 0,{current:this.formatProgressNumber(this.activeIndex+1),total:this.formatProgressNumber(total)}),panelName=authoredName===null?fallbackName:suppliedName,describedBy=[this.hasSlotContent||!!step.content?this.bodyId:"",this.withoutProgress?"":this.progressTextId].filter(id=>id.length>0).join(" ");return this.nativeModal.render(html`
2
2
  <svg part="backdrop" aria-hidden="true" @click=${this.onBackdropClick}>
3
3
  ${this.unanchored?html`<rect class="scrim" x="0" y="0" width="100%" height="100%"></rect>`:html`
4
4
  <defs>
@@ -1 +1 @@
1
- import{css}from"lit";const styles=css`:host{contain-intrinsic-inline-size:var(--lr-size-20rem);--_lr-document-compare-pane-max-height:var(--lr-size-24rem);display:block;container-type:inline-size}[part=base]{gap:var(--lr-space-m);color:var(--lr-color-text);flex-direction:column;display:flex}[part=diff]{display:block}[part=panes]{gap:var(--lr-space-m);align-items:stretch;display:flex}[part=pane-old],[part=pane-new]{gap:var(--lr-space-xs);border:var(--lr-border-width-thin) solid var(--lr-color-border);border-radius:var(--lr-radius);min-inline-size:0;padding:var(--lr-space-m);max-block-size:var(--_lr-document-compare-pane-max-height-attr,var(--lr-document-compare-pane-max-height,var(--_lr-document-compare-pane-max-height)));transition:border-color var(--lr-transition-fast);flex-direction:column;flex:1 1 0;display:flex;overflow:hidden auto}[part=pane-old]:focus-visible,[part=pane-new]:focus-visible{outline:var(--lr-focus-ring);outline-offset:calc(-1 * var(--lr-focus-ring-width))}[part=pane-old]:hover,[part=pane-new]:hover{border-color:var(--lr-color-border-strong)}[part=pane-header]{font-weight:var(--lr-font-weight-semibold);font-size:var(--lr-font-size-xs);color:var(--lr-color-text-quiet);text-transform:uppercase;letter-spacing:var(--lr-size-0-02em)}[part=pane-empty]{color:var(--lr-color-text-quiet);font-size:var(--lr-font-size-sm);margin:0}@container (inline-size<=639.98px){[part=panes]{flex-direction:column}[part=pane-old],[part=pane-new]{flex-basis:auto}}`;export{styles};
1
+ import{css}from"lit";const styles=css`:host{contain-intrinsic-inline-size:var(--lr-size-20rem);--_lr-document-compare-pane-max-height:var(--lr-size-24rem);display:block;container-type:inline-size}[part=base]{gap:var(--lr-space-m);color:var(--lr-color-text);flex-direction:column;display:flex}[part=diff]{display:block}[part=panes]{gap:var(--lr-space-m);align-items:stretch;display:flex}[part=pane-old],[part=pane-new]{gap:var(--lr-space-xs);border:var(--lr-border-width-thin) solid var(--lr-color-border);border-radius:var(--lr-radius);min-inline-size:0;padding:var(--lr-space-m);max-block-size:var(--_lr-document-compare-pane-max-height-attr,var(--lr-document-compare-pane-max-height,var(--_lr-document-compare-pane-max-height)));transition:border-color var(--lr-transition-fast);flex-direction:column;flex:1 1 0;display:flex;overflow:hidden auto}[part=pane-old]:focus-visible,[part=pane-new]:focus-visible{outline:var(--lr-focus-ring);outline-offset:calc(-1 * var(--lr-focus-ring-width))}[part=pane-old]:hover,[part=pane-new]:hover{border-color:color-mix(in oklab, var(--lr-color-border-strong), var(--lr-color-mix-partner) var(--lr-color-mix-hover))}[part=pane-header]{font-weight:var(--lr-font-weight-semibold);font-size:var(--lr-font-size-xs);color:var(--lr-color-text-quiet);text-transform:uppercase;letter-spacing:var(--lr-size-0-02em)}[part=pane-empty]{color:var(--lr-color-text-quiet);font-size:var(--lr-font-size-sm);margin:0}@container (inline-size<=639.98px){[part=panes]{flex-direction:column}[part=pane-old],[part=pane-new]{flex-basis:auto}}`;export{styles};
@@ -15,7 +15,7 @@ import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,
15
15
  aria-hidden="true"
16
16
  focusable="false"
17
17
  >${paths}</svg>
18
- `}class LyraDocumentPreview extends LyraElement{constructor(){super(...arguments),this.src="",this.mimeType="",this.filename="",this.status="idle",this.errorText="",this.maxHeight="",this.zoomable=!1,this.suppressDownload=!1,this._highlights=snapshotLyraHighlights([]),this._regionHighlights=EMPTY_REGION_HIGHLIGHTS,this.activeHighlightId=null,this.anchorKinds=["region"],this.hasUnsupportedSlot=!1,this.textFetch=IDLE_TEXT_FETCH,this.generation=0,this.invalidUrlReportedFor=null,this.announcements=new ViewerAnnouncementController(this),this.onUnsupportedSlotChange=()=>{this.hasUnsupportedSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="unsupported")},this.onDownloadClick=()=>{this.emit("lr-download",{src:this.src,filename:this.filename})}}static{this.defaultStrings={...super.defaultStrings,convertingDocument:LYRA_DEFAULT_convertingDocument,documentPreviewAlt:LYRA_DEFAULT_documentPreviewAlt,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewGenericError:LYRA_DEFAULT_documentPreviewGenericError,documentPreviewGenericFile:LYRA_DEFAULT_documentPreviewGenericFile,documentPreviewNotAvailable:LYRA_DEFAULT_documentPreviewNotAvailable,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,download:LYRA_DEFAULT_download,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,srOnly]}get highlights(){return this._highlights}set highlights(value){const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this._regionHighlights=this.projectRegionHighlights(this._highlights),this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&classifyFormat(this.mimeType)==="text"&&(this.textFetch=IDLE_TEXT_FETCH,this.scheduleAfterUpdate(()=>{const url=safeFetchUrl(this.src);url&&this.status!=="converting"&&this.status!=="error"&&this.fetchText(url)}))}disconnectedCallback(){this.generation++,this.beginAbortableLoad(),this.textFetch=IDLE_TEXT_FETCH,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasUnsupportedSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="unsupported"))}updated(changed){super.updated(changed),this.syncAnnouncementState();const safeTextSrc=safeFetchUrl(this.src);classifyFormat(this.mimeType)==="text"&&safeTextSrc!==null&&this.status!=="converting"&&this.status!=="error"?(changed.has("src")||changed.has("mimeType")||changed.has("status")&&this.textFetch.kind==="idle")&&this.scheduleAfterUpdate(()=>{this.fetchText(safeTextSrc)}):this.textFetch.kind!=="idle"&&(this.generation++,this.beginAbortableLoad(),this.textFetch=IDLE_TEXT_FETCH)}syncAnnouncementState(){if(this.status==="converting"){if(this.progress!=null&&Number.isFinite(this.progress)){this.announcements.transition("preview","progress");return}this.announcements.transition("preview","loading",this.localize("convertingDocument"));return}if(this.status==="error"){this.announcements.transition("preview","error",this.errorText||this.localize("documentPreviewGenericError"));return}if(classifyFormat(this.mimeType)!=="text"||this.src===""){this.announcements.transition("preview","idle");return}if(safeFetchUrl(this.src)===null){this.announcements.transition("preview","error",this.localize("documentPreviewUrlNotAllowed"));return}if(this.textFetch.kind==="error"){this.announcements.transition("preview","error",this.textFetch.message);return}if(this.textFetch.kind==="loaded"){this.announcements.transition("preview","loaded");return}this.announcements.transition("preview","loading",this.localize("loadingDocument"))}async fetchText(url){const generation=++this.generation,signal=this.beginAbortableLoad(),fetchTarget=resolveOwnerFetchTarget(this,url);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.textFetch={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.textFetch={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const text=await readResponseText(response);if(!this.isConnected||generation!==this.generation)return;this.textFetch={kind:"loaded",text}}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;const message=this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad");this.textFetch={kind:"error",message},this.emit("lr-render-error",{error})}}renderSpinner(label,progressValue){if(progressValue!=null&&Number.isFinite(progressValue)){const clamped=finiteRange(progressValue,0,0,100),rounded=Math.round(clamped),formatted=getNumberFormat(this.effectiveLocale,{style:"percent",maximumFractionDigits:0}).format(clamped/100);return html`
18
+ `}class LyraDocumentPreview extends LyraElement{constructor(){super(...arguments),this.src="",this.mimeType="",this.filename="",this.status="idle",this.errorText="",this.maxHeight="",this.zoomable=!1,this.suppressDownload=!1,this._highlights=snapshotLyraHighlights([]),this._regionHighlights=EMPTY_REGION_HIGHLIGHTS,this.activeHighlightId=null,this.anchorKinds=["region"],this.hasUnsupportedSlot=!1,this.textFetch=IDLE_TEXT_FETCH,this.generation=0,this.invalidUrlReportedFor=null,this.announcements=new ViewerAnnouncementController(this),this.onUnsupportedSlotChange=()=>{this.hasUnsupportedSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="unsupported")},this.onDownloadClick=()=>{this.emit("lr-download",{src:this.src,filename:this.filename})}}static{this.defaultStrings={...super.defaultStrings,convertingDocument:LYRA_DEFAULT_convertingDocument,documentPreviewAlt:LYRA_DEFAULT_documentPreviewAlt,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewGenericError:LYRA_DEFAULT_documentPreviewGenericError,documentPreviewGenericFile:LYRA_DEFAULT_documentPreviewGenericFile,documentPreviewNotAvailable:LYRA_DEFAULT_documentPreviewNotAvailable,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,download:LYRA_DEFAULT_download,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,srOnly]}get highlights(){return this._highlights}set highlights(value){const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this._regionHighlights=this.projectRegionHighlights(this._highlights),this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&classifyFormat(this.mimeType)==="text"&&(this.textFetch=IDLE_TEXT_FETCH,this.scheduleAfterUpdate(()=>{const url=safeFetchUrl(this.src);url&&this.status!=="converting"&&this.status!=="error"&&this.fetchText(url)}))}disconnectedCallback(){this.generation++,this.beginAbortableLoad(),this.textFetch=IDLE_TEXT_FETCH,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasUnsupportedSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="unsupported")),this.textFetch.kind!=="idle"&&(classifyFormat(this.mimeType)!=="text"||safeFetchUrl(this.src)===null||this.status==="converting"||this.status==="error")&&(this.generation++,this.beginAbortableLoad(),this.textFetch=IDLE_TEXT_FETCH)}updated(changed){super.updated(changed),this.syncAnnouncementState();const safeTextSrc=safeFetchUrl(this.src);classifyFormat(this.mimeType)==="text"&&safeTextSrc!==null&&this.status!=="converting"&&this.status!=="error"&&(changed.has("src")||changed.has("mimeType")||changed.has("status")&&this.textFetch.kind==="idle")&&this.scheduleAfterUpdate(()=>{this.fetchText(safeTextSrc)})}syncAnnouncementState(){if(this.status==="converting"){if(this.progress!=null&&Number.isFinite(this.progress)){this.announcements.transition("preview","progress");return}this.announcements.transition("preview","loading",this.localize("convertingDocument"));return}if(this.status==="error"){this.announcements.transition("preview","error",this.errorText||this.localize("documentPreviewGenericError"));return}if(classifyFormat(this.mimeType)!=="text"||this.src===""){this.announcements.transition("preview","idle");return}if(safeFetchUrl(this.src)===null){this.announcements.transition("preview","error",this.localize("documentPreviewUrlNotAllowed"));return}if(this.textFetch.kind==="error"){this.announcements.transition("preview","error",this.textFetch.message);return}if(this.textFetch.kind==="loaded"){this.announcements.transition("preview","loaded");return}this.announcements.transition("preview","loading",this.localize("loadingDocument"))}async fetchText(url){const generation=++this.generation,signal=this.beginAbortableLoad(),fetchTarget=resolveOwnerFetchTarget(this,url);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.textFetch={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.textFetch={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const text=await readResponseText(response);if(!this.isConnected||generation!==this.generation)return;this.textFetch={kind:"loaded",text}}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;const message=this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad");this.textFetch={kind:"error",message},this.emit("lr-render-error",{error})}}renderSpinner(label,progressValue){if(progressValue!=null&&Number.isFinite(progressValue)){const clamped=finiteRange(progressValue,0,0,100),rounded=Math.round(clamped),formatted=getNumberFormat(this.effectiveLocale,{style:"percent",maximumFractionDigits:0}).format(clamped/100);return html`
19
19
  <div
20
20
  part="spinner"
21
21
  role="progressbar"