@aceshooting/lyra-ui 28.0.0 → 28.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/dist/components/agent-tools/commit-card/commit-card.class.d.ts +2 -2
- package/dist/components/agent-tools/commit-card/commit-card.class.js +7 -8
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +4 -4
- package/dist/components/charts/chart/box-plot.class.d.ts +5 -3
- package/dist/components/charts/chart/box-plot.class.js +18 -17
- package/dist/components/charts/chart/chart.class.d.ts +6 -4
- package/dist/components/charts/chart/chart.class.js +19 -18
- package/dist/components/charts/chart/lite-chart.class.d.ts +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +8 -8
- package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/data/data-grid/data-grid-processing.js +1 -1
- package/dist/components/data/gauge/gauge.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +2 -2
- package/dist/components/data/heatmap/heatmap-label-cache.js +1 -0
- package/dist/components/data/heatmap/heatmap.class.d.ts +3 -2
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/heatmap/heatmap.styles.js +1 -1
- package/dist/components/data/stat/stat.class.d.ts +11 -9
- package/dist/components/data/stat/stat.class.js +4 -2
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.js +3 -3
- package/dist/components/forms/combobox/combobox.class.d.ts +2 -4
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +5 -5
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/select/select.class.js +4 -3
- package/dist/components/forms/toggle-group/toggle-group.class.js +1 -1
- package/dist/components/layout/command-palette/command-palette.styles.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +3 -3
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/menubar/menubar.class.js +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.d.ts +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.d.ts +1 -1
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +2 -2
- package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
- package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.js +1 -1
- package/dist/components/retrieval/graph-legend/graph-legend.class.js +2 -2
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +4 -4
- package/dist/components/retrieval/source-picker/source-picker.class.d.ts +1 -1
- package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/default-strings/charts.generated.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/native-modal-carrier.js +2 -2
- package/dist/internal/nonmodal-overlay-manager.js +1 -1
- package/dist/internal/open-overlay-ancestors.js +1 -0
- package/dist/internal/open-overlay-raise.styles.js +1 -1
- package/dist/internal/overlay-manager.d.ts +2 -0
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/testing/happy-dom-shims.d.ts +3 -1
- package/dist/testing/happy-dom-shims.js +1 -1
- package/llms/components/lr-box-plot.md +5 -0
- package/llms/components/lr-chart.md +6 -0
- package/llms/components/lr-color-picker.md +2 -0
- package/llms/components/lr-commit-card.md +3 -2
- package/llms/components/lr-heatmap.md +10 -2
- package/llms/components/lr-select.md +2 -0
- package/llms/components/lr-stat.md +4 -0
- package/llms/peers.md +1 -1
- package/llms/shared/ai-and-peers.md +44 -0
- package/llms/shared/testing-and-utilities.md +14 -1
- package/llms/shared.md +58 -1
- package/locales.json +138 -138
- package/package.json +7 -6
- package/registrations.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{chevronIcon}from"../../../internal/icons.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{tag}from"../../../internal/prefix.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{styles}from"./tab-group.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_scrollNext,LYRA_DEFAULT_scrollPrevious}from"../../../internal/default-strings/layout.generated.js";function isInertChild(child){return isHtmlElement(child)&&child.inert}function isTabLabelSubtreeExcludedWithoutInert(element){if(element.hasAttribute("hidden")||element.getAttribute("aria-hidden")?.trim().toLowerCase()==="true")return!0;const rendered=element.ownerDocument.defaultView?.getComputedStyle(element);return rendered?.display==="none"||rendered?.contentVisibility==="hidden"}const SYNTHETIC_PANEL_PREFIX="lr-tab-",SCROLL_STEP_RATIO=.8;class LyraTabGroup extends LyraElement{constructor(){super(...arguments),this.active="",this.accessibleLabel=null,this.placement="top",this.activation="auto",this.withoutScrollControls=!1,this.noScrollControls=!1,this.fixedScrollControls=!1,this.tabs=[],this.focusedTab="",this.baseId=nextId("tab-group"),this.nextOpaqueId=0,this.idsBySlot=new Map,this.mutationObserverGeneration=0,this.projectedSourceSnapshots=new Map,this.projectedSlotSnapshots=new Map,this.projectedSourceObserverGeneration=0,this.rehomeTabFocus=!1,this.scrollStartAvailable=!1,this.scrollEndAvailable=!1,this.scrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part~="tablist"]'),()=>this.measureTabScrollEdges()),this.syncTabs=()=>{const children=Array.from(this.children);this.adoptProjectedSourceInertStates(),this.adoptProjectedSlotStates();const projectedSlots=new Set,next=this.readElementModel(children,projectedSlots);this.syncProjectedSlots(projectedSlots),this.syncProjectedSources(next);const liveSlots=new Set(next.map(tab=>tab.slotName));for(const slotName of this.idsBySlot.keys())liveSlots.has(slotName)||this.idsBySlot.delete(slotName);this.tabs=next},this.onTabListKeyDown=e=>{if(e.altKey||e.ctrlKey||e.metaKey||e.isComposing)return;const navigable=this.tabs.filter(t=>this.isNavigable(t));if(navigable.length===0)return;const origin=this.keyboardOriginTab(e,navigable),currentIndex=origin?navigable.indexOf(origin):-1;if(e.key==="Delete"){if(!origin?.element.closable)return;e.preventDefault(),origin.element.requestCloseFromOwner();return}if(this.activation==="manual"&&(e.key==="Enter"||e.key===" "||e.key==="Spacebar")){if(!origin)return;e.preventDefault(),this.activateTab(origin);return}const targetIndex=resolveListMove(e,{count:navigable.length,current:currentIndex,orientation:this.isVertical?"vertical":"horizontal",direction:this.effectiveDirection});if(targetIndex===null)return;e.preventDefault();const target=navigable[targetIndex];if(this.activation==="manual"){this.focusOnly(target);return}this.activateTab(target),this.focusTab(target.slotName)},this.onTabListScroll=()=>{this.measureTabScrollEdges()},this.onScrollControlMouseDown=event=>{event.preventDefault()},this.onScrollControlPointerDown=event=>{const control=event.currentTarget;control instanceof HTMLElement&&(control.setAttribute("data-pressed",""),control.setPointerCapture(event.pointerId))},this.onScrollControlPointerEnd=event=>{const control=event.currentTarget;control instanceof HTMLElement&&(control.removeAttribute("data-pressed"),control.hasPointerCapture(event.pointerId)&&control.releasePointerCapture(event.pointerId))}}static{this.defaultStrings={...super.defaultStrings,scrollNext:LYRA_DEFAULT_scrollNext,scrollPrevious:LYRA_DEFAULT_scrollPrevious}}static{this.styles=[LyraElement.styles,scrollOverflowFadeStyles,styles]}connectedCallback(){super.connectedCallback(),this.hasUpdated?this.syncTabs():this.seedFirstRenderState(this.syncTabs),this.resetMutationObserver();const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.mutationObserverGeneration,observer=new MutationObserverCtor(records=>{if(this.mutationObserver!==observer||this.mutationObserverDocument!==ownerDocument||this.mutationObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;const isDirectChild=node=>node.parentNode===this,isElementTabContent=node=>{let current=node.nodeType===1?node:node.parentElement;for(;current&¤t!==this;){if(current.localName===tag("tab")&¤t.parentNode===this)return!0;current=current.parentElement}return!1};records.some(record=>record.type==="childList"?record.target===this||isElementTabContent(record.target):record.type==="characterData"?isElementTabContent(record.target):record.attributeName==="inert"&&this.projectedSourceSnapshots.has(record.target)?!1:isDirectChild(record.target)||isElementTabContent(record.target))&&this.syncTabs()});this.mutationObserver=observer,this.mutationObserverDocument=ownerDocument,observer.observe(this,{childList:!0,subtree:!0,attributes:!0,characterData:!0,attributeFilter:["alt","aria-hidden","aria-label","aria-labelledby","class","closable","disabled","hidden","inert","id","label","name","open","panel","slot","style"]})}disconnectedCallback(){this.resetMutationObserver(),this.resetProjectedSourceObserver(),this.restoreProjectedSources(),this.restoreProjectedSlots(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetMutationObserver(),this.resetProjectedSourceObserver()}resetMutationObserver(){this.mutationObserverGeneration+=1,this.mutationObserver?.disconnect(),this.mutationObserver=void 0,this.mutationObserverDocument=void 0}readElementModel(children,projectedSlots){const seen=new Set,next=[],panels=children.filter(child=>child.localName===tag("tab-panel")),authoredNames=new Set(children.flatMap(child=>{if(child.localName===tag("tab")){const name=child.getAttribute("panel");return name?[name]:[]}if(child.localName===tag("tab-panel")){const name=child.getAttribute("name");return name?[name]:[]}return[]}));let index=0;for(const child of children){if(child.localName!==tag("tab"))continue;const authoredPanel=child.getAttribute("panel")||void 0;let slotName=authoredPanel??`${SYNTHETIC_PANEL_PREFIX}${index}`;if(!authoredPanel){let collision=0;for(;authoredNames.has(slotName)||seen.has(slotName);)collision+=1,slotName=`${SYNTHETIC_PANEL_PREFIX}${index}-${collision}`}if(index+=1,!authoredPanel&&!this.readElementLabel(child,{allowUnprojected:!0})||seen.has(slotName))continue;seen.add(slotName);const tabSlot=this.tabSlotName(slotName);this.projectSlot(child,tabSlot,projectedSlots);const visibleLabel=this.readElementLabel(child);if(!authoredPanel&&!visibleLabel)continue;const label=visibleLabel||slotName,panel=panels.find(candidate=>candidate.getAttribute("name")===slotName);panel&&this.projectSlot(panel,slotName,projectedSlots),next.push({slotName,label,disabled:child.hasAttribute("disabled"),inert:isInertChild(child),element:child}),!this.active&&child.hasAttribute("active")&&(this.active=slotName)}return next}readElementLabel(tab,options={}){const labelNodes=Array.from(tab.childNodes).filter(node=>node.nodeType!==Node.ELEMENT_NODE||node.getAttribute("slot")===null||node.getAttribute("slot")==="");return composedAccessibilityText(labelNodes,{ancestorBoundary:tab,isSubtreeExcluded:element=>this.isTabLabelSubtreeExcluded(element),requireRendered:!options.allowUnprojected,skipRootAncestorValidation:options.allowUnprojected,ignoreInheritedVisibility:!0}).replace(/\s+/g," ").trim()}libraryOwnsSourceInert(element){return this.projectedSourceSnapshots.get(element)?.libraryOwnsInert===!0}isTabLabelSubtreeExcluded(element){return isTabLabelSubtreeExcludedWithoutInert(element)||element.hasAttribute("inert")&&!this.libraryOwnsSourceInert(element)}snapshotProjectedSource(source){const inert=source.getAttribute("inert");return{inert,appliedInert:inert,libraryOwnsInert:!1}}adoptProjectedSourceInert(source,snapshot){const current=source.getAttribute("inert");current!==snapshot.appliedInert&&(snapshot.inert=current,snapshot.libraryOwnsInert=!1)}makeProjectedSourceInert(source,snapshot){source.hasAttribute("inert")||(source.setAttribute("inert",""),snapshot.libraryOwnsInert=!0),snapshot.appliedInert=source.getAttribute("inert")}restoreProjectedSource(source,snapshot){this.adoptProjectedSourceInert(source,snapshot),snapshot.inert===null?source.removeAttribute("inert"):source.setAttribute("inert",snapshot.inert)}restoreProjectedSources(){for(const[source,snapshot]of this.projectedSourceSnapshots)this.restoreProjectedSource(source,snapshot);this.projectedSourceSnapshots.clear()}resetProjectedSourceObserver(){this.projectedSourceObserverGeneration+=1,this.projectedSourceObserver?.disconnect(),this.projectedSourceObserver=void 0,this.projectedSourceObserverDocument=void 0}observeProjectedSources(){this.resetProjectedSourceObserver();const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected||this.projectedSourceSnapshots.size===0)return;const generation=this.projectedSourceObserverGeneration,observer=new MutationObserverCtor(records=>{this.projectedSourceObserver!==observer||this.projectedSourceObserverDocument!==ownerDocument||this.projectedSourceObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||records.some(record=>this.projectedSourceSnapshots.has(record.target))&&this.syncTabs()});this.projectedSourceObserver=observer,this.projectedSourceObserverDocument=ownerDocument;for(const source of this.projectedSourceSnapshots.keys())observer.observe(source,{attributes:!0,attributeFilter:["inert"]})}projectedSources(tabs){const sources=new Set;for(const tab of tabs)for(const child of Array.from(tab.element.children))(child.getAttribute("slot")??"")===""&&sources.add(child);return sources}syncProjectedSources(tabs){const sources=this.projectedSources(tabs);for(const[source,snapshot]of this.projectedSourceSnapshots)this.adoptProjectedSourceInert(source,snapshot),sources.has(source)||(this.restoreProjectedSource(source,snapshot),this.projectedSourceSnapshots.delete(source));for(const source of sources){const snapshot=this.projectedSourceSnapshots.get(source)??this.snapshotProjectedSource(source);this.projectedSourceSnapshots.set(source,snapshot),this.adoptProjectedSourceInert(source,snapshot),this.makeProjectedSourceInert(source,snapshot)}this.observeProjectedSources()}adoptProjectedSourceInertStates(){for(const[source,snapshot]of this.projectedSourceSnapshots)this.adoptProjectedSourceInert(source,snapshot)}snapshotProjectedSlot(source){const slot=source.getAttribute("slot");return{slot,appliedSlot:slot,libraryOwnsSlot:!1}}adoptProjectedSlot(source,snapshot){const current=source.getAttribute("slot");current!==snapshot.appliedSlot&&(snapshot.slot=current,snapshot.libraryOwnsSlot=!1)}projectSlot(source,slot,projectedSlots){const snapshot=this.projectedSlotSnapshots.get(source)??this.snapshotProjectedSlot(source);this.projectedSlotSnapshots.set(source,snapshot),this.adoptProjectedSlot(source,snapshot),source.getAttribute("slot")!==slot&&(source.setAttribute("slot",slot),snapshot.libraryOwnsSlot=!0),snapshot.appliedSlot=source.getAttribute("slot"),projectedSlots.add(source)}restoreProjectedSlot(source,snapshot){this.adoptProjectedSlot(source,snapshot),snapshot.slot===null?source.removeAttribute("slot"):source.setAttribute("slot",snapshot.slot)}syncProjectedSlots(projectedSlots){for(const[source,snapshot]of this.projectedSlotSnapshots)projectedSlots.has(source)||(this.restoreProjectedSlot(source,snapshot),this.projectedSlotSnapshots.delete(source))}restoreProjectedSlots(){for(const[source,snapshot]of this.projectedSlotSnapshots)this.restoreProjectedSlot(source,snapshot);this.projectedSlotSnapshots.clear()}adoptProjectedSlotStates(){for(const[source,snapshot]of this.projectedSlotSnapshots)this.adoptProjectedSlot(source,snapshot)}isNavigable(tab){return!tab.disabled&&!tab.inert}willUpdate(changed){if(super.willUpdate(changed),!changed.has("tabs")&&!changed.has("active"))return;const focused=shadowFocusTarget(this),focusedSlot=focused?.getAttribute("part")==="tab"?focused.getAttribute("data-slot"):null;focusedSlot!==null&&!this.tabs.some(tab=>tab.slotName===focusedSlot&&this.isNavigable(tab))&&(this.rehomeTabFocus=!0,this.focusedTab=this.active);const current=this.tabs.find(t=>t.slotName===this.active);if(current&&this.isNavigable(current))return;this.rehomeTabFocus=this.rehomeTabFocus||focusedSlot!==null;const outgoing=this.active,before=changed.get("tabs")??this.tabs,at=this.hasUpdated&&changed.has("tabs")&&!changed.has("active")?before.findIndex(t=>t.slotName===outgoing):-1,renamed=at<0?void 0:this.tabs.find(t=>t.element===before[at].element&&this.isNavigable(t)),candidates=at<0?this.tabs:[...before.slice(at+1),...before.slice(0,at).reverse()].map(t=>this.tabs.find(live=>live.slotName===t.slotName));this.active=(renamed??candidates.find(t=>t&&this.isNavigable(t)))?.slotName??"",this.focusedTab=this.active,at>=0&&!renamed&&(this.emit("lr-tab-hide",{name:outgoing}),this.active&&this.emit("lr-tab-show",{name:this.active}))}updated(changed){super.updated(changed),(changed.has("active")||changed.has("tabs"))&&this.syncElementActiveState(),this.scrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="tab"]')),this.measureTabScrollEdges(),this.rehomeTabFocus&&(this.rehomeTabFocus=!1,this.renderRoot.querySelector('[part="tab"][tabindex="0"]')?.focus())}selectTab(tab){if(!this.isNavigable(tab)||tab.slotName===this.active)return;const previous=this.active;this.active=tab.slotName,this.focusedTab=tab.slotName,previous&&this.emit("lr-tab-hide",{name:previous}),this.emit("lr-tab-show",{name:tab.slotName})}activateTab(tab){this.isNavigable(tab)&&(this.selectTab(tab),this.emit("lr-activate",{value:tab.slotName}))}show(panel){const tab=this.tabs.find(candidate=>candidate.slotName===panel);tab&&this.selectTab(tab)}syncElementActiveState(){for(const child of Array.from(this.children))if(child.localName===tag("tab")){const definition=this.tabs.find(tab=>tab.element===child);child.toggleAttribute("active",definition?.slotName===this.active)}else child.localName===tag("tab-panel")&&child.toggleAttribute("active",child.getAttribute("name")===this.active)}focusOnly(tab){this.focusedTab=tab.slotName,this.focusTab(tab.slotName)}get rovingTab(){if(this.activation!=="manual")return this.active;const candidate=this.tabs.find(t=>t.slotName===this.focusedTab&&this.isNavigable(t));return candidate?candidate.slotName:this.active}keyboardOriginTab(event,navigable){const eventButton=event.composedPath().find(candidate=>candidate.nodeType===1&&candidate.getAttribute?.("part")==="tab"&&candidate.getRootNode()===this.renderRoot),focused=shadowFocusTarget(this),owned=(eventButton??(focused?.getAttribute("part")==="tab"?focused:void 0))?.dataset.slot;return navigable.find(tab=>tab.slotName===owned)??navigable.find(tab=>tab.slotName===this.rovingTab)}focusTab(slotName){const buttons=this.renderRoot.querySelectorAll('[part="tab"]');for(const button of Array.from(buttons))if(button.dataset.slot===slotName){button.focus();return}}get isVertical(){return this.placement==="start"||this.placement==="end"}tabId(slotName){return this.idsFor(slotName).tab}panelId(slotName){return this.idsFor(slotName).panel}idsFor(slotName){const existing=this.idsBySlot.get(slotName);if(existing)return existing;const token=`${this.baseId}-${this.nextOpaqueId++}`,ids={tab:`${token}-tab`,panel:`${token}-panel`};return this.idsBySlot.set(slotName,ids),ids}tabSlotName(slotName){return`${slotName}-tab`}get scrollControlsSuppressed(){return this.withoutScrollControls||this.noScrollControls}measureTabScrollEdges(){const tablist=this.renderRoot.querySelector('[part~="tablist"]');if(!tablist||this.isVertical){this.setTabScrollEdges(!1,!1,tablist);return}const maximum=Math.max(0,tablist.scrollWidth-tablist.clientWidth),position=Math.max(0,Math.min(maximum,this.effectiveDirection==="rtl"?-tablist.scrollLeft:tablist.scrollLeft));this.setTabScrollEdges(position>1,position<maximum-1,tablist)}setTabScrollEdges(start,end,tablist){tablist?.toggleAttribute("data-scroll-start",start),tablist?.toggleAttribute("data-scroll-end",end),!(start===this.scrollStartAvailable&&end===this.scrollEndAvailable)&&(this.scrollStartAvailable=start,this.scrollEndAvailable=end)}scrollTabs(edge){const tablist=this.renderRoot.querySelector('[part~="tablist"]');if(!tablist||!isHtmlElement(tablist)||typeof tablist.scrollBy!="function")return;const step=Math.max(1,tablist.clientWidth*SCROLL_STEP_RATIO),towardEnd=edge==="end"?1:-1,physical=this.effectiveDirection==="rtl"?-towardEnd:towardEnd;tablist.scrollBy({left:step*physical,behavior:prefersReducedMotion(this)?"instant":"smooth"})}renderScrollControl(edge){if(this.isVertical||this.scrollControlsSuppressed)return nothing;const available=edge==="start"?this.scrollStartAvailable:this.scrollEndAvailable;return html`<button
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{chevronIcon}from"../../../internal/icons.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{tag}from"../../../internal/prefix.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{styles}from"./tab-group.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_scrollNext,LYRA_DEFAULT_scrollPrevious}from"../../../internal/default-strings/layout.generated.js";function isInertChild(child){return isHtmlElement(child)&&child.inert}function isTabLabelSubtreeExcludedWithoutInert(element){if(element.hasAttribute("hidden")||element.getAttribute("aria-hidden")?.trim().toLowerCase()==="true")return!0;const rendered=element.ownerDocument.defaultView?.getComputedStyle(element);return rendered?.display==="none"||rendered?.contentVisibility==="hidden"}const SYNTHETIC_PANEL_PREFIX="lr-tab-",SCROLL_STEP_RATIO=.8;class LyraTabGroup extends LyraElement{constructor(){super(...arguments),this.active="",this.accessibleLabel=null,this.placement="top",this.activation="auto",this.withoutScrollControls=!1,this.noScrollControls=!1,this.fixedScrollControls=!1,this.tabs=[],this.focusedTab="",this.baseId=nextId("tab-group"),this.nextOpaqueId=0,this.idsBySlot=new Map,this.mutationObserverGeneration=0,this.projectedSourceSnapshots=new Map,this.projectedSlotSnapshots=new Map,this.projectedSourceObserverGeneration=0,this.rehomeTabFocus=!1,this.scrollStartAvailable=!1,this.scrollEndAvailable=!1,this.scrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part~="tablist"]'),()=>this.measureTabScrollEdges()),this.syncTabs=()=>{const children=Array.from(this.children);this.adoptProjectedSourceInertStates(),this.adoptProjectedSlotStates();const projectedSlots=new Set,next=this.readElementModel(children,projectedSlots);this.syncProjectedSlots(projectedSlots),this.syncProjectedSources(next);const liveSlots=new Set(next.map(tab=>tab.slotName));for(const slotName of this.idsBySlot.keys())liveSlots.has(slotName)||this.idsBySlot.delete(slotName);this.tabs=next},this.onTabListKeyDown=e=>{if(e.altKey||e.ctrlKey||e.metaKey||e.isComposing)return;const navigable=this.tabs.filter(t=>this.isNavigable(t));if(navigable.length===0)return;const origin=this.keyboardOriginTab(e,navigable),currentIndex=origin?navigable.indexOf(origin):-1;if(e.key==="Delete"){if(!origin?.element.closable)return;e.preventDefault(),origin.element.requestCloseFromOwner();return}if(this.activation==="manual"&&(e.key==="Enter"||e.key===" "||e.key==="Spacebar")){if(!origin)return;e.preventDefault(),this.activateTab(origin);return}const targetIndex=resolveListMove(e,{count:navigable.length,current:currentIndex,orientation:this.isVertical?"vertical":"horizontal",direction:this.effectiveDirection});if(targetIndex===null)return;e.preventDefault();const target=navigable[targetIndex];if(this.activation==="manual"){this.focusOnly(target);return}this.activateTab(target),this.focusTab(target.slotName)},this.onTabListScroll=()=>{this.measureTabScrollEdges()},this.onScrollControlMouseDown=event=>{event.preventDefault()},this.onScrollControlPointerDown=event=>{const control=event.currentTarget;control instanceof HTMLElement&&(control.setAttribute("data-pressed",""),control.setPointerCapture(event.pointerId))},this.onScrollControlPointerEnd=event=>{const control=event.currentTarget;control instanceof HTMLElement&&(control.removeAttribute("data-pressed"),control.hasPointerCapture(event.pointerId)&&control.releasePointerCapture(event.pointerId))}}static{this.defaultStrings={...super.defaultStrings,scrollNext:LYRA_DEFAULT_scrollNext,scrollPrevious:LYRA_DEFAULT_scrollPrevious}}static{this.styles=[LyraElement.styles,scrollOverflowFadeStyles,styles]}connectedCallback(){super.connectedCallback(),this.hasUpdated?this.syncTabs():this.seedFirstRenderState(this.syncTabs),this.resetMutationObserver();const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.mutationObserverGeneration,observer=new MutationObserverCtor(records=>{if(this.mutationObserver!==observer||this.mutationObserverDocument!==ownerDocument||this.mutationObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;const isDirectChild=node=>node.parentNode===this,isElementTabContent=node=>{let current=node.nodeType===1?node:node.parentElement;for(;current&¤t!==this;){if(current.localName===tag("tab")&¤t.parentNode===this)return!0;current=current.parentElement}return!1};records.some(record=>record.type==="childList"?record.target===this||isElementTabContent(record.target):record.type==="characterData"?isElementTabContent(record.target):record.attributeName==="inert"&&this.projectedSourceSnapshots.has(record.target)?!1:isDirectChild(record.target)||isElementTabContent(record.target))&&this.syncTabs()});this.mutationObserver=observer,this.mutationObserverDocument=ownerDocument,observer.observe(this,{childList:!0,subtree:!0,attributes:!0,characterData:!0,attributeFilter:["alt","aria-hidden","aria-label","aria-labelledby","class","closable","disabled","hidden","inert","id","label","name","open","panel","slot","style"]})}disconnectedCallback(){this.resetMutationObserver(),this.resetProjectedSourceObserver(),this.restoreProjectedSources(),this.restoreProjectedSlots(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetMutationObserver(),this.resetProjectedSourceObserver()}resetMutationObserver(){this.mutationObserverGeneration+=1,this.mutationObserver?.disconnect(),this.mutationObserver=void 0,this.mutationObserverDocument=void 0}readElementModel(children,projectedSlots){const seen=new Set,next=[],panelsByName=new Map;for(const child of children){if(child.localName!==tag("tab-panel"))continue;const name=child.getAttribute("name");name!==null&&!panelsByName.has(name)&&panelsByName.set(name,child)}const authoredNames=new Set(children.flatMap(child=>{if(child.localName===tag("tab")){const name=child.getAttribute("panel");return name?[name]:[]}if(child.localName===tag("tab-panel")){const name=child.getAttribute("name");return name?[name]:[]}return[]}));let index=0;for(const child of children){if(child.localName!==tag("tab"))continue;const authoredPanel=child.getAttribute("panel")||void 0;let slotName=authoredPanel??`${SYNTHETIC_PANEL_PREFIX}${index}`;if(!authoredPanel){let collision=0;for(;authoredNames.has(slotName)||seen.has(slotName);)collision+=1,slotName=`${SYNTHETIC_PANEL_PREFIX}${index}-${collision}`}if(index+=1,!authoredPanel&&!this.readElementLabel(child,{allowUnprojected:!0})||seen.has(slotName))continue;seen.add(slotName);const tabSlot=this.tabSlotName(slotName);this.projectSlot(child,tabSlot,projectedSlots);const visibleLabel=this.readElementLabel(child);if(!authoredPanel&&!visibleLabel)continue;const label=visibleLabel||slotName,panel=panelsByName.get(slotName);panel&&this.projectSlot(panel,slotName,projectedSlots),next.push({slotName,label,disabled:child.hasAttribute("disabled"),inert:isInertChild(child),element:child}),!this.active&&child.hasAttribute("active")&&(this.active=slotName)}return next}readElementLabel(tab,options={}){const labelNodes=Array.from(tab.childNodes).filter(node=>node.nodeType!==Node.ELEMENT_NODE||node.getAttribute("slot")===null||node.getAttribute("slot")==="");return composedAccessibilityText(labelNodes,{ancestorBoundary:tab,isSubtreeExcluded:element=>this.isTabLabelSubtreeExcluded(element),requireRendered:!options.allowUnprojected,skipRootAncestorValidation:options.allowUnprojected,ignoreInheritedVisibility:!0}).replace(/\s+/g," ").trim()}libraryOwnsSourceInert(element){return this.projectedSourceSnapshots.get(element)?.libraryOwnsInert===!0}isTabLabelSubtreeExcluded(element){return isTabLabelSubtreeExcludedWithoutInert(element)||element.hasAttribute("inert")&&!this.libraryOwnsSourceInert(element)}snapshotProjectedSource(source){const inert=source.getAttribute("inert");return{inert,appliedInert:inert,libraryOwnsInert:!1}}adoptProjectedSourceInert(source,snapshot){const current=source.getAttribute("inert");current!==snapshot.appliedInert&&(snapshot.inert=current,snapshot.libraryOwnsInert=!1)}makeProjectedSourceInert(source,snapshot){source.hasAttribute("inert")||(source.setAttribute("inert",""),snapshot.libraryOwnsInert=!0),snapshot.appliedInert=source.getAttribute("inert")}restoreProjectedSource(source,snapshot){this.adoptProjectedSourceInert(source,snapshot),snapshot.inert===null?source.removeAttribute("inert"):source.setAttribute("inert",snapshot.inert)}restoreProjectedSources(){for(const[source,snapshot]of this.projectedSourceSnapshots)this.restoreProjectedSource(source,snapshot);this.projectedSourceSnapshots.clear()}resetProjectedSourceObserver(){this.projectedSourceObserverGeneration+=1,this.projectedSourceObserver?.disconnect(),this.projectedSourceObserver=void 0,this.projectedSourceObserverDocument=void 0}observeProjectedSources(){this.resetProjectedSourceObserver();const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected||this.projectedSourceSnapshots.size===0)return;const generation=this.projectedSourceObserverGeneration,observer=new MutationObserverCtor(records=>{this.projectedSourceObserver!==observer||this.projectedSourceObserverDocument!==ownerDocument||this.projectedSourceObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||records.some(record=>this.projectedSourceSnapshots.has(record.target))&&this.syncTabs()});this.projectedSourceObserver=observer,this.projectedSourceObserverDocument=ownerDocument;for(const source of this.projectedSourceSnapshots.keys())observer.observe(source,{attributes:!0,attributeFilter:["inert"]})}projectedSources(tabs){const sources=new Set;for(const tab of tabs)for(const child of Array.from(tab.element.children))(child.getAttribute("slot")??"")===""&&sources.add(child);return sources}syncProjectedSources(tabs){const sources=this.projectedSources(tabs);for(const[source,snapshot]of this.projectedSourceSnapshots)this.adoptProjectedSourceInert(source,snapshot),sources.has(source)||(this.restoreProjectedSource(source,snapshot),this.projectedSourceSnapshots.delete(source));for(const source of sources){const snapshot=this.projectedSourceSnapshots.get(source)??this.snapshotProjectedSource(source);this.projectedSourceSnapshots.set(source,snapshot),this.adoptProjectedSourceInert(source,snapshot),this.makeProjectedSourceInert(source,snapshot)}this.observeProjectedSources()}adoptProjectedSourceInertStates(){for(const[source,snapshot]of this.projectedSourceSnapshots)this.adoptProjectedSourceInert(source,snapshot)}snapshotProjectedSlot(source){const slot=source.getAttribute("slot");return{slot,appliedSlot:slot,libraryOwnsSlot:!1}}adoptProjectedSlot(source,snapshot){const current=source.getAttribute("slot");current!==snapshot.appliedSlot&&(snapshot.slot=current,snapshot.libraryOwnsSlot=!1)}projectSlot(source,slot,projectedSlots){const snapshot=this.projectedSlotSnapshots.get(source)??this.snapshotProjectedSlot(source);this.projectedSlotSnapshots.set(source,snapshot),this.adoptProjectedSlot(source,snapshot),source.getAttribute("slot")!==slot&&(source.setAttribute("slot",slot),snapshot.libraryOwnsSlot=!0),snapshot.appliedSlot=source.getAttribute("slot"),projectedSlots.add(source)}restoreProjectedSlot(source,snapshot){this.adoptProjectedSlot(source,snapshot),snapshot.slot===null?source.removeAttribute("slot"):source.setAttribute("slot",snapshot.slot)}syncProjectedSlots(projectedSlots){for(const[source,snapshot]of this.projectedSlotSnapshots)projectedSlots.has(source)||(this.restoreProjectedSlot(source,snapshot),this.projectedSlotSnapshots.delete(source))}restoreProjectedSlots(){for(const[source,snapshot]of this.projectedSlotSnapshots)this.restoreProjectedSlot(source,snapshot);this.projectedSlotSnapshots.clear()}adoptProjectedSlotStates(){for(const[source,snapshot]of this.projectedSlotSnapshots)this.adoptProjectedSlot(source,snapshot)}isNavigable(tab){return!tab.disabled&&!tab.inert}willUpdate(changed){if(super.willUpdate(changed),!changed.has("tabs")&&!changed.has("active"))return;const focused=shadowFocusTarget(this),focusedSlot=focused?.getAttribute("part")==="tab"?focused.getAttribute("data-slot"):null;focusedSlot!==null&&!this.tabs.some(tab=>tab.slotName===focusedSlot&&this.isNavigable(tab))&&(this.rehomeTabFocus=!0,this.focusedTab=this.active);const current=this.tabs.find(t=>t.slotName===this.active);if(current&&this.isNavigable(current))return;this.rehomeTabFocus=this.rehomeTabFocus||focusedSlot!==null;const outgoing=this.active,before=changed.get("tabs")??this.tabs,at=this.hasUpdated&&changed.has("tabs")&&!changed.has("active")?before.findIndex(t=>t.slotName===outgoing):-1,renamed=at<0?void 0:this.tabs.find(t=>t.element===before[at].element&&this.isNavigable(t));let candidates=this.tabs;if(at>=0){const liveByName=new Map;for(const tab of this.tabs)liveByName.has(tab.slotName)||liveByName.set(tab.slotName,tab);candidates=[...before.slice(at+1),...before.slice(0,at).reverse()].map(tab=>liveByName.get(tab.slotName))}this.active=(renamed??candidates.find(t=>t&&this.isNavigable(t)))?.slotName??"",this.focusedTab=this.active,at>=0&&!renamed&&(this.emit("lr-tab-hide",{name:outgoing}),this.active&&this.emit("lr-tab-show",{name:this.active}))}updated(changed){super.updated(changed),(changed.has("active")||changed.has("tabs"))&&this.syncElementActiveState(),this.scrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="tab"]')),this.measureTabScrollEdges(),this.rehomeTabFocus&&(this.rehomeTabFocus=!1,this.renderRoot.querySelector('[part="tab"][tabindex="0"]')?.focus())}selectTab(tab){if(!this.isNavigable(tab)||tab.slotName===this.active)return;const previous=this.active;this.active=tab.slotName,this.focusedTab=tab.slotName,previous&&this.emit("lr-tab-hide",{name:previous}),this.emit("lr-tab-show",{name:tab.slotName})}activateTab(tab){this.isNavigable(tab)&&(this.selectTab(tab),this.emit("lr-activate",{value:tab.slotName}))}show(panel){const tab=this.tabs.find(candidate=>candidate.slotName===panel);tab&&this.selectTab(tab)}syncElementActiveState(){const definitions=new Map;for(const tab of this.tabs)definitions.has(tab.element)||definitions.set(tab.element,tab);for(const child of Array.from(this.children))if(child.localName===tag("tab")){const definition=definitions.get(child);child.toggleAttribute("active",definition?.slotName===this.active)}else child.localName===tag("tab-panel")&&child.toggleAttribute("active",child.getAttribute("name")===this.active)}focusOnly(tab){this.focusedTab=tab.slotName,this.focusTab(tab.slotName)}get rovingTab(){if(this.activation!=="manual")return this.active;const candidate=this.tabs.find(t=>t.slotName===this.focusedTab&&this.isNavigable(t));return candidate?candidate.slotName:this.active}keyboardOriginTab(event,navigable){const eventButton=event.composedPath().find(candidate=>candidate.nodeType===1&&candidate.getAttribute?.("part")==="tab"&&candidate.getRootNode()===this.renderRoot),focused=shadowFocusTarget(this),owned=(eventButton??(focused?.getAttribute("part")==="tab"?focused:void 0))?.dataset.slot;return navigable.find(tab=>tab.slotName===owned)??navigable.find(tab=>tab.slotName===this.rovingTab)}focusTab(slotName){const buttons=this.renderRoot.querySelectorAll('[part="tab"]');for(const button of Array.from(buttons))if(button.dataset.slot===slotName){button.focus();return}}get isVertical(){return this.placement==="start"||this.placement==="end"}tabId(slotName){return this.idsFor(slotName).tab}panelId(slotName){return this.idsFor(slotName).panel}idsFor(slotName){const existing=this.idsBySlot.get(slotName);if(existing)return existing;const token=`${this.baseId}-${this.nextOpaqueId++}`,ids={tab:`${token}-tab`,panel:`${token}-panel`};return this.idsBySlot.set(slotName,ids),ids}tabSlotName(slotName){return`${slotName}-tab`}get scrollControlsSuppressed(){return this.withoutScrollControls||this.noScrollControls}measureTabScrollEdges(){const tablist=this.renderRoot.querySelector('[part~="tablist"]');if(!tablist||this.isVertical){this.setTabScrollEdges(!1,!1,tablist);return}const maximum=Math.max(0,tablist.scrollWidth-tablist.clientWidth),position=Math.max(0,Math.min(maximum,this.effectiveDirection==="rtl"?-tablist.scrollLeft:tablist.scrollLeft));this.setTabScrollEdges(position>1,position<maximum-1,tablist)}setTabScrollEdges(start,end,tablist){tablist?.toggleAttribute("data-scroll-start",start),tablist?.toggleAttribute("data-scroll-end",end),!(start===this.scrollStartAvailable&&end===this.scrollEndAvailable)&&(this.scrollStartAvailable=start,this.scrollEndAvailable=end)}scrollTabs(edge){const tablist=this.renderRoot.querySelector('[part~="tablist"]');if(!tablist||!isHtmlElement(tablist)||typeof tablist.scrollBy!="function")return;const step=Math.max(1,tablist.clientWidth*SCROLL_STEP_RATIO),towardEnd=edge==="end"?1:-1,physical=this.effectiveDirection==="rtl"?-towardEnd:towardEnd;tablist.scrollBy({left:step*physical,behavior:prefersReducedMotion(this)?"instant":"smooth"})}renderScrollControl(edge){if(this.isVertical||this.scrollControlsSuppressed)return nothing;const available=edge==="start"?this.scrollStartAvailable:this.scrollEndAvailable;return html`<button
|
|
2
2
|
type="button"
|
|
3
3
|
part=${edge==="start"?"scroll-button scroll-button__base scroll-button-start scroll-button--start":"scroll-button scroll-button__base scroll-button-end scroll-button--end"}
|
|
4
4
|
tabindex="-1"
|
|
@@ -25,7 +25,7 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
25
25
|
<path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>
|
|
26
26
|
<line x1="12" y1="19" x2="12" y2="23"></line>
|
|
27
27
|
<line x1="8" y1="23" x2="16" y2="23"></line>
|
|
28
|
-
`)}const CAPABILITY_META={files:{icon:paperclipIcon,triggerKey:"attachmentTriggerFiles",menuKey:"attachmentMenuFiles"},image:{icon:imageIcon,triggerKey:"attachmentTriggerImage",menuKey:"attachmentMenuImage"},camera:{icon:cameraIcon,triggerKey:"attachmentTriggerCamera",menuKey:"attachmentMenuCamera"},audio:{icon:audioIcon,triggerKey:"attachmentTriggerAudio",menuKey:"attachmentMenuAudio"}},OWNED_CAPABILITY_SNAPSHOTS=new WeakSet;function ownCapabilitySnapshot(values){const snapshot=Object.freeze(values);return OWNED_CAPABILITY_SNAPSHOTS.add(snapshot),snapshot}const DEFAULT_CAPABILITIES=ownCapabilitySnapshot(["files"]),MAX_ATTACHMENT_CAPABILITIES=4,ATTACHMENT_CAPABILITY_SCAN_LIMIT=64;function normalizeCapabilities(value){try{if(!Array.isArray(value))return DEFAULT_CAPABILITIES;if(OWNED_CAPABILITY_SNAPSHOTS.has(value))return value;const normalized=[],length=Math.min(value.length,ATTACHMENT_CAPABILITY_SCAN_LIMIT);for(let index=0;index<length&&normalized.length<MAX_ATTACHMENT_CAPABILITIES;index++){const candidate=value[index];typeof candidate=="string"&&Object.prototype.hasOwnProperty.call(CAPABILITY_META,candidate)&&!normalized.includes(candidate)&&normalized.push(candidate)}return ownCapabilitySnapshot(normalized)}catch{return DEFAULT_CAPABILITIES}}function isCanonicalCapabilitySnapshot(source){try{return typeof source=="object"&&source!==null&&OWNED_CAPABILITY_SNAPSHOTS.has(source)}catch{return!1}}class LyraAttachmentTrigger extends LyraElement{constructor(){super(...arguments),this.capabilities=DEFAULT_CAPABILITIES,this.accept="",this.hostAccessibleLabel=null,this.multiple=!1,this.disabled=!1,this.appearance="plain",this.size="m",this.descriptionSyncGeneration=0,this.hasSyncedDescribedByElements=!1,this.pendingCapability="files",this.pickerGeneration=0,this.pendingPickerGeneration=-1,this.onTriggerClick=()=>{const capability=this.effectiveCapabilities[0];capability!==void 0&&this.activateCapability(capability)},this.onMenuSelect=e=>{e.stopPropagation();const capability=e.detail.item.value;Object.prototype.hasOwnProperty.call(CAPABILITY_META,capability)&&this.effectiveCapabilities.includes(capability)&&this.activateCapability(capability)},this.onInputChange=e=>{e.stopPropagation();const input=e.target,selected=input.files,generation=this.pendingPickerGeneration;if(this.pendingPickerGeneration=-1,this.isConnected&&generation===this.pickerGeneration&&!this.disabled&&selected&&selected.length>0){const accept=this.effectiveAccept(this.pendingCapability),files=Array.from(selected),matching=files.filter(file=>matchesAccept(file,accept));this.emit("lr-files",{capability:this.pendingCapability,files:matching,rejected:files.filter(file=>!
|
|
28
|
+
`)}const CAPABILITY_META={files:{icon:paperclipIcon,triggerKey:"attachmentTriggerFiles",menuKey:"attachmentMenuFiles"},image:{icon:imageIcon,triggerKey:"attachmentTriggerImage",menuKey:"attachmentMenuImage"},camera:{icon:cameraIcon,triggerKey:"attachmentTriggerCamera",menuKey:"attachmentMenuCamera"},audio:{icon:audioIcon,triggerKey:"attachmentTriggerAudio",menuKey:"attachmentMenuAudio"}},OWNED_CAPABILITY_SNAPSHOTS=new WeakSet;function ownCapabilitySnapshot(values){const snapshot=Object.freeze(values);return OWNED_CAPABILITY_SNAPSHOTS.add(snapshot),snapshot}const DEFAULT_CAPABILITIES=ownCapabilitySnapshot(["files"]),MAX_ATTACHMENT_CAPABILITIES=4,ATTACHMENT_CAPABILITY_SCAN_LIMIT=64;function normalizeCapabilities(value){try{if(!Array.isArray(value))return DEFAULT_CAPABILITIES;if(OWNED_CAPABILITY_SNAPSHOTS.has(value))return value;const normalized=[],length=Math.min(value.length,ATTACHMENT_CAPABILITY_SCAN_LIMIT);for(let index=0;index<length&&normalized.length<MAX_ATTACHMENT_CAPABILITIES;index++){const candidate=value[index];typeof candidate=="string"&&Object.prototype.hasOwnProperty.call(CAPABILITY_META,candidate)&&!normalized.includes(candidate)&&normalized.push(candidate)}return ownCapabilitySnapshot(normalized)}catch{return DEFAULT_CAPABILITIES}}function isCanonicalCapabilitySnapshot(source){try{return typeof source=="object"&&source!==null&&OWNED_CAPABILITY_SNAPSHOTS.has(source)}catch{return!1}}class LyraAttachmentTrigger extends LyraElement{constructor(){super(...arguments),this.capabilities=DEFAULT_CAPABILITIES,this.accept="",this.hostAccessibleLabel=null,this.multiple=!1,this.disabled=!1,this.appearance="plain",this.size="m",this.descriptionSyncGeneration=0,this.hasSyncedDescribedByElements=!1,this.pendingCapability="files",this.pickerGeneration=0,this.pendingPickerGeneration=-1,this.onTriggerClick=()=>{const capability=this.effectiveCapabilities[0];capability!==void 0&&this.activateCapability(capability)},this.onMenuSelect=e=>{e.stopPropagation();const capability=e.detail.item.value;Object.prototype.hasOwnProperty.call(CAPABILITY_META,capability)&&this.effectiveCapabilities.includes(capability)&&this.activateCapability(capability)},this.onInputChange=e=>{e.stopPropagation();const input=e.target,selected=input.files,generation=this.pendingPickerGeneration;if(this.pendingPickerGeneration=-1,this.isConnected&&generation===this.pickerGeneration&&!this.disabled&&selected&&selected.length>0){const accept=this.effectiveAccept(this.pendingCapability),files=Array.from(selected),matching=files.filter(file=>matchesAccept(file,accept)),matchingFiles=new Set(matching);this.emit("lr-files",{capability:this.pendingCapability,files:matching,rejected:files.filter(file=>!matchingFiles.has(file)).map(file=>({file,reason:"type"})),remainingFiles:null,remainingTotalSize:null})}input.value=""},this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,attachmentAdd:LYRA_DEFAULT_attachmentAdd,attachmentMenuAudio:LYRA_DEFAULT_attachmentMenuAudio,attachmentMenuCamera:LYRA_DEFAULT_attachmentMenuCamera,attachmentMenuFiles:LYRA_DEFAULT_attachmentMenuFiles,attachmentMenuImage:LYRA_DEFAULT_attachmentMenuImage,attachmentTriggerAudio:LYRA_DEFAULT_attachmentTriggerAudio,attachmentTriggerCamera:LYRA_DEFAULT_attachmentTriggerCamera,attachmentTriggerFiles:LYRA_DEFAULT_attachmentTriggerFiles,attachmentTriggerImage:LYRA_DEFAULT_attachmentTriggerImage,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["capabilities"])}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.immutableEventDetails=Object.freeze(["lr-files"])}get triggerEl(){return this.composedTriggerEl?.control??this.composedTriggerEl}get effectiveCapabilities(){return normalizeCapabilities(this.capabilities)}get hasFileCapability(){return this.effectiveCapabilities.includes("files")||this.effectiveCapabilities.includes("image")}willUpdate(changed){if(super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.dropdownEl?.hide(),changed.has("capabilities")){const normalized=normalizeCapabilities(this.capabilities);isCanonicalCapabilitySnapshot(this.capabilities)||(this.capabilities=normalized)}}updated(changed){super.updated(changed),this.syncTriggerDescription();const composed=this.composedTriggerEl;if(!composed||composed.control)return;const generation=++this.descriptionSyncGeneration;composed.updateComplete.then(()=>{generation!==this.descriptionSyncGeneration||!this.isConnected||this.syncTriggerDescription()})}syncTriggerDescription(){const hostDescribedBy=this.getAttribute("aria-describedby");!hostDescribedBy&&!this.hasSyncedDescribedByElements||(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.triggerEl,hostDescribedBy))}effectiveAccept(capability){return capability==="image"?this.accept||"image/*":this.accept}activateCapability(capability){if(this.disabled)return;if(capability==="camera"){this.emit("lr-camera-request",null);return}if(capability==="audio"){this.emit("lr-audio-request",null);return}this.pendingCapability=capability,this.pendingPickerGeneration=++this.pickerGeneration;const input=this.inputEl;input&&(input.accept=this.effectiveAccept(capability),input.click())}disconnectedCallback(){this.pendingPickerGeneration=-1,this.pickerGeneration++,this.dropdownEl?.hide(),super.disconnectedCallback()}primaryControl(){return this.renderRoot.querySelector('[part="trigger"], [part="menu-trigger"]')??void 0}focus(options){this.primaryControl()?.focus(options)}blur(){this.primaryControl()?.blur()}click(){this.primaryControl()?.click()}renderHiddenInput(){return html`
|
|
29
29
|
<input
|
|
30
30
|
part="hidden-input"
|
|
31
31
|
type="file"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController}from"../../../internal/form-control-controller.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{DropSessionController,isFileValue,readFileList}from"../../../internal/drop-session-controller.js";import{falseDefaultBooleanConverter}from"../../../internal/converters.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{classifyFiles,EMPTY_MIME_TYPES,freezeDetail,handleDrop,mimeTypeFilter,outcomeText,snapshotMimeTypes}from"./file-intake.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize,localizedNumberLabel}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedMaxFiles,LYRA_DEFAULT_fileInputRejectedMaxTotalSize,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}import{DEFAULT_MAX_FILE_SIZE_BYTES,DEFAULT_MAX_FILES,DEFAULT_MAX_TOTAL_SIZE_BYTES}from"./file-intake.js";const MAX_DROPPED_FOLDER_ENTRIES=1e4,INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}class LyraFileInput extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedMaxFiles:LYRA_DEFAULT_fileInputRejectedMaxFiles,fileInputRejectedMaxTotalSize:LYRA_DEFAULT_fileInputRejectedMaxTotalSize,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-files","lr-input","lr-change"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["value"]),"lr-change":Object.freeze(["value"])})}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){if(next===this.inputs.allowed)return;this.inputs.allowed=next;const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){if(next===this.inputs.forbidden)return;this.inputs.forbidden=next;const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.accept="",this.capture="",this.inputs={},this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.maxFiles=0,this.maxTotalSize=0,this.heldFileCount=0,this.heldTotalSize=0,this.nonRetaining=!1,this.valuePresent=!1,this.directory=!1,this.withoutPaste=!1,this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.hostAccessibleLabel=null,this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.hasSyncedDescribedByElements=!1,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.markInteracted=()=>{this.touched||(this.touched=!0,this.updateValidity(),this.publishCustomStates())},this.onDragEnter=e=>this.dropSession.onDragEnter(e),this.onDragOver=e=>this.dropSession.onDragOver(e),this.onDragLeave=e=>this.dropSession.onDragLeave(e),this.onDrop=e=>handleDrop(this,this.dropSession,e,this.effectiveMultiple,(files,rejected)=>this.emitFiles(files,rejected)),this.onPaste=e=>{if(this.withoutPaste||this.liveDisabled)return;const files=readFileList(e.clipboardData?.files);files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,this.internals.setFormValue(null),this.dropSession=new DropSessionController(this,{isDisabled:()=>this.liveDisabled,previewRejects:items=>this.classify(items,!0).rejected.length>0,onStateChange:()=>{this.dragState=this.dropSession.state,this.publishCustomStates()}})}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){if(next===this.inputs.files)return;this.inputs.files=next;const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=[...valid];const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.dropSession.reset(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory")||changed.has("files"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files.slice(0,1):this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.disconnectValidatorAttributeObserver(),this.dropSession.reset();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),(changed.has("valuePresent")||changed.has("nonRetaining"))&&this.updateValidity();const hostDescribedBy=this.getAttribute("aria-describedby");(hostDescribedBy||this.hasSyncedDescribedByElements)&&(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.baseEl,hostDescribedBy)),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of validators){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&!this.hasEffectiveValue&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}get hasEffectiveValue(){return this._files.length>0||this.nonRetaining&&this.valuePresent}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",!this.hasEffectiveValue),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.dropSession.reset(),this.updateValidity(),this.requestUpdate())}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!this._files.includes(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}classify(fileList,isPreview=!1){const multiple=this.effectiveMultiple;return classifyFiles(this,fileList,multiple,this.nonRetaining||!multiple?[]:this._files,isPreview,mimeTypeFilter(this.allowedMimeTypes,this.forbiddenMimeTypes))}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename});case"maxFiles":return this.localize("fileInputRejectedMaxFiles",void 0,{filename});case"maxTotalSize":return this.localize("fileInputRejectedMaxTotalSize",void 0,{filename})}}outcomeMessage(key,override,count){return outcomeText(override,()=>this.localize(key,void 0,{count}),count)}emitFiles(fileList,additionalRejected=[]){const detail=freezeDetail(this.classify(fileList),additionalRejected),{files,rejected}=detail;this.rejectedFiles=rejected;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);if(files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length){this.nonRetaining||(this.files=this.effectiveMultiple?[...this._files,...files]:files);const value=Object.freeze([...this._files]);emitValueEvents(this,"input",{value},detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",{value},detail2=>this.emit("lr-change",detail2))}this.emit("lr-files",detail)}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get dropzoneInstruction(){return this.localize("fileInputDefaultLabel")}removeFile(index){if(this.liveDisabled||index<0||index>=this._files.length)return;this.touched=!0;const hadFocus=shadowFocusTarget(this)?.matches('[part="remove-button"]');this.files=this._files.filter((_,candidate)=>candidate!==index);const value=Object.freeze([...this._files]);emitValueEvents(this,"input",{value},detail=>this.emit("lr-input",detail)),emitValueEvents(this,"change",{value},detail=>this.emit("lr-change",detail)),hadFocus&&this.updateComplete.then(()=>{const buttons=this.renderRoot.querySelectorAll('[part="remove-button"]');(buttons[Math.min(index,buttons.length-1)]??this.baseEl)?.focus()})}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),localizedNumberLabel(this.effectiveLocale))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
|
|
1
|
+
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController}from"../../../internal/form-control-controller.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{DropSessionController,isFileValue,readFileList}from"../../../internal/drop-session-controller.js";import{falseDefaultBooleanConverter}from"../../../internal/converters.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{classifyFiles,EMPTY_MIME_TYPES,freezeDetail,handleDrop,mimeTypeFilter,outcomeText,snapshotMimeTypes}from"./file-intake.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize,localizedNumberLabel}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedMaxFiles,LYRA_DEFAULT_fileInputRejectedMaxTotalSize,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}import{DEFAULT_MAX_FILE_SIZE_BYTES,DEFAULT_MAX_FILES,DEFAULT_MAX_TOTAL_SIZE_BYTES}from"./file-intake.js";const MAX_DROPPED_FOLDER_ENTRIES=1e4,INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}class LyraFileInput extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedMaxFiles:LYRA_DEFAULT_fileInputRejectedMaxFiles,fileInputRejectedMaxTotalSize:LYRA_DEFAULT_fileInputRejectedMaxTotalSize,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-files","lr-input","lr-change"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["value"]),"lr-change":Object.freeze(["value"])})}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){if(next===this.inputs.allowed)return;this.inputs.allowed=next;const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){if(next===this.inputs.forbidden)return;this.inputs.forbidden=next;const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.accept="",this.capture="",this.inputs={},this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.maxFiles=0,this.maxTotalSize=0,this.heldFileCount=0,this.heldTotalSize=0,this.nonRetaining=!1,this.valuePresent=!1,this.directory=!1,this.withoutPaste=!1,this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.hostAccessibleLabel=null,this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.hasSyncedDescribedByElements=!1,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.markInteracted=()=>{this.touched||(this.touched=!0,this.updateValidity(),this.publishCustomStates())},this.onDragEnter=e=>this.dropSession.onDragEnter(e),this.onDragOver=e=>this.dropSession.onDragOver(e),this.onDragLeave=e=>this.dropSession.onDragLeave(e),this.onDrop=e=>handleDrop(this,this.dropSession,e,this.effectiveMultiple,(files,rejected)=>this.emitFiles(files,rejected)),this.onPaste=e=>{if(this.withoutPaste||this.liveDisabled)return;const files=readFileList(e.clipboardData?.files);files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,this.internals.setFormValue(null),this.dropSession=new DropSessionController(this,{isDisabled:()=>this.liveDisabled,previewRejects:items=>this.classify(items,!0).rejected.length>0,onStateChange:()=>{this.dragState=this.dropSession.state,this.publishCustomStates()}})}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){if(next===this.inputs.files)return;this.inputs.files=next;const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=[...valid];const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.dropSession.reset(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory")||changed.has("files"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files.slice(0,1):this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.disconnectValidatorAttributeObserver(),this.dropSession.reset();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),(changed.has("valuePresent")||changed.has("nonRetaining"))&&this.updateValidity();const hostDescribedBy=this.getAttribute("aria-describedby");(hostDescribedBy||this.hasSyncedDescribedByElements)&&(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.baseEl,hostDescribedBy)),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of validators){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&!this.hasEffectiveValue&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}get hasEffectiveValue(){return this._files.length>0||this.nonRetaining&&this.valuePresent}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",!this.hasEffectiveValue),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.dropSession.reset(),this.updateValidity(),this.requestUpdate())}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function",retainedFiles=new Set(this._files);let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!retainedFiles.has(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}classify(fileList,isPreview=!1){const multiple=this.effectiveMultiple;return classifyFiles(this,fileList,multiple,this.nonRetaining||!multiple?[]:this._files,isPreview,mimeTypeFilter(this.allowedMimeTypes,this.forbiddenMimeTypes))}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename});case"maxFiles":return this.localize("fileInputRejectedMaxFiles",void 0,{filename});case"maxTotalSize":return this.localize("fileInputRejectedMaxTotalSize",void 0,{filename})}}outcomeMessage(key,override,count){return outcomeText(override,()=>this.localize(key,void 0,{count}),count)}emitFiles(fileList,additionalRejected=[]){const detail=freezeDetail(this.classify(fileList),additionalRejected),{files,rejected}=detail;this.rejectedFiles=rejected;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);if(files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length){this.nonRetaining||(this.files=this.effectiveMultiple?[...this._files,...files]:files);const value=Object.freeze([...this._files]);emitValueEvents(this,"input",{value},detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",{value},detail2=>this.emit("lr-change",detail2))}this.emit("lr-files",detail)}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get dropzoneInstruction(){return this.localize("fileInputDefaultLabel")}removeFile(index){if(this.liveDisabled||index<0||index>=this._files.length)return;this.touched=!0;const hadFocus=shadowFocusTarget(this)?.matches('[part="remove-button"]');this.files=this._files.filter((_,candidate)=>candidate!==index);const value=Object.freeze([...this._files]);emitValueEvents(this,"input",{value},detail=>this.emit("lr-input",detail)),emitValueEvents(this,"change",{value},detail=>this.emit("lr-change",detail)),hadFocus&&this.updateComplete.then(()=>{const buttons=this.renderRoot.querySelectorAll('[part="remove-button"]');(buttons[Math.min(index,buttons.length-1)]??this.baseEl)?.focus()})}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),localizedNumberLabel(this.effectiveLocale))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
|
|
2
2
|
<span part="file-thumbnail" aria-hidden="true">
|
|
3
3
|
${thumbnail?html`<img part="file-image" src=${thumbnail} alt="" />`:html`<span part="file-icon">${fileIcon()}</span>`}
|
|
4
4
|
</span>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{formatMediaTime}from"../../../internal/media-time.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{finiteRange}from"../../../internal/numbers.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{tag}from"../../../internal/prefix.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./video-playlist.styles.js";import{LYRA_DEFAULT_videoPlaylistLabel,LYRA_DEFAULT_videoPlaylistUntitled}from"../../../internal/default-strings/media.generated.js";function safeControls(value){return value==="none"||value==="standard"?value:"full"}function safeRepeat(value){return value==="one"||value==="all"?value:"none"}function sameVideos(left,right){return left.length===right.length&&left.every((video,index)=>video===right[index])}function sourceSnapshot(src,type,media){return{src,type,media}}function trackSnapshot(src,kind,srclang,label,isDefault){return{src,kind,srclang,label,default:isDefault}}class LyraVideoPlaylist extends LyraElement{constructor(){super(...arguments),this.controls="full",this.iconLibrary="system",this.withoutAutoAdvance=!1,this.repeat="none",this.items=[],this.playlistVideos=[],this.liveChildrenReady=!1,this.activeIndex=-1,this.navigationIndex=-1,this.listeners=new Map,this.lastKnownPlaying=new WeakMap,this.nativeVideos=new WeakMap,this.needsReload=new WeakSet,this.ownedVideoState=new WeakMap,this.preferences={},this.activationGeneration=0,this.reconcileGeneration=0,this.onSlotChange=()=>this.reconcileChildren(),this.onItemFocus=event=>{relayNativeEvent(this,event)},this.onItemBlur=event=>{relayNativeEvent(this,event)}}static{this.defaultStrings={...super.defaultStrings,videoPlaylistLabel:LYRA_DEFAULT_videoPlaylistLabel,videoPlaylistUntitled:LYRA_DEFAULT_videoPlaylistUntitled}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-video-change"])}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.observeChildren(),this.hasUpdated?this.scheduleAfterUpdate(()=>this.reconcileChildren(),"video-playlist-reconcile"):this.seedFirstRenderState(()=>{this.directVideos().length>0&&this.reconcileChildren()})}disconnectedCallback(){this.activationGeneration+=1,this.reconcileGeneration+=1,this.pendingPlay=void 0,this.mutationObserver?.disconnect(),this.mutationObserver=void 0;for(const video of this.playlistVideos)this.unbindVideo(video),video.hidden=!0,this.pauseAndUnload(video);super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed),changed.has("controls")&&(this.controls=safeControls(this.controls)),changed.has("repeat")&&(this.repeat=safeRepeat(this.repeat)),(changed.has("controls")||changed.has("iconLibrary"))&&this.scheduleAfterUpdate(()=>this.reconcileChildren(),"video-playlist-reconcile")}observeChildren(){this.mutationObserver?.disconnect(),this.mutationObserver=void 0;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;MutationObserverCtor&&(this.mutationObserver=new MutationObserverCtor(()=>{this.scheduleAfterUpdate(()=>{this.reconcileChildren(),this.requestUpdate()},"video-playlist-reconcile")}),this.mutationObserver.observe(this,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["default","inert","kind","label","media","poster","src","srclang","title","type"]}))}directVideos(){const videoTag=tag("video");return[...this.children].filter(child=>child.localName===videoTag)}isEnabled(video){return!video.inert}nearestEnabledIndex(videos,preferred){if(!videos.length)return-1;const start=Math.min(Math.max(preferred,0),videos.length-1);for(let index=start;index<videos.length;index+=1)if(this.isEnabled(videos[index]))return index;for(let index=start-1;index>=0;index-=1)if(this.isEnabled(videos[index]))return index;return-1}reconcileChildren(){if(!this.isConnected)return;const previousVideos=this.playlistVideos,previousActive=this.activeVideo,previousIndex=this.activeIndex,previousNavigation=previousVideos[this.navigationIndex],navigationHadFocus=shadowFocusTarget(this)?.getAttribute("part")==="playlist-item",videos=this.directVideos();(videos.length>0||this.liveChildrenReady)&&(this.liveChildrenReady=!0);let active=previousActive&&videos.includes(previousActive)&&this.isEnabled(previousActive)?previousActive:void 0,nextIndex=active?videos.indexOf(active):this.nearestEnabledIndex(videos,previousIndex);!active&&nextIndex>=0&&(active=videos[nextIndex]),active||(nextIndex=-1);const activeChanged=active!==previousActive,outgoingWasRemoved=!!(previousActive&&!videos.includes(previousActive)),resumePlayback=activeChanged&&previousActive?outgoingWasRemoved?this.lastKnownPlaying.get(previousActive)??previousActive.getState().playing:previousActive.getState().playing:!1,outgoingPreferences=activeChanged&&previousActive?outgoingWasRemoved?this.capturePreferences(previousActive,this.nativeVideos.get(previousActive)):this.capturePreferences(previousActive):void 0;for(const video of previousVideos)videos.includes(video)||this.releaseVideo(video);for(const video of videos)this.claimVideo(video),this.bindVideo(video);activeChanged&&previousActive?(this.preferences=outgoingPreferences??{},outgoingWasRemoved||this.pauseAndUnload(previousActive),this.activationGeneration+=1):activeChanged&&(this.activationGeneration+=1),this.activeVideo=active,this.activeIndex=nextIndex,sameVideos(previousVideos,videos)||(this.playlistVideos=videos);for(const video of videos){video.controls!==this.controls&&(video.controls=this.controls),video.iconLibrary!==this.iconLibrary&&(video.iconLibrary=this.iconLibrary);const isActive=video===active;video.hidden=!isActive,isActive||this.pauseAndUnload(video)}active?(activeChanged||this.needsReload.has(active))&&this.activateVideo(active,resumePlayback,this.activationGeneration):this.pendingPlay=void 0;const keptNavigation=previousNavigation&&videos.includes(previousNavigation)&&this.isEnabled(previousNavigation)?videos.indexOf(previousNavigation):-1;this.navigationIndex=keptNavigation>=0?keptNavigation:nextIndex,navigationHadFocus&&keptNavigation<0&&this.navigationIndex>=0&&this.focusItem(this.navigationIndex),activeChanged&&previousActive&&this.emitChange(previousIndex,nextIndex,active??null),this.scheduleChildrenReady(videos)}scheduleChildrenReady(videos){const reconcileGeneration=++this.reconcileGeneration;Promise.all(videos.map(video=>video.updateComplete)).then(()=>{if(!this.isConnected||reconcileGeneration!==this.reconcileGeneration)return;for(const video of this.playlistVideos)this.rememberNativeVideo(video);for(const video of this.playlistVideos)video!==this.activeVideo&&this.pauseAndUnload(video);const active=this.activeVideo;if(!active||!this.needsReload.has(active))return;const shouldPlay=this.pendingPlay?.video===active&&this.pendingPlay.generation===this.activationGeneration;this.activateVideo(active,shouldPlay,this.activationGeneration)})}bindVideo(video){if(this.listeners.has(video))return;const listeners={ended:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!1),this.handleCompletion(video)},error:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!1)},loadedmetadata:()=>{this.rememberNativeVideo(video),this.handleLoadedMetadata(video)},pause:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!1)},play:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!0),video!==this.activeVideo&&this.pauseAndUnload(video)}};this.lastKnownPlaying.set(video,video.getState().playing),this.rememberNativeVideo(video),this.listeners.set(video,listeners),video.addEventListener("ended",listeners.ended),video.addEventListener("error",listeners.error),video.addEventListener("loadedmetadata",listeners.loadedmetadata),video.addEventListener("pause",listeners.pause),video.addEventListener("play",listeners.play)}unbindVideo(video){const listeners=this.listeners.get(video);listeners&&(video.removeEventListener("ended",listeners.ended),video.removeEventListener("error",listeners.error),video.removeEventListener("loadedmetadata",listeners.loadedmetadata),video.removeEventListener("pause",listeners.pause),video.removeEventListener("play",listeners.play),this.listeners.delete(video))}claimVideo(video){this.ownedVideoState.has(video)||this.ownedVideoState.set(video,{controls:video.controls,iconLibrary:video.iconLibrary,hidden:!!video.hidden})}releaseVideo(video){const authored=this.ownedVideoState.get(video);this.unbindVideo(video),this.pauseAndUnload(video),authored&&(video.controls=authored.controls,video.iconLibrary=authored.iconLibrary,video.hidden=authored.hidden,this.ownedVideoState.delete(video),video.isConnected&&video.load())}rememberNativeVideo(video){const native=video.getVideoElement();native&&this.nativeVideos.set(video,native)}pauseAndUnload(video){video.pause(),video.hidden=!0,this.needsReload.add(video),video.unloadMedia()}activateVideo(video,shouldPlay,generation){if(video.hidden=!1,!video.getVideoElement()){this.needsReload.add(video),shouldPlay&&(this.pendingPlay={video,generation});return}if(this.rememberNativeVideo(video),video.load(),this.needsReload.delete(video),this.applyPreferences(video,this.preferences),!shouldPlay){this.pendingPlay?.video===video&&(this.pendingPlay=void 0);return}this.pendingPlay=void 0,video.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo})}capturePreferences(video,native=video.getVideoElement()){return video.captureMediaPreferences(native)}applyPreferences(video,preferences){video.applyMediaPreferences(preferences)}handleLoadedMetadata(video){video===this.activeVideo&&(this.applyPreferences(video,this.preferences),this.requestUpdate())}handleCompletion(video){if(video!==this.activeVideo||this.withoutAutoAdvance)return;if(this.repeat==="one"){video.seek(0);const generation=this.activationGeneration;video.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo});return}const nextIndex=this.nearestEnabledIndex(this.playlistVideos,this.activeIndex+1);if(nextIndex>this.activeIndex){this.switchTo(nextIndex,!0);return}if(this.repeat==="all"){const first=this.nearestEnabledIndex(this.playlistVideos,0);if(first>=0&&first!==this.activeIndex)this.switchTo(first,!0);else if(first===this.activeIndex){video.seek(0);const generation=this.activationGeneration;video.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo})}}}snapshotVideo(video){const sources=[],directSrc=video.src.trim();directSrc&&sources.push(sourceSnapshot(directSrc,"",""));const tracks=[];for(const child of video.children)if(child.localName==="source"){const src=child.getAttribute("src")?.trim()??"";src&&sources.push(sourceSnapshot(src,child.getAttribute("type")??"",child.getAttribute("media")??""))}else if(child.localName==="track"){const src=child.getAttribute("src")?.trim()??"";src&&tracks.push(trackSnapshot(src,child.getAttribute("kind")??"",child.getAttribute("srclang")??"",child.getAttribute("label")??"",child.hasAttribute("default")))}return{title:video.title,poster:video.poster,sources,tracks}}emitChange(previousIndex,currentIndex,video){this.emit("lr-video-change",{previousIndex,currentIndex,video:video?this.snapshotVideo(video):null})}switchTo(index,forcePlay=!1){const incoming=this.playlistVideos[index];if(!incoming||!this.isEnabled(incoming))return;const previousIndex=this.activeIndex,outgoing=this.activeVideo;if(incoming===outgoing){if(this.navigationIndex=index,this.requestUpdate(),forcePlay){const generation=this.activationGeneration;incoming.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo})}this.emitChange(previousIndex,index,incoming);return}const wasPlaying=forcePlay||!!outgoing?.getState().playing;outgoing&&(this.preferences=this.capturePreferences(outgoing),this.pauseAndUnload(outgoing)),this.activationGeneration+=1,this.activeVideo=incoming,this.activeIndex=index,this.navigationIndex=index;for(const video of this.playlistVideos){const isActive=video===incoming;video.hidden=!isActive,!isActive&&video!==outgoing&&this.pauseAndUnload(video)}this.activateVideo(incoming,wasPlaying,this.activationGeneration),this.requestUpdate(),this.emitChange(previousIndex,index,incoming)}goTo(index){!Number.isFinite(index)||!Number.isInteger(index)||index<0||index>=this.playlistVideos.length||this.switchTo(index)}next(){const index=this.nearestEnabledIndex(this.playlistVideos,this.activeIndex+1);index>this.activeIndex&&this.switchTo(index)}previous(){for(let index=this.activeIndex-1;index>=0;index-=1)if(this.isEnabled(this.playlistVideos[index])){this.switchTo(index);return}}onItemClick(event){const button=event.currentTarget,index=Number(button.dataset.index);Number.isInteger(index)&&(this.navigationIndex=index,this.goTo(index))}enabledIndices(){const result=[];for(let index=0;index<this.playlistVideos.length;index+=1)this.isEnabled(this.playlistVideos[index])&&result.push(index);return result}moveNavigation(from,direction){const enabled=this.enabledIndices(),position=enabled.indexOf(from);if(position<0)return;const next=enabled[position+direction];next!==void 0&&this.focusItem(next)}get navigationItem(){const rows=[...this.renderRoot.querySelectorAll('[part~="playlist-item"]')];return rows.find(row=>!row.disabled&&row.getAttribute("aria-current")==="true")??rows.find(row=>!row.disabled)??null}focus(options){this.navigationItem?.focus(options)}blur(){this.navigationItem?.blur()}click(){this.navigationItem?.click()}focusItem(index){this.isEnabled(this.playlistVideos[index])&&(this.navigationIndex=index,this.requestUpdate(),this.updateComplete.then(()=>{this.navigationIndex===index&&this.shadowRoot?.querySelector(`[data-index="${index}"]`)?.focus()}))}onItemKeyDown(event){const button=event.currentTarget,index=Number(button.dataset.index);if(!Number.isInteger(index)||button.disabled)return;const forward=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight",backward=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";if(event.key==="Enter"||event.key===" ")event.preventDefault(),this.navigationIndex=index,this.goTo(index);else if(event.key==="ArrowDown"||event.key===forward)event.preventDefault(),this.moveNavigation(index,1);else if(event.key==="ArrowUp"||event.key===backward)event.preventDefault(),this.moveNavigation(index,-1);else if(event.key==="Home"){event.preventDefault();const first=this.enabledIndices()[0];first!==void 0&&this.focusItem(first)}else if(event.key==="End"){event.preventDefault();const enabled=this.enabledIndices(),last=enabled[enabled.length-1];last!==void 0&&this.focusItem(last)}}itemTitle(value,index){const title=typeof value=="string"?value.trim():"";if(title)return title;const position=getNumberFormat(this.effectiveLocale).format(index+1);return this.localize("videoPlaylistUntitled",void 0,{position})}renderItem(item,index,current,disabled){const title=this.itemTitle(item.title,index),poster=safeMediaSrc(typeof item.poster=="string"?item.poster:""),duration=finiteRange(typeof item.duration=="number"?item.duration:0,0,0),durationId=`playlist-duration-${index}`;return html`
|
|
1
|
+
import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{formatMediaTime}from"../../../internal/media-time.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{finiteRange}from"../../../internal/numbers.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{tag}from"../../../internal/prefix.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./video-playlist.styles.js";import{LYRA_DEFAULT_videoPlaylistLabel,LYRA_DEFAULT_videoPlaylistUntitled}from"../../../internal/default-strings/media.generated.js";function safeControls(value){return value==="none"||value==="standard"?value:"full"}function safeRepeat(value){return value==="one"||value==="all"?value:"none"}function sameVideos(left,right){return left.length===right.length&&left.every((video,index)=>video===right[index])}function sourceSnapshot(src,type,media){return{src,type,media}}function trackSnapshot(src,kind,srclang,label,isDefault){return{src,kind,srclang,label,default:isDefault}}class LyraVideoPlaylist extends LyraElement{constructor(){super(...arguments),this.controls="full",this.iconLibrary="system",this.withoutAutoAdvance=!1,this.repeat="none",this.items=[],this.playlistVideos=[],this.liveChildrenReady=!1,this.activeIndex=-1,this.navigationIndex=-1,this.listeners=new Map,this.lastKnownPlaying=new WeakMap,this.nativeVideos=new WeakMap,this.needsReload=new WeakSet,this.ownedVideoState=new WeakMap,this.preferences={},this.activationGeneration=0,this.reconcileGeneration=0,this.onSlotChange=()=>this.reconcileChildren(),this.onItemFocus=event=>{relayNativeEvent(this,event)},this.onItemBlur=event=>{relayNativeEvent(this,event)}}static{this.defaultStrings={...super.defaultStrings,videoPlaylistLabel:LYRA_DEFAULT_videoPlaylistLabel,videoPlaylistUntitled:LYRA_DEFAULT_videoPlaylistUntitled}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-video-change"])}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.observeChildren(),this.hasUpdated?this.scheduleAfterUpdate(()=>this.reconcileChildren(),"video-playlist-reconcile"):this.seedFirstRenderState(()=>{this.directVideos().length>0&&this.reconcileChildren()})}disconnectedCallback(){this.activationGeneration+=1,this.reconcileGeneration+=1,this.pendingPlay=void 0,this.mutationObserver?.disconnect(),this.mutationObserver=void 0;for(const video of this.playlistVideos)this.unbindVideo(video),video.hidden=!0,this.pauseAndUnload(video);super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed),changed.has("controls")&&(this.controls=safeControls(this.controls)),changed.has("repeat")&&(this.repeat=safeRepeat(this.repeat)),(changed.has("controls")||changed.has("iconLibrary"))&&this.scheduleAfterUpdate(()=>this.reconcileChildren(),"video-playlist-reconcile")}observeChildren(){this.mutationObserver?.disconnect(),this.mutationObserver=void 0;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;MutationObserverCtor&&(this.mutationObserver=new MutationObserverCtor(()=>{this.scheduleAfterUpdate(()=>{this.reconcileChildren(),this.requestUpdate()},"video-playlist-reconcile")}),this.mutationObserver.observe(this,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["default","inert","kind","label","media","poster","src","srclang","title","type"]}))}directVideos(){const videoTag=tag("video");return[...this.children].filter(child=>child.localName===videoTag)}isEnabled(video){return!video.inert}nearestEnabledIndex(videos,preferred){if(!videos.length)return-1;const start=Math.min(Math.max(preferred,0),videos.length-1);for(let index=start;index<videos.length;index+=1)if(this.isEnabled(videos[index]))return index;for(let index=start-1;index>=0;index-=1)if(this.isEnabled(videos[index]))return index;return-1}reconcileChildren(){if(!this.isConnected)return;const previousVideos=this.playlistVideos,previousActive=this.activeVideo,previousIndex=this.activeIndex,previousNavigation=previousVideos[this.navigationIndex],navigationHadFocus=shadowFocusTarget(this)?.getAttribute("part")==="playlist-item",videos=this.directVideos(),videoSet=new Set(videos);(videos.length>0||this.liveChildrenReady)&&(this.liveChildrenReady=!0);let active=previousActive&&videoSet.has(previousActive)&&this.isEnabled(previousActive)?previousActive:void 0,nextIndex=active?videos.indexOf(active):this.nearestEnabledIndex(videos,previousIndex);!active&&nextIndex>=0&&(active=videos[nextIndex]),active||(nextIndex=-1);const activeChanged=active!==previousActive,outgoingWasRemoved=!!(previousActive&&!videoSet.has(previousActive)),resumePlayback=activeChanged&&previousActive?outgoingWasRemoved?this.lastKnownPlaying.get(previousActive)??previousActive.getState().playing:previousActive.getState().playing:!1,outgoingPreferences=activeChanged&&previousActive?outgoingWasRemoved?this.capturePreferences(previousActive,this.nativeVideos.get(previousActive)):this.capturePreferences(previousActive):void 0;for(const video of previousVideos)videoSet.has(video)||this.releaseVideo(video);for(const video of videos)this.claimVideo(video),this.bindVideo(video);activeChanged&&previousActive?(this.preferences=outgoingPreferences??{},outgoingWasRemoved||this.pauseAndUnload(previousActive),this.activationGeneration+=1):activeChanged&&(this.activationGeneration+=1),this.activeVideo=active,this.activeIndex=nextIndex,sameVideos(previousVideos,videos)||(this.playlistVideos=videos);for(const video of videos){video.controls!==this.controls&&(video.controls=this.controls),video.iconLibrary!==this.iconLibrary&&(video.iconLibrary=this.iconLibrary);const isActive=video===active;video.hidden=!isActive,isActive||this.pauseAndUnload(video)}active?(activeChanged||this.needsReload.has(active))&&this.activateVideo(active,resumePlayback,this.activationGeneration):this.pendingPlay=void 0;const keptNavigation=previousNavigation&&videoSet.has(previousNavigation)&&this.isEnabled(previousNavigation)?videos.indexOf(previousNavigation):-1;this.navigationIndex=keptNavigation>=0?keptNavigation:nextIndex,navigationHadFocus&&keptNavigation<0&&this.navigationIndex>=0&&this.focusItem(this.navigationIndex),activeChanged&&previousActive&&this.emitChange(previousIndex,nextIndex,active??null),this.scheduleChildrenReady(videos)}scheduleChildrenReady(videos){const reconcileGeneration=++this.reconcileGeneration;Promise.all(videos.map(video=>video.updateComplete)).then(()=>{if(!this.isConnected||reconcileGeneration!==this.reconcileGeneration)return;for(const video of this.playlistVideos)this.rememberNativeVideo(video);for(const video of this.playlistVideos)video!==this.activeVideo&&this.pauseAndUnload(video);const active=this.activeVideo;if(!active||!this.needsReload.has(active))return;const shouldPlay=this.pendingPlay?.video===active&&this.pendingPlay.generation===this.activationGeneration;this.activateVideo(active,shouldPlay,this.activationGeneration)})}bindVideo(video){if(this.listeners.has(video))return;const listeners={ended:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!1),this.handleCompletion(video)},error:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!1)},loadedmetadata:()=>{this.rememberNativeVideo(video),this.handleLoadedMetadata(video)},pause:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!1)},play:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!0),video!==this.activeVideo&&this.pauseAndUnload(video)}};this.lastKnownPlaying.set(video,video.getState().playing),this.rememberNativeVideo(video),this.listeners.set(video,listeners),video.addEventListener("ended",listeners.ended),video.addEventListener("error",listeners.error),video.addEventListener("loadedmetadata",listeners.loadedmetadata),video.addEventListener("pause",listeners.pause),video.addEventListener("play",listeners.play)}unbindVideo(video){const listeners=this.listeners.get(video);listeners&&(video.removeEventListener("ended",listeners.ended),video.removeEventListener("error",listeners.error),video.removeEventListener("loadedmetadata",listeners.loadedmetadata),video.removeEventListener("pause",listeners.pause),video.removeEventListener("play",listeners.play),this.listeners.delete(video))}claimVideo(video){this.ownedVideoState.has(video)||this.ownedVideoState.set(video,{controls:video.controls,iconLibrary:video.iconLibrary,hidden:!!video.hidden})}releaseVideo(video){const authored=this.ownedVideoState.get(video);this.unbindVideo(video),this.pauseAndUnload(video),authored&&(video.controls=authored.controls,video.iconLibrary=authored.iconLibrary,video.hidden=authored.hidden,this.ownedVideoState.delete(video),video.isConnected&&video.load())}rememberNativeVideo(video){const native=video.getVideoElement();native&&this.nativeVideos.set(video,native)}pauseAndUnload(video){video.pause(),video.hidden=!0,this.needsReload.add(video),video.unloadMedia()}activateVideo(video,shouldPlay,generation){if(video.hidden=!1,!video.getVideoElement()){this.needsReload.add(video),shouldPlay&&(this.pendingPlay={video,generation});return}if(this.rememberNativeVideo(video),video.load(),this.needsReload.delete(video),this.applyPreferences(video,this.preferences),!shouldPlay){this.pendingPlay?.video===video&&(this.pendingPlay=void 0);return}this.pendingPlay=void 0,video.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo})}capturePreferences(video,native=video.getVideoElement()){return video.captureMediaPreferences(native)}applyPreferences(video,preferences){video.applyMediaPreferences(preferences)}handleLoadedMetadata(video){video===this.activeVideo&&(this.applyPreferences(video,this.preferences),this.requestUpdate())}handleCompletion(video){if(video!==this.activeVideo||this.withoutAutoAdvance)return;if(this.repeat==="one"){video.seek(0);const generation=this.activationGeneration;video.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo});return}const nextIndex=this.nearestEnabledIndex(this.playlistVideos,this.activeIndex+1);if(nextIndex>this.activeIndex){this.switchTo(nextIndex,!0);return}if(this.repeat==="all"){const first=this.nearestEnabledIndex(this.playlistVideos,0);if(first>=0&&first!==this.activeIndex)this.switchTo(first,!0);else if(first===this.activeIndex){video.seek(0);const generation=this.activationGeneration;video.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo})}}}snapshotVideo(video){const sources=[],directSrc=video.src.trim();directSrc&&sources.push(sourceSnapshot(directSrc,"",""));const tracks=[];for(const child of video.children)if(child.localName==="source"){const src=child.getAttribute("src")?.trim()??"";src&&sources.push(sourceSnapshot(src,child.getAttribute("type")??"",child.getAttribute("media")??""))}else if(child.localName==="track"){const src=child.getAttribute("src")?.trim()??"";src&&tracks.push(trackSnapshot(src,child.getAttribute("kind")??"",child.getAttribute("srclang")??"",child.getAttribute("label")??"",child.hasAttribute("default")))}return{title:video.title,poster:video.poster,sources,tracks}}emitChange(previousIndex,currentIndex,video){this.emit("lr-video-change",{previousIndex,currentIndex,video:video?this.snapshotVideo(video):null})}switchTo(index,forcePlay=!1){const incoming=this.playlistVideos[index];if(!incoming||!this.isEnabled(incoming))return;const previousIndex=this.activeIndex,outgoing=this.activeVideo;if(incoming===outgoing){if(this.navigationIndex=index,this.requestUpdate(),forcePlay){const generation=this.activationGeneration;incoming.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo})}this.emitChange(previousIndex,index,incoming);return}const wasPlaying=forcePlay||!!outgoing?.getState().playing;outgoing&&(this.preferences=this.capturePreferences(outgoing),this.pauseAndUnload(outgoing)),this.activationGeneration+=1,this.activeVideo=incoming,this.activeIndex=index,this.navigationIndex=index;for(const video of this.playlistVideos){const isActive=video===incoming;video.hidden=!isActive,!isActive&&video!==outgoing&&this.pauseAndUnload(video)}this.activateVideo(incoming,wasPlaying,this.activationGeneration),this.requestUpdate(),this.emitChange(previousIndex,index,incoming)}goTo(index){!Number.isFinite(index)||!Number.isInteger(index)||index<0||index>=this.playlistVideos.length||this.switchTo(index)}next(){const index=this.nearestEnabledIndex(this.playlistVideos,this.activeIndex+1);index>this.activeIndex&&this.switchTo(index)}previous(){for(let index=this.activeIndex-1;index>=0;index-=1)if(this.isEnabled(this.playlistVideos[index])){this.switchTo(index);return}}onItemClick(event){const button=event.currentTarget,index=Number(button.dataset.index);Number.isInteger(index)&&(this.navigationIndex=index,this.goTo(index))}enabledIndices(){const result=[];for(let index=0;index<this.playlistVideos.length;index+=1)this.isEnabled(this.playlistVideos[index])&&result.push(index);return result}moveNavigation(from,direction){const enabled=this.enabledIndices(),position=enabled.indexOf(from);if(position<0)return;const next=enabled[position+direction];next!==void 0&&this.focusItem(next)}get navigationItem(){const rows=[...this.renderRoot.querySelectorAll('[part~="playlist-item"]')];return rows.find(row=>!row.disabled&&row.getAttribute("aria-current")==="true")??rows.find(row=>!row.disabled)??null}focus(options){this.navigationItem?.focus(options)}blur(){this.navigationItem?.blur()}click(){this.navigationItem?.click()}focusItem(index){this.isEnabled(this.playlistVideos[index])&&(this.navigationIndex=index,this.requestUpdate(),this.updateComplete.then(()=>{this.navigationIndex===index&&this.shadowRoot?.querySelector(`[data-index="${index}"]`)?.focus()}))}onItemKeyDown(event){const button=event.currentTarget,index=Number(button.dataset.index);if(!Number.isInteger(index)||button.disabled)return;const forward=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight",backward=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";if(event.key==="Enter"||event.key===" ")event.preventDefault(),this.navigationIndex=index,this.goTo(index);else if(event.key==="ArrowDown"||event.key===forward)event.preventDefault(),this.moveNavigation(index,1);else if(event.key==="ArrowUp"||event.key===backward)event.preventDefault(),this.moveNavigation(index,-1);else if(event.key==="Home"){event.preventDefault();const first=this.enabledIndices()[0];first!==void 0&&this.focusItem(first)}else if(event.key==="End"){event.preventDefault();const enabled=this.enabledIndices(),last=enabled[enabled.length-1];last!==void 0&&this.focusItem(last)}}itemTitle(value,index){const title=typeof value=="string"?value.trim():"";if(title)return title;const position=getNumberFormat(this.effectiveLocale).format(index+1);return this.localize("videoPlaylistUntitled",void 0,{position})}renderItem(item,index,current,disabled){const title=this.itemTitle(item.title,index),poster=safeMediaSrc(typeof item.poster=="string"?item.poster:""),duration=finiteRange(typeof item.duration=="number"?item.duration:0,0,0),durationId=`playlist-duration-${index}`;return html`
|
|
2
2
|
<li>
|
|
3
3
|
<button
|
|
4
4
|
type="button"
|
|
@@ -103,4 +103,4 @@ label?:string;
|
|
|
103
103
|
* semantics. */
|
|
104
104
|
ordinalIndex?:number;
|
|
105
105
|
/** Logical result count paired with `ordinalIndex`. */
|
|
106
|
-
ordinalTotal?:number;private get dense();private get effectiveVirtualizeAt();private sortedChunksCache?;private chunkOrdinalById;private sortedChunks;private readonly chunkKey;private safeScore;private tier;private tierTone;private tierLabel;private toggleExpand;private chunkTemplate;private renderChunk;private renderVirtualChunk;private virtualRenderItem;private readonly stopOwnedEvent;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-chunk-inspector':LyraChunkInspector;}}
|
|
106
|
+
ordinalTotal?:number;private get dense();private get effectiveVirtualizeAt();private sortedChunksCache?;private chunkOrdinalById;private sortedChunks;private readonly chunkKey;private safeScore;private tier;private tierTone;private tierLabel;private toggleExpand;private chunkTemplate;private expandedMembership?;private isChunkExpanded;private renderChunk;private renderVirtualChunk;private virtualRenderItem;private readonly stopOwnedEvent;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-chunk-inspector':LyraChunkInspector;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{normalizeSize}from"../../../internal/variants.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import"../../layout/virtual-list/virtual-list.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./chunk-inspector.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{resolveScoreTiers}from"../../../internal/score-tiers.js";import{LYRA_DEFAULT_chunkInspectorEmpty,LYRA_DEFAULT_chunkInspectorLabel,LYRA_DEFAULT_chunkInspectorOpenOrdinal,LYRA_DEFAULT_chunkScore,LYRA_DEFAULT_scoreTierHigh,LYRA_DEFAULT_scoreTierLow,LYRA_DEFAULT_scoreTierMedium,LYRA_DEFAULT_showMore,LYRA_DEFAULT_sourcePageSuffix,LYRA_DEFAULT_untitledSource}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_showLess}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_TIERS={high:.75,medium:.5};function isDenseSize(size){const step=normalizeSize(size);return step==="s"||step==="xs"||step==="2xs"}class LyraChunkInspector extends LyraElement{constructor(){super(...arguments),this.chunks=[],this.thresholds={high:.75,medium:.5},this.sort="score",this.activeChunkId="",this.virtualizeAt=50,this.size="m",this.expandedChunkIds=[],this.chunkOrdinalById=new Map,this.chunkKey=item=>item.id,this.renderChunk=item=>this.chunkTemplate(item,this.ordinalIndex!==void 0),this.renderVirtualChunk=item=>this.chunkTemplate(item,!0),this.stopOwnedEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,chunkInspectorEmpty:LYRA_DEFAULT_chunkInspectorEmpty,chunkInspectorLabel:LYRA_DEFAULT_chunkInspectorLabel,chunkInspectorOpenOrdinal:LYRA_DEFAULT_chunkInspectorOpenOrdinal,chunkScore:LYRA_DEFAULT_chunkScore,scoreTierHigh:LYRA_DEFAULT_scoreTierHigh,scoreTierLow:LYRA_DEFAULT_scoreTierLow,scoreTierMedium:LYRA_DEFAULT_scoreTierMedium,showLess:LYRA_DEFAULT_showLess,showMore:LYRA_DEFAULT_showMore,sourcePageSuffix:LYRA_DEFAULT_sourcePageSuffix,untitledSource:LYRA_DEFAULT_untitledSource}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["chunks","expandedChunkIds"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-chunk-open"])}get dense(){return isDenseSize(this.size)}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,50)}sortedChunks(){const cached=this.sortedChunksCache;if(cached&&cached.source===this.chunks&&cached.sort===this.sort)return cached.result;const canonical=firstByRetrievalIdentity(this.chunks,chunk=>chunk.id),result=this.sort==="score"?canonical.sort((a,b)=>this.safeScore(b.score)-this.safeScore(a.score)):canonical;return this.sortedChunksCache={source:this.chunks,sort:this.sort,result},this.chunkOrdinalById=new Map(result.map((chunk,index)=>[chunk.id,index])),result}safeScore(score){return finiteRange(score,0,0,1)}tier(score){const safeScore=this.safeScore(score),{high,medium}=resolveScoreTiers(DEFAULT_TIERS,this.thresholds);return safeScore>=high?"high":safeScore>=medium?"medium":"low"}tierTone(tier){return tier==="high"?"success":tier==="medium"?"warning":"danger"}tierLabel(tier){return this.localize(tier==="high"?"scoreTierHigh":tier==="medium"?"scoreTierMedium":"scoreTierLow")}toggleExpand(chunkId){const expanded=!this.expandedChunkIds.includes(chunkId);this.expandedChunkIds=expanded?[...this.expandedChunkIds,chunkId]:this.expandedChunkIds.filter(id=>id!==chunkId),this.emit("lr-chunk-toggle",{chunkId,expanded}),this.emit("lr-toggle",{itemId:chunkId,expanded})}chunkTemplate(chunk,virtualized){const tier=this.tier(chunk.score),tone=this.tierTone(tier),percent=Math.round(this.safeScore(chunk.score)*100),formattedPercent=getNumberFormat(this.effectiveLocale).format(percent),titleText=chunk.title||this.localize("untitledSource"),formattedPage=typeof chunk.page=="number"&&Number.isFinite(chunk.page)?getNumberFormat(this.effectiveLocale).format(finiteNumber(chunk.page,0)):chunk.page,titleWithPage=formattedPage==null||formattedPage===""?titleText:this.localize("sourcePageSuffix",void 0,{base:titleText,page:formattedPage}),ordinalIndex=this.ordinalIndex===void 0?(this.chunkOrdinalById.get(chunk.id)??0)+1:Math.max(1,finiteCount(this.ordinalIndex,1)),ordinalTotal=this.ordinalTotal===void 0?this.sortedChunks().length:Math.max(ordinalIndex,finiteCount(this.ordinalTotal,ordinalIndex)),expanded=this.
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{normalizeSize}from"../../../internal/variants.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import"../../layout/virtual-list/virtual-list.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./chunk-inspector.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{resolveScoreTiers}from"../../../internal/score-tiers.js";import{LYRA_DEFAULT_chunkInspectorEmpty,LYRA_DEFAULT_chunkInspectorLabel,LYRA_DEFAULT_chunkInspectorOpenOrdinal,LYRA_DEFAULT_chunkScore,LYRA_DEFAULT_scoreTierHigh,LYRA_DEFAULT_scoreTierLow,LYRA_DEFAULT_scoreTierMedium,LYRA_DEFAULT_showMore,LYRA_DEFAULT_sourcePageSuffix,LYRA_DEFAULT_untitledSource}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_showLess}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_TIERS={high:.75,medium:.5};function isDenseSize(size){const step=normalizeSize(size);return step==="s"||step==="xs"||step==="2xs"}class LyraChunkInspector extends LyraElement{constructor(){super(...arguments),this.chunks=[],this.thresholds={high:.75,medium:.5},this.sort="score",this.activeChunkId="",this.virtualizeAt=50,this.size="m",this.expandedChunkIds=[],this.chunkOrdinalById=new Map,this.chunkKey=item=>item.id,this.renderChunk=item=>this.chunkTemplate(item,this.ordinalIndex!==void 0),this.renderVirtualChunk=item=>this.chunkTemplate(item,!0),this.stopOwnedEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,chunkInspectorEmpty:LYRA_DEFAULT_chunkInspectorEmpty,chunkInspectorLabel:LYRA_DEFAULT_chunkInspectorLabel,chunkInspectorOpenOrdinal:LYRA_DEFAULT_chunkInspectorOpenOrdinal,chunkScore:LYRA_DEFAULT_chunkScore,scoreTierHigh:LYRA_DEFAULT_scoreTierHigh,scoreTierLow:LYRA_DEFAULT_scoreTierLow,scoreTierMedium:LYRA_DEFAULT_scoreTierMedium,showLess:LYRA_DEFAULT_showLess,showMore:LYRA_DEFAULT_showMore,sourcePageSuffix:LYRA_DEFAULT_sourcePageSuffix,untitledSource:LYRA_DEFAULT_untitledSource}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["chunks","expandedChunkIds"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-chunk-open"])}get dense(){return isDenseSize(this.size)}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,50)}sortedChunks(){const cached=this.sortedChunksCache;if(cached&&cached.source===this.chunks&&cached.sort===this.sort)return cached.result;const canonical=firstByRetrievalIdentity(this.chunks,chunk=>chunk.id),result=this.sort==="score"?canonical.sort((a,b)=>this.safeScore(b.score)-this.safeScore(a.score)):canonical;return this.sortedChunksCache={source:this.chunks,sort:this.sort,result},this.chunkOrdinalById=new Map(result.map((chunk,index)=>[chunk.id,index])),result}safeScore(score){return finiteRange(score,0,0,1)}tier(score){const safeScore=this.safeScore(score),{high,medium}=resolveScoreTiers(DEFAULT_TIERS,this.thresholds);return safeScore>=high?"high":safeScore>=medium?"medium":"low"}tierTone(tier){return tier==="high"?"success":tier==="medium"?"warning":"danger"}tierLabel(tier){return this.localize(tier==="high"?"scoreTierHigh":tier==="medium"?"scoreTierMedium":"scoreTierLow")}toggleExpand(chunkId){const expanded=!this.expandedChunkIds.includes(chunkId);this.expandedChunkIds=expanded?[...this.expandedChunkIds,chunkId]:this.expandedChunkIds.filter(id=>id!==chunkId),this.emit("lr-chunk-toggle",{chunkId,expanded}),this.emit("lr-toggle",{itemId:chunkId,expanded})}chunkTemplate(chunk,virtualized){const tier=this.tier(chunk.score),tone=this.tierTone(tier),percent=Math.round(this.safeScore(chunk.score)*100),formattedPercent=getNumberFormat(this.effectiveLocale).format(percent),titleText=chunk.title||this.localize("untitledSource"),formattedPage=typeof chunk.page=="number"&&Number.isFinite(chunk.page)?getNumberFormat(this.effectiveLocale).format(finiteNumber(chunk.page,0)):chunk.page,titleWithPage=formattedPage==null||formattedPage===""?titleText:this.localize("sourcePageSuffix",void 0,{base:titleText,page:formattedPage}),ordinalIndex=this.ordinalIndex===void 0?(this.chunkOrdinalById.get(chunk.id)??0)+1:Math.max(1,finiteCount(this.ordinalIndex,1)),ordinalTotal=this.ordinalTotal===void 0?this.sortedChunks().length:Math.max(ordinalIndex,finiteCount(this.ordinalTotal,ordinalIndex)),expanded=this.isChunkExpanded(chunk.id),current=this.activeChunkId===chunk.id;return html`
|
|
2
2
|
<div
|
|
3
3
|
part=${current?"chunk chunk-current":"chunk"}
|
|
4
4
|
role=${virtualized?nothing:"listitem"}
|
|
@@ -39,7 +39,7 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
39
39
|
${this.localize(expanded?"showLess":"showMore")}
|
|
40
40
|
</button>`}
|
|
41
41
|
</div>
|
|
42
|
-
`}virtualRenderItem(){return item=>this.renderVirtualChunk(item)}render(){const sorted=this.sortedChunks()
|
|
42
|
+
`}isChunkExpanded(id){const source=this.expandedChunkIds;return source.length===0||this.sortedChunks().length<=1?(this.expandedMembership=void 0,source.includes(id)):(this.expandedMembership?.source!==source&&(this.expandedMembership={source,ids:new Set(source)}),this.expandedMembership.ids.has(id))}virtualRenderItem(){return item=>this.renderVirtualChunk(item)}render(){const sorted=this.sortedChunks();(this.expandedMembership?.source!==this.expandedChunkIds||sorted.length<=1)&&(this.expandedMembership=void 0);const label=retrievalSemanticLabel(this,this.label==null?this.localize("chunkInspectorLabel"):this.label),embedded=this.ordinalIndex!==void 0,groupRole=embedded?void 0:retrievalSemanticRole(this,"group");return sorted.length===0?html`<div part="base">
|
|
43
43
|
<lr-empty
|
|
44
44
|
part="empty"
|
|
45
45
|
heading=${this.localize("chunkInspectorEmpty")}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{PreviewDisclosureController}from"../../../internal/preview-disclosure-controller.js";import{nextId}from"../../../internal/a11y.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{finiteInteger}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./citation-badge.styles.js";import{LYRA_DEFAULT_citation,LYRA_DEFAULT_citationHighConfidence,LYRA_DEFAULT_citationLowConfidence,LYRA_DEFAULT_citationMediumConfidence,LYRA_DEFAULT_citationUnverified,LYRA_DEFAULT_citationVerified,LYRA_DEFAULT_citationWithCustomLabel,LYRA_DEFAULT_citationWithStatus}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const STATUS_MESSAGE_KEY={default:null,high:"citationHighConfidence",medium:"citationMediumConfidence",low:"citationLowConfidence",verified:"citationVerified",unverified:"citationUnverified"},HIDE_DELAY_MS=200;class LyraCitationBadge extends LyraElement{constructor(){super(...arguments),this._index=1,this.status="default",this.sourceId="",this.href="",this.label="",this.popoverOpen=!1,this.popoverId=nextId("citation-badge-popover"),this.slotPresence=new SlotPresenceController(this),this.preview=new PreviewDisclosureController({host:this,button:()=>this.buttonEl,panel:()=>this.popoverEl,hasContent:()=>this.hasPreviewSlot,isOpen:()=>this.popoverOpen,setOpen:open=>{this.popoverOpen=open},hideDelayMs:HIDE_DELAY_MS}),this.onKeyDown=e=>{e.key===" "&&!e.repeat&&e.target===this.buttonEl&&(e.preventDefault(),this.emitOpen())},this.onClick=()=>{this.emit("lr-citation-activate",{sourceId:this.sourceId,index:this.index})},this.onDblClick=()=>{this.emitOpen()}}static{this.defaultStrings={...super.defaultStrings,citation:LYRA_DEFAULT_citation,citationHighConfidence:LYRA_DEFAULT_citationHighConfidence,citationLowConfidence:LYRA_DEFAULT_citationLowConfidence,citationMediumConfidence:LYRA_DEFAULT_citationMediumConfidence,citationUnverified:LYRA_DEFAULT_citationUnverified,citationVerified:LYRA_DEFAULT_citationVerified,citationWithCustomLabel:LYRA_DEFAULT_citationWithCustomLabel,citationWithStatus:LYRA_DEFAULT_citationWithStatus,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get index(){return this._index}set index(value){const old=this._index;this._index=finiteInteger(value,1,1),this.requestUpdate("index",old)}get hasPreviewSlot(){return this.slotPresence.has()}willUpdate(changed){super.willUpdate(changed)
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{PreviewDisclosureController}from"../../../internal/preview-disclosure-controller.js";import{nextId}from"../../../internal/a11y.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{finiteInteger}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./citation-badge.styles.js";import{LYRA_DEFAULT_citation,LYRA_DEFAULT_citationHighConfidence,LYRA_DEFAULT_citationLowConfidence,LYRA_DEFAULT_citationMediumConfidence,LYRA_DEFAULT_citationUnverified,LYRA_DEFAULT_citationVerified,LYRA_DEFAULT_citationWithCustomLabel,LYRA_DEFAULT_citationWithStatus}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const STATUS_MESSAGE_KEY={default:null,high:"citationHighConfidence",medium:"citationMediumConfidence",low:"citationLowConfidence",verified:"citationVerified",unverified:"citationUnverified"},HIDE_DELAY_MS=200;class LyraCitationBadge extends LyraElement{constructor(){super(...arguments),this._index=1,this.status="default",this.sourceId="",this.href="",this.label="",this.popoverOpen=!1,this.popoverId=nextId("citation-badge-popover"),this.slotPresence=new SlotPresenceController(this),this.preview=(()=>{const preview=new PreviewDisclosureController({host:this,button:()=>this.buttonEl,panel:()=>this.popoverEl,hasContent:()=>this.hasPreviewSlot,isOpen:()=>this.popoverOpen,setOpen:open=>{this.popoverOpen=open},hideDelayMs:HIDE_DELAY_MS});return this.addController({hostUpdate:()=>preview.ensureContent()}),preview})(),this.onKeyDown=e=>{e.key===" "&&!e.repeat&&e.target===this.buttonEl&&(e.preventDefault(),this.emitOpen())},this.onClick=()=>{this.emit("lr-citation-activate",{sourceId:this.sourceId,index:this.index})},this.onDblClick=()=>{this.emitOpen()}}static{this.defaultStrings={...super.defaultStrings,citation:LYRA_DEFAULT_citation,citationHighConfidence:LYRA_DEFAULT_citationHighConfidence,citationLowConfidence:LYRA_DEFAULT_citationLowConfidence,citationMediumConfidence:LYRA_DEFAULT_citationMediumConfidence,citationUnverified:LYRA_DEFAULT_citationUnverified,citationVerified:LYRA_DEFAULT_citationVerified,citationWithCustomLabel:LYRA_DEFAULT_citationWithCustomLabel,citationWithStatus:LYRA_DEFAULT_citationWithStatus,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get index(){return this._index}set index(value){const old=this._index;this._index=finiteInteger(value,1,1),this.requestUpdate("index",old)}get hasPreviewSlot(){return this.slotPresence.has()}willUpdate(changed){super.willUpdate(changed)}updated(changed){super.updated(changed),changed.has("popoverOpen")&&this.preview.syncOpen()}disconnectedCallback(){super.disconnectedCallback(),this.preview.disconnect()}get accessibleLabel(){const index=getNumberFormat(this.effectiveLocale).format(this.index);if(this.label)return this.localize("citationWithCustomLabel",void 0,{index,label:this.label});const key=STATUS_MESSAGE_KEY[this.status],statusText=key?this.localize(key):"",citationLabel=this.localize("citation",void 0,{index});return statusText?this.localize("citationWithStatus",void 0,{index,status:statusText}):citationLabel}emitOpen(){this.emit("lr-citation-open",{sourceId:this.sourceId,index:this.index,href:this.href||void 0})}render(){const formattedIndex=getNumberFormat(this.effectiveLocale).format(this.index);return html`
|
|
2
2
|
<span
|
|
3
3
|
class="wrapper"
|
|
4
4
|
@pointerenter=${()=>this.preview.pointerEnter()}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isNonBlankIdentity}from"../retrieval-identity.js";import{PreviewDisclosureController}from"../../../internal/preview-disclosure-controller.js";import{nextId}from"../../../internal/a11y.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{styles}from"./entity-chip.styles.js";import{LYRA_DEFAULT_entityChipWithType,LYRA_DEFAULT_untitledEntity}from"../../../internal/default-strings/retrieval.generated.js";const HIDE_DELAY_MS=200;class LyraEntityChip extends LyraElement{constructor(){super(...arguments),this.entityId="",this.text="",this.type="",this.popoverOpen=!1,this.popoverId=nextId("entity-chip-popover"),this.slotPresence=new SlotPresenceController(this),this.preview=new PreviewDisclosureController({host:this,button:()=>this.buttonEl,panel:()=>this.popoverEl,hasContent:()=>this.hasPreviewSlot,isOpen:()=>this.popoverOpen,setOpen:open=>{this.popoverOpen=open},hideDelayMs:HIDE_DELAY_MS}),this.onKeyDown=e=>{this.preview.handleEscape(e)||e.key===" "&&!e.repeat&&e.target===this.buttonEl&&(e.preventDefault(),this.emitOpen())},this.onClick=()=>{isNonBlankIdentity(this.entityId)&&this.emit("lr-entity-select",{entityId:this.entityId})},this.onDblClick=()=>{this.emitOpen()}}static{this.defaultStrings={...super.defaultStrings,entityChipWithType:LYRA_DEFAULT_entityChipWithType,untitledEntity:LYRA_DEFAULT_untitledEntity}}static{this.styles=[LyraElement.styles,styles]}get hasPreviewSlot(){return this.slotPresence.has()}willUpdate(changed){super.willUpdate(changed)
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isNonBlankIdentity}from"../retrieval-identity.js";import{PreviewDisclosureController}from"../../../internal/preview-disclosure-controller.js";import{nextId}from"../../../internal/a11y.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{styles}from"./entity-chip.styles.js";import{LYRA_DEFAULT_entityChipWithType,LYRA_DEFAULT_untitledEntity}from"../../../internal/default-strings/retrieval.generated.js";const HIDE_DELAY_MS=200;class LyraEntityChip extends LyraElement{constructor(){super(...arguments),this.entityId="",this.text="",this.type="",this.popoverOpen=!1,this.popoverId=nextId("entity-chip-popover"),this.slotPresence=new SlotPresenceController(this),this.preview=(()=>{const preview=new PreviewDisclosureController({host:this,button:()=>this.buttonEl,panel:()=>this.popoverEl,hasContent:()=>this.hasPreviewSlot,isOpen:()=>this.popoverOpen,setOpen:open=>{this.popoverOpen=open},hideDelayMs:HIDE_DELAY_MS});return this.addController({hostUpdate:()=>preview.ensureContent()}),preview})(),this.onKeyDown=e=>{this.preview.handleEscape(e)||e.key===" "&&!e.repeat&&e.target===this.buttonEl&&(e.preventDefault(),this.emitOpen())},this.onClick=()=>{isNonBlankIdentity(this.entityId)&&this.emit("lr-entity-select",{entityId:this.entityId})},this.onDblClick=()=>{this.emitOpen()}}static{this.defaultStrings={...super.defaultStrings,entityChipWithType:LYRA_DEFAULT_entityChipWithType,untitledEntity:LYRA_DEFAULT_untitledEntity}}static{this.styles=[LyraElement.styles,styles]}get hasPreviewSlot(){return this.slotPresence.has()}willUpdate(changed){super.willUpdate(changed)}updated(changed){super.updated(changed),changed.has("popoverOpen")&&this.preview.syncOpen()}disconnectedCallback(){super.disconnectedCallback(),this.preview.disconnect()}get accessibleLabel(){const label=(this.text??"").trim()===""?this.localize("untitledEntity"):this.text,typeText=this.typeLabel?.trim()||(this.type??"").trim();return typeText?this.localize("entityChipWithType",void 0,{label,type:typeText}):label}emitOpen(){isNonBlankIdentity(this.entityId)&&this.emit("lr-entity-open",{entityId:this.entityId})}render(){return html`
|
|
2
2
|
<span
|
|
3
3
|
class="wrapper"
|
|
4
4
|
@pointerenter=${()=>this.preview.pointerEnter()}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const NO_DASH=[],HULL_STROKE_WIDTH=48,MIN_PICK_TARGET_PX=24,PICK_RASTER_GUARD_PX=2,EXPAND_BADGE_R=5,EXPAND_BADGE_OFFSET=Math.SQRT1_2;function shapeHalfSide(r){return r*Math.sqrt(Math.PI)/2}function traceShape(path,x,y,r,shape){if(shape==="circle"){path.arc(x,y,r,0,Math.PI*2);return}const s=shapeHalfSide(r);if(shape==="square"){path.rect(x-s,y-s,s*2,s*2);return}const d=s*Math.SQRT2;path.moveTo(x,y-d),path.lineTo(x+d,y),path.lineTo(x,y+d),path.lineTo(x-d,y),path.closePath()}function drawArrowhead(ctx,link){const dx=link.x2-link.x1,dy=link.y2-link.y1,len=Math.hypot(dx,dy)||1,ux=dx/len,uy=dy/len,size=Math.max(6,link.width*3),bx=link.x2-ux*size,by=link.y2-uy*size,px=-uy,py=ux;ctx.beginPath(),ctx.moveTo(link.x2,link.y2),ctx.lineTo(bx+px*size*.4,by+py*size*.4),ctx.lineTo(bx-px*size*.4,by-py*size*.4),ctx.closePath(),ctx.fillStyle=ctx.strokeStyle,ctx.fill()}function drawRing(ctx,ring,color,width){ctx.strokeStyle=color,ctx.lineWidth=width,ctx.beginPath(),ctx.arc(ring.x,ring.y,ring.r,0,Math.PI*2),ctx.stroke()}function drawKeyboardFocusCue(ctx,scene){if(ctx.strokeStyle=scene.haloColor,ctx.setLineDash([4,3]),scene.keyboardFocusLink){const link=scene.keyboardFocusLink;ctx.lineWidth=Math.max(4,link.width+4),ctx.beginPath(),ctx.moveTo(link.x1,link.y1),ctx.lineTo(link.x2,link.y2),ctx.stroke()}scene.keyboardFocusHull&&(ctx.lineWidth=4,ctx.stroke(
|
|
1
|
+
const NO_DASH=[],hullPaths=new WeakMap;function hullPath(hull){const cached=hullPaths.get(hull);if(cached?.d===hull.d)return cached.path;const path=new Path2D(hull.d);return hullPaths.set(hull,{d:hull.d,path}),path}const HULL_STROKE_WIDTH=48,MIN_PICK_TARGET_PX=24,PICK_RASTER_GUARD_PX=2,EXPAND_BADGE_R=5,EXPAND_BADGE_OFFSET=Math.SQRT1_2;function shapeHalfSide(r){return r*Math.sqrt(Math.PI)/2}function traceShape(path,x,y,r,shape){if(shape==="circle"){path.arc(x,y,r,0,Math.PI*2);return}const s=shapeHalfSide(r);if(shape==="square"){path.rect(x-s,y-s,s*2,s*2);return}const d=s*Math.SQRT2;path.moveTo(x,y-d),path.lineTo(x+d,y),path.lineTo(x,y+d),path.lineTo(x-d,y),path.closePath()}function drawArrowhead(ctx,link){const dx=link.x2-link.x1,dy=link.y2-link.y1,len=Math.hypot(dx,dy)||1,ux=dx/len,uy=dy/len,size=Math.max(6,link.width*3),bx=link.x2-ux*size,by=link.y2-uy*size,px=-uy,py=ux;ctx.beginPath(),ctx.moveTo(link.x2,link.y2),ctx.lineTo(bx+px*size*.4,by+py*size*.4),ctx.lineTo(bx-px*size*.4,by-py*size*.4),ctx.closePath(),ctx.fillStyle=ctx.strokeStyle,ctx.fill()}function drawRing(ctx,ring,color,width){ctx.strokeStyle=color,ctx.lineWidth=width,ctx.beginPath(),ctx.arc(ring.x,ring.y,ring.r,0,Math.PI*2),ctx.stroke()}function drawKeyboardFocusCue(ctx,scene){if(ctx.strokeStyle=scene.haloColor,ctx.setLineDash([4,3]),scene.keyboardFocusLink){const link=scene.keyboardFocusLink;ctx.lineWidth=Math.max(4,link.width+4),ctx.beginPath(),ctx.moveTo(link.x1,link.y1),ctx.lineTo(link.x2,link.y2),ctx.stroke()}scene.keyboardFocusHull&&(ctx.lineWidth=4,ctx.stroke(hullPath(scene.keyboardFocusHull))),ctx.setLineDash([]),scene.keyboardFocusRing&&drawRing(ctx,scene.keyboardFocusRing,scene.haloColor,scene.borderWidths?.[1]??2)}function drawGraphScene(ctx,camera,scene){ctx.save(),ctx.transform(camera.k,0,0,camera.k,camera.x,camera.y);const hullOpacity=scene.hullOpacity??.12;for(const hull of scene.hulls){const path=hullPath(hull);ctx.globalAlpha=hullOpacity,ctx.fillStyle=hull.fill,ctx.strokeStyle=hull.fill,ctx.lineWidth=HULL_STROKE_WIDTH,ctx.lineJoin="round",ctx.lineCap="round",ctx.fill(path),ctx.stroke(path),ctx.globalAlpha=1}const dimmedOpacity=scene.dimmedOpacity??1,[thin,medium,thick]=scene.borderWidths??[1,2,3],styleLink=link=>{ctx.strokeStyle=link.selected?scene.selectedColor:link.color,ctx.lineWidth=link.selected?thick:link.width,ctx.setLineDash(link.dash??NO_DASH),ctx.globalAlpha=link.dimmed?dimmedOpacity:1};let style="";ctx.beginPath();for(const link of scene.links){if(link.width<=0)continue;const linkStyle=[link.selected||link.color,link.selected||link.width,link.dash,link.dimmed].join("|");linkStyle!==style&&(ctx.stroke(),ctx.beginPath(),styleLink(link),style=linkStyle),ctx.moveTo(link.x1,link.y1),ctx.lineTo(link.x2,link.y2)}ctx.stroke();for(const link of scene.links)link.width<=0||!link.directed||(styleLink(link),drawArrowhead(ctx,link));if(ctx.globalAlpha=1,ctx.setLineDash([]),scene.edgeLabels.length){ctx.font=scene.font,ctx.textAlign="center",ctx.textBaseline="middle",ctx.lineWidth=thick;for(const label of scene.edgeLabels)ctx.strokeStyle=scene.labelHaloColor,ctx.strokeText(label.text,label.x,label.y),ctx.fillStyle=scene.labelColor,ctx.fillText(label.text,label.x,label.y)}for(const node of scene.nodes)ctx.globalAlpha=node.dimmed?dimmedOpacity:1,ctx.fillStyle=node.fill,ctx.beginPath(),traceShape(ctx,node.x,node.y,node.r,node.shape),ctx.fill(),node.selected&&(ctx.strokeStyle=scene.selectedColor,ctx.lineWidth=medium,ctx.stroke());if(ctx.globalAlpha=1,scene.showNodeLabels&&scene.nodeLabels.length){ctx.font=scene.font,ctx.textAlign="left",ctx.textBaseline="middle",ctx.fillStyle=scene.labelColor;for(const label of scene.nodeLabels)ctx.fillText(label.text,label.x,label.y)}const expandIndicators=scene.expandIndicators??[];if(expandIndicators.length){ctx.lineWidth=thin;for(const indicator of expandIndicators){const bx=indicator.x+indicator.r*EXPAND_BADGE_OFFSET,by=indicator.y-indicator.r*EXPAND_BADGE_OFFSET,path=new Path2D;path.arc(bx,by,EXPAND_BADGE_R,0,Math.PI*2),ctx.fillStyle=scene.expandBadgeFill??"",ctx.fill(path),ctx.strokeStyle=scene.expandBadgeStroke??"",ctx.stroke(path),ctx.strokeStyle=scene.labelColor,ctx.beginPath(),ctx.moveTo(bx-EXPAND_BADGE_R/2,by),ctx.lineTo(bx+EXPAND_BADGE_R/2,by),ctx.moveTo(bx,by-EXPAND_BADGE_R/2),ctx.lineTo(bx,by+EXPAND_BADGE_R/2),ctx.stroke()}}scene.focusHalo&&drawRing(ctx,scene.focusHalo,scene.haloColor,medium),drawKeyboardFocusCue(ctx,scene),ctx.restore()}function indexToPickColor(index){const v=index+1;return`rgb(${v>>16&255},${v>>8&255},${v&255})`}function pickColorToIndex(r,g,b){return(r<<16|g<<8|b)-1}function drawPickingScene(ctx,camera,scene){ctx.imageSmoothingEnabled=!1,ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height),ctx.save(),ctx.transform(camera.k,0,0,camera.k,camera.x,camera.y);const cameraScale=Number.isFinite(camera.k)&&Math.abs(camera.k)>0?Math.abs(camera.k):1,minimumWorldStroke=(MIN_PICK_TARGET_PX+PICK_RASTER_GUARD_PX)/cameraScale;let idx=0;for(const hull of scene.hulls){const color=indexToPickColor(idx++),path=hullPath(hull);ctx.fillStyle=color,ctx.strokeStyle=color,ctx.lineWidth=Math.max(HULL_STROKE_WIDTH,minimumWorldStroke),ctx.lineJoin="round",ctx.lineCap="round",ctx.fill(path),ctx.stroke(path)}for(const link of scene.links)ctx.strokeStyle=indexToPickColor(idx++),ctx.lineWidth=Math.max(link.width+6,8,minimumWorldStroke),ctx.lineCap="round",ctx.beginPath(),ctx.moveTo(link.x1,link.y1),ctx.lineTo(link.x2,link.y2),ctx.stroke();for(const node of scene.nodes)ctx.fillStyle=indexToPickColor(idx++),ctx.beginPath(),traceShape(ctx,node.x,node.y,Math.max(node.r,minimumWorldStroke/2),node.shape),ctx.fill();ctx.restore()}export{EXPAND_BADGE_OFFSET,EXPAND_BADGE_R,drawGraphScene,drawPickingScene,pickColorToIndex,shapeHalfSide};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{canonicalIdentityList,firstByRetrievalIdentity}from"../retrieval-identity.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{srOnly}from"../../../internal/a11y.js";import{styles}from"./graph-legend.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_graphLegendLabel}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_legendTypeHidden,LYRA_DEFAULT_legendTypeShown}from"../../../internal/default-strings/shared.generated.js";class LyraGraphLegend extends LyraElement{constructor(){super(...arguments),this.types=[],this.hiddenTypes=[],this.withoutInteraction=!1,this.liveText=""}static{this.defaultStrings={...super.defaultStrings,graphLegendLabel:LYRA_DEFAULT_graphLegendLabel,legendTypeHidden:LYRA_DEFAULT_legendTypeHidden,legendTypeShown:LYRA_DEFAULT_legendTypeShown}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["types","hiddenTypes","counts"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}static{this.immutableEventDetails=Object.freeze(["lr-visibility-change-request","lr-visibility-change"])}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}isVisible(id){return!canonicalIdentityList(this.hiddenTypes).includes(id)}toggle(type){if(this.withoutInteraction)return;const hiddenTypes=canonicalIdentityList(this.hiddenTypes),wasVisible=this.isVisible(type.id),next=wasVisible?[...hiddenTypes,type.id]:hiddenTypes.filter(id=>id!==type.id);this.emit("lr-visibility-change-request",{hiddenTypes:next},{cancelable:!0}).defaultPrevented||(this.hiddenTypes=next,this.liveText=this.localize(wasVisible?"legendTypeHidden":"legendTypeShown",void 0,{label:type.label}),this.announcementSink?.announce(this.liveText),this.emit("lr-visibility-change",{hiddenTypes:next}))}renderSwatchShape(shape,color){return shape==="square"?svg`<rect x="1" y="1" width="10" height="10" style="fill: ${color}"></rect>`:shape==="diamond"?svg`<polygon points="6,0 12,6 6,12 0,6" style="fill: ${color}"></polygon>`:svg`<circle cx="6" cy="6" r="5" style="fill: ${color}"></circle>`}render(){const types=firstByRetrievalIdentity(this.types,type=>type?.id).filter(type=>typeof type?.label=="string"&&type.label.trim().length>0),groupLabel=retrievalSemanticLabel(this,this.label==null?this.localize("graphLegendLabel"):this.label),groupRole=retrievalSemanticRole(this,"group");return html`
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{canonicalIdentityList,firstByRetrievalIdentity}from"../retrieval-identity.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{srOnly}from"../../../internal/a11y.js";import{styles}from"./graph-legend.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_graphLegendLabel}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_legendTypeHidden,LYRA_DEFAULT_legendTypeShown}from"../../../internal/default-strings/shared.generated.js";class LyraGraphLegend extends LyraElement{constructor(){super(...arguments),this.types=[],this.hiddenTypes=[],this.withoutInteraction=!1,this.liveText=""}static{this.defaultStrings={...super.defaultStrings,graphLegendLabel:LYRA_DEFAULT_graphLegendLabel,legendTypeHidden:LYRA_DEFAULT_legendTypeHidden,legendTypeShown:LYRA_DEFAULT_legendTypeShown}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["types","hiddenTypes","counts"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}static{this.immutableEventDetails=Object.freeze(["lr-visibility-change-request","lr-visibility-change"])}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}isVisible(id){return!canonicalIdentityList(this.hiddenTypes).includes(id)}toggle(type){if(this.withoutInteraction)return;const hiddenTypes=canonicalIdentityList(this.hiddenTypes),wasVisible=this.isVisible(type.id),next=wasVisible?[...hiddenTypes,type.id]:hiddenTypes.filter(id=>id!==type.id);this.emit("lr-visibility-change-request",{hiddenTypes:next},{cancelable:!0}).defaultPrevented||(this.hiddenTypes=next,this.liveText=this.localize(wasVisible?"legendTypeHidden":"legendTypeShown",void 0,{label:type.label}),this.announcementSink?.announce(this.liveText),this.emit("lr-visibility-change",{hiddenTypes:next}))}renderSwatchShape(shape,color){return shape==="square"?svg`<rect x="1" y="1" width="10" height="10" style="fill: ${color}"></rect>`:shape==="diamond"?svg`<polygon points="6,0 12,6 6,12 0,6" style="fill: ${color}"></polygon>`:svg`<circle cx="6" cy="6" r="5" style="fill: ${color}"></circle>`}render(){const types=firstByRetrievalIdentity(this.types,type=>type?.id).filter(type=>typeof type?.label=="string"&&type.label.trim().length>0),groupLabel=retrievalSemanticLabel(this,this.label==null?this.localize("graphLegendLabel"):this.label),groupRole=retrievalSemanticRole(this,"group"),hiddenTypes=new Set(canonicalIdentityList(this.hiddenTypes));return html`
|
|
2
2
|
<div
|
|
3
3
|
part="base"
|
|
4
4
|
role=${groupRole??nothing}
|
|
5
5
|
aria-label=${groupLabel??nothing}
|
|
6
6
|
>
|
|
7
|
-
${types.map((type,index)=>{const visible
|
|
7
|
+
${types.map((type,index)=>{const visible=!hiddenTypes.has(type.id),color=sanitizeCssColor(type.color)??`var(--lr-graph-cat-${index%8+1})`,count=this.counts?.[type.id],content=html`
|
|
8
8
|
<svg
|
|
9
9
|
part="swatch"
|
|
10
10
|
viewBox="0 0 12 12"
|