@aceshooting/lyra-ui 21.0.0 → 21.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/README.md +6 -3
- package/custom-elements.json +1 -1
- package/dist/ai/runtime.js +1 -1
- package/dist/ai/types.d.ts +13 -5
- package/dist/cli/lyra-rename-ledger.mjs +1 -0
- package/dist/cli/migrate-wa.mjs +33 -13
- package/dist/cli/migration-contract.json +1 -1
- package/dist/components/agent-tools/agent-trace/agent-trace.class.d.ts +5 -3
- package/dist/components/agent-tools/agent-trace/agent-trace.class.js +3 -2
- package/dist/components/agent-tools/tool-call-block/tool-call-block.class.d.ts +15 -3
- package/dist/components/agent-tools/tool-call-block/tool-call-block.class.js +3 -3
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.d.ts +24 -8
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +3 -3
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +4 -0
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.d.ts +9 -5
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.styles.js +1 -1
- package/dist/components/agent-tools/tool-status.js +2 -2
- package/dist/components/agent-tools/tool-timeline/tool-timeline.class.d.ts +8 -0
- package/dist/components/agent-tools/tool-timeline/tool-timeline.class.js +3 -2
- package/dist/components/agent-tools/tool-timeline/tool-timeline.styles.js +1 -1
- package/dist/components/agent-tools/trace-tree/span.d.ts +2 -2
- package/dist/components/charts/chart/box-plot.class.d.ts +3 -1
- package/dist/components/charts/chart/box-plot.class.js +9 -9
- package/dist/components/charts/chart/chart-bidi.d.ts +109 -0
- package/dist/components/charts/chart/chart-bidi.js +1 -0
- package/dist/components/charts/chart/chart.class.d.ts +17 -2
- package/dist/components/charts/chart/chart.class.js +10 -8
- package/dist/components/charts/chart/histogram.class.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.d.ts +24 -5
- package/dist/components/charts/chart/lite-chart.class.js +9 -9
- package/dist/components/charts/chart/lite-chart.styles.js +1 -1
- package/dist/components/conversation/code-block/shiki-dark-theme.d.ts +2 -2
- package/dist/components/conversation/code-block/shiki-dark-theme.js +1 -1
- package/dist/components/conversation/conversation-item/conversation-item.class.d.ts +18 -2
- package/dist/components/conversation/conversation-item/conversation-item.class.js +3 -3
- package/dist/components/conversation/conversation-item/conversation-item.styles.js +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.d.ts +3 -1
- package/dist/components/conversation/markdown/markdown.class.d.ts +3 -1
- package/dist/components/conversation/message-actions/message-actions.class.d.ts +7 -2
- package/dist/components/conversation/message-actions/message-actions.class.js +2 -2
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +6 -2
- package/dist/components/conversation/message-parts/message-parts.class.js +5 -3
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +3 -2
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +1 -5
- package/dist/components/conversation/streaming-text/streaming-text-base.class.js +2 -2
- package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +7 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.js +3 -4
- package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +7 -1
- package/dist/components/conversation/streaming-text/streaming-text.class.js +3 -4
- package/dist/components/conversation/thread-list/thread-list.class.d.ts +13 -2
- package/dist/components/conversation/thread-list/thread-list.class.js +3 -3
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/document-library/document-library.class.js +2 -0
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.class.js +1 -1
- package/dist/components/data/flow-node/flow-node.class.d.ts +6 -2
- package/dist/components/data/flow-node/flow-node.class.js +6 -2
- package/dist/components/data/flow-node/flow-node.styles.js +1 -1
- package/dist/components/data/gauge/gauge.styles.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +3 -0
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/heatmap/heatmap.styles.js +1 -1
- package/dist/components/data/sparkline/sparkline.class.d.ts +5 -3
- package/dist/components/data/stat/stat.class.d.ts +4 -3
- package/dist/components/data/table/table.class.d.ts +32 -5
- package/dist/components/data/table/table.class.js +3 -2
- package/dist/components/forms/button/button.class.d.ts +7 -1
- package/dist/components/forms/button/button.styles.js +1 -1
- package/dist/components/forms/date-picker/date-input.styles.js +1 -1
- package/dist/components/forms/input/input.styles.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -0
- package/dist/components/layout/app-rail/app-rail.class.d.ts +50 -11
- package/dist/components/layout/app-rail/app-rail.class.js +2 -2
- package/dist/components/layout/command-palette/command-palette.class.js +1 -1
- package/dist/components/layout/menu/menu.class.d.ts +6 -5
- package/dist/components/layout/split-panel/split-panel.class.d.ts +2 -1
- package/dist/components/media/flag/language-map.d.ts +8 -0
- package/dist/components/media/flag/language-map.js +1 -1
- package/dist/components/media/map/map-loader.d.ts +7 -1
- package/dist/components/media/map/map.class.d.ts +111 -5
- package/dist/components/media/map/map.class.js +3 -3
- package/dist/components/media/media-card/media-card.class.d.ts +18 -5
- package/dist/components/media/media-card/media-card.class.js +1 -1
- package/dist/components/overlays/overlay/popover.class.d.ts +20 -0
- package/dist/components/overlays/overlay/popover.class.js +2 -2
- package/dist/components/retrieval/graph/graph.class.d.ts +3 -3
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +5 -3
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +3 -2
- package/dist/components/retrieval/mind-map/mind-map.class.d.ts +3 -3
- package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +4 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +5 -1
- package/dist/components/retrieval/source-picker/source-picker.class.d.ts +4 -1
- package/dist/components/retrieval/source-picker/source-picker.class.js +5 -1
- package/dist/components/utility/icon/icon.class.d.ts +9 -3
- package/dist/components/utility/icon/icon.class.js +1 -1
- package/dist/components/utility/mutation-observer/mutation-observer.class.d.ts +14 -8
- package/dist/components/utility/mutation-observer/mutation-observer.class.js +1 -1
- package/dist/components/viewers/document-viewer/document-viewer.class.d.ts +6 -1
- package/dist/components/viewers/document-viewer/document-viewer.class.js +7 -1
- package/dist/components/viewers/document-viewer/registry.d.ts +12 -3
- package/dist/components/viewers/geojson-view/geojson-view.class.d.ts +13 -5
- package/dist/components/viewers/geojson-view/geojson-view.class.js +1 -1
- package/dist/components/viewers/geojson-view/geojson-viewer.class.d.ts +3 -2
- package/dist/custom-elements-jsx.d.ts +1 -1
- package/dist/events.d.ts +644 -1242
- package/dist/internal/anchored-overlay-runtime.d.ts +2 -2
- package/dist/internal/cell-range.d.ts +0 -6
- package/dist/internal/cell-range.js +1 -1
- package/dist/internal/css-token-length.d.ts +7 -0
- package/dist/internal/css-token-length.js +1 -0
- package/dist/internal/default-strings.generated.d.ts +1 -1
- package/dist/internal/default-strings.generated.js +1 -1
- package/dist/internal/deferred-focus-return.d.ts +7 -4
- package/dist/internal/deferred-focus-return.js +1 -1
- package/dist/internal/dev-mode-attribute-warning.d.ts +35 -0
- package/dist/internal/dev-mode-attribute-warning.js +1 -1
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +2 -2
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/papaparse-loader.d.ts +1 -1
- package/dist/internal/papaparse-loader.js +1 -1
- package/dist/internal/positioner.d.ts +10 -0
- package/dist/internal/positioner.js +1 -1
- package/dist/internal/shared-unions.d.ts +2 -1
- package/dist/internal/slotted-overlay-controller.d.ts +20 -0
- package/dist/internal/slotted-overlay-controller.js +1 -0
- package/dist/internal/text-quote.d.ts +1 -1
- package/dist/internal/text-quote.js +1 -1
- package/dist/internal/theme-observation.d.ts +4 -0
- package/dist/internal/theme-observation.js +1 -0
- package/dist/internal/theme-watcher.js +1 -1
- package/dist/localization.d.ts +6 -1
- package/dist/localization.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/lyra.js +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/testing/lyra-tag-event-map.js +1 -1
- package/dist/translations/ar/agent-tools.js +1 -1
- package/dist/translations/cs/agent-tools.js +1 -1
- package/dist/translations/da/agent-tools.js +1 -1
- package/dist/translations/de/agent-tools.js +1 -1
- package/dist/translations/de-CH/agent-tools.js +1 -1
- package/dist/translations/es/agent-tools.js +1 -1
- package/dist/translations/fa/agent-tools.js +1 -1
- package/dist/translations/fi/agent-tools.js +1 -1
- package/dist/translations/fr/agent-tools.js +1 -1
- package/dist/translations/he/agent-tools.js +1 -1
- package/dist/translations/hi/agent-tools.js +1 -1
- package/dist/translations/hr/agent-tools.js +1 -1
- package/dist/translations/hu/agent-tools.js +1 -1
- package/dist/translations/id/agent-tools.js +1 -1
- package/dist/translations/it/agent-tools.js +1 -1
- package/dist/translations/ja/agent-tools.js +1 -1
- package/dist/translations/kk/agent-tools.js +1 -1
- package/dist/translations/ko/agent-tools.js +1 -1
- package/dist/translations/nb/agent-tools.js +1 -1
- package/dist/translations/nl/agent-tools.js +1 -1
- package/dist/translations/nn/agent-tools.js +1 -1
- package/dist/translations/pl/agent-tools.js +1 -1
- package/dist/translations/pt-BR/agent-tools.js +1 -1
- package/dist/translations/pt-PT/agent-tools.js +1 -1
- package/dist/translations/pt-PT/charts.js +1 -1
- package/dist/translations/pt-PT/conversation.js +1 -1
- package/dist/translations/pt-PT/data.js +1 -1
- package/dist/translations/pt-PT/forms.js +1 -1
- package/dist/translations/pt-PT/layout.js +1 -1
- package/dist/translations/pt-PT/media.js +1 -1
- package/dist/translations/pt-PT/retrieval.js +1 -1
- package/dist/translations/pt-PT/shared.js +1 -1
- package/dist/translations/pt-PT/utility.js +1 -1
- package/dist/translations/pt-PT/viewers.js +2 -2
- package/dist/translations/ro/agent-tools.js +1 -1
- package/dist/translations/ru/agent-tools.js +1 -1
- package/dist/translations/sl/agent-tools.js +1 -1
- package/dist/translations/sv/agent-tools.js +1 -1
- package/dist/translations/tr/agent-tools.js +1 -1
- package/dist/translations/uk/agent-tools.js +1 -1
- package/dist/translations/zh-CN/agent-tools.js +1 -1
- package/dist/translations/zh-TW/agent-tools.js +1 -1
- package/dist/utilities/index.d.ts +1 -1
- package/dist/utilities/index.js +1 -1
- package/dist/utilities/localization.d.ts +28 -10
- package/dist/vue.d.ts +1 -1
- package/llms/components/lr-accordion-item.md +2 -344
- package/llms/components/lr-accordion.md +2 -344
- package/llms/components/lr-app-rail-group.md +2 -721
- package/llms/components/lr-app-rail-item.md +2 -721
- package/llms/components/lr-app-rail.md +29 -4
- package/llms/components/lr-bar-chart.md +2 -87
- package/llms/components/lr-box-plot.md +1 -1
- package/llms/components/lr-breadcrumb-item.md +2 -67
- package/llms/components/lr-bubble-chart.md +2 -87
- package/llms/components/lr-button.md +7 -0
- package/llms/components/lr-chart.md +4 -5
- package/llms/components/lr-chip-group.md +2 -272
- package/llms/components/lr-conversation-item.md +20 -2
- package/llms/components/lr-date-input.md +2 -457
- package/llms/components/lr-date-picker.md +6 -2
- package/llms/components/lr-document-library.md +3 -3
- package/llms/components/lr-document-viewer.md +14 -5
- package/llms/components/lr-doughnut-chart.md +2 -87
- package/llms/components/lr-dropdown-item.md +2 -306
- package/llms/components/lr-dropdown.md +6 -0
- package/llms/components/lr-flag.md +9 -1
- package/llms/components/lr-flow-node.md +4 -1
- package/llms/components/lr-geojson-view.md +3 -90
- package/llms/components/lr-geojson-viewer.md +13 -5
- package/llms/components/lr-icon-button.md +4 -1
- package/llms/components/lr-icon.md +14 -6
- package/llms/components/lr-input.md +9 -2
- package/llms/components/lr-lite-chart.md +17 -9
- package/llms/components/lr-map.md +87 -2
- package/llms/components/lr-markdown-core.md +5 -4
- package/llms/components/lr-markdown.md +4 -2
- package/llms/components/lr-media-card.md +10 -5
- package/llms/components/lr-menu-item.md +2 -306
- package/llms/components/lr-menu.md +9 -6
- package/llms/components/lr-menubar-item.md +2 -125
- package/llms/components/lr-message-actions.md +4 -1
- package/llms/components/lr-message-parts.md +14 -5
- package/llms/components/lr-mutation-observer.md +12 -6
- package/llms/components/lr-navigation-menu-item.md +2 -237
- package/llms/components/lr-number-input.md +4 -0
- package/llms/components/lr-option.md +2 -712
- package/llms/components/lr-pie-chart.md +2 -87
- package/llms/components/lr-polar-area-chart.md +2 -87
- package/llms/components/lr-popover.md +10 -0
- package/llms/components/lr-prompt-input.md +5 -1
- package/llms/components/lr-radar-chart.md +2 -87
- package/llms/components/lr-reorder-item.md +2 -157
- package/llms/components/lr-result-field.md +2 -117
- package/llms/components/lr-retrieval-results.md +3 -1
- package/llms/components/lr-rubric-form.md +3 -2
- package/llms/components/lr-scatter-chart.md +2 -87
- package/llms/components/lr-selection-toolbar.md +4 -2
- package/llms/components/lr-source-card.md +2 -186
- package/llms/components/lr-source-picker.md +3 -1
- package/llms/components/lr-sparkline.md +9 -4
- package/llms/components/lr-split-panel.md +5 -3
- package/llms/components/lr-stat.md +4 -3
- package/llms/components/lr-streaming-text-core.md +7 -5
- package/llms/components/lr-streaming-text.md +9 -6
- package/llms/components/lr-swatch-picker.md +130 -0
- package/llms/components/lr-tag.md +2 -177
- package/llms/components/lr-thread-list.md +27 -4
- package/llms/components/lr-timeline-item.md +2 -120
- package/llms/components/lr-toast-item.md +2 -223
- package/llms/components/lr-tool-call-block.md +12 -3
- package/llms/components/lr-tool-call-chip.md +12 -6
- package/llms/components/lr-tool-param-form.md +3 -2
- package/llms/components/lr-tool-result-dialog.md +7 -3
- package/llms/components/lr-tool-result-view.md +4 -3
- package/llms/components/lr-tool-timeline.md +12 -5
- package/llms/components/lr-tree-item.md +2 -354
- package/llms/index.md +22 -4
- package/llms/migration.md +75 -1
- package/llms/peers.md +1 -1
- package/llms/shared.md +86 -39
- package/llms-full.txt +739 -163
- package/package.json +6 -6
- package/registrations.json +1 -1
- package/vscode-css-data.json +1 -1
- package/vscode-html-data.json +1 -1
- package/web-types.json +1 -1
package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteRange}from"../../../internal/numbers.js";import{srOnly}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./knowledge-graph-explorer.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{graphLinkIdentity,normalizeGraphModel}from"../graph/graph-model.js";import{canonicalIdentityList,isNonBlankIdentity}from"../retrieval-identity.js";import"../graph/graph.class.js";import"../graph-legend/graph-legend.class.js";import"../entity-card/entity-card.class.js";import"../neighbor-list/neighbor-list.class.js";import"../path-strip/path-strip.class.js";import"../../overlays/overlay/popover.class.js";import"../../forms/input/input.class.js";import"../../overlays/chip/chip.class.js";import"../../forms/button/button.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_graphExplorerFindPath,LYRA_DEFAULT_graphExplorerLabel,LYRA_DEFAULT_graphExplorerPin,LYRA_DEFAULT_graphExplorerPinned,LYRA_DEFAULT_graphExplorerPinnedHeading,LYRA_DEFAULT_graphExplorerSearchPlaceholder,LYRA_DEFAULT_graphExplorerSearchResultsLabel,LYRA_DEFAULT_graphExplorerUnpin,LYRA_DEFAULT_graphExplorerUnpinned,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings.generated.js";function isElementNode(value){if(typeof value!="object"||value===null)return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"&&typeof candidate.getBoundingClientRect=="function"}class LyraKnowledgeGraphExplorer extends LyraElement{constructor(){super(...arguments),this.nodes=[],this.links=[],this.nodeTypes=[],this.communities=[],this.entityDetails={},this.pinnedNodeIds=[],this.path=[],this.hiddenTypes=[],this.selectedNodeId=null,this.renderer="svg",this.fitTo="none",this.width=800,this.height=600,this.highlight="selection",this.searchQuery="",this.pinLiveText="",this.hoveredNodeId=null,this.activationGeneration=0,this.nodeById=new Map,this.linksByNodeId=new Map,this.degreeByNodeId=new Map,this.communityLabelById=new Map,this.onVisibilityChange=event=>{event.stopPropagation(),this.hiddenTypes=event.detail.hiddenTypes,this.emit("lr-hidden-types-change",{hiddenTypes:this.hiddenTypes})},this.onBeforeVisibilityChange=event=>{event.stopPropagation()},this.onSearchInput=event=>{event.stopPropagation();const value=event.detail.value;this.searchQuery!==value&&(this.searchQuery=value,this.emit("lr-search-change",{query:value,matchCount:this.matchingNodes()?.length??0,matchCountExact:!0}))},this.onEntityActivate=event=>{event.stopPropagation(),this.activateEntity(event.detail.entityId)},this.onGraphNodeClick=event=>{const id=event.detail.nodeId;if(!this.canActivateNode(id))return;const generation=this.invalidateActivation();this.setInternalSelectedNodeId(id),this.pendingNodeId=id;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;ownerWindow&&ownerWindow.queueMicrotask(()=>{generation===this.activationGeneration&&this.isConnected&&this.ownerDocument===ownerDocument&&this.pendingNodeId===id&&(this.pendingNodeId=void 0,this.selectedNodeId===id&&this.isVisibleNode(id)&&this.activateEntity(id))})},this.onGraphNativeClick=event=>{const id=this.pendingNodeId;id&&(this.pendingNodeId=void 0,this.openDetailAt(id,this.resolveDirectClickAnchor(event)))},this.onGraphViewportChange=()=>{const el=this.trackedNodeEl,popover=this.popoverEl;if(!el?.isConnected||!popover?.open)return;const rect=el.getBoundingClientRect();popover.showAt({x:rect.left+rect.width/2,y:rect.top,width:rect.width,height:rect.height})},this.onGraphNodeEnter=event=>{this.highlight==="hover"&&(this.hoveredNodeId=event.detail.nodeId)},this.onGraphNodeLeave=event=>{this.highlight==="hover"&&this.hoveredNodeId===event.detail.nodeId&&(this.hoveredNodeId=null)},this.onPopoverHide=()=>{this.invalidateActivation(),this.trackedNodeEl=void 0,this.setInternalSelectedNodeId(null)}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,graphExplorerFindPath:LYRA_DEFAULT_graphExplorerFindPath,graphExplorerLabel:LYRA_DEFAULT_graphExplorerLabel,graphExplorerPin:LYRA_DEFAULT_graphExplorerPin,graphExplorerPinned:LYRA_DEFAULT_graphExplorerPinned,graphExplorerPinnedHeading:LYRA_DEFAULT_graphExplorerPinnedHeading,graphExplorerSearchPlaceholder:LYRA_DEFAULT_graphExplorerSearchPlaceholder,graphExplorerSearchResultsLabel:LYRA_DEFAULT_graphExplorerSearchResultsLabel,graphExplorerUnpin:LYRA_DEFAULT_graphExplorerUnpin,graphExplorerUnpinned:LYRA_DEFAULT_graphExplorerUnpinned,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.ownedCollectionProperties=Object.freeze(["nodes","links","nodeTypes","communities","entityDetails","pinnedNodeIds","path","hiddenTypes"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static{this.immutableEventDetails=Object.freeze(["lr-pin-change","lr-hidden-types-change"])}get graphModel(){const sources=this.normalizedGraphSources;return(!sources||sources[0]!==this.nodes||sources[1]!==this.links||sources[2]!==this.nodeTypes||sources[3]!==this.communities)&&(this.normalizedGraphSources=[this.nodes,this.links,this.nodeTypes,this.communities],this.normalizedGraphModel=normalizeGraphModel(this.nodes,this.links,this.nodeTypes,this.communities)),this.normalizedGraphModel}get canonicalPinnedNodeIds(){return canonicalIdentityList(this.pinnedNodeIds)}get canonicalHiddenTypes(){return canonicalIdentityList(this.hiddenTypes)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.hasUpdated&&this.resumePresetActivation()}syncAnnouncementSink(){!this.isConnected||this.announcementSink?.element.ownerDocument===this.ownerDocument||(this.announcementSink?.release(),this.announcementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}willUpdate(changed){super.willUpdate(changed),(changed.has("nodes")||changed.has("links")||changed.has("communities"))&&this.rebuildDerivedCollections(),(changed.has("nodes")||changed.has("hiddenTypes"))&&this.selectedNodeId&&!this.isVisibleNode(this.selectedNodeId)&&(this.invalidateActivation(),this.setInternalSelectedNodeId(null),this.popoverEl&&(this.popoverEl.open=!1)),this.hasUpdated&&(this.searchQuery??"").trim()&&(changed.has("searchQuery")||changed.has("nodes")||changed.has("hiddenTypes")||changed.has("locale")||changed.has("strings"))&&this.announcementSink?.announce(this.searchResultAnnouncement())}updated(changed){if(super.updated(changed),!changed.has("selectedNodeId"))return;const internallyAssigned=this.internalSelectionAssignment!==void 0&&Object.is(this.internalSelectionAssignment.value,this.selectedNodeId);if(this.internalSelectionAssignment=void 0,internallyAssigned)return;const generation=this.invalidateActivation(),id=this.selectedNodeId;if(!isNonBlankIdentity(id)){id!==null&&(this.selectedNodeId=null),this.popoverEl&&(this.popoverEl.open=!1);return}const graph=this.graphEl;graph&&this.isVisibleNode(id)&&this.activatePresetWhenGraphReady(id,graph,generation)}async activatePresetWhenGraphReady(id,graph,generation){for(await graph.updateComplete;generation===this.activationGeneration&&this.isConnected&&graph.isConnected&&this.selectedNodeId===id&&graph.shadowRoot?.querySelector("lr-skeleton");)if(!await this.waitForActivationFrame(generation))return;generation===this.activationGeneration&&this.isConnected&&this.selectedNodeId===id&&this.isVisibleNode(id)&&await this.activateEntity(id)}waitForActivationFrame(generation){this.cancelActivationFrame();const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;return!ownerWindow||!this.isConnected||generation!==this.activationGeneration?Promise.resolve(!1):new Promise(resolve=>{let settled=!1;const settle=ready=>{settled||(settled=!0,resolve(ready))};let handle;const onPageHide=()=>{this.activationFrameOwner===ownerWindow&&this.activationFrameDocument===ownerDocument&&this.activationFrameResolve===settle&&this.cancelActivationFrame()};try{handle=ownerWindow.requestAnimationFrame(()=>{const current=this.activationFrameId===handle&&this.activationFrameOwner===ownerWindow&&this.activationFrameDocument===ownerDocument&&this.activationFrameResolve===settle&&generation===this.activationGeneration&&this.isConnected&&this.ownerDocument===ownerDocument;current&&this.clearActivationFrameRecord(),settle(current)})}catch{settle(!1);return}this.activationFrameId=handle,this.activationFrameOwner=ownerWindow,this.activationFrameDocument=ownerDocument,this.activationFrameResolve=settle,this.activationFramePageHide=onPageHide,ownerWindow.addEventListener("pagehide",onPageHide,{once:!0})})}clearActivationFrameRecord(){this.activationFramePageHide&&this.activationFrameOwner?.removeEventListener("pagehide",this.activationFramePageHide),this.activationFrameId=void 0,this.activationFrameOwner=void 0,this.activationFrameDocument=void 0,this.activationFrameResolve=void 0,this.activationFramePageHide=void 0}cancelActivationFrame(){const handle=this.activationFrameId,ownerWindow=this.activationFrameOwner,settle=this.activationFrameResolve;this.clearActivationFrameRecord();try{handle!==void 0&&ownerWindow?.cancelAnimationFrame(handle)}finally{settle?.(!1)}}invalidateActivation(){return this.activationGeneration+=1,this.cancelActivationFrame(),this.activationGeneration}resumePresetActivation(){const id=this.selectedNodeId,graph=this.graphEl;if(!id||!graph||!this.isVisibleNode(id))return;const generation=this.invalidateActivation();this.activatePresetWhenGraphReady(id,graph,generation)}setInternalSelectedNodeId(value){Object.is(this.selectedNodeId,value)||(this.internalSelectionAssignment={value},this.selectedNodeId=value,this.emit("lr-selection-change",{selectedNodeId:value}))}disconnectedCallback(){this.invalidateActivation(),this.pendingNodeId=void 0,this.trackedNodeEl=void 0,this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.invalidateActivation(),this.announcementSink?.release(),this.announcementSink=void 0,this.isConnected&&(this.syncAnnouncementSink(),this.resumePresetActivation())}rebuildDerivedCollections(){const model=this.graphModel;this.nodeById=new Map(model.nodes.map(node=>[node.id,node])),this.communityLabelById=new Map(model.communities.map(community=>[community.id,community.label]));const linksByNodeId=new Map,degrees=new Map;for(const link of model.links)for(const id of new Set([link.source,link.target])){const adjacent=linksByNodeId.get(id);adjacent?adjacent.push(link):linksByNodeId.set(id,[link]),degrees.set(id,(degrees.get(id)??0)+1)}this.linksByNodeId=linksByNodeId,this.degreeByNodeId=degrees}isVisibleNode(id){const node=this.nodeById.get(id);return!!node&&(node.type==null||!this.canonicalHiddenTypes.includes(node.type))}canActivateNode(id){const node=this.graphModel.nodes.find(candidate=>candidate.id===id);return node?node.type==null||!this.canonicalHiddenTypes.includes(node.type):!this.hasUpdated&&this.graphModel.nodes.length===0}nodeLabel(id){const node=this.nodeById.get(id);return node?.label||node?.accessibleLabel||id}degreeOf(id){return this.degreeByNodeId.get(id)??0}entityFor(id){const node=this.nodeById.get(id);if(!node)return;const details=this.entityDetails[id];return{id:node.id,label:node.label||node.accessibleLabel||node.id,type:node.type,communityId:node.communityId,description:details?.description,properties:details?.properties,degree:details?.degree??this.degreeOf(node.id)}}communityLabelFor(communityId){return communityId?this.communityLabelById.get(communityId)??communityId:""}neighborRowsFor(id){const rows=[];for(const link of this.linksByNodeId.get(id)??[])if(link.source===id){const node=this.entityFor(link.target);node&&this.isVisibleNode(link.target)&&rows.push({relation:link.label??"",direction:"out",node})}else if(link.target===id){const node=this.entityFor(link.source);node&&this.isVisibleNode(link.source)&&rows.push({relation:link.label??"",direction:"in",node})}return rows}searchableNamesOf(node){return[node.label,node.accessibleLabel,node.id].filter(name=>typeof name=="string"&&name!=="")}matchingNodes(){const q=(this.searchQuery??"").trim().toLocaleLowerCase(this.effectiveLocale);if(q)return this.graphModel.nodes.filter(node=>this.isVisibleNode(node.id)&&this.searchableNamesOf(node).some(name=>name.toLocaleLowerCase(this.effectiveLocale).includes(q)))}searchResultAnnouncement(matches=this.matchingNodes()){return matches?matches.length===0?this.localize("viewerSearchNoMatches"):this.localize("viewerSearchMatchCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(matches.length),pluralCount:matches.length}):""}neighborIdsOf(id){const ids=new Set;for(const link of this.linksByNodeId.get(id)??[])link.source===id?ids.add(link.target):link.target===id&&ids.add(link.source);return ids}linkKey(link){return graphLinkIdentity(link)}get computedDimmedNodeIds(){if(this.highlight==="none")return[];const matches=this.matchingNodes();if(matches){const matchIds=new Set(matches.map(n=>n.id));return this.graphModel.nodes.filter(n=>!matchIds.has(n.id)).map(n=>n.id)}const focusNodeId=this.selectedNodeId??(this.highlight==="hover"?this.hoveredNodeId:null);if(focusNodeId){const keep=this.neighborIdsOf(focusNodeId);return keep.add(focusNodeId),this.graphModel.nodes.filter(n=>!keep.has(n.id)).map(n=>n.id)}return[]}get computedDimmedLinkIds(){const dimmedNodes=new Set(this.computedDimmedNodeIds);return dimmedNodes.size===0?[]:this.graphModel.links.filter(l=>dimmedNodes.has(l.source)||dimmedNodes.has(l.target)).map(l=>this.linkKey(l))}togglePin(id){if(!isNonBlankIdentity(id))return;const pinnedNodeIds=this.canonicalPinnedNodeIds,wasPinned=pinnedNodeIds.includes(id),next=wasPinned?pinnedNodeIds.filter(existing=>existing!==id):[...pinnedNodeIds,id];this.pinnedNodeIds=next,this.pinLiveText=this.localize(wasPinned?"graphExplorerUnpinned":"graphExplorerPinned",void 0,{label:this.nodeLabel(id)}),this.announcementSink?.announce(this.pinLiveText),this.emit("lr-pin-change",{pinnedNodeIds:next})}requestPath(){const pinnedNodeIds=this.canonicalPinnedNodeIds;if(pinnedNodeIds.length!==2)return;const[sourceNodeId,targetNodeId]=pinnedNodeIds;this.emit("lr-path-request",{sourceNodeId,targetNodeId})}async activateEntity(id){if(!this.canActivateNode(id))return;const generation=this.invalidateActivation();this.setInternalSelectedNodeId(id),this.trackedNodeEl=void 0;const graph=this.graphEl,focused=graph?await graph.focusNode(id):!1;if(generation!==this.activationGeneration||!this.isConnected||this.selectedNodeId!==id||!this.isVisibleNode(id)||!focused)return;const rect=graph?.getBoundingClientRect();rect&&this.openDetailAt(id,{x:rect.left+rect.width/2,y:rect.top+rect.height/2,width:0,height:0})}openDetailAt(id,rect){const popover=this.popoverEl;popover&&(popover.accessibleLabel=this.entityFor(id)?.label||"",popover.showAt(rect))}resolveDirectClickAnchor(event){if(this.renderer==="canvas")return this.trackedNodeEl=void 0,{x:event.clientX,y:event.clientY,width:0,height:0};const nodeEl=event.composedPath().find(el=>isElementNode(el)&&el.matches('[part="node"]'));if(!nodeEl)return this.trackedNodeEl=void 0,{x:event.clientX,y:event.clientY,width:0,height:0};this.trackedNodeEl=nodeEl;const rect=nodeEl.getBoundingClientRect();return{x:rect.left+rect.width/2,y:rect.top,width:rect.width,height:rect.height}}render(){const groupLabel=retrievalSemanticLabel(this,this.label==null?this.localize("graphExplorerLabel"):this.label),groupRole=retrievalSemanticRole(this,"group"),matches=this.matchingNodes(),model=this.graphModel,pinnedNodeIds=this.canonicalPinnedNodeIds,hiddenTypes=this.canonicalHiddenTypes,selectedEntity=this.selectedNodeId?this.entityFor(this.selectedNodeId)??null:null,isPinned=this.selectedNodeId!=null&&pinnedNodeIds.includes(this.selectedNodeId);return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteRange}from"../../../internal/numbers.js";import{srOnly}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./knowledge-graph-explorer.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{graphLinkIdentity,normalizeGraphModel}from"../graph/graph-model.js";import{canonicalIdentityList,isNonBlankIdentity}from"../retrieval-identity.js";import"../graph/graph.class.js";import"../graph-legend/graph-legend.class.js";import"../entity-card/entity-card.class.js";import"../neighbor-list/neighbor-list.class.js";import"../path-strip/path-strip.class.js";import"../../overlays/overlay/popover.class.js";import"../../forms/input/input.class.js";import"../../overlays/chip/chip.class.js";import"../../forms/button/button.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_graphExplorerFindPath,LYRA_DEFAULT_graphExplorerLabel,LYRA_DEFAULT_graphExplorerPin,LYRA_DEFAULT_graphExplorerPinned,LYRA_DEFAULT_graphExplorerPinnedHeading,LYRA_DEFAULT_graphExplorerSearchPlaceholder,LYRA_DEFAULT_graphExplorerSearchResultsLabel,LYRA_DEFAULT_graphExplorerUnpin,LYRA_DEFAULT_graphExplorerUnpinned,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings.generated.js";function isElementNode(value){if(typeof value!="object"||value===null)return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"&&typeof candidate.getBoundingClientRect=="function"}class LyraKnowledgeGraphExplorer extends LyraElement{constructor(){super(...arguments),this.nodes=[],this.links=[],this.nodeTypes=[],this.communities=[],this.entityDetails={},this.pinnedNodeIds=[],this.path=[],this.hiddenTypes=[],this.selectedNodeId=null,this.renderer="svg",this.fitTo="none",this.width=800,this.height=600,this.highlight="selection",this.searchQuery="",this.pinLiveText="",this.hoveredNodeId=null,this.activationGeneration=0,this.nodeById=new Map,this.linksByNodeId=new Map,this.degreeByNodeId=new Map,this.communityLabelById=new Map,this.onVisibilityChange=event=>{event.stopPropagation(),this.hiddenTypes=event.detail.hiddenTypes,this.emit("lr-hidden-types-change",{hiddenTypes:this.hiddenTypes})},this.onVisibilityChangeProposal=event=>{event.stopPropagation()},this.onSearchInput=event=>{event.stopPropagation();const value=event.detail.value;this.searchQuery!==value&&(this.searchQuery=value,this.emit("lr-search-change",{query:value,matchCount:this.matchingNodes()?.length??0,matchCountExact:!0}))},this.onEntityActivate=event=>{event.stopPropagation(),this.activateEntity(event.detail.entityId)},this.onGraphNodeClick=event=>{const id=event.detail.nodeId;if(!this.canActivateNode(id))return;const generation=this.invalidateActivation();this.setInternalSelectedNodeId(id),this.pendingNodeId=id;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;ownerWindow&&ownerWindow.queueMicrotask(()=>{generation===this.activationGeneration&&this.isConnected&&this.ownerDocument===ownerDocument&&this.pendingNodeId===id&&(this.pendingNodeId=void 0,this.selectedNodeId===id&&this.isVisibleNode(id)&&this.activateEntity(id))})},this.onGraphNativeClick=event=>{const id=this.pendingNodeId;id&&(this.pendingNodeId=void 0,this.openDetailAt(id,this.resolveDirectClickAnchor(event)))},this.onGraphViewportChange=()=>{const el=this.trackedNodeEl,popover=this.popoverEl;if(!el?.isConnected||!popover?.open)return;const rect=el.getBoundingClientRect();popover.showAt({x:rect.left+rect.width/2,y:rect.top,width:rect.width,height:rect.height})},this.onGraphNodeEnter=event=>{this.highlight==="hover"&&(this.hoveredNodeId=event.detail.nodeId)},this.onGraphNodeLeave=event=>{this.highlight==="hover"&&this.hoveredNodeId===event.detail.nodeId&&(this.hoveredNodeId=null)},this.onPopoverHide=()=>{this.invalidateActivation(),this.trackedNodeEl=void 0,this.setInternalSelectedNodeId(null)}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,graphExplorerFindPath:LYRA_DEFAULT_graphExplorerFindPath,graphExplorerLabel:LYRA_DEFAULT_graphExplorerLabel,graphExplorerPin:LYRA_DEFAULT_graphExplorerPin,graphExplorerPinned:LYRA_DEFAULT_graphExplorerPinned,graphExplorerPinnedHeading:LYRA_DEFAULT_graphExplorerPinnedHeading,graphExplorerSearchPlaceholder:LYRA_DEFAULT_graphExplorerSearchPlaceholder,graphExplorerSearchResultsLabel:LYRA_DEFAULT_graphExplorerSearchResultsLabel,graphExplorerUnpin:LYRA_DEFAULT_graphExplorerUnpin,graphExplorerUnpinned:LYRA_DEFAULT_graphExplorerUnpinned,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.ownedCollectionProperties=Object.freeze(["nodes","links","nodeTypes","communities","entityDetails","pinnedNodeIds","path","hiddenTypes"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static{this.immutableEventDetails=Object.freeze(["lr-pin-change","lr-hidden-types-change"])}get graphModel(){const sources=this.normalizedGraphSources;return(!sources||sources[0]!==this.nodes||sources[1]!==this.links||sources[2]!==this.nodeTypes||sources[3]!==this.communities)&&(this.normalizedGraphSources=[this.nodes,this.links,this.nodeTypes,this.communities],this.normalizedGraphModel=normalizeGraphModel(this.nodes,this.links,this.nodeTypes,this.communities)),this.normalizedGraphModel}get canonicalPinnedNodeIds(){return canonicalIdentityList(this.pinnedNodeIds)}get canonicalHiddenTypes(){return canonicalIdentityList(this.hiddenTypes)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.hasUpdated&&this.resumePresetActivation()}syncAnnouncementSink(){!this.isConnected||this.announcementSink?.element.ownerDocument===this.ownerDocument||(this.announcementSink?.release(),this.announcementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}willUpdate(changed){super.willUpdate(changed),(changed.has("nodes")||changed.has("links")||changed.has("communities"))&&this.rebuildDerivedCollections(),(changed.has("nodes")||changed.has("hiddenTypes"))&&this.selectedNodeId&&!this.isVisibleNode(this.selectedNodeId)&&(this.invalidateActivation(),this.setInternalSelectedNodeId(null),this.popoverEl&&(this.popoverEl.open=!1)),this.hasUpdated&&(this.searchQuery??"").trim()&&(changed.has("searchQuery")||changed.has("nodes")||changed.has("hiddenTypes")||changed.has("locale")||changed.has("strings"))&&this.announcementSink?.announce(this.searchResultAnnouncement())}updated(changed){if(super.updated(changed),!changed.has("selectedNodeId"))return;const internallyAssigned=this.internalSelectionAssignment!==void 0&&Object.is(this.internalSelectionAssignment.value,this.selectedNodeId);if(this.internalSelectionAssignment=void 0,internallyAssigned)return;const generation=this.invalidateActivation(),id=this.selectedNodeId;if(!isNonBlankIdentity(id)){id!==null&&(this.selectedNodeId=null),this.popoverEl&&(this.popoverEl.open=!1);return}const graph=this.graphEl;graph&&this.isVisibleNode(id)&&this.activatePresetWhenGraphReady(id,graph,generation)}async activatePresetWhenGraphReady(id,graph,generation){for(await graph.updateComplete;generation===this.activationGeneration&&this.isConnected&&graph.isConnected&&this.selectedNodeId===id&&graph.shadowRoot?.querySelector("lr-skeleton");)if(!await this.waitForActivationFrame(generation))return;generation===this.activationGeneration&&this.isConnected&&this.selectedNodeId===id&&this.isVisibleNode(id)&&await this.activateEntity(id)}waitForActivationFrame(generation){this.cancelActivationFrame();const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;return!ownerWindow||!this.isConnected||generation!==this.activationGeneration?Promise.resolve(!1):new Promise(resolve=>{let settled=!1;const settle=ready=>{settled||(settled=!0,resolve(ready))};let handle;const onPageHide=()=>{this.activationFrameOwner===ownerWindow&&this.activationFrameDocument===ownerDocument&&this.activationFrameResolve===settle&&this.cancelActivationFrame()};try{handle=ownerWindow.requestAnimationFrame(()=>{const current=this.activationFrameId===handle&&this.activationFrameOwner===ownerWindow&&this.activationFrameDocument===ownerDocument&&this.activationFrameResolve===settle&&generation===this.activationGeneration&&this.isConnected&&this.ownerDocument===ownerDocument;current&&this.clearActivationFrameRecord(),settle(current)})}catch{settle(!1);return}this.activationFrameId=handle,this.activationFrameOwner=ownerWindow,this.activationFrameDocument=ownerDocument,this.activationFrameResolve=settle,this.activationFramePageHide=onPageHide,ownerWindow.addEventListener("pagehide",onPageHide,{once:!0})})}clearActivationFrameRecord(){this.activationFramePageHide&&this.activationFrameOwner?.removeEventListener("pagehide",this.activationFramePageHide),this.activationFrameId=void 0,this.activationFrameOwner=void 0,this.activationFrameDocument=void 0,this.activationFrameResolve=void 0,this.activationFramePageHide=void 0}cancelActivationFrame(){const handle=this.activationFrameId,ownerWindow=this.activationFrameOwner,settle=this.activationFrameResolve;this.clearActivationFrameRecord();try{handle!==void 0&&ownerWindow?.cancelAnimationFrame(handle)}finally{settle?.(!1)}}invalidateActivation(){return this.activationGeneration+=1,this.cancelActivationFrame(),this.activationGeneration}resumePresetActivation(){const id=this.selectedNodeId,graph=this.graphEl;if(!id||!graph||!this.isVisibleNode(id))return;const generation=this.invalidateActivation();this.activatePresetWhenGraphReady(id,graph,generation)}setInternalSelectedNodeId(value){Object.is(this.selectedNodeId,value)||(this.internalSelectionAssignment={value},this.selectedNodeId=value,this.emit("lr-selection-change",{selectedNodeId:value}))}disconnectedCallback(){this.invalidateActivation(),this.pendingNodeId=void 0,this.trackedNodeEl=void 0,this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.invalidateActivation(),this.announcementSink?.release(),this.announcementSink=void 0,this.isConnected&&(this.syncAnnouncementSink(),this.resumePresetActivation())}rebuildDerivedCollections(){const model=this.graphModel;this.nodeById=new Map(model.nodes.map(node=>[node.id,node])),this.communityLabelById=new Map(model.communities.map(community=>[community.id,community.label]));const linksByNodeId=new Map,degrees=new Map;for(const link of model.links)for(const id of new Set([link.source,link.target])){const adjacent=linksByNodeId.get(id);adjacent?adjacent.push(link):linksByNodeId.set(id,[link]),degrees.set(id,(degrees.get(id)??0)+1)}this.linksByNodeId=linksByNodeId,this.degreeByNodeId=degrees}isVisibleNode(id){const node=this.nodeById.get(id);return!!node&&(node.type==null||!this.canonicalHiddenTypes.includes(node.type))}canActivateNode(id){const node=this.graphModel.nodes.find(candidate=>candidate.id===id);return node?node.type==null||!this.canonicalHiddenTypes.includes(node.type):!this.hasUpdated&&this.graphModel.nodes.length===0}nodeLabel(id){const node=this.nodeById.get(id);return node?.label||node?.accessibleLabel||id}degreeOf(id){return this.degreeByNodeId.get(id)??0}entityFor(id){const node=this.nodeById.get(id);if(!node)return;const details=this.entityDetails[id];return{id:node.id,label:node.label||node.accessibleLabel||node.id,type:node.type,communityId:node.communityId,description:details?.description,properties:details?.properties,degree:details?.degree??this.degreeOf(node.id)}}communityLabelFor(communityId){return communityId?this.communityLabelById.get(communityId)??communityId:""}neighborRowsFor(id){const rows=[];for(const link of this.linksByNodeId.get(id)??[])if(link.source===id){const node=this.entityFor(link.target);node&&this.isVisibleNode(link.target)&&rows.push({relation:link.label??"",direction:"out",node})}else if(link.target===id){const node=this.entityFor(link.source);node&&this.isVisibleNode(link.source)&&rows.push({relation:link.label??"",direction:"in",node})}return rows}searchableNamesOf(node){return[node.label,node.accessibleLabel,node.id].filter(name=>typeof name=="string"&&name!=="")}matchingNodes(){const q=(this.searchQuery??"").trim().toLocaleLowerCase(this.effectiveLocale);if(q)return this.graphModel.nodes.filter(node=>this.isVisibleNode(node.id)&&this.searchableNamesOf(node).some(name=>name.toLocaleLowerCase(this.effectiveLocale).includes(q)))}searchResultAnnouncement(matches=this.matchingNodes()){return matches?matches.length===0?this.localize("viewerSearchNoMatches"):this.localize("viewerSearchMatchCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(matches.length),pluralCount:matches.length}):""}neighborIdsOf(id){const ids=new Set;for(const link of this.linksByNodeId.get(id)??[])link.source===id?ids.add(link.target):link.target===id&&ids.add(link.source);return ids}linkKey(link){return graphLinkIdentity(link)}get computedDimmedNodeIds(){if(this.highlight==="none")return[];const matches=this.matchingNodes();if(matches){const matchIds=new Set(matches.map(n=>n.id));return this.graphModel.nodes.filter(n=>!matchIds.has(n.id)).map(n=>n.id)}const focusNodeId=this.selectedNodeId??(this.highlight==="hover"?this.hoveredNodeId:null);if(focusNodeId){const keep=this.neighborIdsOf(focusNodeId);return keep.add(focusNodeId),this.graphModel.nodes.filter(n=>!keep.has(n.id)).map(n=>n.id)}return[]}get computedDimmedLinkIds(){const dimmedNodes=new Set(this.computedDimmedNodeIds);return dimmedNodes.size===0?[]:this.graphModel.links.filter(l=>dimmedNodes.has(l.source)||dimmedNodes.has(l.target)).map(l=>this.linkKey(l))}togglePin(id){if(!isNonBlankIdentity(id))return;const pinnedNodeIds=this.canonicalPinnedNodeIds,wasPinned=pinnedNodeIds.includes(id),next=wasPinned?pinnedNodeIds.filter(existing=>existing!==id):[...pinnedNodeIds,id];this.pinnedNodeIds=next,this.pinLiveText=this.localize(wasPinned?"graphExplorerUnpinned":"graphExplorerPinned",void 0,{label:this.nodeLabel(id)}),this.announcementSink?.announce(this.pinLiveText),this.emit("lr-pin-change",{pinnedNodeIds:next})}requestPath(){const pinnedNodeIds=this.canonicalPinnedNodeIds;if(pinnedNodeIds.length!==2)return;const[sourceNodeId,targetNodeId]=pinnedNodeIds;this.emit("lr-path-request",{sourceNodeId,targetNodeId})}async activateEntity(id){if(!this.canActivateNode(id))return;const generation=this.invalidateActivation();this.setInternalSelectedNodeId(id),this.trackedNodeEl=void 0;const graph=this.graphEl,focused=graph?await graph.focusNode(id):!1;if(generation!==this.activationGeneration||!this.isConnected||this.selectedNodeId!==id||!this.isVisibleNode(id)||!focused)return;const rect=graph?.getBoundingClientRect();rect&&this.openDetailAt(id,{x:rect.left+rect.width/2,y:rect.top+rect.height/2,width:0,height:0})}openDetailAt(id,rect){const popover=this.popoverEl;popover&&(popover.accessibleLabel=this.entityFor(id)?.label||"",popover.showAt(rect))}resolveDirectClickAnchor(event){if(this.renderer==="canvas")return this.trackedNodeEl=void 0,{x:event.clientX,y:event.clientY,width:0,height:0};const nodeEl=event.composedPath().find(el=>isElementNode(el)&&el.matches('[part="node"]'));if(!nodeEl)return this.trackedNodeEl=void 0,{x:event.clientX,y:event.clientY,width:0,height:0};this.trackedNodeEl=nodeEl;const rect=nodeEl.getBoundingClientRect();return{x:rect.left+rect.width/2,y:rect.top,width:rect.width,height:rect.height}}render(){const groupLabel=retrievalSemanticLabel(this,this.label==null?this.localize("graphExplorerLabel"):this.label),groupRole=retrievalSemanticRole(this,"group"),matches=this.matchingNodes(),model=this.graphModel,pinnedNodeIds=this.canonicalPinnedNodeIds,hiddenTypes=this.canonicalHiddenTypes,selectedEntity=this.selectedNodeId?this.entityFor(this.selectedNodeId)??null:null,isPinned=this.selectedNodeId!=null&&pinnedNodeIds.includes(this.selectedNodeId);return html`
|
|
2
2
|
<div
|
|
3
3
|
part="base"
|
|
4
4
|
role=${groupRole??nothing}
|
|
@@ -17,7 +17,8 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
17
17
|
part="legend"
|
|
18
18
|
.types=${model.nodeTypes}
|
|
19
19
|
.hiddenTypes=${hiddenTypes}
|
|
20
|
-
@lr-
|
|
20
|
+
@lr-visibility-change-request=${this.onVisibilityChangeProposal}
|
|
21
|
+
@lr-before-visibility-change=${this.onVisibilityChangeProposal}
|
|
21
22
|
@lr-visibility-change=${this.onVisibilityChange}
|
|
22
23
|
></lr-graph-legend>
|
|
23
24
|
</div>
|
|
@@ -62,7 +62,7 @@ private get effectiveExpandDepth();private isExpanded;
|
|
|
62
62
|
/** Resolves `--lr-mind-map-ring-gap` to a real used pixel value for whatever unit it carries --
|
|
63
63
|
* a live root/host font-size read for rem/em (a hardcoded `* 16` gets ring spacing wrong on any
|
|
64
64
|
* page whose root font-size isn't the browser default 16px), delegated to the shared
|
|
65
|
-
* `
|
|
66
|
-
*
|
|
67
|
-
*
|
|
65
|
+
* `resolveCssTokenLength()` so every unit-resolving component agrees on what a length means. A value
|
|
66
|
+
* with no usable pixel length (including a percentage with no base) falls back to the default
|
|
67
|
+
* gap rather than being read as raw pixels. CSS math uses the host's theme scope. */
|
|
68
68
|
private ringGapPx;private relayout;protected willUpdate(changed:PropertyValues):void;private setAnnouncement;private toggle;private activate;private siblingsOf;private childrenOf;private announce;private focusNodeById;private onKeyDown;private onFocusIn;private onNodeClick;private connectorControlPoint;private renderSemanticNode;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-mind-map':LyraMindMap;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{isRtl}from"../../../internal/rtl.js";import{finiteCount}from"../../../internal/numbers.js";import{
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{isRtl}from"../../../internal/rtl.js";import{finiteCount}from"../../../internal/numbers.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{decimateMindMapLayout,layoutMindMap}from"./mind-map-layout.js";import{styles}from"./mind-map.styles.js";import{LYRA_DEFAULT_mindMapCollapsed,LYRA_DEFAULT_mindMapExpanded,LYRA_DEFAULT_mindMapLabel,LYRA_DEFAULT_mindMapLeafStatus,LYRA_DEFAULT_mindMapNodeLimit,LYRA_DEFAULT_mindMapTopicStatus,LYRA_DEFAULT_noData}from"../../../internal/default-strings.generated.js";const DEFAULT_RING_GAP_PX=96,MAX_RENDERED_MIND_MAP_NODES=500,NAV_KEYS=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","Enter"," "]);class LyraMindMap extends LyraElement{constructor(){super(...arguments),this.topics=[],this.expandDepth=1,this.expandedOverrides=new Map,this.focusedId=null,this.liveText="",this.cachedLayout={placed:[],links:[],width:0,height:0,centerX:0,centerY:0},this.totalTopicCount=0,this.topicsTruncated=!1,this.ownerRealmGeneration=0,this.observedSize="",this.layoutInvalidated=!0,this.layoutContext="",this.onKeyDown=e=>{const placed=this.cachedLayout.placed;if(placed.length===0||!NAV_KEYS.has(e.key))return;if(e.preventDefault(),this.focusedId===null){this.focusNodeById(placed[0].id);return}const current=placed.find(p=>p.id===this.focusedId);if(!current)return;if(e.key==="Enter"||e.key===" "){this.activate(current);return}if(e.key==="ArrowUp"){current.parentId&&this.focusNodeById(current.parentId);return}if(e.key==="ArrowDown"){if(!current.hasChildren)return;this.isExpanded(current.id,current.depth)||this.toggle(current,!1);const child=this.childrenOf(current.id)[0];child&&this.focusNodeById(child.id);return}const rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";if(e.key===forwardKey||e.key===backwardKey||e.key==="Home"||e.key==="End"){const siblings=this.siblingsOf(current),index=siblings.findIndex(s=>s.id===current.id);let next=index;e.key===forwardKey?next=Math.min(siblings.length-1,index+1):e.key===backwardKey?next=Math.max(0,index-1):e.key==="Home"?next=0:next=siblings.length-1;const target=siblings[next];target&&this.focusNodeById(target.id)}},this.onFocusIn=()=>{if(this.focusedId!==null)return;const first=this.cachedLayout.placed[0];first&&(this.focusedId=first.id)}}static{this.defaultStrings={...super.defaultStrings,mindMapCollapsed:LYRA_DEFAULT_mindMapCollapsed,mindMapExpanded:LYRA_DEFAULT_mindMapExpanded,mindMapLabel:LYRA_DEFAULT_mindMapLabel,mindMapLeafStatus:LYRA_DEFAULT_mindMapLeafStatus,mindMapNodeLimit:LYRA_DEFAULT_mindMapNodeLimit,mindMapTopicStatus:LYRA_DEFAULT_mindMapTopicStatus,noData:LYRA_DEFAULT_noData}}static{this.ownedCollectionProperties=Object.freeze(["topics"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"dir","lang"])]}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.layoutInvalidated=!0,this.armResizeObserver()}armResizeObserver(){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!this.isConnected||!ownerWindow?.ResizeObserver||this.resizeObserver&&this.resizeObserverDocument===ownerDocument)return;this.resetResizeWork();const generation=this.ownerRealmGeneration,observer=new ownerWindow.ResizeObserver(entries=>{if(this.resizeObserver!==observer||this.resizeObserverDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;const rect=entries[0]?.contentRect,size=rect?`${rect.width}:${rect.height}`:"";if(size&&size===this.observedSize)return;this.observedSize=size,this.resizeRafId!=null&&this.resizeRafOwner?.cancelAnimationFrame(this.resizeRafId);const handle=ownerWindow.requestAnimationFrame(()=>{this.resizeRafId!==handle||this.resizeRafOwner!==ownerWindow||this.resizeRafDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.resizeRafId=void 0,this.resizeRafOwner=void 0,this.resizeRafDocument=void 0,this.layoutInvalidated=!0,this.requestUpdate())});this.resizeRafId=handle,this.resizeRafOwner=ownerWindow,this.resizeRafDocument=ownerDocument});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,observer.observe(this)}disconnectedCallback(){this.resetResizeWork(),this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetResizeWork(),this.announcementSink?.release(),this.announcementSink=void 0}resetResizeWork(){this.ownerRealmGeneration+=1,this.resizeRafId!=null&&this.resizeRafOwner?.cancelAnimationFrame(this.resizeRafId),this.resizeRafId=void 0,this.resizeRafOwner=void 0,this.resizeRafDocument=void 0,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0,this.observedSize=""}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),(name==="dir"||name==="lang")&&oldValue!==value&&(this.layoutInvalidated=!0,this.requestUpdate())}get effectiveExpandDepth(){return finiteCount(this.expandDepth,1)}isExpanded(id,depth){return this.expandedOverrides.get(id)??depth<this.effectiveExpandDepth}ringGapPx(){const hostStyle=this.ownerDocument.defaultView?.getComputedStyle(this)??this.style,raw=hostStyle.getPropertyValue("--lr-mind-map-ring-gap").trim()||hostStyle.getPropertyValue("--_lr-mind-map-ring-gap").trim();return resolveCssTokenLength(raw,{host:this})??DEFAULT_RING_GAP_PX}relayout(){const hubLabel=this.label==null?this.localize("mindMapLabel"):this.label,fullLayout=layoutMindMap(this.topics,hubLabel,{ringGap:this.ringGapPx(),rtl:isRtl(this),isExpanded:(id,depth)=>this.isExpanded(id,depth)}),decimated=decimateMindMapLayout(fullLayout.placed,fullLayout.links,MAX_RENDERED_MIND_MAP_NODES);this.totalTopicCount=decimated.totalCount,this.topicsTruncated=decimated.truncated,this.cachedLayout={...fullLayout,placed:[...decimated.placed],links:[...decimated.links]}}willUpdate(changed){super.willUpdate(changed);const context=`${this.label==null?this.localize("mindMapLabel"):this.label}\0${isRtl(this)?"rtl":"ltr"}\0${this.ringGapPx()}`,structuralChange=changed.has("topics")||changed.has("expandDepth")||changed.has("expandedOverrides")||changed.has("label")||changed.has("strings")||changed.has("locale");(this.layoutInvalidated||structuralChange||context!==this.layoutContext)&&(this.relayout(),this.layoutContext=context,this.layoutInvalidated=!1,this.focusedId&&!this.cachedLayout.placed.some(topic=>topic.id===this.focusedId)&&(this.focusedId=this.cachedLayout.placed[0]?.id??null))}setAnnouncement(text){this.liveText=text,this.announcementSink?.announce(text)}toggle(node,announce=!0){const expanded=!this.isExpanded(node.id,node.depth),next=new Map(this.expandedOverrides);next.set(node.id,expanded),this.expandedOverrides=next,this.emit("lr-topic-toggle",{topicId:node.id,expanded}),announce&&this.setAnnouncement(this.localize(expanded?"mindMapExpanded":"mindMapCollapsed",void 0,{label:node.label}))}activate(node){node.hasChildren?this.toggle(node):this.emit("lr-topic-select",{topicId:node.id})}siblingsOf(node){return this.cachedLayout.placed.filter(p=>p.parentId===node.parentId)}childrenOf(id){return this.cachedLayout.placed.filter(p=>p.parentId===id)}announce(node){const numberFormat=getNumberFormat(this.effectiveLocale);this.setAnnouncement(node.hasChildren?this.localize("mindMapTopicStatus",void 0,{label:node.label,level:numberFormat.format(node.depth+1),count:numberFormat.format(this.childrenOf(node.id).length)}):this.localize("mindMapLeafStatus",void 0,{label:node.label,level:numberFormat.format(node.depth+1)}))}focusNodeById(id){this.focusedId=id;const node=this.cachedLayout.placed.find(p=>p.id===id);node&&this.announce(node)}onNodeClick(node){this.focusedId=node.id,this.svgEl?.focus(),node.hasChildren||this.announce(node),this.activate(node)}connectorControlPoint(from,to){const layout=this.cachedLayout,parentR=Math.hypot(from.x-layout.centerX,from.y-layout.centerY),dir=isRtl(this)?-1:1;return{x:layout.centerX+dir*parentR*Math.sin(to.angle),y:layout.centerY-parentR*Math.cos(to.angle)}}renderSemanticNode(node,childrenByParent){const children=childrenByParent.get(node.id)??[];return html`
|
|
2
2
|
<div
|
|
3
3
|
role="treeitem"
|
|
4
4
|
aria-level=${node.depth+1}
|
|
@@ -190,4 +190,7 @@ private canonicalChunks;private normalizedSelectedChunkIds;private get processed
|
|
|
190
190
|
/** Group-id order: a comparator sorts the first-seen ids; an explicit array leads, with any
|
|
191
191
|
* first-seen id it omits following in its own order (never dropped, which would silently hide
|
|
192
192
|
* rows). */
|
|
193
|
-
private orderedGroupKeys;private bucketed;
|
|
193
|
+
private orderedGroupKeys;private bucketed;
|
|
194
|
+
/** The row checkbox is internal selection chrome: its toggle proposal and every alias of its
|
|
195
|
+
* commit stay inside, and `lr-select` is the one host-level report of the interaction. */
|
|
196
|
+
private stopOwnedEvent;private toggleSelect;private formatMetadataValue;private renderMetadata;private renderRow;private renderLoadMoreFooter;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-retrieval-results':LyraRetrievalResults;}}
|
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity,canonicalIdentityList,isValidRetrievalChunk}from"../retrieval-identity.js";import{finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{styles}from"./retrieval-results.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{announceAfterFirstPaint}from"../retrieval-announcements.js";import{LYRA_DEFAULT_chunkInspectorEmpty,LYRA_DEFAULT_chunkInspectorLabel,LYRA_DEFAULT_loadMore,LYRA_DEFAULT_retrievalResultsSelectRow,LYRA_DEFAULT_untitledSource}from"../../../internal/default-strings.generated.js";function toLyraChunk(chunk){return{id:chunk.id,text:chunk.text,score:chunk.score,sourceId:chunk.source.id,title:chunk.source.name,anchor:chunk.locator,page:chunk.locator?.kind==="page"?chunk.locator.page:void 0}}function safeScore(score){return finiteRange(score,0,0,1)}class LyraRetrievalResults extends LyraElement{constructor(){super(...arguments),this.chunks=[],this.selectedChunkIds=[],this.selectable=!0,this.dedupe=!0,this.sort="score",this.grouping="none",this.presentation="expanded",this.thresholds={high:.75,medium:.5},this.virtualizeAt=50,this.activeChunkId="",this.loading=!1,this.hasMore=!1,this.errorText="",this.announce=!1,this.previousProcessedChunkIds=[],this.focusRestoreGeneration=0,this.isMounting=!0,this.initialStateAnnounced=!1,this.connectionGeneration=0,this.retrievalChunkKey=item=>item.id,this.wasEmptyPresented=!1,this.processedGroupingLocaleSignature="",this.renderRow=item=>{const chunk=item,selected=this.selectedChunkIds.includes(chunk.id),rowLabel=chunk.source.name||this.localize("untitledSource");return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity,canonicalIdentityList,isValidRetrievalChunk}from"../retrieval-identity.js";import{finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{styles}from"./retrieval-results.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{announceAfterFirstPaint}from"../retrieval-announcements.js";import{LYRA_DEFAULT_chunkInspectorEmpty,LYRA_DEFAULT_chunkInspectorLabel,LYRA_DEFAULT_loadMore,LYRA_DEFAULT_retrievalResultsSelectRow,LYRA_DEFAULT_untitledSource}from"../../../internal/default-strings.generated.js";function toLyraChunk(chunk){return{id:chunk.id,text:chunk.text,score:chunk.score,sourceId:chunk.source.id,title:chunk.source.name,anchor:chunk.locator,page:chunk.locator?.kind==="page"?chunk.locator.page:void 0}}function safeScore(score){return finiteRange(score,0,0,1)}class LyraRetrievalResults extends LyraElement{constructor(){super(...arguments),this.chunks=[],this.selectedChunkIds=[],this.selectable=!0,this.dedupe=!0,this.sort="score",this.grouping="none",this.presentation="expanded",this.thresholds={high:.75,medium:.5},this.virtualizeAt=50,this.activeChunkId="",this.loading=!1,this.hasMore=!1,this.errorText="",this.announce=!1,this.previousProcessedChunkIds=[],this.focusRestoreGeneration=0,this.isMounting=!0,this.initialStateAnnounced=!1,this.connectionGeneration=0,this.retrievalChunkKey=item=>item.id,this.wasEmptyPresented=!1,this.processedGroupingLocaleSignature="",this.stopOwnedEvent=event=>{event.stopPropagation()},this.renderRow=item=>{const chunk=item,selected=this.selectedChunkIds.includes(chunk.id),rowLabel=chunk.source.name||this.localize("untitledSource");return html`
|
|
2
2
|
${this.selectable?html`<lr-checkbox
|
|
3
3
|
part="select"
|
|
4
4
|
data-chunk-id=${chunk.id}
|
|
5
5
|
.checked=${selected}
|
|
6
6
|
aria-label=${this.localize("retrievalResultsSelectRow",void 0,{label:rowLabel})}
|
|
7
|
+
@lr-checkbox-toggle-request=${this.stopOwnedEvent}
|
|
8
|
+
@input=${this.stopOwnedEvent}
|
|
9
|
+
@lr-input=${this.stopOwnedEvent}
|
|
10
|
+
@change=${this.stopOwnedEvent}
|
|
7
11
|
@lr-change=${event=>{event.stopPropagation(),this.toggleSelect(chunk)}}
|
|
8
12
|
></lr-checkbox>`:nothing}
|
|
9
13
|
<div
|
|
@@ -83,4 +83,7 @@ label?:string;
|
|
|
83
83
|
* as a whole, so it is not cloned onto the inner tree. */
|
|
84
84
|
accessibleLabel:string|null;private expandedIds;private query;private activeId;private pendingFocusIndex;private keyboardFocusGeneration;private normalizedInput?;private normalizedModel?;private announcementSink?;private isMounting;private lastFilterAnnouncement;private get sourceEntries();private get selectedIds();connectedCallback():void;disconnectedCallback():void;
|
|
85
85
|
/** Builds a bounded, acyclic, nonblank first-id-wins tree once per `sources` identity. */
|
|
86
|
-
private get sourceModel();private allLeafIds;private descendantLeafIds;private normalizedSelectedSourceIds;private checkedState;private matchesQuery;private isFiltering;private visibleRows;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private commitSelection;private toggleEntry;
|
|
86
|
+
private get sourceModel();private allLeafIds;private descendantLeafIds;private normalizedSelectedSourceIds;private checkedState;private matchesQuery;private isFiltering;private visibleRows;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private commitSelection;private toggleEntry;
|
|
87
|
+
/** The select-all checkbox is internal chrome: its toggle proposal and every alias of its
|
|
88
|
+
* commit stay inside, and `lr-sources-change` is the one host-level report of the toggle. */
|
|
89
|
+
private stopOwnedEvent;private toggleSelectAll;private focusRowByIndex;private onTreeKeyDown;private renderRow;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-source-picker':LyraSourcePicker;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isNonBlankIdentity}from"../retrieval-identity.js";import{isRtl}from"../../../internal/rtl.js";import"../../media/file-icon/file-icon.class.js";import"../../forms/input/input.class.js";import"../../forms/checkbox/checkbox.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./source-picker.styles.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,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_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_selectAllSources,LYRA_DEFAULT_sourceListDefaultLabel,LYRA_DEFAULT_sourcePickerSelection,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const MAX_SOURCE_NODES=2e3,MAX_SOURCE_DEPTH=64,EMPTY_SOURCE_ENTRIES=Object.freeze([]),EMPTY_SOURCE_IDS=Object.freeze([]);class LyraSourcePicker extends LyraElement{constructor(){super(...arguments),this.sources=[],this.selectedSourceIds=[],this.showSelectAll=!0,this.searchable=!0,this.accessibleLabel=null,this.expandedIds=new Set,this.query="",this.activeId=null,this.keyboardFocusGeneration=0,this.isMounting=!0,this.lastFilterAnnouncement="",this.onTreeKeyDown=e=>{const rows=this.visibleRows();if(rows.length===0)return;const currentIndex=Math.max(0,rows.findIndex(r=>r.entry.id===this.activeId)),current=rows[currentIndex],rtl=isRtl(this),expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRowByIndex(Math.min(rows.length-1,currentIndex+1),rows);break;case"ArrowUp":e.preventDefault(),this.focusRowByIndex(Math.max(0,currentIndex-1),rows);break;case"Home":e.preventDefault(),this.focusRowByIndex(0,rows);break;case"End":e.preventDefault(),this.focusRowByIndex(rows.length-1,rows);break;case expandKey:if(e.preventDefault(),current.hasChildren&&!this.expandedIds.has(current.entry.id))this.expandedIds=new Set(this.expandedIds).add(current.entry.id);else if(current.hasChildren){const next=this.visibleRows()[currentIndex+1];next&&next.depth>current.depth&&this.focusRowByIndex(currentIndex+1,this.visibleRows())}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&this.expandedIds.has(current.entry.id)){const set=new Set(this.expandedIds);set.delete(current.entry.id),this.expandedIds=set}else for(let i=currentIndex-1;i>=0;i--)if(rows[i].depth<current.depth){this.focusRowByIndex(i,rows);break}break;case"Enter":case" ":e.preventDefault(),this.toggleEntry(current.entry);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,selectAllSources:LYRA_DEFAULT_selectAllSources,sourceListDefaultLabel:LYRA_DEFAULT_sourceListDefaultLabel,sourcePickerSelection:LYRA_DEFAULT_sourcePickerSelection,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.ownedCollectionProperties=Object.freeze(["sources","selectedSourceIds"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-sources-change"])}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get sourceEntries(){return Array.isArray(this.sources)?this.sources:EMPTY_SOURCE_ENTRIES}get selectedIds(){return Array.isArray(this.selectedSourceIds)?this.selectedSourceIds:EMPTY_SOURCE_IDS}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.isMounting=!0,this.lastFilterAnnouncement="",this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}get sourceModel(){if(this.normalizedInput===this.sourceEntries&&this.normalizedModel)return this.normalizedModel;const roots=[],nodes=[],byEntry=new WeakMap,seenObjects=new WeakSet,seenIds=new Set;let limited=!1;const stack=[];stack.push({sources:this.sourceEntries,target:roots,depth:0,index:0});let inspected=0;for(;stack.length;){const frame=stack[stack.length-1];if(frame.index>=frame.sources.length){stack.pop();continue}if(inspected>=MAX_SOURCE_NODES){limited=!0;break}const source=frame.sources[frame.index++];if(inspected++,!source||typeof source!="object"||seenObjects.has(source)||!isNonBlankIdentity(source.id)||!isNonBlankIdentity(source.label)||seenIds.has(source.id)){limited=!0;continue}if(nodes.length>=MAX_SOURCE_NODES||frame.depth>MAX_SOURCE_DEPTH){limited=!0;continue}seenObjects.add(source),seenIds.add(source.id);const declaredGroup=Array.isArray(source.children),entry={id:source.id,label:source.label,...source.mimeType!==void 0?{mimeType:source.mimeType}:{},...source.name!==void 0?{name:source.name}:{},...declaredGroup?{children:[]}:{}},node={entry,depth:frame.depth,children:[],leafIds:[]};declaredGroup&&(entry.children=node.children.map(child=>child.entry)),frame.target.push(node),nodes.push(node),byEntry.set(entry,node);const children=Array.isArray(source.children)?source.children:[];children.length&&frame.depth>=MAX_SOURCE_DEPTH&&(limited=!0),children.length&&frame.depth<MAX_SOURCE_DEPTH&&stack.push({sources:children,target:node.children,depth:frame.depth+1,index:0})}for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.entry.children!==void 0&&(node.entry.children=node.children.map(child=>child.entry)),node.leafIds=node.entry.children===void 0?[node.entry.id]:[...new Set(node.children.flatMap(child=>child.leafIds))]}const leafIds=[...new Set(roots.flatMap(root=>root.leafIds))];return this.normalizedInput=this.sourceEntries,this.normalizedModel={roots,nodes,byEntry,leafIds,limited},this.normalizedModel}allLeafIds(){return this.sourceModel.leafIds}descendantLeafIds(entry){return this.sourceModel.byEntry.get(entry)?.leafIds??[]}normalizedSelectedSourceIds(){const valid=new Set(this.allLeafIds()),seen=new Set;return this.selectedIds.filter(id=>!valid.has(id)||seen.has(id)?!1:(seen.add(id),!0))}checkedState(entry,selectedIds){const leaves=this.descendantLeafIds(entry),selected=leaves.filter(id=>selectedIds.has(id));return selected.length===0?"false":selected.length===leaves.length?"true":"mixed"}matchesQuery(entry){return entry.label.toLocaleLowerCase(this.effectiveLocale).includes(this.query.trim().toLocaleLowerCase(this.effectiveLocale))}isFiltering(){return this.searchable&&this.query.trim().length>0}visibleRows(){const rows=[],filtering=this.isFiltering(),matches=new Set;if(filtering)for(let index=this.sourceModel.nodes.length-1;index>=0;index--){const node=this.sourceModel.nodes[index];(this.matchesQuery(node.entry)||node.children.some(child=>matches.has(child)))&&matches.add(node)}const stack=[...this.sourceModel.roots].reverse();for(;stack.length;){const node=stack.pop();if(filtering&&!matches.has(node))continue;const hasChildren=node.entry.children!==void 0;if(rows.push({entry:node.entry,depth:node.depth,hasChildren}),hasChildren&&(filtering||this.expandedIds.has(node.entry.id)))for(let index=node.children.length-1;index>=0;index--)stack.push(node.children[index])}return rows}willUpdate(changed){if(super.willUpdate(changed),changed.has("sources")||changed.has("selectedSourceIds")){const normalized=this.normalizedSelectedSourceIds(),current=this.selectedIds;if(normalized.length!==current.length||normalized.some((id,index)=>id!==current[index])){const shouldAnnounce=this.hasUpdated&&changed.has("sources");this.selectedSourceIds=normalized,shouldAnnounce&&this.emit("lr-sources-change",{selectedSourceIds:normalized})}}if(!changed.has("sources")&&!changed.has("query")&&!changed.has("expandedIds")&&!changed.has("searchable"))return;const focusedIndex=Array.from(this.renderRoot.querySelectorAll('[part~="item"]')).indexOf(activeElementIn(this.shadowRoot)),rows=this.visibleRows(),retainedIndex=rows.findIndex(row=>row.entry.id===this.activeId),nextIndex=retainedIndex>=0?retainedIndex:rows.length?Math.min(Math.max(focusedIndex,0),rows.length-1):-1;this.activeId=nextIndex>=0?rows[nextIndex].entry.id:null,focusedIndex>=0&&(this.pendingFocusIndex=nextIndex>=0?nextIndex:this.sourceEntries.length===0||!this.searchable?"base":"search")}updated(changed){super.updated(changed);const pending=this.pendingFocusIndex;pending!==void 0&&(this.pendingFocusIndex=void 0,pending==="search"?this.renderRoot.querySelector('[part~="search"]')?.focus():pending==="base"?this.renderRoot.querySelector('[part="base"]')?.focus():this.renderRoot.querySelectorAll('[part~="item"]')[pending]?.focus());const wasMounting=this.isMounting;if(this.isMounting=!1,wasMounting||!changed.has("query")&&!changed.has("sources"))return;if(!this.isFiltering()){this.lastFilterAnnouncement="";return}const count=this.visibleRows().length,signature=`${this.query.trim().toLocaleLowerCase(this.effectiveLocale)}\0${count}`;signature!==this.lastFilterAnnouncement&&(this.lastFilterAnnouncement=signature,count===0&&this.announcementSink?.announce(this.localize("noMatches")))}commitSelection(next){this.selectedSourceIds=next,this.emit("lr-sources-change",{selectedSourceIds:next})}toggleEntry(entry){const leaves=this.descendantLeafIds(entry),set=new Set(this.normalizedSelectedSourceIds()),willSelect=this.checkedState(entry,set)!=="true";for(const id of leaves)willSelect?set.add(id):set.delete(id);this.commitSelection([...set])}toggleSelectAll(){const all=this.allLeafIds(),selectedIds=new Set(this.normalizedSelectedSourceIds()),allSelected=all.length>0&&all.every(id=>selectedIds.has(id));this.commitSelection(allSelected?[]:all)}focusRowByIndex(index,rows){const targetId=rows[index]?.entry.id;if(!targetId)return;this.activeId=targetId;const generation=++this.keyboardFocusGeneration;this.updateComplete.then(()=>{if(!this.isConnected||generation!==this.keyboardFocusGeneration)return;const currentIndex=this.visibleRows().findIndex(row=>row.entry.id===targetId);if(currentIndex<0)return;this.renderRoot.querySelectorAll('[part~="item"]')[currentIndex]?.focus()})}renderRow(row,active,selectedIds){const state2=this.checkedState(row.entry,selectedIds),expanded=row.hasChildren&&(this.expandedIds.has(row.entry.id)||this.isFiltering());return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isNonBlankIdentity}from"../retrieval-identity.js";import{isRtl}from"../../../internal/rtl.js";import"../../media/file-icon/file-icon.class.js";import"../../forms/input/input.class.js";import"../../forms/checkbox/checkbox.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./source-picker.styles.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,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_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_selectAllSources,LYRA_DEFAULT_sourceListDefaultLabel,LYRA_DEFAULT_sourcePickerSelection,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const MAX_SOURCE_NODES=2e3,MAX_SOURCE_DEPTH=64,EMPTY_SOURCE_ENTRIES=Object.freeze([]),EMPTY_SOURCE_IDS=Object.freeze([]);class LyraSourcePicker extends LyraElement{constructor(){super(...arguments),this.sources=[],this.selectedSourceIds=[],this.showSelectAll=!0,this.searchable=!0,this.accessibleLabel=null,this.expandedIds=new Set,this.query="",this.activeId=null,this.keyboardFocusGeneration=0,this.isMounting=!0,this.lastFilterAnnouncement="",this.stopOwnedEvent=event=>{event.stopPropagation()},this.onTreeKeyDown=e=>{const rows=this.visibleRows();if(rows.length===0)return;const currentIndex=Math.max(0,rows.findIndex(r=>r.entry.id===this.activeId)),current=rows[currentIndex],rtl=isRtl(this),expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRowByIndex(Math.min(rows.length-1,currentIndex+1),rows);break;case"ArrowUp":e.preventDefault(),this.focusRowByIndex(Math.max(0,currentIndex-1),rows);break;case"Home":e.preventDefault(),this.focusRowByIndex(0,rows);break;case"End":e.preventDefault(),this.focusRowByIndex(rows.length-1,rows);break;case expandKey:if(e.preventDefault(),current.hasChildren&&!this.expandedIds.has(current.entry.id))this.expandedIds=new Set(this.expandedIds).add(current.entry.id);else if(current.hasChildren){const next=this.visibleRows()[currentIndex+1];next&&next.depth>current.depth&&this.focusRowByIndex(currentIndex+1,this.visibleRows())}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&this.expandedIds.has(current.entry.id)){const set=new Set(this.expandedIds);set.delete(current.entry.id),this.expandedIds=set}else for(let i=currentIndex-1;i>=0;i--)if(rows[i].depth<current.depth){this.focusRowByIndex(i,rows);break}break;case"Enter":case" ":e.preventDefault(),this.toggleEntry(current.entry);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,selectAllSources:LYRA_DEFAULT_selectAllSources,sourceListDefaultLabel:LYRA_DEFAULT_sourceListDefaultLabel,sourcePickerSelection:LYRA_DEFAULT_sourcePickerSelection,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.ownedCollectionProperties=Object.freeze(["sources","selectedSourceIds"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-sources-change"])}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get sourceEntries(){return Array.isArray(this.sources)?this.sources:EMPTY_SOURCE_ENTRIES}get selectedIds(){return Array.isArray(this.selectedSourceIds)?this.selectedSourceIds:EMPTY_SOURCE_IDS}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.isMounting=!0,this.lastFilterAnnouncement="",this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}get sourceModel(){if(this.normalizedInput===this.sourceEntries&&this.normalizedModel)return this.normalizedModel;const roots=[],nodes=[],byEntry=new WeakMap,seenObjects=new WeakSet,seenIds=new Set;let limited=!1;const stack=[];stack.push({sources:this.sourceEntries,target:roots,depth:0,index:0});let inspected=0;for(;stack.length;){const frame=stack[stack.length-1];if(frame.index>=frame.sources.length){stack.pop();continue}if(inspected>=MAX_SOURCE_NODES){limited=!0;break}const source=frame.sources[frame.index++];if(inspected++,!source||typeof source!="object"||seenObjects.has(source)||!isNonBlankIdentity(source.id)||!isNonBlankIdentity(source.label)||seenIds.has(source.id)){limited=!0;continue}if(nodes.length>=MAX_SOURCE_NODES||frame.depth>MAX_SOURCE_DEPTH){limited=!0;continue}seenObjects.add(source),seenIds.add(source.id);const declaredGroup=Array.isArray(source.children),entry={id:source.id,label:source.label,...source.mimeType!==void 0?{mimeType:source.mimeType}:{},...source.name!==void 0?{name:source.name}:{},...declaredGroup?{children:[]}:{}},node={entry,depth:frame.depth,children:[],leafIds:[]};declaredGroup&&(entry.children=node.children.map(child=>child.entry)),frame.target.push(node),nodes.push(node),byEntry.set(entry,node);const children=Array.isArray(source.children)?source.children:[];children.length&&frame.depth>=MAX_SOURCE_DEPTH&&(limited=!0),children.length&&frame.depth<MAX_SOURCE_DEPTH&&stack.push({sources:children,target:node.children,depth:frame.depth+1,index:0})}for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.entry.children!==void 0&&(node.entry.children=node.children.map(child=>child.entry)),node.leafIds=node.entry.children===void 0?[node.entry.id]:[...new Set(node.children.flatMap(child=>child.leafIds))]}const leafIds=[...new Set(roots.flatMap(root=>root.leafIds))];return this.normalizedInput=this.sourceEntries,this.normalizedModel={roots,nodes,byEntry,leafIds,limited},this.normalizedModel}allLeafIds(){return this.sourceModel.leafIds}descendantLeafIds(entry){return this.sourceModel.byEntry.get(entry)?.leafIds??[]}normalizedSelectedSourceIds(){const valid=new Set(this.allLeafIds()),seen=new Set;return this.selectedIds.filter(id=>!valid.has(id)||seen.has(id)?!1:(seen.add(id),!0))}checkedState(entry,selectedIds){const leaves=this.descendantLeafIds(entry),selected=leaves.filter(id=>selectedIds.has(id));return selected.length===0?"false":selected.length===leaves.length?"true":"mixed"}matchesQuery(entry){return entry.label.toLocaleLowerCase(this.effectiveLocale).includes(this.query.trim().toLocaleLowerCase(this.effectiveLocale))}isFiltering(){return this.searchable&&this.query.trim().length>0}visibleRows(){const rows=[],filtering=this.isFiltering(),matches=new Set;if(filtering)for(let index=this.sourceModel.nodes.length-1;index>=0;index--){const node=this.sourceModel.nodes[index];(this.matchesQuery(node.entry)||node.children.some(child=>matches.has(child)))&&matches.add(node)}const stack=[...this.sourceModel.roots].reverse();for(;stack.length;){const node=stack.pop();if(filtering&&!matches.has(node))continue;const hasChildren=node.entry.children!==void 0;if(rows.push({entry:node.entry,depth:node.depth,hasChildren}),hasChildren&&(filtering||this.expandedIds.has(node.entry.id)))for(let index=node.children.length-1;index>=0;index--)stack.push(node.children[index])}return rows}willUpdate(changed){if(super.willUpdate(changed),changed.has("sources")||changed.has("selectedSourceIds")){const normalized=this.normalizedSelectedSourceIds(),current=this.selectedIds;if(normalized.length!==current.length||normalized.some((id,index)=>id!==current[index])){const shouldAnnounce=this.hasUpdated&&changed.has("sources");this.selectedSourceIds=normalized,shouldAnnounce&&this.emit("lr-sources-change",{selectedSourceIds:normalized})}}if(!changed.has("sources")&&!changed.has("query")&&!changed.has("expandedIds")&&!changed.has("searchable"))return;const focusedIndex=Array.from(this.renderRoot.querySelectorAll('[part~="item"]')).indexOf(activeElementIn(this.shadowRoot)),rows=this.visibleRows(),retainedIndex=rows.findIndex(row=>row.entry.id===this.activeId),nextIndex=retainedIndex>=0?retainedIndex:rows.length?Math.min(Math.max(focusedIndex,0),rows.length-1):-1;this.activeId=nextIndex>=0?rows[nextIndex].entry.id:null,focusedIndex>=0&&(this.pendingFocusIndex=nextIndex>=0?nextIndex:this.sourceEntries.length===0||!this.searchable?"base":"search")}updated(changed){super.updated(changed);const pending=this.pendingFocusIndex;pending!==void 0&&(this.pendingFocusIndex=void 0,pending==="search"?this.renderRoot.querySelector('[part~="search"]')?.focus():pending==="base"?this.renderRoot.querySelector('[part="base"]')?.focus():this.renderRoot.querySelectorAll('[part~="item"]')[pending]?.focus());const wasMounting=this.isMounting;if(this.isMounting=!1,wasMounting||!changed.has("query")&&!changed.has("sources"))return;if(!this.isFiltering()){this.lastFilterAnnouncement="";return}const count=this.visibleRows().length,signature=`${this.query.trim().toLocaleLowerCase(this.effectiveLocale)}\0${count}`;signature!==this.lastFilterAnnouncement&&(this.lastFilterAnnouncement=signature,count===0&&this.announcementSink?.announce(this.localize("noMatches")))}commitSelection(next){this.selectedSourceIds=next,this.emit("lr-sources-change",{selectedSourceIds:next})}toggleEntry(entry){const leaves=this.descendantLeafIds(entry),set=new Set(this.normalizedSelectedSourceIds()),willSelect=this.checkedState(entry,set)!=="true";for(const id of leaves)willSelect?set.add(id):set.delete(id);this.commitSelection([...set])}toggleSelectAll(){const all=this.allLeafIds(),selectedIds=new Set(this.normalizedSelectedSourceIds()),allSelected=all.length>0&&all.every(id=>selectedIds.has(id));this.commitSelection(allSelected?[]:all)}focusRowByIndex(index,rows){const targetId=rows[index]?.entry.id;if(!targetId)return;this.activeId=targetId;const generation=++this.keyboardFocusGeneration;this.updateComplete.then(()=>{if(!this.isConnected||generation!==this.keyboardFocusGeneration)return;const currentIndex=this.visibleRows().findIndex(row=>row.entry.id===targetId);if(currentIndex<0)return;this.renderRoot.querySelectorAll('[part~="item"]')[currentIndex]?.focus()})}renderRow(row,active,selectedIds){const state2=this.checkedState(row.entry,selectedIds),expanded=row.hasChildren&&(this.expandedIds.has(row.entry.id)||this.isFiltering());return html`
|
|
2
2
|
<div
|
|
3
3
|
part="item"
|
|
4
4
|
role="treeitem"
|
|
@@ -44,6 +44,10 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
44
44
|
aria-label=${this.localize("selectAllSources")}
|
|
45
45
|
.checked=${selectAllState==="true"}
|
|
46
46
|
.indeterminate=${selectAllState==="mixed"}
|
|
47
|
+
@lr-checkbox-toggle-request=${this.stopOwnedEvent}
|
|
48
|
+
@input=${this.stopOwnedEvent}
|
|
49
|
+
@lr-input=${this.stopOwnedEvent}
|
|
50
|
+
@change=${this.stopOwnedEvent}
|
|
47
51
|
@lr-change=${event=>{event.stopPropagation(),this.toggleSelectAll()}}
|
|
48
52
|
>${this.localize("selectAllSources")}</lr-checkbox
|
|
49
53
|
>
|
|
@@ -27,8 +27,9 @@ export type LyraIconAnimation='beat'|'fade'|'beat-fade'|'bounce'|'flip'|'flip-36
|
|
|
27
27
|
* icon and its composed ancestors are exposed to the accessibility tree.
|
|
28
28
|
* @csspart empty - Marker rendered when a remote icon resolved to an empty but valid document.
|
|
29
29
|
* @cssprop [--lr-icon-size] - Optional inline and block size override for every canvas.
|
|
30
|
-
* @cssprop [--lr-icon-fixed-width=var(--lr-size-1-5em)] -
|
|
31
|
-
*
|
|
30
|
+
* @cssprop [--lr-icon-fixed-width=var(--lr-size-1-5em)] - Deprecated together with `fixed-width`
|
|
31
|
+
* (removal not before 23.0.0): the inline size of the box while `fixed-width` is set, with the
|
|
32
|
+
* glyph kept at `--lr-icon-size` and centered inside it. Set `inline-size` on the host instead.
|
|
32
33
|
* @cssprop [--lr-icon-rotate=0deg] - Rotation applied to the box. Written inline from the `rotate`
|
|
33
34
|
* property, so set that rather than this property.
|
|
34
35
|
* @cssprop [--lr-icon-flip-x=1] - Horizontal scale factor, set to `-1` by `flip`.
|
|
@@ -111,7 +112,12 @@ autoWidth:boolean;
|
|
|
111
112
|
swapOpacity:boolean;
|
|
112
113
|
/** Optional built-in motion treatment; all variants honor `prefers-reduced-motion`. */
|
|
113
114
|
animation?:LyraIconAnimation;
|
|
114
|
-
/** Widens the icon box to `--lr-icon-fixed-width`
|
|
115
|
+
/** Widens the icon box to `--lr-icon-fixed-width` and pins the glyph to a 1em-wide box, so a
|
|
116
|
+
* column of icons aligns its labels. Setting it logs a one-time development warning.
|
|
117
|
+
* @deprecated The default canvas already gives every icon the same 1.25em box; for the 1.5em box
|
|
118
|
+
* set `lr-icon { inline-size: var(--lr-size-1-5em) }` on the host instead. A glyph wider than
|
|
119
|
+
* 1em then keeps its intrinsic width rather than being squeezed to 1em. Removal not before
|
|
120
|
+
* 23.0.0. */
|
|
115
121
|
fixedWidth:boolean;private fetchState;private svgEl?;private customSlot?;private customContentObserver?;private stopLibrarySubscription?;private resourceLease?;private errorAnnouncementSink?;
|
|
116
122
|
/** Bumped by every load start and by disconnect, and re-checked after every `await`, so a
|
|
117
123
|
* superseded response can never paint over a newer one. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeFetchUrl}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement}from"../../../internal/safe-svg.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getIconLibrary,subscribeIconLibrary}from"./icon-library.js";import{acquireSanitizedIconResource,IconResourceError}from"./icon-resource.js";import{styles}from"./icon.styles.js";import{LYRA_DEFAULT_iconLoadError,LYRA_DEFAULT_iconSanitizerMissing,LYRA_DEFAULT_iconTooLarge}from"../../../internal/default-strings.generated.js";const PATHS={add:"M12 5v14M5 12h14",check:"m5 12 4 4L19 6",close:"m6 6 12 12M18 6 6 18",search:"m21 21-4.35-4.35M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z",menu:"M4 6h16M4 12h16M4 18h16","chevron-left":"m15 18-6-6 6-6","chevron-right":"m9 18 6-6-6-6","chevron-down":"m6 9 6 6 6-6",calendar:"M6 3v3M18 3v3M4 9h16M5 5h14a1 1 0 0 1 1 1v13H4V6a1 1 0 0 1 1-1Z",command:"M6 6h4v4H6zM14 6h4v4h-4zM6 14h4v4H6zM14 14h4v4h-4z",trash:"M4 7h16M10 11v6M14 11v6M6 7l1 14h10l1-14M9 7V4h6v3"};class LyraIcon extends LyraElement{constructor(){super(...arguments),this._name="",this.path="",this.label="",this.library="default",this.family="",this.variant="",this._src="",this.rotate=0,this.autoWidth=!1,this.swapOpacity=!1,this.fixedWidth=!1,this.fetchState={kind:"idle"},this.generation=0,this.onCustomSlotChange=()=>{this.syncCustomNodes()}}static{this.defaultStrings={...super.defaultStrings,iconLoadError:LYRA_DEFAULT_iconLoadError,iconSanitizerMissing:LYRA_DEFAULT_iconSanitizerMissing,iconTooLarge:LYRA_DEFAULT_iconTooLarge}}static{this.styles=[LyraElement.styles,styles,srOnly]}get name(){return this._name}set name(value){const old=this._name;this._name=value??"",this.requestUpdate("name",old)}get src(){return this._src}set src(value){const old=this._src;this._src=value??"",this.requestUpdate("src",old)}connectedCallback(){super.connectedCallback(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.stopLibrarySubscription??=subscribeIconLibrary(name=>{name===this.library&&this.load()}),this.hasUpdated&&(queueMicrotask(()=>{this.isConnected&&this.syncCustomNodes()}),this.hasRemoteSource()&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.generation++,this.releaseResourceLease(),this.stopLibrarySubscription?.(),this.stopLibrarySubscription=void 0,this.customContentObserver?.disconnect(),this.customContentObserver=void 0,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"}),super.disconnectedCallback()}updated(changed){if(super.updated(changed),changed.has("rotate")){const angle=finiteNumber(this.rotate??0,0);angle?this.style.setProperty("--lr-icon-rotate",`${angle}deg`):this.style.removeProperty("--lr-icon-rotate")}this.applyRemoteA11y(),this.syncCustomNodes(),(changed.has("src")||changed.has("library")||changed.has("name")||changed.has("family")||changed.has("variant"))&&this.scheduleAfterUpdate(()=>{this.load()})}syncCustomNodes(){if(this.fetchState.kind!=="idle")return;const svgEl=this.svgEl;if(!svgEl)return;svgEl.querySelectorAll("[data-lr-custom-copy]").forEach(node=>node.remove()),this.customContentObserver?.disconnect();const slot=this.customSlot;if(slot){for(const node of slot.assignedNodes({flatten:!0})){const copy=this.cloneSvgNode(node);copy&&(copy.setAttribute("data-lr-custom-copy",""),svgEl.append(copy))}this.observeCustomContent(slot)}}observeCustomContent(slot){if(this.customContentObserver?.disconnect(),!this.isConnected)return;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){this.customContentObserver??=new MutationObserverCtor(()=>{this.isConnected&&this.syncCustomNodes()});for(const node of slot.assignedNodes({flatten:!0}))node.nodeType===1&&this.customContentObserver.observe(node,{attributes:!0,childList:!0,subtree:!0})}}cloneSvgNode(node){if(node.nodeType!==1)return null;const element=node;if(element.localName.includes("-")||isUnsafeSvgCloneElement(element.localName))return null;const copy=this.ownerDocument.createElementNS("http://www.w3.org/2000/svg",element.localName);for(const attribute of element.attributes)isUnsafeSvgCloneAttribute(attribute.name,attribute.value)||copy.setAttribute(attribute.name,attribute.value);for(const child of element.childNodes){const childCopy=this.cloneSvgNode(child);childCopy?copy.append(childCopy):child.nodeType===3&©.append(this.ownerDocument.createTextNode(child.textContent??""))}return copy}accessibleLabel(){return this.getAttribute("aria-label")??this.label}hasRemoteSource(){return!!(this.src||this.name&&this.library&&getIconLibrary(this.library))}releaseResourceLease(){this.resourceLease?.release(),this.resourceLease=void 0}async load(){const generation=++this.generation;this.releaseResourceLease();const library=this.name&&this.library?getIconLibrary(this.library):void 0;if(!library&&!this.src){this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"});return}this.fetchState={kind:"loading"};let source=this.src;try{if(library){if(source=await library.resolver(this.name,this.family,this.variant),!this.isConnected||generation!==this.generation)return;if(typeof source!="string")throw new TypeError("icon resolver did not return a URL")}}catch(error){await this.fail("load",generation,this.name,error);return}if(!source){this.isConnected&&generation===this.generation&&(this.fetchState={kind:"idle"});return}const safeSource=safeFetchUrl(source);if(!safeSource){await this.fail("load",generation,source,new Error("icon URL is not allowed"));return}const fetchTarget=resolveOwnerFetchTarget(this,safeSource);if(!fetchTarget){await this.fail("load",generation,safeSource,new Error("icon URL is not available"));return}let lease;try{lease=acquireSanitizedIconResource(fetchTarget),this.resourceLease=lease;const canonical=await lease.promise;if(!this.isConnected||generation!==this.generation)return;if(!canonical){if(this.fetchState={kind:"empty"},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource});return}const node=this.ownerDocument.importNode(canonical,!0);if(library?.mutator?.(node),this.fetchState={kind:"loaded",node},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource})}catch(error){if(isAbortError(error))return;const reason=error instanceof IconResourceError?error.reason:"load";await this.fail(reason,generation,safeSource,error)}finally{this.resourceLease===lease&&(this.resourceLease=void 0),lease?.release()}}async fail(reason,generation,src,error){!this.isConnected||generation!==this.generation||(this.fetchState={kind:"error",reason},await this.updateComplete,!(!this.isConnected||generation!==this.generation)&&(isAccessibilityVisible(this)&&this.errorAnnouncementSink?.announce(this.errorMessage(reason)),this.emit("lr-error",{src,error})))}errorMessage(reason){return reason==="sanitizer"?this.localize("iconSanitizerMissing"):reason==="too-large"?this.localize("iconTooLarge"):this.localize("iconLoadError")}applyRemoteA11y(){const state2=this.fetchState;if(state2.kind==="loaded"){state2.node.setAttribute("part","svg"),state2.node.setAttribute("focusable","false"),state2.node.setAttribute("aria-hidden","true"),state2.node.removeAttribute("aria-label");for(const use of state2.node.querySelectorAll("use")){const parts=new Set((use.getAttribute("part")??"").split(/\s+/).filter(Boolean));parts.add("use"),use.setAttribute("part",[...parts].join(" "))}}}renderBuiltIn(){const path=this.path||PATHS[this.name]||"";return html`<svg
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{warnDeprecatedUsage}from"../../../internal/dev-mode-attribute-warning.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeFetchUrl}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement}from"../../../internal/safe-svg.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getIconLibrary,subscribeIconLibrary}from"./icon-library.js";import{acquireSanitizedIconResource,IconResourceError}from"./icon-resource.js";import{styles}from"./icon.styles.js";import{LYRA_DEFAULT_iconLoadError,LYRA_DEFAULT_iconSanitizerMissing,LYRA_DEFAULT_iconTooLarge}from"../../../internal/default-strings.generated.js";const PATHS={add:"M12 5v14M5 12h14",check:"m5 12 4 4L19 6",close:"m6 6 12 12M18 6 6 18",search:"m21 21-4.35-4.35M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z",menu:"M4 6h16M4 12h16M4 18h16","chevron-left":"m15 18-6-6 6-6","chevron-right":"m9 18 6-6-6-6","chevron-down":"m6 9 6 6 6-6",calendar:"M6 3v3M18 3v3M4 9h16M5 5h14a1 1 0 0 1 1 1v13H4V6a1 1 0 0 1 1-1Z",command:"M6 6h4v4H6zM14 6h4v4h-4zM6 14h4v4H6zM14 14h4v4h-4z",trash:"M4 7h16M10 11v6M14 11v6M6 7l1 14h10l1-14M9 7V4h6v3"};class LyraIcon extends LyraElement{constructor(){super(...arguments),this._name="",this.path="",this.label="",this.library="default",this.family="",this.variant="",this._src="",this.rotate=0,this.autoWidth=!1,this.swapOpacity=!1,this.fixedWidth=!1,this.fetchState={kind:"idle"},this.generation=0,this.onCustomSlotChange=()=>{this.syncCustomNodes()}}static{this.defaultStrings={...super.defaultStrings,iconLoadError:LYRA_DEFAULT_iconLoadError,iconSanitizerMissing:LYRA_DEFAULT_iconSanitizerMissing,iconTooLarge:LYRA_DEFAULT_iconTooLarge}}static{this.styles=[LyraElement.styles,styles,srOnly]}get name(){return this._name}set name(value){const old=this._name;this._name=value??"",this.requestUpdate("name",old)}get src(){return this._src}set src(value){const old=this._src;this._src=value??"",this.requestUpdate("src",old)}connectedCallback(){super.connectedCallback(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.stopLibrarySubscription??=subscribeIconLibrary(name=>{name===this.library&&this.load()}),this.hasUpdated&&(queueMicrotask(()=>{this.isConnected&&this.syncCustomNodes()}),this.hasRemoteSource()&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.generation++,this.releaseResourceLease(),this.stopLibrarySubscription?.(),this.stopLibrarySubscription=void 0,this.customContentObserver?.disconnect(),this.customContentObserver=void 0,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"}),super.disconnectedCallback()}updated(changed){if(super.updated(changed),changed.has("fixedWidth")&&this.fixedWidth&&warnDeprecatedUsage(this,"property","fixedWidth","the default canvas or inline-size"),changed.has("rotate")){const angle=finiteNumber(this.rotate??0,0);angle?this.style.setProperty("--lr-icon-rotate",`${angle}deg`):this.style.removeProperty("--lr-icon-rotate")}this.applyRemoteA11y(),this.syncCustomNodes(),(changed.has("src")||changed.has("library")||changed.has("name")||changed.has("family")||changed.has("variant"))&&this.scheduleAfterUpdate(()=>{this.load()})}syncCustomNodes(){if(this.fetchState.kind!=="idle")return;const svgEl=this.svgEl;if(!svgEl)return;svgEl.querySelectorAll("[data-lr-custom-copy]").forEach(node=>node.remove()),this.customContentObserver?.disconnect();const slot=this.customSlot;if(slot){for(const node of slot.assignedNodes({flatten:!0})){const copy=this.cloneSvgNode(node);copy&&(copy.setAttribute("data-lr-custom-copy",""),svgEl.append(copy))}this.observeCustomContent(slot)}}observeCustomContent(slot){if(this.customContentObserver?.disconnect(),!this.isConnected)return;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){this.customContentObserver??=new MutationObserverCtor(()=>{this.isConnected&&this.syncCustomNodes()});for(const node of slot.assignedNodes({flatten:!0}))node.nodeType===1&&this.customContentObserver.observe(node,{attributes:!0,childList:!0,subtree:!0})}}cloneSvgNode(node){if(node.nodeType!==1)return null;const element=node;if(element.localName.includes("-")||isUnsafeSvgCloneElement(element.localName))return null;const copy=this.ownerDocument.createElementNS("http://www.w3.org/2000/svg",element.localName);for(const attribute of element.attributes)isUnsafeSvgCloneAttribute(attribute.name,attribute.value)||copy.setAttribute(attribute.name,attribute.value);for(const child of element.childNodes){const childCopy=this.cloneSvgNode(child);childCopy?copy.append(childCopy):child.nodeType===3&©.append(this.ownerDocument.createTextNode(child.textContent??""))}return copy}accessibleLabel(){return this.getAttribute("aria-label")??this.label}hasRemoteSource(){return!!(this.src||this.name&&this.library&&getIconLibrary(this.library))}releaseResourceLease(){this.resourceLease?.release(),this.resourceLease=void 0}async load(){const generation=++this.generation;this.releaseResourceLease();const library=this.name&&this.library?getIconLibrary(this.library):void 0;if(!library&&!this.src){this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"});return}this.fetchState={kind:"loading"};let source=this.src;try{if(library){if(source=await library.resolver(this.name,this.family,this.variant),!this.isConnected||generation!==this.generation)return;if(typeof source!="string")throw new TypeError("icon resolver did not return a URL")}}catch(error){await this.fail("load",generation,this.name,error);return}if(!source){this.isConnected&&generation===this.generation&&(this.fetchState={kind:"idle"});return}const safeSource=safeFetchUrl(source);if(!safeSource){await this.fail("load",generation,source,new Error("icon URL is not allowed"));return}const fetchTarget=resolveOwnerFetchTarget(this,safeSource);if(!fetchTarget){await this.fail("load",generation,safeSource,new Error("icon URL is not available"));return}let lease;try{lease=acquireSanitizedIconResource(fetchTarget),this.resourceLease=lease;const canonical=await lease.promise;if(!this.isConnected||generation!==this.generation)return;if(!canonical){if(this.fetchState={kind:"empty"},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource});return}const node=this.ownerDocument.importNode(canonical,!0);if(library?.mutator?.(node),this.fetchState={kind:"loaded",node},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource})}catch(error){if(isAbortError(error))return;const reason=error instanceof IconResourceError?error.reason:"load";await this.fail(reason,generation,safeSource,error)}finally{this.resourceLease===lease&&(this.resourceLease=void 0),lease?.release()}}async fail(reason,generation,src,error){!this.isConnected||generation!==this.generation||(this.fetchState={kind:"error",reason},await this.updateComplete,!(!this.isConnected||generation!==this.generation)&&(isAccessibilityVisible(this)&&this.errorAnnouncementSink?.announce(this.errorMessage(reason)),this.emit("lr-error",{src,error})))}errorMessage(reason){return reason==="sanitizer"?this.localize("iconSanitizerMissing"):reason==="too-large"?this.localize("iconTooLarge"):this.localize("iconLoadError")}applyRemoteA11y(){const state2=this.fetchState;if(state2.kind==="loaded"){state2.node.setAttribute("part","svg"),state2.node.setAttribute("focusable","false"),state2.node.setAttribute("aria-hidden","true"),state2.node.removeAttribute("aria-label");for(const use of state2.node.querySelectorAll("use")){const parts=new Set((use.getAttribute("part")??"").split(/\s+/).filter(Boolean));parts.add("use"),use.setAttribute("part",[...parts].join(" "))}}}renderBuiltIn(){const path=this.path||PATHS[this.name]||"";return html`<svg
|
|
2
2
|
part="svg"
|
|
3
3
|
viewBox="0 0 24 24"
|
|
4
4
|
fill="none"
|
|
@@ -17,15 +17,21 @@ export declare class LyraMutationObserver extends LyraElement<LyraMutationObserv
|
|
|
17
17
|
/** Mapped attribute selector: `*` observes all attributes; otherwise use space-separated names. */
|
|
18
18
|
attr:string|null;attrOldValue:boolean;charData:boolean;charDataOldValue:boolean;
|
|
19
19
|
/**
|
|
20
|
-
* Lyra compatibility alias
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
20
|
+
* Deprecated Lyra compatibility alias that turns on attribute observation. On its own it
|
|
21
|
+
* matches `attr="*"` (every attribute); unlike `attr`, it keeps honoring `attributeFilter`. It
|
|
22
|
+
* still reflects and still enables observation until its removal, and setting it logs a one-time
|
|
23
|
+
* development warning.
|
|
24
|
+
*
|
|
25
|
+
* @deprecated Use `attr="*"`, or remove `attributes` when `attr`, `attr-old-value` or
|
|
26
|
+
* `attributeFilter` is also set (they already enable attribute observation, and `attr` would
|
|
27
|
+
* replace an `attributeFilter`); removal not before 23.0.0.
|
|
24
28
|
*/
|
|
25
29
|
observeAttributes:boolean;
|
|
26
30
|
/**
|
|
27
|
-
* Lyra compatibility alias for `charData
|
|
28
|
-
*
|
|
29
|
-
*
|
|
31
|
+
* Deprecated Lyra compatibility alias for `charData`, with identical behavior. It still reflects
|
|
32
|
+
* and still enables character-data observation until its removal, and setting it logs a one-time
|
|
33
|
+
* development warning.
|
|
34
|
+
*
|
|
35
|
+
* @deprecated Use `char-data` (`charData`); removal not before 23.0.0.
|
|
30
36
|
*/
|
|
31
|
-
characterData:boolean;subtree:boolean;attributeFilter:string[];private observer?;private observerDocument?;private observerGeneration;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;protected updated(changed:PropertyValues):void;private onSlotChange;private disconnect;private observeTargets;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-mutation-observer':LyraMutationObserver;}}
|
|
37
|
+
characterData:boolean;subtree:boolean;attributeFilter:string[];private observer?;private observerDocument?;private observerGeneration;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private onSlotChange;private disconnect;private observeTargets;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-mutation-observer':LyraMutationObserver;}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{styles}from"./mutation-observer.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{disconnectObserver,slottedElementTargets}from"../../../internal/slotted-observer.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";const MAX_OBSERVER_ATTRIBUTE_FILTERS=1e4;function normalizedAttributeFilter(value){try{if(!Array.isArray(value))return Object.freeze([]);const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze([]);const values=[];for(let index=0;index<Math.min(length.value,MAX_OBSERVER_ATTRIBUTE_FILTERS);index+=1){const entry=getOwnDataDescriptor(value,String(index));entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||typeof entry.value!="string"||values.push(entry.value)}return Object.freeze(values)}catch{return Object.freeze([])}}class LyraMutationObserver extends LyraElement{constructor(){super(...arguments),this.disabled=!1,this.childList=!1,this.attr=null,this.attrOldValue=!1,this.charData=!1,this.charDataOldValue=!1,this.observeAttributes=!1,this.characterData=!1,this.subtree=!0,this.attributeFilter=[],this.observerGeneration=0,this.onSlotChange=()=>this.observeTargets(),this.observeTargets=()=>{this.disconnect();const ownerDocument=this.ownerDocument;let MutationObserverCtor;try{MutationObserverCtor=ownerDocument.defaultView?.MutationObserver}catch{return}const disabled=this.disabled===!0,childList=this.childList===!0,attrValue=this.attr,attr=typeof attrValue=="string"?attrValue.trim():null,attrTokens=(attr??"").split(/\s+/).filter(Boolean),mappedAttributes=attr==="*"||attrTokens.length>0,attrOldValue=this.attrOldValue===!0,charData=this.charData===!0,charDataOldValue=this.charDataOldValue===!0,observeAttributes=this.observeAttributes===!0,characterData=this.characterData===!0,subtree=this.subtree===!0,attributeFilter=attr===null?normalizedAttributeFilter(this.attributeFilter):Object.freeze([]),observesAttributes=mappedAttributes||attrOldValue||observeAttributes||attributeFilter.length>0,observesCharacterData=charData||charDataOldValue||characterData;if(disabled||!this.isConnected||!MutationObserverCtor)return;let targets;try{targets=slottedElementTargets(this.renderRoot)}catch{return}if(targets.length===0||!childList&&!observesAttributes&&!observesCharacterData)return;const options={childList,attributes:observesAttributes,characterData:observesCharacterData,subtree},mappedFilter=Object.freeze(attr==="*"?[]:attrTokens),effectiveFilter=attr===null?attributeFilter:mappedFilter;effectiveFilter.length>0&&(options.attributeFilter=[...effectiveFilter]),attrOldValue&&observesAttributes&&(options.attributeOldValue=!0),charDataOldValue&&observesCharacterData&&(options.characterDataOldValue=!0);const generation=this.observerGeneration;let observer;try{observer=new MutationObserverCtor(records=>{if(this.observer!==observer||this.observerDocument!==ownerDocument||this.observerGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;let mutationList;try{mutationList=Object.freeze([...records])}catch{return}this.emit("lr-mutation",{records:mutationList,mutationList})})}catch{return}this.observer=observer,this.observerDocument=ownerDocument;let observed=!1;for(const target of targets)try{observer.observe(target,options),observed=!0}catch{}observed||this.disconnect()}}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-mutation"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-mutation":Object.freeze(["records","mutationList"])})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.scheduleAfterUpdate(this.observeTargets)}disconnectedCallback(){this.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.disconnect()}updated(changed){super.updated(changed),["disabled","childList","attr","attrOldValue","charData","charDataOldValue","observeAttributes","characterData","subtree","attributeFilter"].some(key=>changed.has(key))&&this.scheduleAfterUpdate(this.observeTargets)}disconnect(){this.observerGeneration+=1;const observer=this.observer;this.observer=void 0,this.observerDocument=void 0;try{disconnectObserver(observer)}catch{}}render(){return html`<span part="base"><slot @slotchange=${this.onSlotChange}></slot></span>`}}__decorate([property({type:Boolean,reflect:!0})],LyraMutationObserver.prototype,"disabled",void 0),__decorate([property({type:Boolean,attribute:"child-list",reflect:!0})],LyraMutationObserver.prototype,"childList",void 0),__decorate([property({reflect:!0})],LyraMutationObserver.prototype,"attr",void 0),__decorate([property({type:Boolean,attribute:"attr-old-value",reflect:!0})],LyraMutationObserver.prototype,"attrOldValue",void 0),__decorate([property({type:Boolean,attribute:"char-data",reflect:!0})],LyraMutationObserver.prototype,"charData",void 0),__decorate([property({type:Boolean,attribute:"char-data-old-value",reflect:!0})],LyraMutationObserver.prototype,"charDataOldValue",void 0),__decorate([property({type:Boolean,attribute:"attributes",reflect:!0})],LyraMutationObserver.prototype,"observeAttributes",void 0),__decorate([property({type:Boolean,attribute:"character-data",reflect:!0})],LyraMutationObserver.prototype,"characterData",void 0),__decorate([property({type:Boolean,converter:trueDefaultBooleanConverter})],LyraMutationObserver.prototype,"subtree",void 0),__decorate([property({attribute:!1})],LyraMutationObserver.prototype,"attributeFilter",void 0);export{LyraMutationObserver};
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{styles}from"./mutation-observer.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{disconnectObserver,slottedElementTargets}from"../../../internal/slotted-observer.js";import{warnDeprecatedUsage}from"../../../internal/dev-mode-attribute-warning.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";const MAX_OBSERVER_ATTRIBUTE_FILTERS=1e4;function normalizedAttributeFilter(value){try{if(!Array.isArray(value))return Object.freeze([]);const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze([]);const values=[];for(let index=0;index<Math.min(length.value,MAX_OBSERVER_ATTRIBUTE_FILTERS);index+=1){const entry=getOwnDataDescriptor(value,String(index));entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||typeof entry.value!="string"||values.push(entry.value)}return Object.freeze(values)}catch{return Object.freeze([])}}class LyraMutationObserver extends LyraElement{constructor(){super(...arguments),this.disabled=!1,this.childList=!1,this.attr=null,this.attrOldValue=!1,this.charData=!1,this.charDataOldValue=!1,this.observeAttributes=!1,this.characterData=!1,this.subtree=!0,this.attributeFilter=[],this.observerGeneration=0,this.onSlotChange=()=>this.observeTargets(),this.observeTargets=()=>{this.disconnect();const ownerDocument=this.ownerDocument;let MutationObserverCtor;try{MutationObserverCtor=ownerDocument.defaultView?.MutationObserver}catch{return}const disabled=this.disabled===!0,childList=this.childList===!0,attrValue=this.attr,attr=typeof attrValue=="string"?attrValue.trim():null,attrTokens=(attr??"").split(/\s+/).filter(Boolean),mappedAttributes=attr==="*"||attrTokens.length>0,attrOldValue=this.attrOldValue===!0,charData=this.charData===!0,charDataOldValue=this.charDataOldValue===!0,observeAttributes=this.observeAttributes===!0,characterData=this.characterData===!0,subtree=this.subtree===!0,attributeFilter=attr===null?normalizedAttributeFilter(this.attributeFilter):Object.freeze([]),observesAttributes=mappedAttributes||attrOldValue||observeAttributes||attributeFilter.length>0,observesCharacterData=charData||charDataOldValue||characterData;if(disabled||!this.isConnected||!MutationObserverCtor)return;let targets;try{targets=slottedElementTargets(this.renderRoot)}catch{return}if(targets.length===0||!childList&&!observesAttributes&&!observesCharacterData)return;const options={childList,attributes:observesAttributes,characterData:observesCharacterData,subtree},mappedFilter=Object.freeze(attr==="*"?[]:attrTokens),effectiveFilter=attr===null?attributeFilter:mappedFilter;effectiveFilter.length>0&&(options.attributeFilter=[...effectiveFilter]),attrOldValue&&observesAttributes&&(options.attributeOldValue=!0),charDataOldValue&&observesCharacterData&&(options.characterDataOldValue=!0);const generation=this.observerGeneration;let observer;try{observer=new MutationObserverCtor(records=>{if(this.observer!==observer||this.observerDocument!==ownerDocument||this.observerGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;let mutationList;try{mutationList=Object.freeze([...records])}catch{return}this.emit("lr-mutation",{records:mutationList,mutationList})})}catch{return}this.observer=observer,this.observerDocument=ownerDocument;let observed=!1;for(const target of targets)try{observer.observe(target,options),observed=!0}catch{}observed||this.disconnect()}}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-mutation"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-mutation":Object.freeze(["records","mutationList"])})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.scheduleAfterUpdate(this.observeTargets)}disconnectedCallback(){this.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.disconnect()}willUpdate(changed){super.willUpdate(changed),changed.has("observeAttributes")&&this.observeAttributes===!0&&warnDeprecatedUsage(this,"property","observeAttributes",'attr="*" (or nothing with attr/attributeFilter)'),changed.has("characterData")&&this.characterData===!0&&warnDeprecatedUsage(this,"property","characterData","char-data")}updated(changed){super.updated(changed),["disabled","childList","attr","attrOldValue","charData","charDataOldValue","observeAttributes","characterData","subtree","attributeFilter"].some(key=>changed.has(key))&&this.scheduleAfterUpdate(this.observeTargets)}disconnect(){this.observerGeneration+=1;const observer=this.observer;this.observer=void 0,this.observerDocument=void 0;try{disconnectObserver(observer)}catch{}}render(){return html`<span part="base"><slot @slotchange=${this.onSlotChange}></slot></span>`}}__decorate([property({type:Boolean,reflect:!0})],LyraMutationObserver.prototype,"disabled",void 0),__decorate([property({type:Boolean,attribute:"child-list",reflect:!0})],LyraMutationObserver.prototype,"childList",void 0),__decorate([property({reflect:!0})],LyraMutationObserver.prototype,"attr",void 0),__decorate([property({type:Boolean,attribute:"attr-old-value",reflect:!0})],LyraMutationObserver.prototype,"attrOldValue",void 0),__decorate([property({type:Boolean,attribute:"char-data",reflect:!0})],LyraMutationObserver.prototype,"charData",void 0),__decorate([property({type:Boolean,attribute:"char-data-old-value",reflect:!0})],LyraMutationObserver.prototype,"charDataOldValue",void 0),__decorate([property({type:Boolean,attribute:"attributes",reflect:!0})],LyraMutationObserver.prototype,"observeAttributes",void 0),__decorate([property({type:Boolean,attribute:"character-data",reflect:!0})],LyraMutationObserver.prototype,"characterData",void 0),__decorate([property({type:Boolean,converter:trueDefaultBooleanConverter})],LyraMutationObserver.prototype,"subtree",void 0),__decorate([property({attribute:!1})],LyraMutationObserver.prototype,"attributeFilter",void 0);export{LyraMutationObserver};
|
|
@@ -90,4 +90,9 @@ private failResolution;
|
|
|
90
90
|
* capability at all). A capable embedded viewer's own `DocumentAnchorTarget` mixin emits after
|
|
91
91
|
* its scroll attempt and that composed event surfaces through this element unchanged, so the
|
|
92
92
|
* shell must not also emit in that case. */
|
|
93
|
-
private finishAnchorResult;private isAnchorCapable;private renderWith;
|
|
93
|
+
private finishAnchorResult;private isAnchorCapable;private renderWith;
|
|
94
|
+
/** The shell dialog's lifecycle and dismissal proposals are internal to this viewer: `lr-close`
|
|
95
|
+
* is its one documented dismissal report. Containment only stops propagation, so a proposal's
|
|
96
|
+
* own default action and `defaultPrevented` state are unchanged. Like `onDialogClose`, it
|
|
97
|
+
* leaves a registered renderer's own descendant dialog events on their composed path. */
|
|
98
|
+
private containShellEvent;private onDialogClose;private onDownload;private renderBody;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-document-viewer':LyraDocumentViewer;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement,snapshotPublicCollection}from"../../../internal/lyra-element.js";import{documentRendererRegistrySource}from"./registry-ownership.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{safeDownloadHref}from"../../../internal/safe-url.js";import{adaptDocumentRenderer,createDocumentRendererRegistry,findDocumentRenderer,loadDocumentRenderer,snapshotLyraDocumentRendererPayload}from"./registry.js";import{styles}from"./document-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{LYRA_DEFAULT_documentPreviewGenericError,LYRA_DEFAULT_documentViewerLabel,LYRA_DEFAULT_download,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings.generated.js";class LyraDocumentViewer extends LyraElement{constructor(){super(...arguments),this.open=!1,this.name="",this.mimeType="",this.src="",this.anchor=null,this._highlights=snapshotLyraHighlights([]),this.renderState={kind:"fallback"},this.generation=0,this.builtInRegistry=createDocumentRendererRegistry(),this.announcements=new ViewerAnnouncementController(this),this.onDialogClose=event=>{event.target===event.currentTarget&&(event.stopPropagation(),this.open=!1,this.emit("lr-close",event.detail))},this.onDownload=()=>{const file=this.currentFile();this.emit("lr-download",{src:file.src,filename:file.name})}}static{this.defaultStrings={...super.defaultStrings,documentPreviewGenericError:LYRA_DEFAULT_documentPreviewGenericError,documentViewerLabel:LYRA_DEFAULT_documentViewerLabel,download:LYRA_DEFAULT_download,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.ownedCollectionProperties=Object.freeze(["highlights","registry"])}static{this.styles=[LyraElement.styles,styles]}get payload(){return this._payload}set payload(value){const old=this._payload;this._payload=value===void 0?void 0:snapshotLyraDocumentRendererPayload(value),this.requestUpdate("payload",old)}static{Object.defineProperty(this.prototype,"registry",{configurable:!0,enumerable:!0,get(){return this._registry},set(value){if(value===this.registrySource||value===this._registry)return;const old=this._registry;this._registry=snapshotPublicCollection(documentRendererRegistrySource(value),this.ownerDocument?.defaultView),this.registrySource=value,this.requestUpdate("registry",old)}})}get highlights(){return this._highlights}set highlights(value){const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.open&&this.resolve()}disconnectedCallback(){this.generation++,this.renderState={kind:"fallback"},this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}willUpdate(changed){if(super.willUpdate(changed),!this.open){changed.has("open")&&(this.generation++,this.renderState={kind:"fallback"});return}const legacyFileChanged=this.payload===void 0&&(changed.has("name")||changed.has("mimeType")||changed.has("src")||changed.has("anchor")||changed.has("highlights")||changed.has("alt"));(!this.hasUpdated||changed.has("open")||changed.has("payload")||changed.has("registry")||legacyFileChanged)&&this.resolve()}updated(changed){super.updated(changed),this.announcements.transition("renderer",this.renderState.kind,this.renderState.kind==="error"?this.localize("documentPreviewGenericError"):this.localize("loadingDocument"))}currentFile(){if(this.payload){const file=this.payload.file;return{name:file.name,mimeType:file.mimeType,src:file.src,...file.anchor!==void 0?{anchor:file.anchor}:{},...file.highlights?{highlights:[...file.highlights]}:{},...file.alt!==void 0?{alt:file.alt}:{}}}return{name:this.name,mimeType:this.mimeType,src:this.src,anchor:this.anchor??void 0,highlights:this.highlights,alt:this.alt}}async resolve(){if(!this.isConnected||!this.open)return;const generation=++this.generation,file=this.currentFile(),registry=this.registry??this.builtInRegistry;let def;try{def=findDocumentRenderer(file,registry)}catch{this.failResolution(file,generation);return}if(!def){this.resolvedLazy=void 0,this.renderState={kind:"fallback"},this.finishAnchorResult(void 0,file,generation,!0);return}if(this.resolvedLazy?.def===def){const capabilities2=this.renderWith(this.resolvedLazy.resolved,file);if(capabilities2===!1){this.failResolution(file,generation);return}this.finishAnchorResult(capabilities2,file,generation);return}if(!def.load){this.resolvedLazy={def,resolved:def};const capabilities2=this.renderWith(def,file);if(capabilities2===!1){this.failResolution(file,generation);return}this.finishAnchorResult(capabilities2,file,generation);return}this.renderState={kind:"loading"};let resolved;try{resolved=await loadDocumentRenderer(def)}catch{generation===this.generation&&this.isConnected&&this.open&&(this.renderState={kind:"error"},this.finishAnchorResult(void 0,file,generation));return}if(generation!==this.generation||!this.isConnected||!this.open)return;this.resolvedLazy={def,resolved};const capabilities=this.renderWith(resolved,file);if(capabilities===!1){this.failResolution(file,generation);return}this.finishAnchorResult(capabilities,file,generation)}failResolution(file,generation){generation!==this.generation||!this.isConnected||!this.open||(this.renderState={kind:"error"},file.anchor!=null&&this.scheduleAfterUpdate(()=>{generation!==this.generation||!this.isConnected||!this.open||this.emit("lr-anchor-result",{found:!1})}))}finishAnchorResult(capabilities,file,generation,fallback=!1){if(file.anchor!=null&&!(generation!==this.generation||!this.isConnected||!this.open)){if(fallback){this.scheduleAfterUpdate(()=>{(async()=>{const found=await this.fallbackPreviewEl?.scrollToAnchor(file.anchor)??!1;generation!==this.generation||!this.isConnected||!this.open||this.emit("lr-anchor-result",{found})})()});return}this.isAnchorCapable(capabilities,file.anchor)||this.scheduleAfterUpdate(()=>{generation!==this.generation||!this.isConnected||!this.open||this.emit("lr-anchor-result",{found:!1})})}}isAnchorCapable(capabilities,anchor){const anchors=capabilities?.anchors;return!anchors||anchors.length===0?!1:typeof anchor=="string"?!0:anchors.includes(anchor.kind)}renderWith(definition,file){try{const adapted=adaptDocumentRenderer(definition,file,this.payload);return this.renderState={kind:"rendered",template:adapted.render()},adapted.capabilities}catch{return!1}}renderBody(){const file=this.currentFile();switch(this.renderState.kind){case"rendered":return this.renderState.template;case"loading":return html`<p>${this.localize("loadingDocument")}</p>`;case"error":return html`<div>${this.localize("documentPreviewGenericError")}</div>`;default:return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement,snapshotPublicCollection}from"../../../internal/lyra-element.js";import{documentRendererRegistrySource}from"./registry-ownership.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{safeDownloadHref}from"../../../internal/safe-url.js";import{adaptDocumentRenderer,createDocumentRendererRegistry,findDocumentRenderer,loadDocumentRenderer,snapshotLyraDocumentRendererPayload}from"./registry.js";import{styles}from"./document-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{LYRA_DEFAULT_documentPreviewGenericError,LYRA_DEFAULT_documentViewerLabel,LYRA_DEFAULT_download,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings.generated.js";class LyraDocumentViewer extends LyraElement{constructor(){super(...arguments),this.open=!1,this.name="",this.mimeType="",this.src="",this.anchor=null,this._highlights=snapshotLyraHighlights([]),this.renderState={kind:"fallback"},this.generation=0,this.builtInRegistry=createDocumentRendererRegistry(),this.announcements=new ViewerAnnouncementController(this),this.containShellEvent=event=>{event.target===event.currentTarget&&event.stopPropagation()},this.onDialogClose=event=>{event.target===event.currentTarget&&(event.stopPropagation(),this.open=!1,this.emit("lr-close",event.detail))},this.onDownload=()=>{const file=this.currentFile();this.emit("lr-download",{src:file.src,filename:file.name})}}static{this.defaultStrings={...super.defaultStrings,documentPreviewGenericError:LYRA_DEFAULT_documentPreviewGenericError,documentViewerLabel:LYRA_DEFAULT_documentViewerLabel,download:LYRA_DEFAULT_download,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.ownedCollectionProperties=Object.freeze(["highlights","registry"])}static{this.styles=[LyraElement.styles,styles]}get payload(){return this._payload}set payload(value){const old=this._payload;this._payload=value===void 0?void 0:snapshotLyraDocumentRendererPayload(value),this.requestUpdate("payload",old)}static{Object.defineProperty(this.prototype,"registry",{configurable:!0,enumerable:!0,get(){return this._registry},set(value){if(value===this.registrySource||value===this._registry)return;const old=this._registry;this._registry=snapshotPublicCollection(documentRendererRegistrySource(value),this.ownerDocument?.defaultView),this.registrySource=value,this.requestUpdate("registry",old)}})}get highlights(){return this._highlights}set highlights(value){const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.open&&this.resolve()}disconnectedCallback(){this.generation++,this.renderState={kind:"fallback"},this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}willUpdate(changed){if(super.willUpdate(changed),!this.open){changed.has("open")&&(this.generation++,this.renderState={kind:"fallback"});return}const legacyFileChanged=this.payload===void 0&&(changed.has("name")||changed.has("mimeType")||changed.has("src")||changed.has("anchor")||changed.has("highlights")||changed.has("alt"));(!this.hasUpdated||changed.has("open")||changed.has("payload")||changed.has("registry")||legacyFileChanged)&&this.resolve()}updated(changed){super.updated(changed),this.announcements.transition("renderer",this.renderState.kind,this.renderState.kind==="error"?this.localize("documentPreviewGenericError"):this.localize("loadingDocument"))}currentFile(){if(this.payload){const file=this.payload.file;return{name:file.name,mimeType:file.mimeType,src:file.src,...file.anchor!==void 0?{anchor:file.anchor}:{},...file.highlights?{highlights:[...file.highlights]}:{},...file.alt!==void 0?{alt:file.alt}:{}}}return{name:this.name,mimeType:this.mimeType,src:this.src,anchor:this.anchor??void 0,highlights:this.highlights,alt:this.alt}}async resolve(){if(!this.isConnected||!this.open)return;const generation=++this.generation,file=this.currentFile(),registry=this.registry??this.builtInRegistry;let def;try{def=findDocumentRenderer(file,registry)}catch{this.failResolution(file,generation);return}if(!def){this.resolvedLazy=void 0,this.renderState={kind:"fallback"},this.finishAnchorResult(void 0,file,generation,!0);return}if(this.resolvedLazy?.def===def){const capabilities2=this.renderWith(this.resolvedLazy.resolved,file);if(capabilities2===!1){this.failResolution(file,generation);return}this.finishAnchorResult(capabilities2,file,generation);return}if(!def.load){this.resolvedLazy={def,resolved:def};const capabilities2=this.renderWith(def,file);if(capabilities2===!1){this.failResolution(file,generation);return}this.finishAnchorResult(capabilities2,file,generation);return}this.renderState={kind:"loading"};let resolved;try{resolved=await loadDocumentRenderer(def)}catch{generation===this.generation&&this.isConnected&&this.open&&(this.renderState={kind:"error"},this.finishAnchorResult(void 0,file,generation));return}if(generation!==this.generation||!this.isConnected||!this.open)return;this.resolvedLazy={def,resolved};const capabilities=this.renderWith(resolved,file);if(capabilities===!1){this.failResolution(file,generation);return}this.finishAnchorResult(capabilities,file,generation)}failResolution(file,generation){generation!==this.generation||!this.isConnected||!this.open||(this.renderState={kind:"error"},file.anchor!=null&&this.scheduleAfterUpdate(()=>{generation!==this.generation||!this.isConnected||!this.open||this.emit("lr-anchor-result",{found:!1})}))}finishAnchorResult(capabilities,file,generation,fallback=!1){if(file.anchor!=null&&!(generation!==this.generation||!this.isConnected||!this.open)){if(fallback){this.scheduleAfterUpdate(()=>{(async()=>{const found=await this.fallbackPreviewEl?.scrollToAnchor(file.anchor)??!1;generation!==this.generation||!this.isConnected||!this.open||this.emit("lr-anchor-result",{found})})()});return}this.isAnchorCapable(capabilities,file.anchor)||this.scheduleAfterUpdate(()=>{generation!==this.generation||!this.isConnected||!this.open||this.emit("lr-anchor-result",{found:!1})})}}isAnchorCapable(capabilities,anchor){const anchors=capabilities?.anchors;return!anchors||anchors.length===0?!1:typeof anchor=="string"?!0:anchors.includes(anchor.kind)}renderWith(definition,file){try{const adapted=adaptDocumentRenderer(definition,file,this.payload);return this.renderState={kind:"rendered",template:adapted.render()},adapted.capabilities}catch{return!1}}renderBody(){const file=this.currentFile();switch(this.renderState.kind){case"rendered":return this.renderState.template;case"loading":return html`<p>${this.localize("loadingDocument")}</p>`;case"error":return html`<div>${this.localize("documentPreviewGenericError")}</div>`;default:return html`
|
|
2
2
|
<lr-document-preview
|
|
3
3
|
src=${file.src}
|
|
4
4
|
mime-type=${file.mimeType}
|
|
@@ -14,6 +14,12 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
14
14
|
label=${this.localize("documentViewerLabel")}
|
|
15
15
|
aria-label=${hostAriaLabel(this)??nothing}
|
|
16
16
|
closable
|
|
17
|
+
@lr-show=${this.containShellEvent}
|
|
18
|
+
@lr-after-show=${this.containShellEvent}
|
|
19
|
+
@lr-initial-focus=${this.containShellEvent}
|
|
20
|
+
@lr-request-close=${this.containShellEvent}
|
|
21
|
+
@lr-hide=${this.containShellEvent}
|
|
22
|
+
@lr-after-hide=${this.containShellEvent}
|
|
17
23
|
@lr-close=${this.onDialogClose}
|
|
18
24
|
>
|
|
19
25
|
<div part="body" aria-busy=${this.renderState.kind==="loading"?"true":"false"}
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import type{AnchorTargetCapabilities,LyraAnchor,LyraHighlight}from'./anchors.js';import{type LyraAvCue,type LyraAvTrack}from'../../media/av-player/av-metadata.js';
|
|
2
|
-
/**
|
|
2
|
+
/**
|
|
3
|
+
* A file supplied to a document renderer.
|
|
4
|
+
* @deprecated Use the structurally identical `LyraDocumentFile`; each is assignable to the other.
|
|
5
|
+
* Exported signatures keep this name until its removal, no earlier than 23.0.0.
|
|
6
|
+
*/
|
|
3
7
|
export interface DocumentFile{readonly name:string;readonly mimeType:string;readonly src:string;
|
|
4
8
|
/** A string is a highlight id in `highlights`. */
|
|
5
9
|
readonly anchor?:LyraAnchor|string;readonly highlights?:readonly LyraHighlight[];
|
|
@@ -39,9 +43,14 @@ export type LyraResolvedDocumentRendererDefinition=DirectDocumentRendererDefinit
|
|
|
39
43
|
export interface LazyDocumentRendererDefinition extends DocumentRendererDefinitionBase{readonly render?:never;readonly adapter?:never;
|
|
40
44
|
/** Capability declaration available before the legacy direct renderer is loaded. */
|
|
41
45
|
readonly capabilities?:AnchorTargetCapabilities;readonly load:()=>Promise<DirectDocumentRendererDefinition|{default:DirectDocumentRendererDefinition;}>;}
|
|
42
|
-
/**
|
|
46
|
+
/**
|
|
47
|
+
* A validated renderer definition. Exactly one of `render`, `adapter`, and `load` is present.
|
|
48
|
+
* @deprecated Use `LyraDocumentRendererDefinition`, the same union under the library's prefixed
|
|
49
|
+
* name. Exported signatures keep this name until its removal, no earlier than 23.0.0.
|
|
50
|
+
*/
|
|
43
51
|
export type DocumentRendererDefinition=DirectDocumentRendererDefinition|LyraAdaptedDocumentRendererDefinition|LazyDocumentRendererDefinition;
|
|
44
|
-
/**
|
|
52
|
+
/** Canonical prefixed name for authored renderer definitions: a validated renderer definition in
|
|
53
|
+
* which exactly one of `render`, `adapter`, and `load` is present. */
|
|
45
54
|
export type LyraDocumentRendererDefinition=DocumentRendererDefinition;
|
|
46
55
|
/** One payload-bound renderer invocation and its truthful, immutable capabilities. */
|
|
47
56
|
export interface LyraAdaptedDocumentRenderer{readonly payload:LyraDocumentRendererPayload;readonly capabilities?:AnchorTargetCapabilities;readonly render:()=>unknown;}
|
|
@@ -1,14 +1,22 @@
|
|
|
1
1
|
import{LyraGeoJsonViewer,type LyraGeoJsonViewerEventMap}from'./geojson-viewer.class.js';export{type GeoJsonTypeTag,LyraGeoJsonViewer,type LyraGeoJsonViewerEventMap,}from'./geojson-viewer.class.js';
|
|
2
|
-
/**
|
|
2
|
+
/**
|
|
3
|
+
* Event contract retained by the deprecated `lr-geojson-view` compatibility tag.
|
|
4
|
+
*
|
|
5
|
+
* @deprecated Use `LyraGeoJsonViewerEventMap`; removal not before 23.0.0.
|
|
6
|
+
*/
|
|
3
7
|
export type LyraGeojsonViewEventMap=LyraGeoJsonViewerEventMap;
|
|
4
8
|
/**
|
|
5
|
-
*
|
|
9
|
+
* Deprecated compatibility class for the pre-v9 `lr-geojson-view` tag.
|
|
6
10
|
*
|
|
7
|
-
* Use `LyraGeoJsonViewer` and
|
|
8
|
-
* `
|
|
11
|
+
* Use `LyraGeoJsonViewer` and `<lr-geojson-viewer>` instead, registered by importing
|
|
12
|
+
* `components/lr-geojson-viewer.js`. This alias keeps working unchanged, with the same
|
|
13
|
+
* attributes, events and document-registry contract, until a major release no earlier than 23.0.0
|
|
14
|
+
* removes it; connecting one logs a one-time development warning. It remains a distinct subclass
|
|
15
|
+
* so `instanceof LyraGeoJsonViewer` holds and both tag names share one custom-elements registry.
|
|
9
16
|
*
|
|
10
17
|
* @customElement lr-geojson-view
|
|
18
|
+
* @deprecated Use `<lr-geojson-viewer>` (`LyraGeoJsonViewer`); removal not before 23.0.0.
|
|
11
19
|
* @status stable
|
|
12
20
|
* @since 4.0.0
|
|
13
21
|
*/
|
|
14
|
-
export declare class LyraGeojsonView extends LyraGeoJsonViewer{}declare global{interface HTMLElementTagNameMap{'lr-geojson-view':LyraGeojsonView;}}
|
|
22
|
+
export declare class LyraGeojsonView extends LyraGeoJsonViewer{connectedCallback():void;}declare global{interface HTMLElementTagNameMap{'lr-geojson-view':LyraGeojsonView;}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LyraGeoJsonViewer}from"./geojson-viewer.class.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound}from"../../../internal/default-strings.generated.js";import{LyraGeoJsonViewer as LyraGeoJsonViewer2}from"./geojson-viewer.class.js";class LyraGeojsonView extends LyraGeoJsonViewer{static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound}}}export{LyraGeoJsonViewer2 as LyraGeoJsonViewer,LyraGeojsonView};
|
|
1
|
+
import{LyraGeoJsonViewer}from"./geojson-viewer.class.js";import{warnDeprecatedUsage}from"../../../internal/dev-mode-attribute-warning.js";import{tag}from"../../../internal/prefix.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound}from"../../../internal/default-strings.generated.js";import{LyraGeoJsonViewer as LyraGeoJsonViewer2}from"./geojson-viewer.class.js";class LyraGeojsonView extends LyraGeoJsonViewer{static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound}}connectedCallback(){super.connectedCallback(),warnDeprecatedUsage(this,"component",tag("geojson-view"),`<${tag("geojson-viewer")}>`)}}export{LyraGeoJsonViewer2 as LyraGeoJsonViewer,LyraGeojsonView};
|