@aceshooting/lyra-ui 31.0.0 → 31.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +129 -0
- package/dist/autoloader-cdn.js +1 -1
- package/dist/components/agent-tools/budget-meter/budget-meter.class.d.ts +12 -1
- package/dist/components/agent-tools/budget-meter/budget-meter.class.js +4 -4
- package/dist/components/charts/chart/lite-chart.class.js +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +18 -8
- package/dist/components/conversation/chat-composer/chat-composer.class.js +11 -9
- package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
- package/dist/components/conversation/message-feedback/message-feedback.class.d.ts +11 -3
- package/dist/components/conversation/message-feedback/message-feedback.class.js +12 -6
- package/dist/components/conversation/message-feedback/message-feedback.styles.js +1 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +6 -3
- package/dist/components/conversation/prompt-input/prompt-input.class.js +3 -2
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.d.ts +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
- package/dist/components/data/document-library/document-library-cursor.js +1 -0
- package/dist/components/data/document-library/document-library-types.d.ts +20 -0
- package/dist/components/data/document-library/document-library.class.d.ts +37 -26
- package/dist/components/data/document-library/document-library.class.js +20 -11
- package/dist/components/data/document-library/document-library.styles.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/timeline/timeline.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.d.ts +20 -12
- package/dist/components/forms/combobox/combobox.class.js +2 -2
- package/dist/components/layout/dock-panel/dock-panel.class.d.ts +1 -1
- package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +3 -3
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/segmented/segmented.class.d.ts +20 -7
- package/dist/components/layout/segmented/segmented.class.js +34 -24
- package/dist/components/layout/segmented/segmented.styles.js +1 -1
- package/dist/components/layout/stepper/stepper.styles.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/media/map/map-anchor-controller.js +1 -1
- package/dist/components/media/map/map-canvas-target.js +1 -0
- package/dist/components/media/map/map.class.d.ts +10 -1
- package/dist/components/media/map/map.class.js +4 -4
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +21 -9
- package/dist/components/media/sequence-playback/sequence-playback.class.js +7 -6
- package/dist/components/media/sequence-playback/sequence-playback.styles.js +1 -1
- package/dist/components/overlays/overlay/overlay.styles.js +1 -1
- package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.d.ts +11 -0
- package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.js +1 -0
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +18 -7
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +13 -26
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.styles.js +1 -1
- package/dist/components/utility/diff-view/diff-view.class.d.ts +5 -5
- package/dist/components/utility/diff-view/diff-view.class.js +1 -1
- package/dist/components/utility/icon/icon.class.js +1 -1
- package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
- package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
- package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
- package/dist/components/viewers/document-preview/document-preview.class.js +2 -2
- package/dist/components/viewers/docx-viewer/docx-viewer.class.d.ts +1 -1
- package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.d.ts +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
- package/dist/components/viewers/html-viewer/html-viewer.class.js +1 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
- package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
- package/dist/components/viewers/xml-viewer/xml-viewer.class.js +2 -2
- package/dist/data-sources.d.ts +10 -0
- package/dist/events.d.ts +9 -4
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/default-strings/conversation.generated.js +1 -1
- package/dist/internal/default-strings/data.generated.js +1 -1
- package/dist/internal/default-strings/retrieval.generated.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.js +2 -2
- package/dist/internal/native-modal-context.js +1 -1
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/overlay-order.js +1 -1
- package/dist/internal/overlay-stack.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/runtime-diagnostics.js +1 -0
- package/dist/internal/source-cursor-controller.js +1 -0
- package/dist/internal/source-cursor-projection.js +1 -0
- package/dist/internal/source-page-scope.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/theme/theme-bootstrap.js +1 -1
- package/dist/theme/theme.js +1 -1
- package/dist/utilities/overlay-manager.d.ts +2 -0
- package/llms/components/lr-budget-meter.md +31 -0
- package/llms/components/lr-chat-composer.md +13 -2
- package/llms/components/lr-combobox.md +27 -1
- package/llms/components/lr-diff-view.md +6 -0
- package/llms/components/lr-document-library.md +90 -6
- package/llms/components/lr-graph.md +5 -0
- package/llms/components/lr-ingestion-queue.md +76 -8
- package/llms/components/lr-json-viewer.md +34 -0
- package/llms/components/lr-lite-chart.md +2 -1
- package/llms/components/lr-map.md +33 -0
- package/llms/components/lr-message-feedback.md +38 -3
- package/llms/components/lr-page.md +4 -2
- package/llms/components/lr-prompt-input.md +5 -2
- package/llms/components/lr-segmented.md +30 -10
- package/llms/components/lr-sequence-playback.md +47 -12
- package/llms/components/lr-virtual-list.md +3 -1
- package/llms/peers.md +2 -2
- package/llms/shared/events-and-types.md +61 -2
- package/llms/shared/forms-and-accessibility.md +25 -0
- package/llms/shared/imports-and-registration.md +154 -110
- package/llms/shared/testing-and-utilities.md +5 -1
- package/llms/shared.md +245 -113
- package/locales.json +1 -1
- package/package.json +8 -8
- package/registrations.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{SourcePageController}from"../../../internal/source-page-controller.js";import{finiteInteger}from"../../../internal/numbers.js";import{createHaystackMemo}from"../../../internal/search-haystack.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{archiveIcon,chevronIcon,closeIcon,pinIcon,trashIcon}from"../../../internal/icons.js";import{styles}from"./thread-list.styles.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{renderDataState}from"../../../internal/data-state-renderer.js";import{calendarDaysAgo,startOfLocalDay}from"../../../internal/group-by-recency.js";import{optionalSizeConverter}from"../../../internal/variants.js";import{getDateTimeFormat,getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR,getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{normalizeLyraTimestamp}from"../timestamp.js";import{LYRA_DEFAULT_archiveConversation,LYRA_DEFAULT_deleteConversation,LYRA_DEFAULT_pinConversation,LYRA_DEFAULT_searchThreads,LYRA_DEFAULT_threadGroupArchived,LYRA_DEFAULT_threadGroupCollapse,LYRA_DEFAULT_threadGroupExpand,LYRA_DEFAULT_threadGroupPinned,LYRA_DEFAULT_threadGroupPrevious30Days,LYRA_DEFAULT_threadGroupPrevious7Days,LYRA_DEFAULT_threadGroupToday,LYRA_DEFAULT_threadGroupYesterday,LYRA_DEFAULT_threadListEmpty,LYRA_DEFAULT_threadListInputLimit,LYRA_DEFAULT_threadListLabel,LYRA_DEFAULT_threadListMatchAnnounce,LYRA_DEFAULT_unarchiveConversation,LYRA_DEFAULT_unpinConversation}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_retry,LYRA_DEFAULT_tableLoadFailed}from"../../../internal/default-strings/shared.generated.js";const THREADS_AND_SLOTTED_CONTENT_WARNING_KEY="lyra-thread-list:threads-and-slotted-content",THREADS_AND_SLOTTED_CONTENT_WARNING="<lr-thread-list>: both `threads` and slotted content were supplied; `threads` data mode wins and the default slot is ignored.",canonicalThreadSnapshots=new WeakMap,sourceThreadByProjection=new WeakMap;function normalizeProjectedTimestamp(value){if(!(typeof value!="string"&&typeof value!="number"&&(value===null||typeof value!="object")))return normalizeLyraTimestamp(value)}function isSafeNonArrayObject(value){if(value===null||typeof value!="object")return!1;try{return!Array.isArray(value)}catch{return!1}}function projectThread(value){if(!isSafeNonArrayObject(value))return;const id=getOwnDataDescriptor(value,"id"),title=getOwnDataDescriptor(value,"title"),excerpt=getOwnDataDescriptor(value,"excerpt"),timestamp=getOwnDataDescriptor(value,"timestamp"),pinned=getOwnDataDescriptor(value,"pinned"),archived=getOwnDataDescriptor(value,"archived");if(id===MISSING_OWN_DATA_DESCRIPTOR||id===UNSAFE_OWN_DATA_DESCRIPTOR||title===MISSING_OWN_DATA_DESCRIPTOR||title===UNSAFE_OWN_DATA_DESCRIPTOR||typeof id.value!="string"||id.value.trim().length===0||typeof title.value!="string")return;const thread=Object.freeze({id:id.value,title:title.value,excerpt:excerpt===MISSING_OWN_DATA_DESCRIPTOR||excerpt===UNSAFE_OWN_DATA_DESCRIPTOR||typeof excerpt.value!="string"?void 0:excerpt.value,timestamp:timestamp===MISSING_OWN_DATA_DESCRIPTOR||timestamp===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:normalizeProjectedTimestamp(timestamp.value),pinned:pinned===MISSING_OWN_DATA_DESCRIPTOR||pinned===UNSAFE_OWN_DATA_DESCRIPTOR||typeof pinned.value!="boolean"?!1:pinned.value,archived:archived===MISSING_OWN_DATA_DESCRIPTOR||archived===UNSAFE_OWN_DATA_DESCRIPTOR||typeof archived.value!="boolean"?!1:archived.value});return sourceThreadByProjection.set(thread,value),thread}function canonicalThreads(values){const cached=canonicalThreadSnapshots.get(values);if(cached)return cached;const projected=[],seen=new Set;for(const value of values){const thread=projectThread(value);!thread||seen.has(thread.id)||(seen.add(thread.id),projected.push(thread))}const snapshot=Object.freeze(projected);return canonicalThreadSnapshots.set(values,snapshot),snapshot}class LyraThreadList extends LyraElement{constructor(){super(...arguments),this.inputLimitAnnouncements=new AnnouncementSinkController(this),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="region"]')),this.sourceEpoch=0,this.sourceSyncing=!1,this.sourceRequestVersion=0,this.sourceRows=[],this.sourceRowIdentities=new WeakSet,this.sourceGroupIdentities=new WeakSet,this.sourceStateVersion=0,this.sourcePages=new SourcePageController(this,{normalizeRecord:(record,isCurrent)=>this.projectSourceThread(record,isCurrent),validateMetadata:(result,query2)=>this.validateSourceGroups(result,query2),onChange:()=>{this.sourceStateVersion++}}),this.sourcePage=0,this.sourcePageSize=100,this.onSourcePage=event=>{event.stopPropagation(),this.sourceMode&&!this.sourceBlocked&&(this.sourcePage=event.detail.page-1)},this.threads=[],this.activeConversationId="",this.searchable=!1,this.size="m",this.grouping="date",this.collapsedGroupIds=[],this.rowActions=[],this.withArchived=!1,this.withoutRename=!1,this.stickyGroups=!1,this.error=!1,this.errorDescription="",this.stickyGroupItems=new Map,this.searchText="",this.hasEmptySlot=!1,this.hasDefaultSlotContent=!1,this.focusTaskGeneration=0,this.injectedListItemRoles=new Set,this.contentRefreshPending=!1,this.sourceStatusInitialized=!1,this.previousSourceStatus="",this.titleHaystacks=createHaystackMemo((thread,locale)=>thread.title.toLocaleLowerCase(resolveIntlLocale(locale))),this.excerptHaystacks=createHaystackMemo((thread,locale)=>(thread.excerpt??"").toLocaleLowerCase(resolveIntlLocale(locale))),this.onSearchInput=e=>{e.stopPropagation(),this.setSearchText(e.target.value)},this.onClearSearch=()=>{this.searchText!==""&&(this.setSearchText(""),this.searchInputEl?.focus())},this.onSearchKeyDown=e=>{if(e.key!=="ArrowDown")return;const focusGeneration=++this.focusTaskGeneration
|
|
1
|
+
import{__decorate}from"tslib";import{SourcePageController}from"../../../internal/source-page-controller.js";import{finiteInteger}from"../../../internal/numbers.js";import{createHaystackMemo}from"../../../internal/search-haystack.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{archiveIcon,chevronIcon,closeIcon,pinIcon,trashIcon}from"../../../internal/icons.js";import{styles}from"./thread-list.styles.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{renderDataState}from"../../../internal/data-state-renderer.js";import{calendarDaysAgo,startOfLocalDay}from"../../../internal/group-by-recency.js";import{optionalSizeConverter}from"../../../internal/variants.js";import{getDateTimeFormat,getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR,getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{normalizeLyraTimestamp}from"../timestamp.js";import{LYRA_DEFAULT_archiveConversation,LYRA_DEFAULT_deleteConversation,LYRA_DEFAULT_pinConversation,LYRA_DEFAULT_searchThreads,LYRA_DEFAULT_threadGroupArchived,LYRA_DEFAULT_threadGroupCollapse,LYRA_DEFAULT_threadGroupExpand,LYRA_DEFAULT_threadGroupPinned,LYRA_DEFAULT_threadGroupPrevious30Days,LYRA_DEFAULT_threadGroupPrevious7Days,LYRA_DEFAULT_threadGroupToday,LYRA_DEFAULT_threadGroupYesterday,LYRA_DEFAULT_threadListEmpty,LYRA_DEFAULT_threadListInputLimit,LYRA_DEFAULT_threadListLabel,LYRA_DEFAULT_threadListMatchAnnounce,LYRA_DEFAULT_unarchiveConversation,LYRA_DEFAULT_unpinConversation}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_retry,LYRA_DEFAULT_tableLoadFailed}from"../../../internal/default-strings/shared.generated.js";const THREADS_AND_SLOTTED_CONTENT_WARNING_KEY="lyra-thread-list:threads-and-slotted-content",THREADS_AND_SLOTTED_CONTENT_WARNING="<lr-thread-list>: both `threads` and slotted content were supplied; `threads` data mode wins and the default slot is ignored.",canonicalThreadSnapshots=new WeakMap,sourceThreadByProjection=new WeakMap;function normalizeProjectedTimestamp(value){if(!(typeof value!="string"&&typeof value!="number"&&(value===null||typeof value!="object")))return normalizeLyraTimestamp(value)}function isSafeNonArrayObject(value){if(value===null||typeof value!="object")return!1;try{return!Array.isArray(value)}catch{return!1}}function projectThread(value){if(!isSafeNonArrayObject(value))return;const id=getOwnDataDescriptor(value,"id"),title=getOwnDataDescriptor(value,"title"),excerpt=getOwnDataDescriptor(value,"excerpt"),timestamp=getOwnDataDescriptor(value,"timestamp"),pinned=getOwnDataDescriptor(value,"pinned"),archived=getOwnDataDescriptor(value,"archived");if(id===MISSING_OWN_DATA_DESCRIPTOR||id===UNSAFE_OWN_DATA_DESCRIPTOR||title===MISSING_OWN_DATA_DESCRIPTOR||title===UNSAFE_OWN_DATA_DESCRIPTOR||typeof id.value!="string"||id.value.trim().length===0||typeof title.value!="string")return;const thread=Object.freeze({id:id.value,title:title.value,excerpt:excerpt===MISSING_OWN_DATA_DESCRIPTOR||excerpt===UNSAFE_OWN_DATA_DESCRIPTOR||typeof excerpt.value!="string"?void 0:excerpt.value,timestamp:timestamp===MISSING_OWN_DATA_DESCRIPTOR||timestamp===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:normalizeProjectedTimestamp(timestamp.value),pinned:pinned===MISSING_OWN_DATA_DESCRIPTOR||pinned===UNSAFE_OWN_DATA_DESCRIPTOR||typeof pinned.value!="boolean"?!1:pinned.value,archived:archived===MISSING_OWN_DATA_DESCRIPTOR||archived===UNSAFE_OWN_DATA_DESCRIPTOR||typeof archived.value!="boolean"?!1:archived.value});return sourceThreadByProjection.set(thread,value),thread}function canonicalThreads(values){const cached=canonicalThreadSnapshots.get(values);if(cached)return cached;const projected=[],seen=new Set;for(const value of values){const thread=projectThread(value);!thread||seen.has(thread.id)||(seen.add(thread.id),projected.push(thread))}const snapshot=Object.freeze(projected);return canonicalThreadSnapshots.set(values,snapshot),snapshot}class LyraThreadList extends LyraElement{constructor(){super(...arguments),this.inputLimitAnnouncements=new AnnouncementSinkController(this),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="region"]')),this.sourceEpoch=0,this.sourceSyncing=!1,this.sourceRequestVersion=0,this.sourceRows=[],this.sourceRowIdentities=new WeakSet,this.sourceGroupIdentities=new WeakSet,this.sourceStateVersion=0,this.sourcePages=new SourcePageController(this,{normalizeRecord:(record,isCurrent)=>this.projectSourceThread(record,isCurrent),validateMetadata:(result,query2)=>this.validateSourceGroups(result,query2),onChange:()=>{this.sourceStateVersion++}}),this.sourcePage=0,this.sourcePageSize=100,this.onSourcePage=event=>{event.stopPropagation(),this.sourceMode&&!this.sourceBlocked&&(this.sourcePage=event.detail.page-1)},this.threads=[],this.activeConversationId="",this.searchable=!1,this.size="m",this.grouping="date",this.collapsedGroupIds=[],this.rowActions=[],this.withArchived=!1,this.withoutRename=!1,this.stickyGroups=!1,this.error=!1,this.errorDescription="",this.stickyGroupItems=new Map,this.searchText="",this.hasEmptySlot=!1,this.hasDefaultSlotContent=!1,this.focusTaskGeneration=0,this.excerptObservationGeneration=0,this.injectedListItemRoles=new Set,this.contentRefreshPending=!1,this.sourceStatusInitialized=!1,this.previousSourceStatus="",this.titleHaystacks=createHaystackMemo((thread,locale)=>thread.title.toLocaleLowerCase(resolveIntlLocale(locale))),this.excerptHaystacks=createHaystackMemo((thread,locale)=>(thread.excerpt??"").toLocaleLowerCase(resolveIntlLocale(locale))),this.onSearchInput=e=>{e.stopPropagation(),this.setSearchText(e.target.value)},this.onClearSearch=()=>{this.searchText!==""&&(this.setSearchText(""),this.searchInputEl?.focus())},this.onSearchKeyDown=e=>{if(e.key!=="ArrowDown")return;const focusGeneration=++this.focusTaskGeneration;this.stopPendingFocus?.();const rows=this.navigableRows(),list=this.virtualListEl,items=list?.items??[],first=items[items.findIndex(item=>item.kind==="thread")],firstId=first?.kind==="thread"?first.thread.id:void 0;rows[0]&&(!this.dataMode||rows[0].conversationId===firstId)?(e.preventDefault(),this.selectButtonEl(rows[0])?.focus()):this.dataMode&&list?.scrollContainer&&firstId!==void 0&&(e.preventDefault(),this.focusVirtualThreadFromItemIndex(list,items,0,1,focusGeneration))},this.onSearchFocus=event=>{relayNativeEvent(this,event)},this.onSearchBlur=event=>{relayNativeEvent(this,event)},this.onListKeyDown=e=>{if(e.key!=="ArrowDown"&&e.key!=="ArrowUp"&&e.key!=="Home"&&e.key!=="End"||e.defaultPrevented)return;const origin=e.composedPath()[0];if(origin?.nodeType===1&&origin.closest('[part="group-toggle"]'))return;const focusGeneration=++this.focusTaskGeneration;this.stopPendingFocus?.();const list=this.virtualListEl;if(this.dataMode&&(e.key==="Home"||e.key==="End")&&list?.scrollContainer){const items2=list.items;e.preventDefault(),this.focusVirtualThreadFromItemIndex(list,items2,e.key==="Home"?0:items2.length-1,e.key==="Home"?1:-1,focusGeneration);return}const rows=this.navigableRows();if(rows.length===0)return;const currentIndex=this.focusedRowIndex(rows);let targetIndex;if(e.key==="Home"?targetIndex=0:e.key==="End"?targetIndex=rows.length-1:e.key==="ArrowDown"?targetIndex=currentIndex<0?0:currentIndex+1:targetIndex=currentIndex<0?rows.length-1:currentIndex-1,e.preventDefault(),targetIndex>=0&&targetIndex<rows.length){this.selectButtonEl(rows[targetIndex])?.focus();return}if(!list?.scrollContainer)return;const currentRow=rows[currentIndex];if(!currentRow)return;const items=list.items,currentItemIndex=items.findIndex(item=>item.kind==="thread"&&item.thread.id===currentRow.conversationId);if(currentItemIndex<0)return;const direction=e.key==="ArrowDown"?1:-1;this.focusVirtualThreadFromItemIndex(list,items,currentItemIndex+direction,direction,focusGeneration)},this.renderRow=item=>{const thread=item,source=this.sourceThread(thread),row=html`
|
|
2
2
|
<lr-conversation-item
|
|
3
3
|
exportparts="base:row-item-base, base-menu-open:row-item-base-menu-open, active-indicator:row-item-active-indicator, select-button:row-item-select-button, start:row-item-start, content:row-item-content, label:row-item-label, label-input:row-item-label-input, rename-button:row-item-rename-button, excerpt:row-item-excerpt, meta:row-item-meta, timestamp:row-item-timestamp, actions:row-item-actions"
|
|
4
4
|
conversation-id=${thread.id}
|
|
@@ -28,7 +28,7 @@ import{__decorate}from"tslib";import{SourcePageController}from"../../../internal
|
|
|
28
28
|
>`:nothing}
|
|
29
29
|
${this.rowActions.length>0||this.renderActions?this.renderRowActions(thread):nothing}
|
|
30
30
|
</lr-conversation-item>
|
|
31
|
-
`;return this.wrapRow?html`<div part="row-wrapper">${this.wrapRow(source,row)}</div>`:row},this.renderItem=item=>{const listItem=item;return listItem.kind==="group"?this.renderGroupHeader(listItem):this.renderRow(listItem.thread)},this.renderStickyGroup=group=>{const item=this.stickyGroupItems.get(String(group.key));return item?this.renderGroupHeader(item,{sticky:!0}):nothing},this.itemKey=item=>{const listItem=item;return listItem.kind==="group"?this.groupItemKey(listItem.id):this.threadItemKey(listItem.thread.id)},this.onDefaultSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0}),keep=new Set(assigned);this.restoreInjectedListItemRoles(keep),this.markAsListItems(assigned),this.hasDefaultSlotContent=assigned.length>0},this.stopEvent=e=>{e.stopPropagation()},this.stopRowFocus=e=>{e.bubbles&&e.stopPropagation()},this.onEmptySlotChange=e=>{this.hasEmptySlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorRetry=()=>{this.error=!1}}static{this.defaultStrings={...super.defaultStrings,archiveConversation:LYRA_DEFAULT_archiveConversation,clear:LYRA_DEFAULT_clear,deleteConversation:LYRA_DEFAULT_deleteConversation,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,pinConversation:LYRA_DEFAULT_pinConversation,retry:LYRA_DEFAULT_retry,searchThreads:LYRA_DEFAULT_searchThreads,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,threadGroupArchived:LYRA_DEFAULT_threadGroupArchived,threadGroupCollapse:LYRA_DEFAULT_threadGroupCollapse,threadGroupExpand:LYRA_DEFAULT_threadGroupExpand,threadGroupPinned:LYRA_DEFAULT_threadGroupPinned,threadGroupPrevious30Days:LYRA_DEFAULT_threadGroupPrevious30Days,threadGroupPrevious7Days:LYRA_DEFAULT_threadGroupPrevious7Days,threadGroupToday:LYRA_DEFAULT_threadGroupToday,threadGroupYesterday:LYRA_DEFAULT_threadGroupYesterday,threadListEmpty:LYRA_DEFAULT_threadListEmpty,threadListInputLimit:LYRA_DEFAULT_threadListInputLimit,threadListLabel:LYRA_DEFAULT_threadListLabel,threadListMatchAnnounce:LYRA_DEFAULT_threadListMatchAnnounce,unarchiveConversation:LYRA_DEFAULT_unarchiveConversation,unpinConversation:LYRA_DEFAULT_unpinConversation}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["threads","groupOrder","collapsedGroupIds","rowActions"])}static{this.identityCollectionProperties=Object.freeze(["threads"])}static{this.styles=[LyraElement.styles,contextualSizes,styles]}get inputLimitMessage(){return this.sourceMode?"":publicCollectionTruncation(this,"threads")?this.localize("threadListInputLimit"):""}syncInputLimitAnnouncement(){const loss=this.sourceMode?void 0:publicCollectionTruncation(this,"threads");this.inputLimitAnnouncements.transition("input-limit",loss?`${loss.source}:${loss.retained}:${loss.kept}`:"",this.inputLimitMessage,"polite")}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.inputLimitAnnouncements.adopted(),this.sourcePages.adopted(),this.sourceRequestVersion++,this.sourceActiveInputs=void 0,this.sourceFilterIntent=void 0}get dataSource(){return this._dataSource}set dataSource(value){const previous=this._dataSource;this._dataSource=value,this.sourceEpoch++,this.requestUpdate("dataSource",previous)}get sourceTotal(){return this.sourceMode?this.sourcePages.state.result?.total??null:null}get sourceMode(){return this.dataSource!==void 0}get sourceFailed(){return this.sourceMode&&!this.sourcePages.state.pending&&!this.sourcePages.state.result}get sourceBlocked(){return this.sourceMode&&(!this.isConnected||this.error||this.sourcePages.state.pending||this.sourceFailed)}projectSourceThread(record,isCurrent){const raw=record.value;if(!isSafeNonArrayObject(raw))throw new TypeError("Invalid source thread");let units=0;const snapshot={};for(const key of["id","title","excerpt","timestamp","pinned","archived"]){if(!isCurrent())throw new Error("Obsolete source thread");const field=getOwnDataDescriptor(raw,key);if(!isCurrent())throw new Error("Obsolete source thread");if(field===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid source thread field");if(field!==MISSING_OWN_DATA_DESCRIPTOR&&(snapshot[key]=field.value),field!==MISSING_OWN_DATA_DESCRIPTOR&&typeof field.value=="string"&&(units+=field.value.length,field.value.length>65536||units>65536))throw new RangeError("Source thread text too large")}const value=projectThread(snapshot);if(!isCurrent())throw new Error("Obsolete source thread");if(!value||value.id!==record.key)throw new TypeError("Invalid source thread identity");return sourceThreadByProjection.set(value,raw),this.sourceRowIdentities.add(value),{key:record.key,order:record.order,value}}validateSourceGroups(result,query2){if(query2.grouping==="none"){if(result.groups?.length)throw new TypeError("Unexpected source groups");return}if(!result.groups)throw new TypeError("Missing source groups");if(!result.rows.length)return;const size=this.sourcePages.state.pageSize,start=Math.min(this.sourcePages.state.page,Math.floor((result.total-1)/size))*size,end=start+result.rows.length;let covered=start,previousEnd=-1;for(const group of result.groups){const groupEnd=group.startIndex+group.itemCount;if(group.startIndex<previousEnd||Math.max(start,group.startIndex)!==covered)throw new TypeError("Invalid source group coverage");previousEnd=groupEnd,covered=Math.min(end,groupEnd)}if(covered!==end)throw new TypeError("Incomplete source groups")}syncSource(){if(!(!this.sourcePages||this.sourceSyncing)){this.sourceSyncing=!0;try{if(!this.sourceMode){this.sourceInputs&&(this.sourceRequestVersion++,this.focusTaskGeneration++,this.sourcePages.bind(void 0)),this.sourceInputs=void 0,this.sourceQueryInputs=void 0,this.sourceResult=void 0,this.sourceRows=[],this.sourcePageModel=void 0,this.sourceActiveInputs=void 0,this.sourceActiveReveal=void 0,this.sourceFilterIntent=void 0;return}const source=this.dataSource,size=finiteInteger(this.sourcePageSize,100,1,500);let page=finiteInteger(this.sourcePage,0,0,Math.floor(Number.MAX_SAFE_INTEGER/size));const queryInputs=[this.searchText,this.withArchived,this.grouping,this.filter,this.groupBy,this.getGroupLabel,this.groupOrder,size];this.hasUpdated&&this.sourceQueryInputs&&queryInputs.some((value,index)=>value!==this.sourceQueryInputs[index])&&(page=0,this.sourcePage=0),this.sourceQueryInputs=queryInputs;const revision=source.revision,inputs=[source,revision,this.sourceEpoch,this.effectiveLocale,...queryInputs,this.collapsedGroupIds,page];if(this.sourceInputs&&inputs.every((value,index)=>value===this.sourceInputs[index]))return;this.sourceInputs=inputs,this.sourceRequestVersion++,this.focusTaskGeneration++,this.sourceRows=[],this.sourceResult=void 0,this.sourcePageModel=void 0,this.sourceActiveReveal=void 0,this.sourceFilterIntent=void 0,this.sourcePages.bind({source,revision,epoch:this.sourceEpoch,locale:this.effectiveLocale});const query2=Object.freeze({search:this.searchText,withArchived:this.withArchived,grouping:this.grouping,collapsedGroupIds:this.collapsedGroupIds,filter:this.filter,groupBy:this.groupBy,getGroupLabel:this.getGroupLabel,groupOrder:this.groupOrder});this.sourcePages.request(query2,page,size)}catch{this.sourcePages.bind(void 0),this.sourceRows=[],this.sourceResult=void 0,this.sourcePageModel=void 0}finally{this.sourceSyncing=!1}}}acceptSourcePage(){const result=this.sourcePages.state.result;if(!result||result===this.sourceResult)return;this.sourceResult=result,this.sourceRows=result.rows.map(record=>record.value),this.sourcePageModel=void 0,this.sourcePage!==this.sourcePages.state.page&&(this.sourceSyncing=!0,this.sourcePage=this.sourcePages.state.page,this.sourceSyncing=!1,this.sourceInputs=this.sourceInputs?[...this.sourceInputs.slice(0,-1),this.sourcePages.state.page]:void 0);const intent=this.sourceFilterIntent;if(this.sourceFilterIntent=void 0,intent?.version===this.sourceRequestVersion){const source=this.dataSource,epoch=this.sourceEpoch,state2=this.sourcePages.state,owner=this.ownerDocument;if(this.emit("lr-filter-change",{text:intent.text,matchCount:result.total}),!this.isConnected||this.ownerDocument!==owner||this.dataSource!==source||this.sourceEpoch!==epoch||this.sourceRequestVersion!==intent.version||this.sourcePages.state!==state2||this.sourceBlocked)return;this.announceMatchCount(result.total)}const reveal=this.sourceActiveReveal;this.sourceActiveReveal=void 0,reveal?.version===this.sourceRequestVersion&&this.revealSourceActive(reveal.id,reveal.version)}syncSourceActive(){if(!this.activeConversationId){this.sourceActiveInputs=void 0;return}if(!this.sourceMode||this.sourceBlocked)return;const source=this.dataSource,id=this.activeConversationId,inputs=[source,source.revision,this.sourceEpoch,this.effectiveLocale,...this.sourceQueryInputs??[],id];if(this.sourceActiveInputs&&inputs.every((value,index)=>value===this.sourceActiveInputs[index]))return;this.sourceActiveInputs=inputs;const version=this.sourceRequestVersion,owner=this.ownerDocument;this.sourcePages.locate(id).then(index=>{if(index===null||!this.isConnected||this.ownerDocument!==owner||!this.sourceMode||this.dataSource!==source||this.activeConversationId!==id||this.sourceRequestVersion!==version)return;const page=Math.floor(index/finiteInteger(this.sourcePageSize,100,1,500));if(page===this.sourcePage){this.revealSourceActive(id,version);return}this.sourcePage=page,this.sourceActiveReveal={id,version:this.sourceRequestVersion}})}revealSourceActive(id,version){const owner=this.ownerDocument;this.updateComplete.then(async()=>{const list=this.virtualListEl;if(!list||(await list.updateComplete,!this.isConnected||this.ownerDocument!==owner||!this.sourceMode||this.sourceBlocked||this.sourceRequestVersion!==version||this.activeConversationId!==id||list!==this.virtualListEl))return;const index=this.model().items.findIndex(item=>item.kind==="thread"&&item.thread.id===id);index>=0&&list.scrollToIndex(index,{align:"auto",behavior:"auto"})})}sourceModel(){const key=[this.sourceResult,this.collapsedGroupIds,this.stickyGroups];if(this.sourcePageModel&&key.every((value,index)=>value===this.sourcePageModel.key[index]))return this.sourcePageModel;const items=[],groups=this.sourceResult?.groups??[];if(!groups.length)items.push(...this.sourceRows.map(thread=>({kind:"thread",thread})));else{const collapsed=new Set(this.collapsedGroupIds),start=this.sourcePages.state.page*this.sourcePages.state.pageSize;for(const group of groups){const header={kind:"group",id:group.key,label:group.label,collapsed:collapsed.has(group.key)};if(this.sourceGroupIdentities.add(header),items.push(header),!header.collapsed){const from=Math.max(0,group.startIndex-start),to=Math.min(this.sourceRows.length,group.startIndex+group.itemCount-start);for(let index=from;index<to;index++)items.push({kind:"thread",thread:this.sourceRows[index]})}}}return this.sourcePageModel={key,visible:this.sourceRows,items,groups:this.stickyGroups?this.stickyAnchors(items):void 0},this.sourcePageModel}canUseThread(thread){return!(this.sourceMode||this.sourceRowIdentities.has(thread))||this.sourceMode&&!this.sourceBlocked&&this.sourceRows.includes(thread)}canUseGroup(item){return!(this.sourceMode||this.sourceGroupIdentities.has(item))||this.sourceMode&&!this.sourceBlocked&&this.sourceModel().items.includes(item)}currentSourceRetry(source,state2){return this.isConnected&&this.sourceMode&&this.dataSource===source&&this.sourcePages.state===state2&&(this.error||this.sourceFailed)}retrySource(source,state2){this.currentSourceRetry(source,state2)&&(this.error=!1,this.sourceInputs=void 0,this.syncSource(),this.sourceStateVersion++)}get dataMode(){return this.sourceMode||this.normalizedThreads.length>0||!this.hasDefaultSlotContent}connectedCallback(){if(super.connectedCallback(),this.hasUpdated){this.sourceMode&&(this.sourceActiveInputs=void 0,this.sourceStateVersion++),this.syncInputLimitAnnouncement();const defaultSlotted=this.defaultSlottedElements();this.hasDefaultSlotContent=defaultSlotted.length>0,!this.sourceMode&&this.normalizedThreads.length===0&&this.markAsListItems(defaultSlotted)}}requestUpdate(...args){args[0]===void 0&&(this.contentRefreshPending=!0,this.sourceEpoch=(this.sourceEpoch??0)+1),(args[0]===void 0||["dataSource","sourcePage","sourcePageSize","searchText","withArchived","grouping","filter","groupBy","getGroupLabel","groupOrder","collapsedGroupIds"].includes(String(args[0])))&&this.syncSource(),super.requestUpdate(...args)}willUpdate(changed){super.willUpdate(changed),this.syncSource(),this.sourceMode&&(this.acceptSourcePage(),this.syncSourceActive()),this.contentRefreshPending&&(this.dataModel=void 0),this.contentRefreshPending=!1,changed.has("size")&&optionalSizeConverter.normalize(this.size)===void 0&&(this.size="m"),(changed.has("threads")||changed.has("searchText")||changed.has("filter")||changed.has("grouping")||changed.has("groupBy")||changed.has("groupOrder")||changed.has("collapsedGroupIds")||changed.has("withArchived"))&&this.focusTaskGeneration++;const syncSlottedContent=()=>{const defaultSlotted=this.defaultSlottedElements();this.hasDefaultSlotContent=defaultSlotted.length>0;const hasDataThreads=this.sourceMode||this.normalizedThreads.length>0;hasDataThreads&&defaultSlotted.length>0?(this.restoreInjectedListItemRoles(),this.sourceMode||devWarnOnce(THREADS_AND_SLOTTED_CONTENT_WARNING_KEY,THREADS_AND_SLOTTED_CONTENT_WARNING)):hasDataThreads||this.markAsListItems(defaultSlotted)};this.hasUpdated?(changed.has("threads")||changed.has("dataSource"))&&syncSlottedContent():this.seedFirstRenderState(()=>{this.hasEmptySlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="empty"),syncSlottedContent()})}updated(changed){super.updated(changed),this.syncInputLimitAnnouncement();const status=this.sourceMode&&this.sourcePages.state.pending?this.localize("loading"):this.sourceMode&&this.sourceFailed?this.localize("tableLoadFailed"):"";this.sourceStatusInitialized&&status&&status!==this.previousSourceStatus&&this.inputLimitAnnouncements.announcePolite(status),this.sourceStatusInitialized=!0,this.previousSourceStatus=status,this.virtualListEl?.requestUpdate("renderItem")}defaultSlottedElements(){return Array.from(this.children).filter(el=>!el.getAttribute("slot"))}markAsListItems(elements){for(const el of elements)el.hasAttribute("role")||(el.setAttribute("role","listitem"),this.injectedListItemRoles.add(el))}restoreInjectedListItemRoles(keep=new Set){for(const element of this.injectedListItemRoles)keep.has(element)||(element.getAttribute("role")==="listitem"&&element.removeAttribute("role"),this.injectedListItemRoles.delete(element))}disconnectedCallback(){this.sourceRequestVersion++,this.sourceActiveInputs=void 0,this.sourceActiveReveal=void 0,this.sourceFilterIntent=void 0,this.sourceStatusInitialized=!1,this.previousSourceStatus="",this.focusTaskGeneration++,this.restoreInjectedListItemRoles(),super.disconnectedCallback()}get normalizedThreads(){return canonicalThreads(this.threads)}sourceThread(thread){return sourceThreadByProjection.get(thread)??thread}sourceThreads(threads){return Object.freeze(threads.map(thread=>this.sourceThread(thread)))}get visibleThreads(){const q=this.searchText.trim().toLocaleLowerCase(this.effectiveLocale),threads=this.normalizedThreads,titles=q&&!this.filter?this.titleHaystacks(threads,this.effectiveLocale):[],excerpts=q&&!this.filter?this.excerptHaystacks(threads,this.effectiveLocale):[];return threads.filter((thread,index)=>(this.withArchived||!thread.archived)&&(!q||(this.filter?this.filter(this.sourceThread(thread),q):titles[index].includes(q)||excerpts[index].includes(q))))}bucketFor(thread,today){if(thread.archived)return"archived";if(thread.pinned)return"pinned";const ts=thread.timestamp===void 0?void 0:normalizeLyraTimestamp(thread.timestamp);if(!ts)return"previous30";const diffDays=calendarDaysAgo(today,ts);return diffDays<=0?"today":diffDays===1?"yesterday":diffDays<=7?"previous7":diffDays<=30?"previous30":`month:${ts.getFullYear()}-${String(ts.getMonth()+1).padStart(2,"0")}`}bucketLabel(key){const groupDate=key.startsWith("month:")?this.dateForBucket(key):void 0;switch(key){case"pinned":return this.localize("threadGroupPinned");case"today":return this.localize("threadGroupToday");case"yesterday":return this.localize("threadGroupYesterday");case"previous7":return this.localize("threadGroupPrevious7Days");case"previous30":return this.localize("threadGroupPrevious30Days");case"archived":return this.localize("threadGroupArchived");default:return this.formatDate?.(groupDate)??getDateTimeFormat(this.effectiveLocale,{month:"long",year:"numeric"}).format(groupDate)}}dateForBucket(key){if(!key.startsWith("month:"))return;const[,ym]=key.split(":"),[year,month]=ym.split("-").map(Number);return new Date(year,month-1,1)}orderedCustomGroupIds(grouped){const firstSeen=[...grouped.keys()];if(typeof this.groupOrder=="function")try{return[...firstSeen].sort(this.groupOrder)}catch{return firstSeen}if(!this.groupOrder)return firstSeen;const ordered=[...new Set(this.groupOrder)].filter(id=>grouped.has(id)),listed=new Set(ordered);return[...ordered,...firstSeen.filter(id=>!listed.has(id))]}groupedItems(grouped,order,contextFor,defaultLabel){const collapsedIds=new Set(this.collapsedGroupIds),items=[];for(const id of order){const groupedThreads=grouped.get(id);if(!groupedThreads||groupedThreads.length===0)continue;const context=contextFor(id,groupedThreads),label=this.getGroupLabel?.(context)??defaultLabel(context);items.push({kind:"group",id,label,adornment:this.renderGroupAdornment?.(context),collapsed:collapsedIds.has(id)}),collapsedIds.has(id)||items.push(...groupedThreads.map(thread=>({kind:"thread",thread})))}return items}buildItems(visible,today){if(this.grouping==="none")return visible.map(thread=>({kind:"thread",thread}));if(this.grouping==="custom"){if(!this.groupBy)return visible.map(thread=>({kind:"thread",thread}));const grouped2=new Map;for(const thread of visible){let id;try{id=this.groupBy(this.sourceThread(thread))}catch{continue}if(typeof id!="string"||id.trim().length===0)continue;const existing=grouped2.get(id);existing?existing.push(thread):grouped2.set(id,[thread])}return this.groupedItems(grouped2,this.orderedCustomGroupIds(grouped2),(id,groupedThreads)=>({id,threads:this.sourceThreads(groupedThreads)}),context=>context.id)}const grouped=new Map,monthKeys=new Set;for(const thread of visible){const id=this.bucketFor(thread,today),existing=grouped.get(id);existing?existing.push(thread):grouped.set(id,[thread]),id.startsWith("month:")&&monthKeys.add(id)}const order=["pinned","today","yesterday","previous7","previous30",...[...monthKeys].sort().reverse(),"archived"];return this.groupedItems(grouped,order,(id,groupedThreads)=>{const bucket=id;return{id,threads:this.sourceThreads(groupedThreads),bucket,date:bucket.startsWith("month:")?this.dateForBucket(bucket):void 0}},context=>this.bucketLabel(context.bucket))}setSearchText(text){if(this.focusTaskGeneration++,this.searchText=text,this.sourceMode){this.sourceFilterIntent={text,version:this.sourceRequestVersion};return}if(!this.dataMode){this.emit("lr-query-change",{text});return}const count=this.model().visible.length;this.emit("lr-filter-change",{text,matchCount:count}),this.announceMatchCount(count)}announceMatchCount(count){this.searchText.trim()!==""&&this.liveRegion?.announce(this.localize("threadListMatchAnnounce",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count}))}itemElement(conversationId){return this.rowElements().find(row=>row.conversationId===conversationId)??null}rowElements(){return this.dataMode?(this.virtualListEl?.renderedRows??[]).flatMap(row=>[...row.querySelectorAll(tag("conversation-item"))]):this.defaultSlottedElements().flatMap(element=>element.localName===tag("conversation-item")?[element]:[...element.querySelectorAll(tag("conversation-item"))])}selectButtonEl(row){return row.shadowRoot?.querySelector('[part="select-button"]')??null}isNavigableRow(row){const option=this.selectButtonEl(row);return!!(option&&option.getAttribute("role")==="button"&&row.hidden===!1&&row.getAttribute("aria-hidden")!=="true"&&row.getAttribute("aria-disabled")!=="true"&&!row.inert&&row.closest("[inert]")===null&&option.hidden===!1&&option.getAttribute("aria-hidden")!=="true"&&option.getAttribute("aria-disabled")!=="true"&&!option.inert&&option.closest("[inert]")===null)}navigableRows(){return this.rowElements().filter(row=>this.isNavigableRow(row))}focusedRowIndex(rows){return rows.findIndex(row=>row.matches(":focus-within"))}focusVirtualThreadFromItemIndex(list,items,initialItemIndex,direction,focusGeneration){(async()=>{let targetItemIndex=initialItemIndex;for(;targetItemIndex>=0&&targetItemIndex<items.length;){for(;items[targetItemIndex]?.kind==="group";)targetItemIndex+=direction;const targetItem=items[targetItemIndex];if(!targetItem||targetItem.kind!=="thread")return;const targetId=targetItem.thread.id;list.scrollToIndex(targetItemIndex,{align:"auto",behavior:"auto"});let targetRow;for(let attempt=0;attempt<2;attempt+=1){if(await new Promise(resolve=>{const view=this.ownerDocument.defaultView;view?view.requestAnimationFrame(()=>resolve()):requestAnimationFrame(()=>resolve())}),focusGeneration!==this.focusTaskGeneration||!this.isConnected||this.virtualListEl!==list||(await list.updateComplete,focusGeneration!==this.focusTaskGeneration||!this.isConnected||this.virtualListEl!==list))return;if(targetRow=this.rowElements().find(row=>row.conversationId===targetId),targetRow)break}if(targetRow&&this.isNavigableRow(targetRow)){this.selectButtonEl(targetRow)?.focus();return}targetItemIndex+=direction}})()}renderRowActions(thread){const source=this.sourceThread(thread);return html`
|
|
31
|
+
`;return this.wrapRow?html`<div part="row-wrapper">${this.wrapRow(source,row)}</div>`:row},this.renderItem=item=>{const listItem=item;return listItem.kind==="group"?this.renderGroupHeader(listItem):this.renderRow(listItem.thread)},this.renderStickyGroup=group=>{const item=this.stickyGroupItems.get(String(group.key));return item?this.renderGroupHeader(item,{sticky:!0}):nothing},this.itemKey=item=>{const listItem=item;return listItem.kind==="group"?this.groupItemKey(listItem.id):this.threadItemKey(listItem.thread.id)},this.onDefaultSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0}),keep=new Set(assigned);this.restoreInjectedListItemRoles(keep),this.markAsListItems(assigned),this.hasDefaultSlotContent=assigned.length>0},this.stopEvent=e=>{e.stopPropagation()},this.stopRowFocus=e=>{e.bubbles&&e.stopPropagation()},this.onEmptySlotChange=e=>{this.hasEmptySlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorRetry=()=>{this.error=!1}}static{this.defaultStrings={...super.defaultStrings,archiveConversation:LYRA_DEFAULT_archiveConversation,clear:LYRA_DEFAULT_clear,deleteConversation:LYRA_DEFAULT_deleteConversation,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,pinConversation:LYRA_DEFAULT_pinConversation,retry:LYRA_DEFAULT_retry,searchThreads:LYRA_DEFAULT_searchThreads,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,threadGroupArchived:LYRA_DEFAULT_threadGroupArchived,threadGroupCollapse:LYRA_DEFAULT_threadGroupCollapse,threadGroupExpand:LYRA_DEFAULT_threadGroupExpand,threadGroupPinned:LYRA_DEFAULT_threadGroupPinned,threadGroupPrevious30Days:LYRA_DEFAULT_threadGroupPrevious30Days,threadGroupPrevious7Days:LYRA_DEFAULT_threadGroupPrevious7Days,threadGroupToday:LYRA_DEFAULT_threadGroupToday,threadGroupYesterday:LYRA_DEFAULT_threadGroupYesterday,threadListEmpty:LYRA_DEFAULT_threadListEmpty,threadListInputLimit:LYRA_DEFAULT_threadListInputLimit,threadListLabel:LYRA_DEFAULT_threadListLabel,threadListMatchAnnounce:LYRA_DEFAULT_threadListMatchAnnounce,unarchiveConversation:LYRA_DEFAULT_unarchiveConversation,unpinConversation:LYRA_DEFAULT_unpinConversation}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["threads","groupOrder","collapsedGroupIds","rowActions"])}static{this.identityCollectionProperties=Object.freeze(["threads"])}static{this.styles=[LyraElement.styles,contextualSizes,styles]}get inputLimitMessage(){return this.sourceMode?"":publicCollectionTruncation(this,"threads")?this.localize("threadListInputLimit"):""}syncInputLimitAnnouncement(){const loss=this.sourceMode?void 0:publicCollectionTruncation(this,"threads");this.inputLimitAnnouncements.transition("input-limit",loss?`${loss.source}:${loss.retained}:${loss.kept}`:"",this.inputLimitMessage,"polite")}adoptedCallback(){this.focusTaskGeneration++,this.stopPendingFocus?.(),super.adoptedCallback(),this.hostDescription.adopted(),this.inputLimitAnnouncements.adopted(),this.sourcePages.adopted(),this.sourceRequestVersion++,this.sourceActiveInputs=void 0,this.sourceFilterIntent=void 0}get dataSource(){return this._dataSource}set dataSource(value){const previous=this._dataSource;this._dataSource=value,this.sourceEpoch++,this.requestUpdate("dataSource",previous)}get sourceTotal(){return this.sourceMode?this.sourcePages.state.result?.total??null:null}get sourceMode(){return this.dataSource!==void 0}get sourceFailed(){return this.sourceMode&&!this.sourcePages.state.pending&&!this.sourcePages.state.result}get sourceBlocked(){return this.sourceMode&&(!this.isConnected||this.error||this.sourcePages.state.pending||this.sourceFailed)}projectSourceThread(record,isCurrent){const raw=record.value;if(!isSafeNonArrayObject(raw))throw new TypeError("Invalid source thread");let units=0;const snapshot={};for(const key of["id","title","excerpt","timestamp","pinned","archived"]){if(!isCurrent())throw new Error("Obsolete source thread");const field=getOwnDataDescriptor(raw,key);if(!isCurrent())throw new Error("Obsolete source thread");if(field===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid source thread field");if(field!==MISSING_OWN_DATA_DESCRIPTOR&&(snapshot[key]=field.value),field!==MISSING_OWN_DATA_DESCRIPTOR&&typeof field.value=="string"&&(units+=field.value.length,field.value.length>65536||units>65536))throw new RangeError("Source thread text too large")}const value=projectThread(snapshot);if(!isCurrent())throw new Error("Obsolete source thread");if(!value||value.id!==record.key)throw new TypeError("Invalid source thread identity");return sourceThreadByProjection.set(value,raw),this.sourceRowIdentities.add(value),{key:record.key,order:record.order,value}}validateSourceGroups(result,query2){if(query2.grouping==="none"){if(result.groups?.length)throw new TypeError("Unexpected source groups");return}if(!result.groups)throw new TypeError("Missing source groups");if(!result.rows.length)return;const size=this.sourcePages.state.pageSize,start=Math.min(this.sourcePages.state.page,Math.floor((result.total-1)/size))*size,end=start+result.rows.length;let covered=start,previousEnd=-1;for(const group of result.groups){const groupEnd=group.startIndex+group.itemCount;if(group.startIndex<previousEnd||Math.max(start,group.startIndex)!==covered)throw new TypeError("Invalid source group coverage");previousEnd=groupEnd,covered=Math.min(end,groupEnd)}if(covered!==end)throw new TypeError("Incomplete source groups")}syncSource(){if(!(!this.sourcePages||this.sourceSyncing)){this.sourceSyncing=!0;try{if(!this.sourceMode){this.sourceInputs&&(this.sourceRequestVersion++,this.focusTaskGeneration++,this.sourcePages.bind(void 0)),this.sourceInputs=void 0,this.sourceQueryInputs=void 0,this.sourceResult=void 0,this.sourceRows=[],this.sourcePageModel=void 0,this.sourceActiveInputs=void 0,this.sourceActiveReveal=void 0,this.sourceFilterIntent=void 0;return}const source=this.dataSource,size=finiteInteger(this.sourcePageSize,100,1,500);let page=finiteInteger(this.sourcePage,0,0,Math.floor(Number.MAX_SAFE_INTEGER/size));const queryInputs=[this.searchText,this.withArchived,this.grouping,this.filter,this.groupBy,this.getGroupLabel,this.groupOrder,size];this.hasUpdated&&this.sourceQueryInputs&&queryInputs.some((value,index)=>value!==this.sourceQueryInputs[index])&&(page=0,this.sourcePage=0),this.sourceQueryInputs=queryInputs;const revision=source.revision,inputs=[source,revision,this.sourceEpoch,this.effectiveLocale,...queryInputs,this.collapsedGroupIds,page];if(this.sourceInputs&&inputs.every((value,index)=>value===this.sourceInputs[index]))return;this.sourceInputs=inputs,this.sourceRequestVersion++,this.focusTaskGeneration++,this.sourceRows=[],this.sourceResult=void 0,this.sourcePageModel=void 0,this.sourceActiveReveal=void 0,this.sourceFilterIntent=void 0,this.sourcePages.bind({source,revision,epoch:this.sourceEpoch,locale:this.effectiveLocale});const query2=Object.freeze({search:this.searchText,withArchived:this.withArchived,grouping:this.grouping,collapsedGroupIds:this.collapsedGroupIds,filter:this.filter,groupBy:this.groupBy,getGroupLabel:this.getGroupLabel,groupOrder:this.groupOrder});this.sourcePages.request(query2,page,size)}catch{this.sourcePages.bind(void 0),this.sourceRows=[],this.sourceResult=void 0,this.sourcePageModel=void 0}finally{this.sourceSyncing=!1}}}acceptSourcePage(){const result=this.sourcePages.state.result;if(!result||result===this.sourceResult)return;this.sourceResult=result,this.sourceRows=result.rows.map(record=>record.value),this.sourcePageModel=void 0,this.sourcePage!==this.sourcePages.state.page&&(this.sourceSyncing=!0,this.sourcePage=this.sourcePages.state.page,this.sourceSyncing=!1,this.sourceInputs=this.sourceInputs?[...this.sourceInputs.slice(0,-1),this.sourcePages.state.page]:void 0);const intent=this.sourceFilterIntent;if(this.sourceFilterIntent=void 0,intent?.version===this.sourceRequestVersion){const source=this.dataSource,epoch=this.sourceEpoch,state2=this.sourcePages.state,owner=this.ownerDocument;if(this.emit("lr-filter-change",{text:intent.text,matchCount:result.total}),!this.isConnected||this.ownerDocument!==owner||this.dataSource!==source||this.sourceEpoch!==epoch||this.sourceRequestVersion!==intent.version||this.sourcePages.state!==state2||this.sourceBlocked)return;this.announceMatchCount(result.total)}const reveal=this.sourceActiveReveal;this.sourceActiveReveal=void 0,reveal?.version===this.sourceRequestVersion&&this.revealSourceActive(reveal.id,reveal.version)}syncSourceActive(){if(!this.activeConversationId){this.sourceActiveInputs=void 0;return}if(!this.sourceMode||this.sourceBlocked)return;const source=this.dataSource,id=this.activeConversationId,inputs=[source,source.revision,this.sourceEpoch,this.effectiveLocale,...this.sourceQueryInputs??[],id];if(this.sourceActiveInputs&&inputs.every((value,index)=>value===this.sourceActiveInputs[index]))return;this.sourceActiveInputs=inputs;const version=this.sourceRequestVersion,owner=this.ownerDocument;this.sourcePages.locate(id).then(index=>{if(index===null||!this.isConnected||this.ownerDocument!==owner||!this.sourceMode||this.dataSource!==source||this.activeConversationId!==id||this.sourceRequestVersion!==version)return;const page=Math.floor(index/finiteInteger(this.sourcePageSize,100,1,500));if(page===this.sourcePage){this.revealSourceActive(id,version);return}this.sourcePage=page,this.sourceActiveReveal={id,version:this.sourceRequestVersion}})}revealSourceActive(id,version){const owner=this.ownerDocument;this.updateComplete.then(async()=>{const list=this.virtualListEl;if(!list||(await list.updateComplete,!this.isConnected||this.ownerDocument!==owner||!this.sourceMode||this.sourceBlocked||this.sourceRequestVersion!==version||this.activeConversationId!==id||list!==this.virtualListEl))return;const index=this.model().items.findIndex(item=>item.kind==="thread"&&item.thread.id===id);index>=0&&list.scrollToIndex(index,{align:"auto",behavior:"auto"})})}sourceModel(){const key=[this.sourceResult,this.collapsedGroupIds,this.stickyGroups];if(this.sourcePageModel&&key.every((value,index)=>value===this.sourcePageModel.key[index]))return this.sourcePageModel;const items=[],groups=this.sourceResult?.groups??[];if(!groups.length)items.push(...this.sourceRows.map(thread=>({kind:"thread",thread})));else{const collapsed=new Set(this.collapsedGroupIds),start=this.sourcePages.state.page*this.sourcePages.state.pageSize;for(const group of groups){const header={kind:"group",id:group.key,label:group.label,collapsed:collapsed.has(group.key)};if(this.sourceGroupIdentities.add(header),items.push(header),!header.collapsed){const from=Math.max(0,group.startIndex-start),to=Math.min(this.sourceRows.length,group.startIndex+group.itemCount-start);for(let index=from;index<to;index++)items.push({kind:"thread",thread:this.sourceRows[index]})}}}return this.sourcePageModel={key,visible:this.sourceRows,items,groups:this.stickyGroups?this.stickyAnchors(items):void 0},this.sourcePageModel}canUseThread(thread){return!(this.sourceMode||this.sourceRowIdentities.has(thread))||this.sourceMode&&!this.sourceBlocked&&this.sourceRows.includes(thread)}canUseGroup(item){return!(this.sourceMode||this.sourceGroupIdentities.has(item))||this.sourceMode&&!this.sourceBlocked&&this.sourceModel().items.includes(item)}currentSourceRetry(source,state2){return this.isConnected&&this.sourceMode&&this.dataSource===source&&this.sourcePages.state===state2&&(this.error||this.sourceFailed)}retrySource(source,state2){this.currentSourceRetry(source,state2)&&(this.error=!1,this.sourceInputs=void 0,this.syncSource(),this.sourceStateVersion++)}get dataMode(){return this.sourceMode||this.normalizedThreads.length>0||!this.hasDefaultSlotContent}connectedCallback(){if(super.connectedCallback(),this.hasUpdated){this.sourceMode&&(this.sourceActiveInputs=void 0,this.sourceStateVersion++),this.syncInputLimitAnnouncement();const defaultSlotted=this.defaultSlottedElements();this.hasDefaultSlotContent=defaultSlotted.length>0,!this.sourceMode&&this.normalizedThreads.length===0&&this.markAsListItems(defaultSlotted),this.observeRenderedExcerpts()}}requestUpdate(...args){args[0]===void 0&&(this.contentRefreshPending=!0,this.sourceEpoch=(this.sourceEpoch??0)+1),(args[0]===void 0||["dataSource","sourcePage","sourcePageSize","searchText","withArchived","grouping","filter","groupBy","getGroupLabel","groupOrder","collapsedGroupIds"].includes(String(args[0])))&&this.syncSource(),super.requestUpdate(...args)}willUpdate(changed){super.willUpdate(changed),this.syncSource(),this.sourceMode&&(this.acceptSourcePage(),this.syncSourceActive()),this.contentRefreshPending&&(this.dataModel=void 0),this.contentRefreshPending=!1,changed.has("size")&&optionalSizeConverter.normalize(this.size)===void 0&&(this.size="m"),(changed.has("threads")||changed.has("searchText")||changed.has("filter")||changed.has("grouping")||changed.has("groupBy")||changed.has("groupOrder")||changed.has("collapsedGroupIds")||changed.has("withArchived"))&&this.focusTaskGeneration++;const syncSlottedContent=()=>{const defaultSlotted=this.defaultSlottedElements();this.hasDefaultSlotContent=defaultSlotted.length>0;const hasDataThreads=this.sourceMode||this.normalizedThreads.length>0;hasDataThreads&&defaultSlotted.length>0?(this.restoreInjectedListItemRoles(),this.sourceMode||devWarnOnce(THREADS_AND_SLOTTED_CONTENT_WARNING_KEY,THREADS_AND_SLOTTED_CONTENT_WARNING)):hasDataThreads||this.markAsListItems(defaultSlotted)};this.hasUpdated?(changed.has("threads")||changed.has("dataSource"))&&syncSlottedContent():this.seedFirstRenderState(()=>{this.hasEmptySlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="empty"),syncSlottedContent()})}updated(changed){super.updated(changed),this.syncInputLimitAnnouncement();const status=this.sourceMode&&this.sourcePages.state.pending?this.localize("loading"):this.sourceMode&&this.sourceFailed?this.localize("tableLoadFailed"):"";this.sourceStatusInitialized&&status&&status!==this.previousSourceStatus&&this.inputLimitAnnouncements.announcePolite(status),this.sourceStatusInitialized=!0,this.previousSourceStatus=status,this.virtualListEl?.requestUpdate("renderItem"),this.observeRenderedExcerpts()}async observeRenderedExcerpts(){const generation=++this.excerptObservationGeneration,list=this.virtualListEl;if(list&&await list.updateComplete,!this.isConnected||generation!==this.excerptObservationGeneration||list!==this.virtualListEl)return;const root=this.renderExcerpt?list?.renderRoot:void 0;if(root!==this.excerptRoot){this.excerptObserver?.disconnect(),this.excerptObserver=void 0,this.excerptRoot=root;const Observer=this.ownerDocument.defaultView?.MutationObserver;if(root&&Observer){const observer=new Observer(()=>{this.isConnected&&this.excerptObserver===observer&&this.virtualListEl?.renderRoot===root&&this.syncRenderedExcerpts(root)});this.excerptObserver=observer,observer.observe(root,{childList:!0,characterData:!0,subtree:!0})}}root&&this.syncRenderedExcerpts(root)}syncRenderedExcerpts(root){for(const wrapper of root.querySelectorAll('[part="row-excerpt"]')){if(wrapper.parentElement?.localName!==tag("conversation-item"))continue;const slot=Array.from(wrapper.childNodes).some(node=>node.nodeType===1||node.nodeType===3&&(node.textContent??"").trim().length>0)?"excerpt":"";wrapper.slot!==slot&&(wrapper.slot=slot)}}defaultSlottedElements(){return Array.from(this.children).filter(el=>!el.getAttribute("slot"))}markAsListItems(elements){for(const el of elements)el.hasAttribute("role")||(el.setAttribute("role","listitem"),this.injectedListItemRoles.add(el))}restoreInjectedListItemRoles(keep=new Set){for(const element of this.injectedListItemRoles)keep.has(element)||(element.getAttribute("role")==="listitem"&&element.removeAttribute("role"),this.injectedListItemRoles.delete(element))}disconnectedCallback(){this.excerptObservationGeneration++,this.excerptObserver?.disconnect(),this.excerptObserver=void 0,this.excerptRoot=void 0,this.sourceRequestVersion++,this.sourceActiveInputs=void 0,this.sourceActiveReveal=void 0,this.sourceFilterIntent=void 0,this.sourceStatusInitialized=!1,this.previousSourceStatus="",this.focusTaskGeneration++,this.stopPendingFocus?.(),this.restoreInjectedListItemRoles(),super.disconnectedCallback()}get normalizedThreads(){return canonicalThreads(this.threads)}sourceThread(thread){return sourceThreadByProjection.get(thread)??thread}sourceThreads(threads){return Object.freeze(threads.map(thread=>this.sourceThread(thread)))}get visibleThreads(){const q=this.searchText.trim().toLocaleLowerCase(this.effectiveLocale),threads=this.normalizedThreads,titles=q&&!this.filter?this.titleHaystacks(threads,this.effectiveLocale):[],excerpts=q&&!this.filter?this.excerptHaystacks(threads,this.effectiveLocale):[];return threads.filter((thread,index)=>(this.withArchived||!thread.archived)&&(!q||(this.filter?this.filter(this.sourceThread(thread),q):titles[index].includes(q)||excerpts[index].includes(q))))}bucketFor(thread,today){if(thread.archived)return"archived";if(thread.pinned)return"pinned";const ts=thread.timestamp===void 0?void 0:normalizeLyraTimestamp(thread.timestamp);if(!ts)return"previous30";const diffDays=calendarDaysAgo(today,ts);return diffDays<=0?"today":diffDays===1?"yesterday":diffDays<=7?"previous7":diffDays<=30?"previous30":`month:${ts.getFullYear()}-${String(ts.getMonth()+1).padStart(2,"0")}`}bucketLabel(key){const groupDate=key.startsWith("month:")?this.dateForBucket(key):void 0;switch(key){case"pinned":return this.localize("threadGroupPinned");case"today":return this.localize("threadGroupToday");case"yesterday":return this.localize("threadGroupYesterday");case"previous7":return this.localize("threadGroupPrevious7Days");case"previous30":return this.localize("threadGroupPrevious30Days");case"archived":return this.localize("threadGroupArchived");default:return this.formatDate?.(groupDate)??getDateTimeFormat(this.effectiveLocale,{month:"long",year:"numeric"}).format(groupDate)}}dateForBucket(key){if(!key.startsWith("month:"))return;const[,ym]=key.split(":"),[year,month]=ym.split("-").map(Number);return new Date(year,month-1,1)}orderedCustomGroupIds(grouped){const firstSeen=[...grouped.keys()];if(typeof this.groupOrder=="function")try{return[...firstSeen].sort(this.groupOrder)}catch{return firstSeen}if(!this.groupOrder)return firstSeen;const ordered=[...new Set(this.groupOrder)].filter(id=>grouped.has(id)),listed=new Set(ordered);return[...ordered,...firstSeen.filter(id=>!listed.has(id))]}groupedItems(grouped,order,contextFor,defaultLabel){const collapsedIds=new Set(this.collapsedGroupIds),items=[];for(const id of order){const groupedThreads=grouped.get(id);if(!groupedThreads||groupedThreads.length===0)continue;const context=contextFor(id,groupedThreads),label=this.getGroupLabel?.(context)??defaultLabel(context);items.push({kind:"group",id,label,adornment:this.renderGroupAdornment?.(context),collapsed:collapsedIds.has(id)}),collapsedIds.has(id)||items.push(...groupedThreads.map(thread=>({kind:"thread",thread})))}return items}buildItems(visible,today){if(this.grouping==="none")return visible.map(thread=>({kind:"thread",thread}));if(this.grouping==="custom"){if(!this.groupBy)return visible.map(thread=>({kind:"thread",thread}));const grouped2=new Map;for(const thread of visible){let id;try{id=this.groupBy(this.sourceThread(thread))}catch{continue}if(typeof id!="string"||id.trim().length===0)continue;const existing=grouped2.get(id);existing?existing.push(thread):grouped2.set(id,[thread])}return this.groupedItems(grouped2,this.orderedCustomGroupIds(grouped2),(id,groupedThreads)=>({id,threads:this.sourceThreads(groupedThreads)}),context=>context.id)}const grouped=new Map,monthKeys=new Set;for(const thread of visible){const id=this.bucketFor(thread,today),existing=grouped.get(id);existing?existing.push(thread):grouped.set(id,[thread]),id.startsWith("month:")&&monthKeys.add(id)}const order=["pinned","today","yesterday","previous7","previous30",...[...monthKeys].sort().reverse(),"archived"];return this.groupedItems(grouped,order,(id,groupedThreads)=>{const bucket=id;return{id,threads:this.sourceThreads(groupedThreads),bucket,date:bucket.startsWith("month:")?this.dateForBucket(bucket):void 0}},context=>this.bucketLabel(context.bucket))}setSearchText(text){if(this.focusTaskGeneration++,this.searchText=text,this.sourceMode){this.sourceFilterIntent={text,version:this.sourceRequestVersion};return}if(!this.dataMode){this.emit("lr-query-change",{text});return}const count=this.model().visible.length;this.emit("lr-filter-change",{text,matchCount:count}),this.announceMatchCount(count)}announceMatchCount(count){this.searchText.trim()!==""&&this.liveRegion?.announce(this.localize("threadListMatchAnnounce",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count}))}itemElement(conversationId){return this.rowElements().find(row=>row.conversationId===conversationId)??null}rowElements(){return this.dataMode?(this.virtualListEl?.renderedRows??[]).flatMap(row=>[...row.querySelectorAll(tag("conversation-item"))]):this.defaultSlottedElements().flatMap(element=>element.localName===tag("conversation-item")?[element]:[...element.querySelectorAll(tag("conversation-item"))])}selectButtonEl(row){return row.shadowRoot?.querySelector('[part="select-button"]')??null}isNavigableRow(row){const option=this.selectButtonEl(row);return!!(option&&option.getAttribute("role")==="button"&&row.hidden===!1&&row.getAttribute("aria-hidden")!=="true"&&row.getAttribute("aria-disabled")!=="true"&&!row.inert&&row.closest("[inert]")===null&&option.hidden===!1&&option.getAttribute("aria-hidden")!=="true"&&option.getAttribute("aria-disabled")!=="true"&&!option.inert&&option.closest("[inert]")===null)}navigableRows(){return this.rowElements().filter(row=>this.isNavigableRow(row))}focusedRowIndex(rows){return rows.findIndex(row=>row.matches(":focus-within"))}focusVirtualThreadFromItemIndex(list,items,initialItemIndex,direction,focusGeneration){this.stopPendingFocus?.();const ownerDocument=this.ownerDocument,stop=()=>{ownerDocument.removeEventListener("focusin",onFocusIn,!0),this.stopPendingFocus===stop&&(this.stopPendingFocus=void 0)},onFocusIn=event=>{!event.isTrusted||this.matches(":focus-within")||(focusGeneration===this.focusTaskGeneration&&this.focusTaskGeneration++,stop())};this.stopPendingFocus=stop,ownerDocument.addEventListener("focusin",onFocusIn,!0),(async()=>{let targetItemIndex=initialItemIndex;for(;targetItemIndex>=0&&targetItemIndex<items.length;){for(;items[targetItemIndex]?.kind==="group";)targetItemIndex+=direction;const targetItem=items[targetItemIndex];if(!targetItem||targetItem.kind!=="thread")return;const targetId=targetItem.thread.id;list.scrollToIndex(targetItemIndex,{align:"auto",behavior:"auto"});let targetRow;for(let attempt=0;attempt<2;attempt+=1){if(await new Promise(resolve=>{const view=ownerDocument.defaultView;view?view.requestAnimationFrame(()=>resolve()):requestAnimationFrame(()=>resolve())}),focusGeneration!==this.focusTaskGeneration||!this.isConnected||this.ownerDocument!==ownerDocument||this.virtualListEl!==list||(await list.updateComplete,focusGeneration!==this.focusTaskGeneration||!this.isConnected||this.ownerDocument!==ownerDocument||this.virtualListEl!==list))return;if(targetRow=this.rowElements().find(row=>row.conversationId===targetId),targetRow)break}if(targetRow&&this.isNavigableRow(targetRow)){this.selectButtonEl(targetRow)?.focus();return}targetItemIndex+=direction}})().finally(stop)}renderRowActions(thread){const source=this.sourceThread(thread);return html`
|
|
32
32
|
<span slot="actions" part="row-actions">
|
|
33
33
|
${this.rowActions.includes("pin")?html`<button
|
|
34
34
|
type="button"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";function cursorIds(value,maximum,current){const field=key=>{if(!current())throw new TypeError("Obsolete cursor input");const descriptor=getOwnDataDescriptor(value,key);if(!current())throw new TypeError("Obsolete cursor input");if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid cursor list");return descriptor.value};if(!Array.isArray(value))throw new TypeError("Invalid cursor list");const length=field("length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>1e4)throw new RangeError("Cursor list limit");const ids=new Set;let units=0;for(let index=0;index<length;index++){const id=field(String(index));if(typeof id!="string"||!id.trim()||id.length>65536)throw new TypeError("Invalid cursor key");if(!ids.has(id)){if(units+=id.length,units>2e6)throw new RangeError("Cursor input text limit");if(ids.add(id),ids.size>maximum)throw new RangeError("Cursor unique-key limit")}}return Object.freeze([...ids])}function cursorQueryText(searchTerm,tags,current){if(typeof searchTerm!="string"||searchTerm.length>65536)throw new TypeError("Invalid cursor search");const tagFilter=cursorIds(tags,500,current);if(tagFilter.reduce((units,tag)=>units+tag.length,searchTerm.length)>2e6)throw new RangeError("Cursor query text limit");return Object.freeze({searchTerm,tagFilter})}export{cursorIds,cursorQueryText};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type{DocumentRef}from'../../../ai/types.js';
|
|
2
|
+
/** How recently a document's content was verified/updated, consumer-computed (this component
|
|
3
|
+
* performs no staleness calculation of its own -- it only renders whichever bucket the host
|
|
4
|
+
* already assigned). Ordered fresh -> aging -> stale for `freshness`-column sorting. */
|
|
5
|
+
export type LibraryDocumentFreshness='fresh'|'aging'|'stale';
|
|
6
|
+
/**
|
|
7
|
+
* One inventory row. Extends the shared `DocumentRef` (`src/ai/types.ts`) -- `id`/`name`/
|
|
8
|
+
* `mimeType`/`uri`/`version` assign directly onto/from it with no adapter -- with the
|
|
9
|
+
* tags/owner/freshness fields specific to an inventory view that the provider-neutral
|
|
10
|
+
* `DocumentRef` deliberately doesn't carry. `updatedAt` reuses
|
|
11
|
+
* `ChatMessage.timestamp`'s own `Date | string` shape from the same `src/ai/types.ts` module for
|
|
12
|
+
* consistency across this component family.
|
|
13
|
+
*/
|
|
14
|
+
export interface LibraryDocument extends DocumentRef{
|
|
15
|
+
/** Optional tags. An own undefined value is treated like omission.*/
|
|
16
|
+
tags?:readonly string[];owner?:string;
|
|
17
|
+
/** Last-updated timestamp. `Date | string` (ISO-8601), matching `ChatMessage.timestamp`.*/
|
|
18
|
+
updatedAt?:Date|string;freshness?:LibraryDocumentFreshness;}
|
|
19
|
+
/** Column keys `sortKey` accepts. Not every column is sortable (`type`/`tags`/`select` are not).*/
|
|
20
|
+
export type LibraryDocumentSortKey='name'|'version'|'owner'|'freshness'|'updatedAt';
|
|
@@ -1,27 +1,10 @@
|
|
|
1
|
-
import type{LyraPageSource}from'../../../data-sources.js';import type{LyraEventDetailSnapshot}from'../../../internal/lyra-element.js';import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{
|
|
2
|
-
/** How recently a document's content was verified/updated, consumer-computed (this component
|
|
3
|
-
* performs no staleness calculation of its own -- it only renders whichever bucket the host
|
|
4
|
-
* already assigned). Ordered fresh -> aging -> stale for `freshness`-column sorting. */
|
|
5
|
-
export type LibraryDocumentFreshness='fresh'|'aging'|'stale';
|
|
6
|
-
/**
|
|
7
|
-
* One inventory row. Extends the shared `DocumentRef` (`src/ai/types.ts`) -- `id`/`name`/
|
|
8
|
-
* `mimeType`/`uri`/`version` assign directly onto/from it with no adapter -- with the
|
|
9
|
-
* tags/owner/freshness fields specific to an inventory view that the provider-neutral
|
|
10
|
-
* `DocumentRef` deliberately doesn't carry. `updatedAt` reuses
|
|
11
|
-
* `ChatMessage.timestamp`'s own `Date | string` shape from the same `src/ai/types.ts` module for
|
|
12
|
-
* consistency across this component family.
|
|
13
|
-
*/
|
|
14
|
-
export interface LibraryDocument extends DocumentRef{
|
|
15
|
-
/** Optional tags. An own undefined value is treated like omission.*/
|
|
16
|
-
tags?:readonly string[];owner?:string;
|
|
17
|
-
/** Last-updated timestamp. `Date | string` (ISO-8601), matching `ChatMessage.timestamp`.*/
|
|
18
|
-
updatedAt?:Date|string;freshness?:LibraryDocumentFreshness;}
|
|
19
|
-
/** Column keys `sortKey` accepts. Not every column is sortable (`type`/`tags`/`select` are not).*/
|
|
20
|
-
export type LibraryDocumentSortKey='name'|'version'|'owner'|'freshness'|'updatedAt';
|
|
1
|
+
import type{LyraPageSource,LyraCursorSource,LyraCursorNavigationState}from'../../../data-sources.js';import type{LibraryDocument,LibraryDocumentSortKey}from'./document-library-types.js';export type{LibraryDocument,LibraryDocumentFreshness,LibraryDocumentSortKey}from'./document-library-types.js';import type{LyraEventDetailSnapshot}from'../../../internal/lyra-element.js';import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{TableSortDirection}from'../table/table.class.js';import{type LyraSize}from'../../../internal/variants.js';
|
|
21
2
|
/** Full-source document query; tags use AND semantics and filter receives folded search text.*/
|
|
22
|
-
export interface DocumentLibrarySourceQuery{readonly searchTerm:string;readonly tagFilter:readonly string[];readonly sortKey:LibraryDocumentSortKey;readonly sortDir:'asc'|'desc';readonly filter:LyraDocumentLibrary['filter'];}export type DocumentLibrarySource=LyraPageSource<LibraryDocument,DocumentLibrarySourceQuery>;
|
|
3
|
+
export interface DocumentLibrarySourceQuery{readonly searchTerm:string;readonly tagFilter:readonly string[];readonly sortKey:LibraryDocumentSortKey;readonly sortDir:'asc'|'desc';readonly filter:LyraDocumentLibrary['filter'];}export type DocumentLibrarySource=LyraPageSource<LibraryDocument,DocumentLibrarySourceQuery>;
|
|
4
|
+
/** Unknown-total document batches; the provider owns the complete query.*/
|
|
5
|
+
export type DocumentLibraryCursorSource=LyraCursorSource<LibraryDocument,DocumentLibrarySourceQuery>;export interface DocumentLibraryQueryChangeDetail{readonly searchTerm:string;readonly tags:readonly string[];}export interface DocumentLibraryFilterChangeDetail{readonly searchTerm:string;readonly tags:readonly string[];readonly matchCount:number;}export interface DocumentLibrarySortRequestDetail{readonly phase:'request';readonly sortKey:LibraryDocumentSortKey;readonly sortDir:TableSortDirection;}export interface DocumentLibrarySortCommitDetail{readonly phase:'commit';readonly sortKey:LibraryDocumentSortKey;readonly sortDir:TableSortDirection;}
|
|
23
6
|
/** Canonical request/commit sort transaction detail.*/
|
|
24
|
-
export type DocumentLibrarySortDetail=DocumentLibrarySortRequestDetail|DocumentLibrarySortCommitDetail;export interface DocumentLibrarySelectionChangeDetail{readonly documentIds:readonly string[];}export interface DocumentLibraryOpenDetail{readonly documentId:string;}export interface LyraDocumentLibraryEventMap{'lr-filter-change':CustomEvent<LyraEventDetailSnapshot<DocumentLibraryFilterChangeDetail>>;'lr-sort-request':CustomEvent<DocumentLibrarySortRequestDetail>;'lr-sort':CustomEvent<DocumentLibrarySortCommitDetail>;'lr-selection-change':CustomEvent<LyraEventDetailSnapshot<DocumentLibrarySelectionChangeDetail>>;'lr-open':CustomEvent<DocumentLibraryOpenDetail>;
|
|
7
|
+
export type DocumentLibrarySortDetail=DocumentLibrarySortRequestDetail|DocumentLibrarySortCommitDetail;export interface DocumentLibrarySelectionChangeDetail{readonly documentIds:readonly string[];}export interface DocumentLibraryOpenDetail{readonly documentId:string;}export interface LyraDocumentLibraryEventMap{'lr-query-change':CustomEvent<LyraEventDetailSnapshot<DocumentLibraryQueryChangeDetail>>;'lr-filter-change':CustomEvent<LyraEventDetailSnapshot<DocumentLibraryFilterChangeDetail>>;'lr-sort-request':CustomEvent<DocumentLibrarySortRequestDetail>;'lr-sort':CustomEvent<DocumentLibrarySortCommitDetail>;'lr-selection-change':CustomEvent<LyraEventDetailSnapshot<DocumentLibrarySelectionChangeDetail>>;'lr-open':CustomEvent<DocumentLibraryOpenDetail>;
|
|
25
8
|
/** Cancelable retry proposal. The default action clears the parent and nested table error.*/
|
|
26
9
|
'lr-retry-request':CustomEvent<null>;}
|
|
27
10
|
/**
|
|
@@ -78,6 +61,23 @@ export type DocumentLibrarySortDetail=DocumentLibrarySortRequestDetail|DocumentL
|
|
|
78
61
|
* lookup absence prunes IDs, and only unavailableSelected prunes controlled tag filters. Source
|
|
79
62
|
* replacement, explicit refresh and teardown revoke old work; ordinary named paints reuse it.
|
|
80
63
|
*
|
|
64
|
+
* With cursorSource, batches have unknown totals and opaque continuation tokens. This input is
|
|
65
|
+
* mutually exclusive with dataSource. sourceTotal stays null; sourcePage is inactive. The provider
|
|
66
|
+
* owns the entire query and sort; no facet catalogue is inferred. Select page preserves off-page
|
|
67
|
+
* selected-ID intent. A different scope clears selection; assign restored IDs after the source.
|
|
68
|
+
* Cursor tag/selection inputs scan at most 10,000 raw entries and deduplicate stably, admitting
|
|
69
|
+
* at most 500 unique tags or 10,000 unique selected IDs with 2,000,000 owned text units. Invalid
|
|
70
|
+
* or oversized input fails atomically rather than truncating.
|
|
71
|
+
* Previous refetches at most 32 retained visited cursors; Start over discards them. Retry repeats
|
|
72
|
+
* the failed request. A callback ignoring abort holds the shared page permit until it settles.
|
|
73
|
+
*
|
|
74
|
+
* @event lr-query-change - Cursor-mode user search edit. Frozen readonly detail: { searchTerm, tags },
|
|
75
|
+
* without a match count. Programmatic assignments are silent.
|
|
76
|
+
* @csspart cursor-navigation - Named cursor navigation region.
|
|
77
|
+
* @csspart cursor-previous - Refetch the preceding retained batch.
|
|
78
|
+
* @csspart cursor-next - Fetch the next available batch.
|
|
79
|
+
* @csspart cursor-restart - Discard continuation history and start over.
|
|
80
|
+
* @csspart cursor-status - End-of-results and retained-history boundary text.
|
|
81
81
|
* @csspart selection-status - Provider selection loading/error text.
|
|
82
82
|
* @csspart selection-retry - Retry the current provider selection lookup.
|
|
83
83
|
* @customElement lr-document-library
|
|
@@ -128,7 +128,18 @@ export type DocumentLibrarySortDetail=DocumentLibrarySortRequestDetail|DocumentL
|
|
|
128
128
|
* @status stable
|
|
129
129
|
* @since 4.1.0
|
|
130
130
|
*/
|
|
131
|
-
export declare class LyraDocumentLibrary extends LyraElement<LyraDocumentLibraryEventMap>{static styles:import("lit").CSSResultGroup[];protected static collectionSupport:import("../../../internal/lyra-element.js").LyraCollectionSupport;protected static readonly immutableEventDetails:readonly string[];private sourceStateVersion;private _dataSource?;private sourceEpoch;private sourceSyncing;private sourceInputs?;private sourceQueryInputs?;private sourceFailure;private sourceResult?;private sourceRows;private sourceTags;private sourceFacetLabels;private sourceSelectionInputs?;private sourceSelectionEvent?;private sourceLifecycleVersion;private sourceFilterEvent;private sourceSelectionAnnouncement;private readonly sourcePages;
|
|
131
|
+
export declare class LyraDocumentLibrary extends LyraElement<LyraDocumentLibraryEventMap>{static styles:import("lit").CSSResultGroup[];protected static collectionSupport:import("../../../internal/lyra-element.js").LyraCollectionSupport;protected static readonly immutableEventDetails:readonly string[];private sourceStateVersion;private _dataSource?;private sourceEpoch;private sourceSyncing;private sourceInputs?;private sourceQueryInputs?;private sourceFailure;private sourceResult?;private sourceRows;private sourceTags;private sourceFacetLabels;private sourceSelectionInputs?;private sourceSelectionEvent?;private sourceLifecycleVersion;private sourceFilterEvent;private sourceSelectionAnnouncement;private readonly sourcePages;private _cursorSource?;private cursorEpoch;private cursorBindingVersion;private cursorSelectionVersion;private cursorInputs?;private cursorScope?;private cursorRows;private readonly cursorDocuments;private readonly cursorBatches;private cursorAcceptedRows?;private cursorSelectionInvalid;private cursorTagInvalid;private cursorRequest;private cursorAnnounceTransition;private cursorRetryActive;private cursorSortVersion;private cursorSortBatch;private cursorSortProposal?;private readonly cursorPages;
|
|
132
|
+
/** Unknown-total, opaque-cursor batches. Mutually exclusive with dataSource. Reassignment or
|
|
133
|
+
* keyless requestUpdate starts over. A new scope clears selection; assign restored IDs afterward. */
|
|
134
|
+
get cursorSource():DocumentLibraryCursorSource|undefined;set cursorSource(value:DocumentLibraryCursorSource|undefined);private get cursorMode();
|
|
135
|
+
/** Frozen navigation capabilities without totals, positions or continuation tokens.*/
|
|
136
|
+
get cursorNavigation():LyraCursorNavigationState;
|
|
137
|
+
/** Fetch the next batch. Resolves true only when this operation commits.*/
|
|
138
|
+
nextCursorPage():Promise<boolean>;
|
|
139
|
+
/** Refetch the preceding retained batch; at most 32 visited cursors are retained.*/
|
|
140
|
+
previousCursorPage():Promise<boolean>;
|
|
141
|
+
/** Discard continuation history and request the first batch. External loading/error blocks it.*/
|
|
142
|
+
restartCursorSource():Promise<boolean>;private ensurePageScope;private prepareCursorTransition;private rehomeCursorFocus;private syncCursor;private acceptCursorPage;private renderCursorNavigation;
|
|
132
143
|
/** Host-owned full-source pages. Takes precedence over documents, including when invalid.
|
|
133
144
|
* Reassign the same provider or call requestUpdate() to refresh; undefined restores documents. */
|
|
134
145
|
get dataSource():DocumentLibrarySource|undefined;set dataSource(value:DocumentLibrarySource|undefined);
|
|
@@ -137,7 +148,7 @@ sourcePage:number;
|
|
|
137
148
|
/** Provider rows per page, normalized to 1..500.*/
|
|
138
149
|
sourcePageSize:number;
|
|
139
150
|
/** Exact current-query total, or null while pending, invalid or outside provider mode.*/
|
|
140
|
-
get sourceTotal():number|null;private get sourceMode();private get sourceBlocked();private get sourceSelectionBlocked();private projectSourceDocument;private syncSource;private syncSourceSelection;private acceptSourcePage;private onSourcePage;private _documents;
|
|
151
|
+
get sourceTotal():number|null;private get sourceMode();private get providerMode();private get sourceBlocked();private get sourceSelectionBlocked();private projectSourceDocument;private projectSourceValue;private syncSource;private syncSourceSelection;private acceptSourcePage;private onSourcePage;private _documents;
|
|
141
152
|
/** Clone-owned readonly inventory, bounded to the first 10,000 source documents and 10,000 tags
|
|
142
153
|
* per document. Document records, nested tag arrays, and dates are snapshotted at assignment
|
|
143
154
|
* time; records without a string name or with non-string tag entries, blank ids, and later
|
|
@@ -164,7 +175,7 @@ error:boolean;
|
|
|
164
175
|
* own `tableLoadFailed` default. */
|
|
165
176
|
errorHeading?:string;
|
|
166
177
|
/** Failed-load supporting copy, forwarded to the nested table.*/
|
|
167
|
-
errorDescription:string;private readonly slotPresence;private get hasErrorSlot();private onTableRetry;private _size?;
|
|
178
|
+
errorDescription:string;private readonly slotPresence;private get hasErrorSlot();private onTableRetry;private onCountedTableRetry;private _size?;
|
|
168
179
|
/** Density tier for the toolbar's own search field and tag filter, on the library's one size
|
|
169
180
|
* ladder, in either spelling -- `2xs`/`xs`/`s`/`m`/`l`/`xl`, or Web Awesome's and Shoelace's
|
|
170
181
|
* `small`/`medium`/`large`. Forwarded verbatim to the composed `<lr-input>` and `<lr-combobox>`,
|
|
@@ -179,4 +190,4 @@ get size():LyraSize|undefined;set size(next:LyraSize|undefined);
|
|
|
179
190
|
/** Accessible name for the region and the inner grid. Defaults to the localized
|
|
180
191
|
* `documentLibraryLabel` when unset. An explicitly empty string renders as an empty label
|
|
181
192
|
* rather than falling back. */
|
|
182
|
-
label?:string;private readonly announcements;connectedCallback():void;private invalidateSourceSelection;disconnectedCallback():void;adoptedCallback():void;private sourceAnnouncementInitialized;protected updated(changed:PropertyValues):void;private snapshotDocuments;private snapshotIds;private explicitRefresh;requestUpdate(...args:Parameters<LyraElement['requestUpdate']>):void;protected willUpdate(changed:PropertyValues):void;private selectionCountText;private normalizeDate;private corpusMemo?;private defaultFilter;private readonly documentTags;private matchesTagFilter;private readonly documentDates;private documentDate;private sortCollator?;private compareDocuments;private matchingMemo?;private get matchingDocuments();private sortedMemo?;private get sortedDocuments();private tagsMemo?;private get allTags();private get tagSet();private selectedMemo?;private get selectedIdSet();private emitFilterChange;private onSearchInput;private onTagFilterChange;private isSortKey;private onTableSortRequest;private onTableSortCommit;private stopOwnedEvent;private onTableSelectionChange;private openDocument;private setSelected;private toggleSelection;private toggleSelectAll;private clearSelection;private freshnessLabel;private renderSelectAllCheckbox;private renderRowCheckbox;private renderNameCell;private renderTagsCell;private renderFreshnessCell;private renderUpdatedCell;private columnsMemo?;private buildColumns;private createColumns;private tagOptionsMemo?;private renderTagOptions;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-document-library':LyraDocumentLibrary;}}
|
|
193
|
+
label?:string;private readonly announcements;connectedCallback():void;private invalidateSourceSelection;disconnectedCallback():void;adoptedCallback():void;private sourceAnnouncementInitialized;protected updated(changed:PropertyValues):void;private snapshotDocuments;private snapshotIds;private explicitRefresh;requestUpdate(...args:Parameters<LyraElement['requestUpdate']>):void;protected willUpdate(changed:PropertyValues):void;private selectionCountText;private normalizeDate;private corpusMemo?;private defaultFilter;private readonly documentTags;private matchesTagFilter;private readonly documentDates;private documentDate;private sortCollator?;private compareDocuments;private matchingMemo?;private get matchingDocuments();private sortedMemo?;private get sortedDocuments();private tagsMemo?;private get allTags();private get tagSet();private selectedMemo?;private get selectedIdSet();private emitFilterChange;private onSearchInput;private onTagFilterChange;private isSortKey;private onTableSortRequest;private onTableSortCommit;private isCurrentTableEvent;private stopOwnedEvent;private onTableSelectionChange;private openDocument;private setSelected;private toggleSelection;private toggleSelectAll;private clearSelection;private freshnessLabel;private renderSelectAllCheckbox;private renderRowCheckbox;private renderNameCell;private renderTagsCell;private renderFreshnessCell;private renderUpdatedCell;private columnsMemo?;private buildColumns;private createColumns;private tagOptionsMemo?;private renderTagOptions;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-document-library':LyraDocumentLibrary;}}
|
|
@@ -1,7 +1,15 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{SourcePageController}from"../../../internal/source-page-controller.js";import{finiteInteger}from"../../../internal/numbers.js";import{indexByKey}from"../../../internal/keyed-index.js";import{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{createRetryForwarder}from"../../../internal/retry-forwarder.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{getCollator,getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{styles}from"./document-library.styles.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{LYRA_DEFAULT_documentLibraryClearSelection,LYRA_DEFAULT_documentLibraryEmptyHeading,LYRA_DEFAULT_documentLibraryFilterByTag,LYRA_DEFAULT_documentLibraryFreshnessAging,LYRA_DEFAULT_documentLibraryFreshnessColumn,LYRA_DEFAULT_documentLibraryFreshnessFresh,LYRA_DEFAULT_documentLibraryFreshnessStale,LYRA_DEFAULT_documentLibraryLabel,LYRA_DEFAULT_documentLibraryNameColumn,LYRA_DEFAULT_documentLibraryNoMatchesHeading,LYRA_DEFAULT_documentLibraryOwnerColumn,LYRA_DEFAULT_documentLibrarySearchPlaceholder,LYRA_DEFAULT_documentLibrarySelectAll,LYRA_DEFAULT_documentLibrarySelectColumn,LYRA_DEFAULT_documentLibrarySelectDocument,LYRA_DEFAULT_documentLibrarySelectPage,LYRA_DEFAULT_documentLibrarySelectedCount,LYRA_DEFAULT_documentLibraryTagsColumn,LYRA_DEFAULT_documentLibraryTypeColumn,LYRA_DEFAULT_documentLibraryUpdatedColumn,LYRA_DEFAULT_documentLibraryVersionColumn}from"../../../internal/default-strings/data.generated.js";import{LYRA_DEFAULT_retry,LYRA_DEFAULT_sourceSelectionFailed,LYRA_DEFAULT_sourceSelectionLoading,LYRA_DEFAULT_tagFacetLimit}from"../../../internal/default-strings/shared.generated.js";const FRESHNESS_RANK={fresh:0,aging:1,stale:2},MAX_LIBRARY_COLLECTION_ENTRIES=1e4,MAX_TAG_FACETS=500,documentKey=document=>document.id,INVALID_DOCUMENT_DATE=Symbol("invalid-document-date"),FRESHNESS_TONE={fresh:"success",aging:"warning",stale:"danger"};function projectLibraryStringArray(value){try{if(!Array.isArray(value))return;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;const tags=[];for(let index=0;index<Math.min(length.value,MAX_LIBRARY_COLLECTION_ENTRIES);index+=1){const entry=getOwnDataDescriptor(value,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||typeof entry.value!="string")return;tags.push(entry.value)}return Object.freeze(tags)}catch{return}}function projectLibraryDate(value){if(typeof value=="string")return value;if(typeof value=="number")return new Date(value);try{return new Date(Date.prototype.getTime.call(value))}catch{return INVALID_DOCUMENT_DATE}}function projectLibraryDocument(candidate){try{if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))return;const id=getOwnDataDescriptor(candidate,"id"),name=getOwnDataDescriptor(candidate,"name"),mimeType=getOwnDataDescriptor(candidate,"mimeType"),uri=getOwnDataDescriptor(candidate,"uri"),version=getOwnDataDescriptor(candidate,"version"),tags=getOwnDataDescriptor(candidate,"tags"),owner=getOwnDataDescriptor(candidate,"owner"),updatedAt=getOwnDataDescriptor(candidate,"updatedAt"),freshness=getOwnDataDescriptor(candidate,"freshness");if(id===MISSING_OWN_DATA_DESCRIPTOR||id===UNSAFE_OWN_DATA_DESCRIPTOR||name===MISSING_OWN_DATA_DESCRIPTOR||name===UNSAFE_OWN_DATA_DESCRIPTOR||mimeType===UNSAFE_OWN_DATA_DESCRIPTOR||uri===UNSAFE_OWN_DATA_DESCRIPTOR||version===UNSAFE_OWN_DATA_DESCRIPTOR||tags===UNSAFE_OWN_DATA_DESCRIPTOR||owner===UNSAFE_OWN_DATA_DESCRIPTOR||updatedAt===UNSAFE_OWN_DATA_DESCRIPTOR||freshness===UNSAFE_OWN_DATA_DESCRIPTOR||typeof id.value!="string"||id.value.trim().length===0||typeof name.value!="string")return;const mimeTypeValue=mimeType===MISSING_OWN_DATA_DESCRIPTOR?void 0:mimeType.value,uriValue=uri===MISSING_OWN_DATA_DESCRIPTOR?void 0:uri.value,versionValue=version===MISSING_OWN_DATA_DESCRIPTOR?void 0:version.value,ownerValue=owner===MISSING_OWN_DATA_DESCRIPTOR?void 0:owner.value,freshnessValue=freshness===MISSING_OWN_DATA_DESCRIPTOR?void 0:freshness.value;if(mimeTypeValue!==void 0&&typeof mimeTypeValue!="string"||uriValue!==void 0&&typeof uriValue!="string"||versionValue!==void 0&&typeof versionValue!="string"||ownerValue!==void 0&&typeof ownerValue!="string"||freshnessValue!==void 0&&freshnessValue!=="fresh"&&freshnessValue!=="aging"&&freshnessValue!=="stale")return;const tagsValue=tags===MISSING_OWN_DATA_DESCRIPTOR?void 0:tags.value,tagValues=tagsValue===void 0?void 0:projectLibraryStringArray(tagsValue);if(tagsValue!==void 0&&!tagValues)return;const updatedAtValue=updatedAt===MISSING_OWN_DATA_DESCRIPTOR||updatedAt.value===void 0?void 0:projectLibraryDate(updatedAt.value);return updatedAtValue===INVALID_DOCUMENT_DATE?void 0:Object.freeze({id:id.value,name:name.value,...mimeTypeValue===void 0?{}:{mimeType:mimeTypeValue},...uriValue===void 0?{}:{uri:uriValue},...versionValue===void 0?{}:{version:versionValue},...tagValues===void 0?{}:{tags:tagValues},...ownerValue===void 0?{}:{owner:ownerValue},...updatedAtValue===void 0?{}:{updatedAt:updatedAtValue},...freshnessValue===void 0?{}:{freshness:freshnessValue}})}catch{return}}class LyraDocumentLibrary extends LyraElement{constructor(){super(...arguments),this.sourceStateVersion=0,this.sourceEpoch=0,this.sourceSyncing=!1,this.sourceRows=[],this.sourceTags=[],this.sourceFacetLabels=new Map,this.sourceLifecycleVersion=0,this.sourceFilterEvent=!1,this.sourceSelectionAnnouncement="",this.sourcePages=new SourcePageController(this,{normalizeRecord:(record,isCurrent)=>this.projectSourceDocument(record,isCurrent),validateMetadata:(result,query)=>{if(!result.tags||query.tagFilter.length>MAX_TAG_FACETS||result.tags.unavailableSelected.some(key=>!query.tagFilter.includes(key)))throw new TypeError("Invalid document source facets")},onChange:()=>{this.sourceStateVersion++}}),this.sourcePage=0,this.sourcePageSize=100,this.onSourcePage=event=>{event.stopPropagation(),this.sourceMode&&(this.sourcePage=event.detail.page-1)},this._documents=Object.freeze([]),this._selectedDocumentIds=Object.freeze([]),this._tagFilter=Object.freeze([]),this.sortKey="name",this.sortDir="asc",this.searchTerm="",this.loading=!1,this.error=!1,this.errorDescription="",this.slotPresence=new SlotPresenceController(this,{observeLightDom:!0}),this.onTableRetry=createRetryForwarder(init=>this.emit("lr-retry-request",null,init),()=>{this.error=!1,this.sourceMode&&(this.sourceInputs=void 0,this.syncSource(),this.sourceStateVersion++)}),this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.sourceAnnouncementInitialized=!1,this.explicitRefresh=0,this.defaultFilter=(document,query)=>{const locale=this.effectiveLocale;if(this.corpusMemo?.documents!==this._documents||this.corpusMemo.locale!==locale){const fields=new Map;for(const row of this._documents)fields.set(row,[row.name,row.owner??"",...row.tags??[]].map(value=>value.toLocaleLowerCase(locale)));this.corpusMemo={documents:this._documents,locale,fields}}return this.corpusMemo.fields.get(document).some(value=>value.includes(query))},this.documentTags=new WeakMap,this.documentDates=new WeakMap,this.compareDocuments=(a,b)=>{const collator=this.sortCollator,dir=this.sortDir==="asc"?1:-1;let result=0;switch(this.sortKey){case"name":result=collator.compare(a.name,b.name);break;case"version":result=collator.compare(a.version??"",b.version??"");break;case"owner":result=collator.compare(a.owner??"",b.owner??"");break;case"freshness":result=(a.freshness?FRESHNESS_RANK[a.freshness]:3)-(b.freshness?FRESHNESS_RANK[b.freshness]:3);break;case"updatedAt":result=(this.documentDate(a)?.getTime()??0)-(this.documentDate(b)?.getTime()??0);break}return result*dir},this.onSearchInput=event=>{event.stopPropagation(),this.searchTerm=event.detail.value,this.emitFilterChange()},this.onTagFilterChange=event=>{event.stopPropagation();const combobox=event.target;this.tagFilter=Array.isArray(combobox.value)?combobox.value:[],this.emitFilterChange()},this.onTableSortRequest=event=>{if(event.stopPropagation(),!this.isSortKey(event.detail.sortKey)){event.preventDefault();return}const detail=Object.freeze({phase:"request",sortKey:event.detail.sortKey,sortDir:event.detail.sortDir});this.emit("lr-sort-request",detail,{cancelable:!0}).defaultPrevented&&event.preventDefault()},this.onTableSortCommit=event=>{event.stopPropagation(),this.isSortKey(event.detail.sortKey)&&(this.sortKey=event.detail.sortKey,this.sortDir=event.detail.sortDir,this.emit("lr-sort",Object.freeze({phase:"commit",sortKey:this.sortKey,sortDir:this.sortDir})))},this.stopOwnedEvent=event=>{event.stopPropagation()},this.onTableSelectionChange=event=>{event.stopPropagation();const table=event.currentTarget;table.selectedRowKeys=new Set(this.selectedDocumentIds)},this.clearSelection=()=>{this.setSelected([])}}static{this.defaultStrings={...super.defaultStrings,documentLibraryClearSelection:LYRA_DEFAULT_documentLibraryClearSelection,documentLibraryEmptyHeading:LYRA_DEFAULT_documentLibraryEmptyHeading,documentLibraryFilterByTag:LYRA_DEFAULT_documentLibraryFilterByTag,documentLibraryFreshnessAging:LYRA_DEFAULT_documentLibraryFreshnessAging,documentLibraryFreshnessColumn:LYRA_DEFAULT_documentLibraryFreshnessColumn,documentLibraryFreshnessFresh:LYRA_DEFAULT_documentLibraryFreshnessFresh,documentLibraryFreshnessStale:LYRA_DEFAULT_documentLibraryFreshnessStale,documentLibraryLabel:LYRA_DEFAULT_documentLibraryLabel,documentLibraryNameColumn:LYRA_DEFAULT_documentLibraryNameColumn,documentLibraryNoMatchesHeading:LYRA_DEFAULT_documentLibraryNoMatchesHeading,documentLibraryOwnerColumn:LYRA_DEFAULT_documentLibraryOwnerColumn,documentLibrarySearchPlaceholder:LYRA_DEFAULT_documentLibrarySearchPlaceholder,documentLibrarySelectAll:LYRA_DEFAULT_documentLibrarySelectAll,documentLibrarySelectColumn:LYRA_DEFAULT_documentLibrarySelectColumn,documentLibrarySelectDocument:LYRA_DEFAULT_documentLibrarySelectDocument,documentLibrarySelectPage:LYRA_DEFAULT_documentLibrarySelectPage,documentLibrarySelectedCount:LYRA_DEFAULT_documentLibrarySelectedCount,documentLibraryTagsColumn:LYRA_DEFAULT_documentLibraryTagsColumn,documentLibraryTypeColumn:LYRA_DEFAULT_documentLibraryTypeColumn,documentLibraryUpdatedColumn:LYRA_DEFAULT_documentLibraryUpdatedColumn,documentLibraryVersionColumn:LYRA_DEFAULT_documentLibraryVersionColumn,retry:LYRA_DEFAULT_retry,sourceSelectionFailed:LYRA_DEFAULT_sourceSelectionFailed,sourceSelectionLoading:LYRA_DEFAULT_sourceSelectionLoading,tagFacetLimit:LYRA_DEFAULT_tagFacetLimit}}static{this.styles=[LyraElement.styles,styles]}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-filter-change","lr-selection-change"])}get dataSource(){return this._dataSource}set dataSource(value){const previous=this._dataSource;this._dataSource=value,this.sourceEpoch=(this.sourceEpoch??0)+1,this.requestUpdate("dataSource",previous)}get sourceTotal(){return this.dataSource===void 0?null:this.sourcePages.state.result?.total??null}get sourceMode(){return this.dataSource!==void 0}get sourceBlocked(){return this.sourceMode&&(this.loading||this.error||this.sourcePages.state.pending||!!this.sourcePages.state.error||!!this.sourceFailure)}get sourceSelectionBlocked(){return this.sourceBlocked||this.sourceMode&&(this.sourcePages.state.selectionPending||!!this.sourcePages.state.selectionError)}projectSourceDocument(record,isCurrent){const assertCurrent=()=>{if(!isCurrent())throw new TypeError("Obsolete source record")},descriptorOf=(target,key)=>{assertCurrent();const descriptor=getOwnDataDescriptor(target,key);return assertCurrent(),descriptor};if(assertCurrent(),record.value===null||typeof record.value!="object"||Array.isArray(record.value))throw new TypeError("Invalid source document");const snapshot={};for(const key of["id","name","mimeType","uri","version","tags","owner","updatedAt","freshness"]){const descriptor=descriptorOf(record.value,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid source document");descriptor!==MISSING_OWN_DATA_DESCRIPTOR&&(snapshot[key]=descriptor.value)}if(snapshot.tags!==void 0){if(!Array.isArray(snapshot.tags))throw new TypeError("Invalid source document tags");const rawTags=snapshot.tags,length=descriptorOf(rawTags,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0||length.value>MAX_TAG_FACETS)throw new RangeError("Invalid source document tags");const tags=[];for(let index=0;index<length.value;index++){const descriptor=descriptorOf(rawTags,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||typeof descriptor.value!="string")throw new TypeError("Invalid source document tag");tags.push(descriptor.value)}snapshot.tags=tags}const value=projectLibraryDocument(snapshot);if(assertCurrent(),!value||value.id!==record.key||(value.tags?.length??0)>MAX_TAG_FACETS)throw new TypeError("Invalid source document");let units=0;for(const text of[value.id,value.name,value.owner,value.mimeType,value.uri,value.version,typeof value.updatedAt=="string"?value.updatedAt:void 0,...value.tags??[]])if(text!==void 0&&(units+=text.length,text.length>65536||units>65536))throw new RangeError("Source document too large");return assertCurrent(),{key:record.key,order:record.order,value}}syncSource(){if(!(!this.sourcePages||this.sourceSyncing)){this.sourceSyncing=!0;try{if(!this.sourceMode){this.sourceInputs&&this.sourcePages.bind(void 0),this.sourceInputs=void 0,this.sourceQueryInputs=void 0,this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0,this.sourceFilterEvent=!1,this.sourceResult=void 0,this.sourceRows=[],this.sourceTags=[],this.sourceFailure=void 0;return}const source=this.dataSource,epoch=this.sourceEpoch+this.explicitRefresh,size=finiteInteger(this.sourcePageSize,100,1,500);let page=finiteInteger(this.sourcePage,0,0,Math.floor(Number.MAX_SAFE_INTEGER/size));const queryInputs=[this.searchTerm,this.tagFilter,this.sortKey,this.sortDir,this.filter,size];this.sourceQueryInputs&&queryInputs.some((value,index)=>value!==this.sourceQueryInputs[index])&&(page=0,this.sourcePage=0),this.sourceQueryInputs=queryInputs;const revision=source.revision,inputs=[source,revision,epoch,this.effectiveLocale,...queryInputs,page];if(this.sourceInputs&&inputs.every((value,index)=>value===this.sourceInputs[index]))return;if(this.sourceInputs&&inputs.slice(0,3).some((value,index)=>value!==this.sourceInputs[index])&&(this.sourceSelectionEvent=void 0,this.sourceFilterEvent=!1),this.sourceInputs=inputs,this.sourceFailure=void 0,this.sourceRows=[],this.sourceTags=[],this.sourceResult=void 0,this.sourcePages.bind({source,revision,epoch,locale:this.effectiveLocale}),this.tagFilter.length>MAX_TAG_FACETS)throw new RangeError("Too many source facets");const query=Object.freeze({searchTerm:this.searchTerm??"",tagFilter:this.tagFilter,sortKey:this.sortKey,sortDir:this.sortDir,filter:this.filter});this.sourcePages.request(query,page,size),this.syncSourceSelection()}catch(error){this.sourcePages.bind(void 0),this.sourceRows=[],this.sourceTags=[],this.sourceResult=void 0,this.sourceFailure=error}finally{this.sourceSyncing=!1}}}syncSourceSelection(){if(!this.sourceMode||this.sourceFailure)return;const ids=this._selectedDocumentIds,source=this.dataSource,epoch=this.sourceEpoch+this.explicitRefresh,inputs=[source,source?.revision,epoch,ids];if(this.sourceSelectionInputs&&inputs.every((value,index)=>value===this.sourceSelectionInputs[index]))return;this.sourceSelectionInputs=inputs;const owner=this.ownerDocument,lifecycle=this.sourceLifecycleVersion;this.sourcePages.resolveSelection(ids).then(records=>{if(!records||lifecycle!==this.sourceLifecycleVersion||!this.isConnected||this.ownerDocument!==owner||this.dataSource!==source||epoch!==this.sourceEpoch+this.explicitRefresh||this._selectedDocumentIds!==ids)return;const retained=new Set(records.map(record=>record.key)),accepted=Object.freeze(ids.filter(id=>retained.has(id)));accepted.length!==ids.length&&(this._selectedDocumentIds=accepted,this.selectionSource=accepted,this.sourceSelectionInputs=void 0),this.sourceSelectionEvent===ids&&(this.sourceSelectionEvent=void 0,this.announcements.announcePolite(this.selectionCountText()),this.emit("lr-selection-change",Object.freeze({documentIds:Object.freeze([...this._selectedDocumentIds])}))),this.sourceStateVersion++})}acceptSourcePage(){const result=this.sourcePages.state.result;if(!result||result===this.sourceResult)return;this.sourceResult=result,this.sourceRows=result.rows.map(record=>record.value),this.sourceTags=result.tags.values.map(facet=>facet.key),this.sourceFacetLabels=new Map(result.tags.values.map(facet=>[facet.key,facet.label]));const removed=new Set(result.tags.unavailableSelected);if(this.tagFilter.some(key=>removed.has(key))){this.tagFilter=this.tagFilter.filter(key=>!removed.has(key));return}this.sourcePage!==this.sourcePages.state.page&&(this.sourceSyncing=!0,this.sourcePage=this.sourcePages.state.page,this.sourceSyncing=!1,this.sourceInputs=this.sourceInputs?[...this.sourceInputs.slice(0,-1),this.sourcePages.state.page]:void 0),this.sourceFilterEvent&&(this.sourceFilterEvent=!1,this.emit("lr-filter-change",Object.freeze({searchTerm:this.searchTerm,tags:Object.freeze([...this.tagFilter]),matchCount:result.total})))}get documents(){return this.documentsView??=this.snapshotDocuments(this._documents)}set documents(value){if(value===this.documentsSource||value===this.documentsView)return;this.documentsSource=value;const previous=this._documents;this._documents=this.snapshotDocuments(value),this.documentsView=void 0,this.requestUpdate("documents",previous)}get selectedDocumentIds(){return this._selectedDocumentIds}set selectedDocumentIds(value){if(value===this.selectionSource||value===this._selectedDocumentIds)return;this.sourceSelectionEvent=void 0,this.selectionSource=value;const previous=this._selectedDocumentIds;this._selectedDocumentIds=this.snapshotIds(Array.isArray(value)?value:[]),this.requestUpdate("selectedDocumentIds",previous)}get tagFilter(){return this._tagFilter}set tagFilter(value){if(value===this.tagFilterSource||value===this._tagFilter)return;this.tagFilterSource=value;const previous=this._tagFilter;this._tagFilter=this.snapshotIds(Array.isArray(value)?value:[]),this.requestUpdate("tagFilter",previous)}get hasErrorSlot(){return this.slotPresence.has("error")}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))}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.sourceMode&&(this.sourceSelectionInputs=void 0,this.syncSourceSelection())}invalidateSourceSelection(){this.sourceLifecycleVersion++,this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0,this.sourceFilterEvent=!1,this.sourceAnnouncementInitialized=!1}disconnectedCallback(){this.invalidateSourceSelection(),super.disconnectedCallback()}adoptedCallback(){this.invalidateSourceSelection(),super.adoptedCallback(),this.announcements.adopted(),this.sourcePages.adopted()}updated(changed){super.updated(changed);const status=this.sourceMode&&this.sourcePages.state.selectionError?this.localize("sourceSelectionFailed"):this.sourceMode&&this.sourcePages.state.selectionPending?this.localize("sourceSelectionLoading"):"";this.sourceAnnouncementInitialized&&status&&status!==this.sourceSelectionAnnouncement&&this.announcements.announcePolite(status),this.sourceAnnouncementInitialized=!0,this.sourceSelectionAnnouncement=status}snapshotDocuments(documents){const snapshot=[],seen=new Set;try{if(!Array.isArray(documents))return Object.freeze(snapshot);const length=getOwnDataDescriptor(documents,"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(snapshot);for(let index=0;index<Math.min(length.value,MAX_LIBRARY_COLLECTION_ENTRIES);index+=1){const entry=getOwnDataDescriptor(documents,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const document=projectLibraryDocument(entry.value);!document||seen.has(document.id)||(seen.add(document.id),snapshot.push(document))}}catch{}return Object.freeze(snapshot)}snapshotIds(ids){const snapshot=[],seen=new Set;try{for(const id of ids)if(!seen.has(id)&&(seen.add(id),snapshot.push(id),snapshot.length>=MAX_LIBRARY_COLLECTION_ENTRIES))break}catch{}return Object.freeze(snapshot)}requestUpdate(...args){args[0]===void 0&&(this.explicitRefresh=(this.explicitRefresh??0)+1),(args[0]===void 0||["dataSource","sourcePage","sourcePageSize","searchTerm","tagFilter","sortKey","sortDir","filter"].includes(String(args[0])))&&this.syncSource(),args[0]==="selectedDocumentIds"&&this.syncSourceSelection(),super.requestUpdate(...args)}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.sourceMode){this.acceptSourcePage(),this.syncSourceSelection();return}if((changed.has("documents")||changed.has("selectedDocumentIds")||changed.has("dataSource"))&&this.selectedDocumentIds.length>0){const existing=indexByKey(this._documents,documentKey),normalized=this.snapshotIds(this.selectedDocumentIds.filter(id=>existing.has(id)));(normalized.length!==this.selectedDocumentIds.length||normalized.some((id,index)=>id!==this.selectedDocumentIds[index]))&&(this.selectedDocumentIds=normalized)}if((changed.has("documents")||changed.has("tagFilter")||changed.has("dataSource"))&&this.tagFilter.length>0){const availableTags=this.tagSet,normalized=this.snapshotIds(this.tagFilter.filter(tag=>availableTags.has(tag)));(normalized.length!==this.tagFilter.length||normalized.some((tag,index)=>tag!==this.tagFilter[index]))&&(this.tagFilter=normalized)}}selectionCountText(){return this.localize("documentLibrarySelectedCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(this.selectedDocumentIds.length)})}normalizeDate(value){if(value===void 0)return;const date=value instanceof Date?value:new Date(value);return Number.isNaN(date.getTime())?void 0:date}matchesTagFilter(document){if(this.tagFilter.length===0)return!0;let tags=this.documentTags.get(document);return tags||(tags=new Set(document.tags??[]),this.documentTags.set(document,tags)),this.tagFilter.every(tag=>tags.has(tag))}documentDate(document){return this.documentDates.has(document)||this.documentDates.set(document,this.normalizeDate(document.updatedAt)),this.documentDates.get(document)}get matchingDocuments(){const query=(this.searchTerm??"").trim().toLocaleLowerCase(this.effectiveLocale),inputs=[this._documents,query,this.tagFilter,this.filter,this.effectiveLocale,this.filter?this.explicitRefresh:0];if(!this.matchingMemo||inputs.some((input,index)=>input!==this.matchingMemo.inputs[index])){const matchFn=this.filter??this.defaultFilter,rows=this._documents.filter(document=>(query===""||matchFn(document,query))&&this.matchesTagFilter(document));this.matchingMemo={inputs,rows}}return this.matchingMemo.rows}get sortedDocuments(){const rows=this.matchingDocuments,locale=this.effectiveLocale,previous=this.sortedMemo;if(previous?.rows===rows&&previous.key===this.sortKey&&previous.dir===this.sortDir&&previous.locale===locale)return previous.sorted;if(this.sortCollator=getCollator(locale,{numeric:!0}),this.sortKey==="updatedAt")for(const row of rows)this.documentDate(row);const sorted=[...rows].sort(this.compareDocuments);return this.sortedMemo={rows,key:this.sortKey,dir:this.sortDir,locale,sorted},sorted}get allTags(){const locale=this.effectiveLocale;if(this.tagsMemo?.documents===this._documents&&this.tagsMemo.locale===locale)return this.tagsMemo.tags;const tags=new Set;for(const document of this._documents)for(const tag of document.tags??[])tags.add(tag);const sorted=[...tags].sort(getCollator(locale).compare);return this.tagsMemo={documents:this._documents,locale,tags:sorted,set:tags},sorted}get tagSet(){return this.allTags,this.tagsMemo.set}get selectedIdSet(){return this.selectedMemo?.ids!==this._selectedDocumentIds&&(this.selectedMemo={ids:this._selectedDocumentIds,set:new Set(this._selectedDocumentIds)}),this.selectedMemo.set}emitFilterChange(){if(this.sourceMode){this.sourceFilterEvent=!0;return}const tags=Object.freeze([...this.tagFilter]);this.emit("lr-filter-change",Object.freeze({searchTerm:this.searchTerm,tags,matchCount:this.matchingDocuments.length}))}isSortKey(value){return value==="name"||value==="version"||value==="owner"||value==="freshness"||value==="updatedAt"}openDocument(document){this.sourceBlocked||this.sourceMode&&!this.sourceRows.includes(document)||this.emit("lr-open",Object.freeze({documentId:document.id}))}setSelected(ids){if(this.sourceSelectionBlocked)return;if(this.selectedDocumentIds=[...ids],this.sourceMode){this.sourceSelectionEvent=this._selectedDocumentIds;return}this.announcements.announcePolite(this.selectionCountText());const eventIds=Object.freeze([...this.selectedDocumentIds]);this.emit("lr-selection-change",Object.freeze({documentIds:eventIds}))}toggleSelection(document,checked){const next=new Set(this.selectedDocumentIds);checked?next.add(document.id):next.delete(document.id),this.setSelected(next)}toggleSelectAll(checked,visible){const next=new Set(this.selectedDocumentIds);for(const document of visible)checked?next.add(document.id):next.delete(document.id);this.setSelected(next)}freshnessLabel(freshness){switch(freshness){case"fresh":return this.localize("documentLibraryFreshnessFresh");case"aging":return this.localize("documentLibraryFreshnessAging");case"stale":return this.localize("documentLibraryFreshnessStale")}}renderSelectAllCheckbox(visible,selected){const allSelected=visible.length>0&&visible.every(document=>selected.has(document.id)),someSelected=!allSelected&&visible.some(document=>selected.has(document.id));return html`<lr-checkbox
|
|
1
|
+
import{__decorate}from"tslib";import{SourceCursorController}from"../../../internal/source-cursor-controller.js";import{setSourcePageScope,sourcePageScope,shareSourcePageQueries}from"../../../internal/source-page-scope.js";import{cursorIds,cursorQueryText}from"./document-library-cursor.js";import{SourcePageController}from"../../../internal/source-page-controller.js";import{finiteInteger}from"../../../internal/numbers.js";import{indexByKey}from"../../../internal/keyed-index.js";import{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{createRetryForwarder}from"../../../internal/retry-forwarder.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{getCollator,getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{styles}from"./document-library.styles.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{LYRA_DEFAULT_documentLibraryClearSelection,LYRA_DEFAULT_documentLibraryCursorEmptyBatch,LYRA_DEFAULT_documentLibraryCursorEnd,LYRA_DEFAULT_documentLibraryCursorFailed,LYRA_DEFAULT_documentLibraryCursorHistoryLimit,LYRA_DEFAULT_documentLibraryCursorNavigation,LYRA_DEFAULT_documentLibraryCursorRestart,LYRA_DEFAULT_documentLibraryEmptyHeading,LYRA_DEFAULT_documentLibraryFilterByTag,LYRA_DEFAULT_documentLibraryFreshnessAging,LYRA_DEFAULT_documentLibraryFreshnessColumn,LYRA_DEFAULT_documentLibraryFreshnessFresh,LYRA_DEFAULT_documentLibraryFreshnessStale,LYRA_DEFAULT_documentLibraryLabel,LYRA_DEFAULT_documentLibraryNameColumn,LYRA_DEFAULT_documentLibraryNoMatchesHeading,LYRA_DEFAULT_documentLibraryOwnerColumn,LYRA_DEFAULT_documentLibrarySearchPlaceholder,LYRA_DEFAULT_documentLibrarySelectAll,LYRA_DEFAULT_documentLibrarySelectColumn,LYRA_DEFAULT_documentLibrarySelectDocument,LYRA_DEFAULT_documentLibrarySelectPage,LYRA_DEFAULT_documentLibrarySelectedCount,LYRA_DEFAULT_documentLibraryTagsColumn,LYRA_DEFAULT_documentLibraryTypeColumn,LYRA_DEFAULT_documentLibraryUpdatedColumn,LYRA_DEFAULT_documentLibraryVersionColumn}from"../../../internal/default-strings/data.generated.js";import{LYRA_DEFAULT_next,LYRA_DEFAULT_previous,LYRA_DEFAULT_retry,LYRA_DEFAULT_sourceSelectionFailed,LYRA_DEFAULT_sourceSelectionLoading,LYRA_DEFAULT_tagFacetLimit}from"../../../internal/default-strings/shared.generated.js";function cursorQuery(value,current){const{searchTerm,tagFilter}=cursorQueryText(value.searchTerm,value.tagFilter,current);if(!["name","version","owner","freshness","updatedAt"].includes(value.sortKey)||value.sortDir!=="asc"&&value.sortDir!=="desc"||value.filter!==void 0&&typeof value.filter!="function")throw new TypeError("Invalid cursor query");return Object.freeze({searchTerm,tagFilter,sortKey:value.sortKey,sortDir:value.sortDir,filter:value.filter})}const FRESHNESS_RANK={fresh:0,aging:1,stale:2},MAX_LIBRARY_COLLECTION_ENTRIES=1e4,MAX_TAG_FACETS=500,documentKey=document=>document.id,INVALID_DOCUMENT_DATE=Symbol("invalid-document-date"),FRESHNESS_TONE={fresh:"success",aging:"warning",stale:"danger"};function projectLibraryStringArray(value){try{if(!Array.isArray(value))return;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;const tags=[];for(let index=0;index<Math.min(length.value,MAX_LIBRARY_COLLECTION_ENTRIES);index+=1){const entry=getOwnDataDescriptor(value,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||typeof entry.value!="string")return;tags.push(entry.value)}return Object.freeze(tags)}catch{return}}function projectLibraryDate(value){if(typeof value=="string")return value;if(typeof value=="number")return new Date(value);try{return new Date(Date.prototype.getTime.call(value))}catch{return INVALID_DOCUMENT_DATE}}function projectLibraryDocument(candidate){try{if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))return;const id=getOwnDataDescriptor(candidate,"id"),name=getOwnDataDescriptor(candidate,"name"),mimeType=getOwnDataDescriptor(candidate,"mimeType"),uri=getOwnDataDescriptor(candidate,"uri"),version=getOwnDataDescriptor(candidate,"version"),tags=getOwnDataDescriptor(candidate,"tags"),owner=getOwnDataDescriptor(candidate,"owner"),updatedAt=getOwnDataDescriptor(candidate,"updatedAt"),freshness=getOwnDataDescriptor(candidate,"freshness");if(id===MISSING_OWN_DATA_DESCRIPTOR||id===UNSAFE_OWN_DATA_DESCRIPTOR||name===MISSING_OWN_DATA_DESCRIPTOR||name===UNSAFE_OWN_DATA_DESCRIPTOR||mimeType===UNSAFE_OWN_DATA_DESCRIPTOR||uri===UNSAFE_OWN_DATA_DESCRIPTOR||version===UNSAFE_OWN_DATA_DESCRIPTOR||tags===UNSAFE_OWN_DATA_DESCRIPTOR||owner===UNSAFE_OWN_DATA_DESCRIPTOR||updatedAt===UNSAFE_OWN_DATA_DESCRIPTOR||freshness===UNSAFE_OWN_DATA_DESCRIPTOR||typeof id.value!="string"||id.value.trim().length===0||typeof name.value!="string")return;const mimeTypeValue=mimeType===MISSING_OWN_DATA_DESCRIPTOR?void 0:mimeType.value,uriValue=uri===MISSING_OWN_DATA_DESCRIPTOR?void 0:uri.value,versionValue=version===MISSING_OWN_DATA_DESCRIPTOR?void 0:version.value,ownerValue=owner===MISSING_OWN_DATA_DESCRIPTOR?void 0:owner.value,freshnessValue=freshness===MISSING_OWN_DATA_DESCRIPTOR?void 0:freshness.value;if(mimeTypeValue!==void 0&&typeof mimeTypeValue!="string"||uriValue!==void 0&&typeof uriValue!="string"||versionValue!==void 0&&typeof versionValue!="string"||ownerValue!==void 0&&typeof ownerValue!="string"||freshnessValue!==void 0&&freshnessValue!=="fresh"&&freshnessValue!=="aging"&&freshnessValue!=="stale")return;const tagsValue=tags===MISSING_OWN_DATA_DESCRIPTOR?void 0:tags.value,tagValues=tagsValue===void 0?void 0:projectLibraryStringArray(tagsValue);if(tagsValue!==void 0&&!tagValues)return;const updatedAtValue=updatedAt===MISSING_OWN_DATA_DESCRIPTOR||updatedAt.value===void 0?void 0:projectLibraryDate(updatedAt.value);return updatedAtValue===INVALID_DOCUMENT_DATE?void 0:Object.freeze({id:id.value,name:name.value,...mimeTypeValue===void 0?{}:{mimeType:mimeTypeValue},...uriValue===void 0?{}:{uri:uriValue},...versionValue===void 0?{}:{version:versionValue},...tagValues===void 0?{}:{tags:tagValues},...ownerValue===void 0?{}:{owner:ownerValue},...updatedAtValue===void 0?{}:{updatedAt:updatedAtValue},...freshnessValue===void 0?{}:{freshness:freshnessValue}})}catch{return}}class LyraDocumentLibrary extends LyraElement{constructor(){super(...arguments),this.sourceStateVersion=0,this.sourceEpoch=0,this.sourceSyncing=!1,this.sourceRows=[],this.sourceTags=[],this.sourceFacetLabels=new Map,this.sourceLifecycleVersion=0,this.sourceFilterEvent=!1,this.sourceSelectionAnnouncement="",this.sourcePages=new SourcePageController(this,{normalizeRecord:(record,isCurrent)=>this.projectSourceDocument(record,isCurrent),validateMetadata:(result,query)=>{if(!result.tags||query.tagFilter.length>MAX_TAG_FACETS||result.tags.unavailableSelected.some(key=>!query.tagFilter.includes(key)))throw new TypeError("Invalid document source facets")},onChange:()=>{this.sourceStateVersion++}}),this.cursorEpoch=0,this.cursorBindingVersion=0,this.cursorSelectionVersion=0,this.cursorRows=[],this.cursorDocuments=new WeakSet,this.cursorBatches=new WeakSet,this.cursorSelectionInvalid=!1,this.cursorTagInvalid=!1,this.cursorRequest=Promise.resolve(!1),this.cursorAnnounceTransition=!1,this.cursorRetryActive=!1,this.cursorSortVersion=0,this.cursorSortBatch=!1,this.cursorPages=new SourceCursorController(this,{normalizeRecord:(key,raw,current)=>{const projected=this.projectSourceValue(key,raw,current),date=projected.value.updatedAt;if(date instanceof Date){const updatedAt=Number.isFinite(date.getTime())?date.toISOString():"";return{value:Object.freeze({...projected.value,updatedAt}),textUnits:projected.textUnits+updatedAt.length}}return projected},onChange:()=>{this.sourceStateVersion++}}),this.sourcePage=0,this.sourcePageSize=100,this.onSourcePage=event=>{event.stopPropagation(),this.isCurrentTableEvent(event)&&this.sourceMode&&(this.sourcePage=event.detail.page-1)},this._documents=Object.freeze([]),this._selectedDocumentIds=Object.freeze([]),this._tagFilter=Object.freeze([]),this.sortKey="name",this.sortDir="asc",this.searchTerm="",this.loading=!1,this.error=!1,this.errorDescription="",this.slotPresence=new SlotPresenceController(this,{observeLightDom:!0}),this.onTableRetry=event=>{if(!this.isCurrentTableEvent(event)){event.stopPropagation(),event.preventDefault();return}if(!this.cursorMode){this.onCountedTableRetry(event);return}if(event.stopPropagation(),event.preventDefault(),this.cursorRetryActive||this.loading||!this.isConnected)return;this.cursorRetryActive=!0;const transaction=this.cursorBindingVersion,owner=this.ownerDocument;try{if(this.emit("lr-retry-request",null,{cancelable:!0}).defaultPrevented||transaction!==this.cursorBindingVersion||!this.isConnected||this.ownerDocument!==owner||!this.prepareCursorTransition())return;this.error?this.error=!1:this.cursorPages.state.navigation.status==="error"&&this.cursorPages.retry()}finally{this.cursorRetryActive=!1}},this.onCountedTableRetry=createRetryForwarder(init=>this.emit("lr-retry-request",null,init),()=>{this.error=!1,this.sourceMode&&(this.sourceInputs=void 0,this.syncSource(),this.sourceStateVersion++)}),this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.sourceAnnouncementInitialized=!1,this.explicitRefresh=0,this.defaultFilter=(document,query)=>{const locale=this.effectiveLocale;if(this.corpusMemo?.documents!==this._documents||this.corpusMemo.locale!==locale){const fields=new Map;for(const row of this._documents)fields.set(row,[row.name,row.owner??"",...row.tags??[]].map(value=>value.toLocaleLowerCase(locale)));this.corpusMemo={documents:this._documents,locale,fields}}return this.corpusMemo.fields.get(document).some(value=>value.includes(query))},this.documentTags=new WeakMap,this.documentDates=new WeakMap,this.compareDocuments=(a,b)=>{const collator=this.sortCollator,dir=this.sortDir==="asc"?1:-1;let result=0;switch(this.sortKey){case"name":result=collator.compare(a.name,b.name);break;case"version":result=collator.compare(a.version??"",b.version??"");break;case"owner":result=collator.compare(a.owner??"",b.owner??"");break;case"freshness":result=(a.freshness?FRESHNESS_RANK[a.freshness]:3)-(b.freshness?FRESHNESS_RANK[b.freshness]:3);break;case"updatedAt":result=(this.documentDate(a)?.getTime()??0)-(this.documentDate(b)?.getTime()??0);break}return result*dir},this.onSearchInput=event=>{event.stopPropagation(),this.searchTerm=event.detail.value,this.cursorMode&&(this.cursorAnnounceTransition=!0),this.emitFilterChange()},this.onTagFilterChange=event=>{event.stopPropagation();const combobox=event.target;this.tagFilter=Array.isArray(combobox.value)?combobox.value:[],this.emitFilterChange()},this.onTableSortRequest=event=>{if(event.stopPropagation(),!this.isCurrentTableEvent(event)){event.preventDefault();return}if(!this.isSortKey(event.detail.sortKey)){event.preventDefault();return}const detail=Object.freeze({phase:"request",sortKey:event.detail.sortKey,sortDir:event.detail.sortDir});if(this.cursorMode){const version=++this.cursorSortVersion,binding=this.cursorBindingVersion,owner=this.ownerDocument;if(this.cursorSortProposal=void 0,!this.isConnected){event.preventDefault();return}if(this.emit("lr-sort-request",detail,{cancelable:!0}).defaultPrevented||version!==this.cursorSortVersion||binding!==this.cursorBindingVersion||!this.isConnected||this.ownerDocument!==owner||!sourcePageScope(this)?.isCurrent()){event.preventDefault();return}this.cursorSortProposal={version,binding,owner,table:event.currentTarget,key:detail.sortKey,direction:detail.sortDir};return}this.emit("lr-sort-request",detail,{cancelable:!0}).defaultPrevented&&event.preventDefault()},this.onTableSortCommit=event=>{if(event.stopPropagation(),!!this.isCurrentTableEvent(event)&&this.isSortKey(event.detail.sortKey)){if(this.cursorMode||this.cursorSortProposal){const proposal=this.cursorSortProposal;if(this.cursorSortProposal=void 0,!proposal||proposal.version!==this.cursorSortVersion||proposal.binding!==this.cursorBindingVersion||proposal.table!==event.currentTarget||proposal.key!==event.detail.sortKey||proposal.direction!==event.detail.sortDir||!this.isConnected||proposal.owner!==this.ownerDocument||!sourcePageScope(this)?.isCurrent())return;this.cursorSortBatch=!0;try{if(this.sortKey=proposal.key,proposal.binding!==this.cursorBindingVersion||!this.isConnected||proposal.owner!==this.ownerDocument)return;this.sortDir=proposal.direction}finally{this.cursorSortBatch=!1}if(proposal.binding!==this.cursorBindingVersion||!this.isConnected||proposal.owner!==this.ownerDocument)return;const expected=proposal.binding+(this.cursorInputs?.[7]!==this.sortKey||this.cursorInputs?.[8]!==this.sortDir?1:0);if(this.syncCursor(),this.cursorBindingVersion!==expected||!this.isConnected||proposal.owner!==this.ownerDocument||this.sortKey!==proposal.key||this.sortDir!==proposal.direction)return;this.cursorAnnounceTransition=!0,this.emit("lr-sort",Object.freeze({phase:"commit",sortKey:proposal.key,sortDir:proposal.direction}));return}this.sortKey=event.detail.sortKey,this.sortDir=event.detail.sortDir,this.emit("lr-sort",Object.freeze({phase:"commit",sortKey:this.sortKey,sortDir:this.sortDir}))}},this.stopOwnedEvent=event=>{event.stopPropagation()},this.onTableSelectionChange=event=>{if(event.stopPropagation(),!this.isCurrentTableEvent(event))return;const table=event.currentTarget;table.selectedRowKeys=new Set(this.selectedDocumentIds)},this.clearSelection=()=>{this.setSelected([])}}static{this.defaultStrings={...super.defaultStrings,documentLibraryClearSelection:LYRA_DEFAULT_documentLibraryClearSelection,documentLibraryCursorEmptyBatch:LYRA_DEFAULT_documentLibraryCursorEmptyBatch,documentLibraryCursorEnd:LYRA_DEFAULT_documentLibraryCursorEnd,documentLibraryCursorFailed:LYRA_DEFAULT_documentLibraryCursorFailed,documentLibraryCursorHistoryLimit:LYRA_DEFAULT_documentLibraryCursorHistoryLimit,documentLibraryCursorNavigation:LYRA_DEFAULT_documentLibraryCursorNavigation,documentLibraryCursorRestart:LYRA_DEFAULT_documentLibraryCursorRestart,documentLibraryEmptyHeading:LYRA_DEFAULT_documentLibraryEmptyHeading,documentLibraryFilterByTag:LYRA_DEFAULT_documentLibraryFilterByTag,documentLibraryFreshnessAging:LYRA_DEFAULT_documentLibraryFreshnessAging,documentLibraryFreshnessColumn:LYRA_DEFAULT_documentLibraryFreshnessColumn,documentLibraryFreshnessFresh:LYRA_DEFAULT_documentLibraryFreshnessFresh,documentLibraryFreshnessStale:LYRA_DEFAULT_documentLibraryFreshnessStale,documentLibraryLabel:LYRA_DEFAULT_documentLibraryLabel,documentLibraryNameColumn:LYRA_DEFAULT_documentLibraryNameColumn,documentLibraryNoMatchesHeading:LYRA_DEFAULT_documentLibraryNoMatchesHeading,documentLibraryOwnerColumn:LYRA_DEFAULT_documentLibraryOwnerColumn,documentLibrarySearchPlaceholder:LYRA_DEFAULT_documentLibrarySearchPlaceholder,documentLibrarySelectAll:LYRA_DEFAULT_documentLibrarySelectAll,documentLibrarySelectColumn:LYRA_DEFAULT_documentLibrarySelectColumn,documentLibrarySelectDocument:LYRA_DEFAULT_documentLibrarySelectDocument,documentLibrarySelectPage:LYRA_DEFAULT_documentLibrarySelectPage,documentLibrarySelectedCount:LYRA_DEFAULT_documentLibrarySelectedCount,documentLibraryTagsColumn:LYRA_DEFAULT_documentLibraryTagsColumn,documentLibraryTypeColumn:LYRA_DEFAULT_documentLibraryTypeColumn,documentLibraryUpdatedColumn:LYRA_DEFAULT_documentLibraryUpdatedColumn,documentLibraryVersionColumn:LYRA_DEFAULT_documentLibraryVersionColumn,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous,retry:LYRA_DEFAULT_retry,sourceSelectionFailed:LYRA_DEFAULT_sourceSelectionFailed,sourceSelectionLoading:LYRA_DEFAULT_sourceSelectionLoading,tagFacetLimit:LYRA_DEFAULT_tagFacetLimit}}static{this.styles=[LyraElement.styles,styles]}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-filter-change","lr-query-change","lr-selection-change"])}get cursorSource(){return this._cursorSource}set cursorSource(value){const previous=this._cursorSource;this._cursorSource=value,this.cursorEpoch=(this.cursorEpoch??0)+1,this.requestUpdate("cursorSource",previous)}get cursorMode(){return this._cursorSource!==void 0}get cursorNavigation(){const state2=this.cursorPages.state.navigation;return this.cursorMode&&(this.error||this.loading)?Object.freeze({...state2,status:this.error?"error":"loading",canGoBack:!1,canGoForward:!1,atEnd:!1}):state2}nextCursorPage(){return!this.cursorMode||!this.cursorNavigation.canGoForward||!this.prepareCursorTransition()?Promise.resolve(!1):this.cursorPages.next()}previousCursorPage(){return!this.cursorMode||!this.cursorNavigation.canGoBack||!this.prepareCursorTransition()?Promise.resolve(!1):this.cursorPages.previous()}restartCursorSource(){if(!this.cursorMode||this.dataSource!==void 0||this.loading||this.error||!this.isConnected||!this.prepareCursorTransition())return Promise.resolve(!1);const transaction=this.cursorBindingVersion+1;return this.cursorEpoch++,this.syncCursor(),this.cursorBindingVersion!==transaction?Promise.resolve(!1):(this.cursorAnnounceTransition=!0,this.cursorRequest)}ensurePageScope(){sourcePageScope(this)||setSourcePageScope(this,this),shareSourcePageQueries(this)}prepareCursorTransition(){const transaction=this.cursorBindingVersion,owner=this.ownerDocument;return this.rehomeCursorFocus(),transaction!==this.cursorBindingVersion||!this.isConnected||this.ownerDocument!==owner?!1:(this.cursorAnnounceTransition=!0,this.cursorRows=[],this.cursorAcceptedRows=void 0,!0)}rehomeCursorFocus(){this.renderRoot?.querySelector('[part="table"]')?.shadowRoot?.activeElement&&this.renderRoot.querySelector('[part="cursor-navigation"]')?.focus()}syncCursor(){if(!this.cursorPages)return;const source=this._cursorSource;if(source===void 0&&this.cursorInputs?.[0]===void 0)return;const inputs=[source,this.dataSource,this.cursorEpoch,this.explicitRefresh,this.effectiveLocale,this.searchTerm,this.tagFilter,this.sortKey,this.sortDir,this.filter,finiteInteger(this.sourcePageSize,100,1,500),this.loading,this.error];if(this.cursorInputs&&inputs.every((value,index)=>value===this.cursorInputs[index]))return;const transaction=++this.cursorBindingVersion,selectionVersion=this.cursorSelectionVersion,current=()=>transaction===this.cursorBindingVersion&&this._cursorSource===source;if(this.cursorInputs=inputs,this.cursorAnnounceTransition=!1,this.rehomeCursorFocus(),!!current()&&(this.cursorRows=[],this.cursorAcceptedRows=void 0,this.cursorPages.invalidate(),!!current()&&source!==void 0&&(this.sourcePages.bind(void 0),!!current()))){this.sourceInputs=void 0,this.sourceSelectionInputs=void 0,this.sourceRows=[],this.sourceTags=[],this.sourceResult=void 0,this.sourceSelectionEvent=void 0,this.sourceFilterEvent=!1;try{if(this.dataSource!==void 0||source===null||typeof source!="object"&&typeof source!="function")throw new TypeError("Conflicting or invalid cursor source");const revision=source.revision;if(!current())return;const scope=source.scope;if(!current())return;if(typeof scope!="string"||scope.length===0||scope.length>8192)throw new TypeError("Invalid cursor scope");if(this.cursorScope!==void 0&&this.cursorScope!==scope&&selectionVersion===this.cursorSelectionVersion&&(this.cursorSelectionVersion++,this._selectedDocumentIds=Object.freeze([]),this.selectionSource=this._selectedDocumentIds,this.cursorSelectionInvalid=!1),!current())return;if(this.cursorScope=scope,this.cursorSelectionInvalid||this.cursorTagInvalid)throw new TypeError("Invalid cursor input");const selectedVersion=this.cursorSelectionVersion;let selected;try{selected=cursorIds(this.selectionSource??this._selectedDocumentIds,MAX_LIBRARY_COLLECTION_ENTRIES,()=>current()&&selectedVersion===this.cursorSelectionVersion)}catch(error){if(!current())return;if(selectedVersion===this.cursorSelectionVersion)throw error;selected=this._selectedDocumentIds}const query=cursorQuery({searchTerm:this.searchTerm??"",tagFilter:this.tagFilterSource??this.tagFilter,sortKey:this.sortKey,sortDir:this.sortDir,filter:this.filter},current);if(!current())return;if(this.cursorSelectionInvalid)throw new TypeError("Invalid cursor selection");if(selectedVersion===this.cursorSelectionVersion&&(this._selectedDocumentIds=selected,this.selectionSource=selected),this._tagFilter=query.tagFilter,this.tagFilterSource=query.tagFilter,this.cursorInputs=[source,this.dataSource,this.cursorEpoch,this.explicitRefresh,this.effectiveLocale,this.searchTerm,this._tagFilter,this.sortKey,this.sortDir,this.filter,finiteInteger(this.sourcePageSize,100,1,500),this.loading,this.error],this.ensurePageScope(),this.cursorPages.bind({source,revision,scope,epoch:transaction,locale:this.effectiveLocale}),!current()||this.loading||this.error||!this.isConnected)return;this.cursorRequest=this.cursorPages.request(query,finiteInteger(this.sourcePageSize,100,1,500))}catch{current()&&(this.cursorPages.fail(),this.cursorRequest=Promise.resolve(!1))}}}acceptCursorPage(){const state2=this.cursorPages.state;if(state2.navigation.status!=="ready"||this.loading||this.error){this.cursorRows=[],this.cursorAcceptedRows=void 0;return}if(this.cursorAcceptedRows!==state2.rows){this.cursorAcceptedRows=state2.rows,this.cursorRows=state2.rows.map(record=>record.value),this.cursorBatches.add(this.cursorRows);for(const document of this.cursorRows)this.cursorDocuments.add(document)}}renderCursorNavigation(){const navigation=this.cursorNavigation,blocked=this.loading||this.error||this.dataSource!==void 0;return html`<nav part="cursor-navigation" tabindex="-1" aria-label=${this.localize("documentLibraryCursorNavigation")}>
|
|
2
|
+
<button type="button" part="cursor-previous" aria-disabled=${String(!navigation.canGoBack)}
|
|
3
|
+
@click=${()=>{this.previousCursorPage()}}>${this.localize("previous")}</button>
|
|
4
|
+
<button type="button" part="cursor-next" aria-disabled=${String(!navigation.canGoForward)}
|
|
5
|
+
@click=${()=>{this.nextCursorPage()}}>${this.localize("next")}</button>
|
|
6
|
+
<button type="button" part="cursor-restart" aria-disabled=${String(blocked)}
|
|
7
|
+
@click=${()=>{this.restartCursorSource()}}>${this.localize("documentLibraryCursorRestart")}</button>
|
|
8
|
+
<span part="cursor-status">${navigation.atEnd?this.localize("documentLibraryCursorEnd"):""}${navigation.historyTruncated?this.localize("documentLibraryCursorHistoryLimit"):""}</span>
|
|
9
|
+
</nav>`}get dataSource(){return this._dataSource}set dataSource(value){const previous=this._dataSource;this._dataSource=value,this.sourceEpoch=(this.sourceEpoch??0)+1,this.requestUpdate("dataSource",previous)}get sourceTotal(){return this.cursorMode||this.dataSource===void 0?null:this.sourcePages.state.result?.total??null}get sourceMode(){return!this.cursorMode&&this.dataSource!==void 0}get providerMode(){return this.cursorMode||this.sourceMode}get sourceBlocked(){return this.cursorMode?!this.isConnected||this.loading||this.error||this.cursorNavigation.status!=="ready":this.sourceMode&&(this.loading||this.error||this.sourcePages.state.pending||!!this.sourcePages.state.error||!!this.sourceFailure)}get sourceSelectionBlocked(){return this.sourceBlocked||this.sourceMode&&(this.sourcePages.state.selectionPending||!!this.sourcePages.state.selectionError)}projectSourceDocument(record,isCurrent){const projected=this.projectSourceValue(record.key,record.value,isCurrent);return{key:record.key,order:record.order,value:projected.value}}projectSourceValue(key,raw,isCurrent){const assertCurrent=()=>{if(!isCurrent())throw new TypeError("Obsolete source record")},descriptorOf=(target,key2)=>{assertCurrent();const descriptor=getOwnDataDescriptor(target,key2);return assertCurrent(),descriptor};if(assertCurrent(),raw===null||typeof raw!="object"||Array.isArray(raw))throw new TypeError("Invalid source document");const snapshot={};for(const key2 of["id","name","mimeType","uri","version","tags","owner","updatedAt","freshness"]){const descriptor=descriptorOf(raw,key2);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid source document");descriptor!==MISSING_OWN_DATA_DESCRIPTOR&&(snapshot[key2]=descriptor.value)}if(snapshot.tags!==void 0){if(!Array.isArray(snapshot.tags))throw new TypeError("Invalid source document tags");const rawTags=snapshot.tags,length=descriptorOf(rawTags,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0||length.value>MAX_TAG_FACETS)throw new RangeError("Invalid source document tags");const tags=[];for(let index=0;index<length.value;index++){const descriptor=descriptorOf(rawTags,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||typeof descriptor.value!="string")throw new TypeError("Invalid source document tag");tags.push(descriptor.value)}snapshot.tags=tags}const value=projectLibraryDocument(snapshot);if(assertCurrent(),!value||value.id!==key||(value.tags?.length??0)>MAX_TAG_FACETS)throw new TypeError("Invalid source document");let units=0;for(const text of[value.id,value.name,value.owner,value.mimeType,value.uri,value.version,typeof value.updatedAt=="string"?value.updatedAt:void 0,...value.tags??[]])if(text!==void 0&&(units+=text.length,text.length>65536||units>65536))throw new RangeError("Source document too large");return assertCurrent(),{value,textUnits:units}}syncSource(){if(!(!this.sourcePages||this.sourceSyncing)){this.sourceSyncing=!0;try{if(!this.sourceMode){this.sourceInputs&&this.sourcePages.bind(void 0),this.sourceInputs=void 0,this.sourceQueryInputs=void 0,this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0,this.sourceFilterEvent=!1,this.sourceResult=void 0,this.sourceRows=[],this.sourceTags=[],this.sourceFailure=void 0;return}this.ensurePageScope();const source=this.dataSource,epoch=this.sourceEpoch+this.explicitRefresh,size=finiteInteger(this.sourcePageSize,100,1,500);let page=finiteInteger(this.sourcePage,0,0,Math.floor(Number.MAX_SAFE_INTEGER/size));const queryInputs=[this.searchTerm,this.tagFilter,this.sortKey,this.sortDir,this.filter,size];this.sourceQueryInputs&&queryInputs.some((value,index)=>value!==this.sourceQueryInputs[index])&&(page=0,this.sourcePage=0),this.sourceQueryInputs=queryInputs;const revision=source.revision,inputs=[source,revision,epoch,this.effectiveLocale,...queryInputs,page];if(this.sourceInputs&&inputs.every((value,index)=>value===this.sourceInputs[index]))return;if(this.sourceInputs&&inputs.slice(0,3).some((value,index)=>value!==this.sourceInputs[index])&&(this.sourceSelectionEvent=void 0,this.sourceFilterEvent=!1),this.sourceInputs=inputs,this.sourceFailure=void 0,this.sourceRows=[],this.sourceTags=[],this.sourceResult=void 0,this.sourcePages.bind({source,revision,epoch,locale:this.effectiveLocale}),this.tagFilter.length>MAX_TAG_FACETS)throw new RangeError("Too many source facets");const query=Object.freeze({searchTerm:this.searchTerm??"",tagFilter:this.tagFilter,sortKey:this.sortKey,sortDir:this.sortDir,filter:this.filter});this.sourcePages.request(query,page,size),this.syncSourceSelection()}catch(error){this.sourcePages.bind(void 0),this.sourceRows=[],this.sourceTags=[],this.sourceResult=void 0,this.sourceFailure=error}finally{this.sourceSyncing=!1}}}syncSourceSelection(){if(!this.sourceMode||this.sourceFailure)return;const ids=this._selectedDocumentIds,source=this.dataSource,epoch=this.sourceEpoch+this.explicitRefresh,inputs=[source,source?.revision,epoch,ids];if(this.sourceSelectionInputs&&inputs.every((value,index)=>value===this.sourceSelectionInputs[index]))return;this.sourceSelectionInputs=inputs;const owner=this.ownerDocument,lifecycle=this.sourceLifecycleVersion;this.sourcePages.resolveSelection(ids).then(records=>{if(!records||lifecycle!==this.sourceLifecycleVersion||!this.isConnected||this.ownerDocument!==owner||this.dataSource!==source||epoch!==this.sourceEpoch+this.explicitRefresh||this._selectedDocumentIds!==ids)return;const retained=new Set(records.map(record=>record.key)),accepted=Object.freeze(ids.filter(id=>retained.has(id)));accepted.length!==ids.length&&(this._selectedDocumentIds=accepted,this.selectionSource=accepted,this.sourceSelectionInputs=void 0),this.sourceSelectionEvent===ids&&(this.sourceSelectionEvent=void 0,this.announcements.announcePolite(this.selectionCountText()),this.emit("lr-selection-change",Object.freeze({documentIds:Object.freeze([...this._selectedDocumentIds])}))),this.sourceStateVersion++})}acceptSourcePage(){const result=this.sourcePages.state.result;if(!result||result===this.sourceResult)return;this.sourceResult=result,this.sourceRows=result.rows.map(record=>record.value),this.sourceTags=result.tags.values.map(facet=>facet.key),this.sourceFacetLabels=new Map(result.tags.values.map(facet=>[facet.key,facet.label]));const removed=new Set(result.tags.unavailableSelected);if(this.tagFilter.some(key=>removed.has(key))){this.tagFilter=this.tagFilter.filter(key=>!removed.has(key));return}this.sourcePage!==this.sourcePages.state.page&&(this.sourceSyncing=!0,this.sourcePage=this.sourcePages.state.page,this.sourceSyncing=!1,this.sourceInputs=this.sourceInputs?[...this.sourceInputs.slice(0,-1),this.sourcePages.state.page]:void 0),this.sourceFilterEvent&&(this.sourceFilterEvent=!1,this.emit("lr-filter-change",Object.freeze({searchTerm:this.searchTerm,tags:Object.freeze([...this.tagFilter]),matchCount:result.total})))}get documents(){return this.documentsView??=this.snapshotDocuments(this._documents)}set documents(value){if(value===this.documentsSource||value===this.documentsView)return;this.documentsSource=value;const previous=this._documents;this._documents=this.snapshotDocuments(value),this.documentsView=void 0,this.requestUpdate("documents",previous)}get selectedDocumentIds(){return this._selectedDocumentIds}set selectedDocumentIds(value){if(value===this.selectionSource||value===this._selectedDocumentIds)return;if(this.cursorMode&&this.cursorPages){const version=++this.cursorSelectionVersion,binding=this.cursorBindingVersion,current=()=>version===this.cursorSelectionVersion&&binding===this.cursorBindingVersion;try{const snapshot=cursorIds(value,MAX_LIBRARY_COLLECTION_ENTRIES,current);if(!current())return;const previous2=this._selectedDocumentIds;this.selectionSource=snapshot,this._selectedDocumentIds=snapshot;const recovering=this.cursorSelectionInvalid;this.cursorSelectionInvalid=!1,recovering&&(this.cursorInputs=void 0,this.syncCursor()),this.requestUpdate("selectedDocumentIds",previous2)}catch{current()&&(this.cursorSelectionInvalid=!0,this.cursorPages.fail(),this.sourceStateVersion++)}return}this.sourceSelectionEvent=void 0,this.selectionSource=value;const previous=this._selectedDocumentIds;this._selectedDocumentIds=this.snapshotIds(Array.isArray(value)?value:[]),this.requestUpdate("selectedDocumentIds",previous)}get tagFilter(){return this._tagFilter}set tagFilter(value){if(value===this.tagFilterSource||value===this._tagFilter)return;if(this.cursorMode&&this.cursorPages){const version=++this.cursorBindingVersion;try{const snapshot=cursorIds(value,MAX_TAG_FACETS,()=>version===this.cursorBindingVersion);if(version!==this.cursorBindingVersion)return;const previous2=this._tagFilter;this.tagFilterSource=snapshot,this._tagFilter=snapshot,this.cursorTagInvalid=!1,this.requestUpdate("tagFilter",previous2)}catch{version===this.cursorBindingVersion&&(this.cursorTagInvalid=!0,this.cursorPages.fail(),this.sourceStateVersion++)}return}this.tagFilterSource=value;const previous=this._tagFilter;this._tagFilter=this.snapshotIds(Array.isArray(value)?value:[]),this.requestUpdate("tagFilter",previous)}get hasErrorSlot(){return this.slotPresence.has("error")}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))}connectedCallback(){super.connectedCallback(),this.cursorMode&&(this.cursorInputs=void 0,this.syncCursor()),this.hasUpdated&&this.sourceMode&&(this.sourceSelectionInputs=void 0,this.syncSourceSelection())}invalidateSourceSelection(){this.sourceLifecycleVersion++,this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0,this.sourceFilterEvent=!1,this.sourceAnnouncementInitialized=!1}disconnectedCallback(){this.invalidateSourceSelection(),this.cursorBindingVersion++,this.cursorInputs=void 0,this.cursorRows=[],this.cursorPages.invalidate(),this.cursorAnnounceTransition=!1,super.disconnectedCallback()}adoptedCallback(){this.invalidateSourceSelection(),super.adoptedCallback(),this.announcements.adopted(),this.sourcePages.adopted(),this.cursorBindingVersion++,this.cursorInputs=void 0,this.cursorRows=[],this.cursorPages.invalidate(),this.syncCursor()}updated(changed){if(super.updated(changed),this.cursorMode){const state2=this.cursorPages.state;this.cursorAnnounceTransition&&(state2.navigation.status==="error"||state2.navigation.atEnd)&&(this.cursorAnnounceTransition=!1,this.announcements.announcePolite(this.localize(state2.navigation.status==="error"?"documentLibraryCursorFailed":"documentLibraryCursorEnd"))),state2.navigation.status==="ready"&&(this.cursorAnnounceTransition=!1)}const status=this.sourceMode&&this.sourcePages.state.selectionError?this.localize("sourceSelectionFailed"):this.sourceMode&&this.sourcePages.state.selectionPending?this.localize("sourceSelectionLoading"):"";this.sourceAnnouncementInitialized&&status&&status!==this.sourceSelectionAnnouncement&&this.announcements.announcePolite(status),this.sourceAnnouncementInitialized=!0,this.sourceSelectionAnnouncement=status}snapshotDocuments(documents){const snapshot=[],seen=new Set;try{if(!Array.isArray(documents))return Object.freeze(snapshot);const length=getOwnDataDescriptor(documents,"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(snapshot);for(let index=0;index<Math.min(length.value,MAX_LIBRARY_COLLECTION_ENTRIES);index+=1){const entry=getOwnDataDescriptor(documents,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const document=projectLibraryDocument(entry.value);!document||seen.has(document.id)||(seen.add(document.id),snapshot.push(document))}}catch{}return Object.freeze(snapshot)}snapshotIds(ids){const snapshot=[],seen=new Set;try{for(const id of ids)if(!seen.has(id)&&(seen.add(id),snapshot.push(id),snapshot.length>=MAX_LIBRARY_COLLECTION_ENTRIES))break}catch{}return Object.freeze(snapshot)}requestUpdate(...args){args[0]===void 0&&(this.explicitRefresh=(this.explicitRefresh??0)+1),super.requestUpdate(...args),!(this.cursorSortBatch&&(args[0]==="sortKey"||args[0]==="sortDir"))&&(args[0]===void 0||["cursorSource","dataSource","sourcePageSize","searchTerm","tagFilter","sortKey","sortDir","filter","locale","lang","loading","error"].includes(String(args[0])))&&this.syncCursor(),(args[0]===void 0||["dataSource","sourcePage","sourcePageSize","searchTerm","tagFilter","sortKey","sortDir","filter"].includes(String(args[0])))&&this.syncSource(),args[0]==="selectedDocumentIds"&&this.syncSourceSelection()}willUpdate(changed){if(super.willUpdate(changed),this.syncCursor(),this.syncSource(),this.cursorMode){this.acceptCursorPage();return}if(this.sourceMode){this.acceptSourcePage(),this.syncSourceSelection();return}if((changed.has("documents")||changed.has("selectedDocumentIds")||changed.has("dataSource"))&&this.selectedDocumentIds.length>0){const existing=indexByKey(this._documents,documentKey),normalized=this.snapshotIds(this.selectedDocumentIds.filter(id=>existing.has(id)));(normalized.length!==this.selectedDocumentIds.length||normalized.some((id,index)=>id!==this.selectedDocumentIds[index]))&&(this.selectedDocumentIds=normalized)}if((changed.has("documents")||changed.has("tagFilter")||changed.has("dataSource"))&&this.tagFilter.length>0){const availableTags=this.tagSet,normalized=this.snapshotIds(this.tagFilter.filter(tag=>availableTags.has(tag)));(normalized.length!==this.tagFilter.length||normalized.some((tag,index)=>tag!==this.tagFilter[index]))&&(this.tagFilter=normalized)}}selectionCountText(){return this.localize("documentLibrarySelectedCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(this.selectedDocumentIds.length)})}normalizeDate(value){if(value===void 0)return;const date=value instanceof Date?value:new Date(value);return Number.isNaN(date.getTime())?void 0:date}matchesTagFilter(document){if(this.tagFilter.length===0)return!0;let tags=this.documentTags.get(document);return tags||(tags=new Set(document.tags??[]),this.documentTags.set(document,tags)),this.tagFilter.every(tag=>tags.has(tag))}documentDate(document){return this.documentDates.has(document)||this.documentDates.set(document,this.normalizeDate(document.updatedAt)),this.documentDates.get(document)}get matchingDocuments(){const query=(this.searchTerm??"").trim().toLocaleLowerCase(this.effectiveLocale),inputs=[this._documents,query,this.tagFilter,this.filter,this.effectiveLocale,this.filter?this.explicitRefresh:0];if(!this.matchingMemo||inputs.some((input,index)=>input!==this.matchingMemo.inputs[index])){const matchFn=this.filter??this.defaultFilter,rows=this._documents.filter(document=>(query===""||matchFn(document,query))&&this.matchesTagFilter(document));this.matchingMemo={inputs,rows}}return this.matchingMemo.rows}get sortedDocuments(){const rows=this.matchingDocuments,locale=this.effectiveLocale,previous=this.sortedMemo;if(previous?.rows===rows&&previous.key===this.sortKey&&previous.dir===this.sortDir&&previous.locale===locale)return previous.sorted;if(this.sortCollator=getCollator(locale,{numeric:!0}),this.sortKey==="updatedAt")for(const row of rows)this.documentDate(row);const sorted=[...rows].sort(this.compareDocuments);return this.sortedMemo={rows,key:this.sortKey,dir:this.sortDir,locale,sorted},sorted}get allTags(){const locale=this.effectiveLocale;if(this.tagsMemo?.documents===this._documents&&this.tagsMemo.locale===locale)return this.tagsMemo.tags;const tags=new Set;for(const document of this._documents)for(const tag of document.tags??[])tags.add(tag);const sorted=[...tags].sort(getCollator(locale).compare);return this.tagsMemo={documents:this._documents,locale,tags:sorted,set:tags},sorted}get tagSet(){return this.allTags,this.tagsMemo.set}get selectedIdSet(){return this.selectedMemo?.ids!==this._selectedDocumentIds&&(this.selectedMemo={ids:this._selectedDocumentIds,set:new Set(this._selectedDocumentIds)}),this.selectedMemo.set}emitFilterChange(){if(this.cursorMode){this.emit("lr-query-change",Object.freeze({searchTerm:this.searchTerm,tags:Object.freeze([...this.tagFilter])}));return}if(this.sourceMode){this.sourceFilterEvent=!0;return}const tags=Object.freeze([...this.tagFilter]);this.emit("lr-filter-change",Object.freeze({searchTerm:this.searchTerm,tags,matchCount:this.matchingDocuments.length}))}isSortKey(value){return value==="name"||value==="version"||value==="owner"||value==="freshness"||value==="updatedAt"}isCurrentTableEvent(event){return this.isConnected&&event.currentTarget===this.renderRoot.querySelector('[part="table"]')}openDocument(document){this.cursorDocuments.has(document)&&(!this.cursorMode||!this.cursorRows.includes(document))||this.sourceBlocked||this.sourceMode&&!this.sourceRows.includes(document)||this.cursorMode&&!this.cursorRows.includes(document)||this.emit("lr-open",Object.freeze({documentId:document.id}))}setSelected(ids){if(this.sourceSelectionBlocked)return;const previous=this._selectedDocumentIds;if(this.selectedDocumentIds=[...ids],this.cursorMode&&(this.cursorSelectionInvalid||this._selectedDocumentIds===previous))return;if(this.sourceMode){this.sourceSelectionEvent=this._selectedDocumentIds;return}this.announcements.announcePolite(this.selectionCountText());const eventIds=Object.freeze([...this.selectedDocumentIds]);this.emit("lr-selection-change",Object.freeze({documentIds:eventIds}))}toggleSelection(document,checked){if((this.cursorMode||this.cursorDocuments.has(document))&&!this.cursorRows.includes(document))return;const next=new Set(this.selectedDocumentIds);checked?next.add(document.id):next.delete(document.id),this.setSelected(next)}toggleSelectAll(checked,visible){if((this.cursorMode||this.cursorBatches.has(visible))&&visible!==this.cursorRows)return;const next=new Set(this.selectedDocumentIds);for(const document of visible)checked?next.add(document.id):next.delete(document.id);this.setSelected(next)}freshnessLabel(freshness){switch(freshness){case"fresh":return this.localize("documentLibraryFreshnessFresh");case"aging":return this.localize("documentLibraryFreshnessAging");case"stale":return this.localize("documentLibraryFreshnessStale")}}renderSelectAllCheckbox(visible,selected){const allSelected=visible.length>0&&visible.every(document=>selected.has(document.id)),someSelected=!allSelected&&visible.some(document=>selected.has(document.id));return html`<lr-checkbox
|
|
2
10
|
.checked=${allSelected}
|
|
3
11
|
.indeterminate=${someSelected}
|
|
4
|
-
aria-label=${this.localize(this.
|
|
12
|
+
aria-label=${this.localize(this.providerMode?"documentLibrarySelectPage":"documentLibrarySelectAll")}
|
|
5
13
|
.disabled=${this.sourceSelectionBlocked}
|
|
6
14
|
@lr-checkbox-toggle-request=${this.stopOwnedEvent}
|
|
7
15
|
@input=${this.stopOwnedEvent}
|
|
@@ -24,7 +32,7 @@ import{__decorate}from"tslib";import{SourcePageController}from"../../../internal
|
|
|
24
32
|
?disabled=${this.sourceBlocked}
|
|
25
33
|
>
|
|
26
34
|
${document.name}
|
|
27
|
-
</button>`}renderTagsCell(document){const tags=document.tags??[];return tags.length===0?nothing:this.
|
|
35
|
+
</button>`}renderTagsCell(document){const tags=document.tags??[];return tags.length===0?nothing:this.providerMode?html`<span>${tags.join(", ")}</span>`:html`<lr-chip-group
|
|
28
36
|
>${tags.map(tag=>html`<lr-chip>${tag}</lr-chip>`)}</lr-chip-group
|
|
29
37
|
>`}renderFreshnessCell(document){return document.freshness?html`<lr-chip variant=${FRESHNESS_TONE[document.freshness]}
|
|
30
38
|
>${this.freshnessLabel(document.freshness)}</lr-chip
|
|
@@ -32,7 +40,7 @@ import{__decorate}from"tslib";import{SourcePageController}from"../../../internal
|
|
|
32
40
|
mime-type=${document.mimeType??""}
|
|
33
41
|
name=${document.name}
|
|
34
42
|
decorative
|
|
35
|
-
></lr-file-icon>`},{key:"name",label:this.localize("documentLibraryNameColumn"),sortable:!0,cell:document=>this.renderNameCell(document)},{key:"version",label:this.localize("documentLibraryVersionColumn"),sortable:!0,priority:"medium",cell:document=>document.version??""},{key:"owner",label:this.localize("documentLibraryOwnerColumn"),sortable:!0,priority:"medium",cell:document=>document.owner??""},{key:"tags",label:this.localize("documentLibraryTagsColumn"),priority:"low",cell:document=>this.renderTagsCell(document)},{key:"freshness",label:this.localize("documentLibraryFreshnessColumn"),sortable:!0,priority:"low",cell:document=>this.renderFreshnessCell(document)},{key:"updatedAt",label:this.localize("documentLibraryUpdatedColumn"),sortable:!0,priority:"low",cell:document=>this.renderUpdatedCell(document)}]}renderTagOptions(tags){return this.tagOptionsMemo?.tags!==tags&&(this.tagOptionsMemo={tags,options:tags.slice(0,MAX_TAG_FACETS).map(tag=>html`<lr-option value=${tag}>${this.sourceMode?this.sourceFacetLabels.get(tag)??tag:tag}</lr-option>`)}),this.tagOptionsMemo.options}render(){const label=hostAriaLabel(this)?.trim()??(this.label==null?this.localize("documentLibraryLabel"):this.label),visible=this.sourceMode?this.sourceRows:this.sortedDocuments,selected=this.selectedIdSet,tags=this.sourceMode?this.sourceTags:this.allTags,facetTotal=this.sourceMode?this.sourceResult?.tags?.total??0:tags.length,emptyHeading=(this.
|
|
43
|
+
></lr-file-icon>`},{key:"name",label:this.localize("documentLibraryNameColumn"),sortable:!0,cell:document=>this.renderNameCell(document)},{key:"version",label:this.localize("documentLibraryVersionColumn"),sortable:!0,priority:"medium",cell:document=>document.version??""},{key:"owner",label:this.localize("documentLibraryOwnerColumn"),sortable:!0,priority:"medium",cell:document=>document.owner??""},{key:"tags",label:this.localize("documentLibraryTagsColumn"),priority:"low",cell:document=>this.renderTagsCell(document)},{key:"freshness",label:this.localize("documentLibraryFreshnessColumn"),sortable:!0,priority:"low",cell:document=>this.renderFreshnessCell(document)},{key:"updatedAt",label:this.localize("documentLibraryUpdatedColumn"),sortable:!0,priority:"low",cell:document=>this.renderUpdatedCell(document)}]}renderTagOptions(tags){return this.tagOptionsMemo?.tags!==tags&&(this.tagOptionsMemo={tags,options:tags.slice(0,MAX_TAG_FACETS).map(tag=>html`<lr-option value=${tag}>${this.sourceMode?this.sourceFacetLabels.get(tag)??tag:tag}</lr-option>`)}),this.tagOptionsMemo.options}render(){const label=hostAriaLabel(this)?.trim()??(this.label==null?this.localize("documentLibraryLabel"):this.label),visible=this.cursorMode?this.cursorRows:this.sourceMode?this.sourceRows:this.sortedDocuments,tableIdentity=this.cursorMode?this.cursorAcceptedRows??this._cursorSource:void 0,selected=this.selectedIdSet,tags=this.cursorMode?[]:this.sourceMode?this.sourceTags:this.allTags,facetTotal=this.sourceMode?this.sourceResult?.tags?.total??0:tags.length,emptyHeading=this.cursorMode&&!(this.cursorPages.state.initial&&this.cursorNavigation.atEnd)?this.localize(this.cursorNavigation.atEnd?"documentLibraryCursorEnd":"documentLibraryCursorEmptyBatch"):(this.providerMode?!this.searchTerm&&this.tagFilter.length===0:this._documents.length===0)?this.localize("documentLibraryEmptyHeading"):this.localize("documentLibraryNoMatchesHeading");return html`
|
|
36
44
|
<div part="base" role="region" aria-label=${label}>
|
|
37
45
|
<div part="toolbar">
|
|
38
46
|
<lr-input
|
|
@@ -83,14 +91,14 @@ import{__decorate}from"tslib";import{SourcePageController}from"../../../internal
|
|
|
83
91
|
</button>
|
|
84
92
|
</div>`:nothing}
|
|
85
93
|
${this.sourceMode&&(this.sourcePages.state.selectionPending||this.sourcePages.state.selectionError)?html`<p part="selection-status">${this.localize(this.sourcePages.state.selectionPending?"sourceSelectionLoading":"sourceSelectionFailed")}${this.sourcePages.state.selectionError?html` <button type="button" part="selection-retry" @click=${()=>{this.sourceSelectionInputs=void 0,this.syncSourceSelection()}}>${this.localize("retry")}</button>`:nothing}</p>`:nothing}
|
|
86
|
-
|
|
94
|
+
${keyed(tableIdentity,html`<lr-table
|
|
87
95
|
part="table"
|
|
88
96
|
exportparts="row, cell, header-cell, document-name, error-row, error-cell, error, error-base, error-icon, error-heading, error-description, error-actions, retry-button"
|
|
89
97
|
aria-label=${label}
|
|
90
98
|
.strings=${this.strings}
|
|
91
99
|
.paginationMode=${this.sourceMode?"server":"client"}
|
|
92
100
|
.page=${this.sourceMode?finiteInteger(this.sourcePage,0,0,Number.MAX_SAFE_INTEGER)+1:1}
|
|
93
|
-
.pageSize=${this.
|
|
101
|
+
.pageSize=${this.providerMode?finiteInteger(this.sourcePageSize,100,1,500):100}
|
|
94
102
|
.totalItems=${this.sourceMode?this.sourceTotal??0:-1}
|
|
95
103
|
.unknownTotal=${this.sourceMode&&this.sourceTotal===null}
|
|
96
104
|
.hasNext=${!this.sourceMode||this.sourceTotal!==null}
|
|
@@ -102,9 +110,9 @@ import{__decorate}from"tslib";import{SourcePageController}from"../../../internal
|
|
|
102
110
|
.sortKey=${this.sortKey}
|
|
103
111
|
.sortDir=${this.sortDir}
|
|
104
112
|
sort-mode="server"
|
|
105
|
-
?loading=${this.loading||this.sourceMode&&this.sourcePages.state.pending}
|
|
113
|
+
?loading=${this.loading||this.cursorMode&&this.cursorNavigation.status==="loading"||this.sourceMode&&this.sourcePages.state.pending}
|
|
106
114
|
empty-heading=${emptyHeading}
|
|
107
|
-
?error=${this.error||this.sourceMode&&!!(this.sourceFailure||this.sourcePages.state.error)}
|
|
115
|
+
?error=${this.error||this.cursorMode&&this.cursorNavigation.status==="error"||this.sourceMode&&!!(this.sourceFailure||this.sourcePages.state.error)}
|
|
108
116
|
error-heading=${this.errorHeading??nothing}
|
|
109
117
|
error-description=${this.errorDescription}
|
|
110
118
|
@lr-sort-request=${this.onTableSortRequest}
|
|
@@ -113,8 +121,9 @@ import{__decorate}from"tslib";import{SourcePageController}from"../../../internal
|
|
|
113
121
|
@lr-priority-columns-visibility-change=${this.stopOwnedEvent}
|
|
114
122
|
@lr-selection-change=${this.onTableSelectionChange}
|
|
115
123
|
@lr-retry-request=${this.onTableRetry}
|
|
116
|
-
@lr-row-activate=${event=>{event.stopPropagation(),this.openDocument(event.detail.row)}}
|
|
124
|
+
@lr-row-activate=${event=>{event.stopPropagation(),this.isCurrentTableEvent(event)&&this.openDocument(event.detail.row)}}
|
|
117
125
|
@lr-row-click=${this.stopOwnedEvent}
|
|
118
|
-
>${this.hasErrorSlot?html`<div slot="error"><slot name="error"></slot></div>`:nothing}</lr-table
|
|
126
|
+
>${this.hasErrorSlot?html`<div slot="error"><slot name="error"></slot></div>`:nothing}</lr-table>`)}
|
|
127
|
+
${this.cursorMode?this.renderCursorNavigation():nothing}
|
|
119
128
|
</div>
|
|
120
|
-
`}}__decorate([state()],LyraDocumentLibrary.prototype,"sourceStateVersion",void 0),__decorate([property({attribute:!1})],LyraDocumentLibrary.prototype,"dataSource",null),__decorate([property({type:Number,attribute:"source-page"})],LyraDocumentLibrary.prototype,"sourcePage",void 0),__decorate([property({type:Number,attribute:"source-page-size"})],LyraDocumentLibrary.prototype,"sourcePageSize",void 0),__decorate([property({attribute:!1})],LyraDocumentLibrary.prototype,"documents",null),__decorate([property({attribute:!1})],LyraDocumentLibrary.prototype,"selectedDocumentIds",null),__decorate([property({attribute:!1})],LyraDocumentLibrary.prototype,"tagFilter",null),__decorate([property({attribute:!1})],LyraDocumentLibrary.prototype,"filter",void 0),__decorate([property({attribute:"sort-key"})],LyraDocumentLibrary.prototype,"sortKey",void 0),__decorate([property({attribute:"sort-dir"})],LyraDocumentLibrary.prototype,"sortDir",void 0),__decorate([property({attribute:"search-term"})],LyraDocumentLibrary.prototype,"searchTerm",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDocumentLibrary.prototype,"loading",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDocumentLibrary.prototype,"error",void 0),__decorate([property({attribute:"error-heading"})],LyraDocumentLibrary.prototype,"errorHeading",void 0),__decorate([property({attribute:"error-description"})],LyraDocumentLibrary.prototype,"errorDescription",void 0),__decorate([property({reflect:!0,converter:optionalSizeConverter})],LyraDocumentLibrary.prototype,"size",null),__decorate([property()],LyraDocumentLibrary.prototype,"label",void 0);export{LyraDocumentLibrary};
|
|
129
|
+
`}}__decorate([state()],LyraDocumentLibrary.prototype,"sourceStateVersion",void 0),__decorate([property({attribute:!1})],LyraDocumentLibrary.prototype,"cursorSource",null),__decorate([property({attribute:!1})],LyraDocumentLibrary.prototype,"dataSource",null),__decorate([property({type:Number,attribute:"source-page"})],LyraDocumentLibrary.prototype,"sourcePage",void 0),__decorate([property({type:Number,attribute:"source-page-size"})],LyraDocumentLibrary.prototype,"sourcePageSize",void 0),__decorate([property({attribute:!1})],LyraDocumentLibrary.prototype,"documents",null),__decorate([property({attribute:!1})],LyraDocumentLibrary.prototype,"selectedDocumentIds",null),__decorate([property({attribute:!1})],LyraDocumentLibrary.prototype,"tagFilter",null),__decorate([property({attribute:!1})],LyraDocumentLibrary.prototype,"filter",void 0),__decorate([property({attribute:"sort-key"})],LyraDocumentLibrary.prototype,"sortKey",void 0),__decorate([property({attribute:"sort-dir"})],LyraDocumentLibrary.prototype,"sortDir",void 0),__decorate([property({attribute:"search-term"})],LyraDocumentLibrary.prototype,"searchTerm",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDocumentLibrary.prototype,"loading",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDocumentLibrary.prototype,"error",void 0),__decorate([property({attribute:"error-heading"})],LyraDocumentLibrary.prototype,"errorHeading",void 0),__decorate([property({attribute:"error-description"})],LyraDocumentLibrary.prototype,"errorDescription",void 0),__decorate([property({reflect:!0,converter:optionalSizeConverter})],LyraDocumentLibrary.prototype,"size",null),__decorate([property()],LyraDocumentLibrary.prototype,"label",void 0);export{LyraDocumentLibrary};
|