@aceshooting/lyra-ui 30.9.0 → 31.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +236 -339
- package/dist/ai/adapters/ag-ui.js +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
- package/dist/components/charts/chart/box-plot.class.js +2 -2
- package/dist/components/charts/chart/chart-sync.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +1 -1
- package/dist/components/charts/chart/chart.class.js +4 -4
- package/dist/components/charts/chart/lite-chart-axis-layout.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +9 -4
- package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
- package/dist/components/conversation/chat-message/chat-message.class.d.ts +27 -3
- package/dist/components/conversation/chat-message/chat-message.class.js +14 -12
- package/dist/components/conversation/chat-message/chat-message.styles.js +1 -1
- package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +29 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +2 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +1 -1
- package/dist/components/conversation/code-block/code-block-shared.js +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.d.ts +10 -0
- package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
- package/dist/components/conversation/markdown/markdown-shared.js +3 -3
- package/dist/components/conversation/markdown/markdown.class.d.ts +10 -0
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
- package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +2 -1
- package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +4 -0
- package/dist/components/conversation/streaming-text/streaming-text-base.class.js +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
- package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +17 -3
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +3 -3
- package/dist/components/conversation/suggestion-chips/suggestion-chips.d.ts +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.js +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
- package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.d.ts +10 -10
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/pagination/pagination.class.js +1 -1
- package/dist/components/data/table/table.class.d.ts +31 -2
- package/dist/components/data/table/table.class.js +3 -3
- package/dist/components/data/table/table.styles.js +1 -1
- package/dist/components/data/timeline/timeline-cluster.js +1 -1
- package/dist/components/data/timeline/timeline-item.class.d.ts +10 -3
- package/dist/components/data/timeline/timeline-item.class.js +16 -12
- package/dist/components/data/timeline/timeline-item.styles.js +1 -1
- package/dist/components/data/timeline/timeline.class.d.ts +14 -2
- package/dist/components/data/timeline/timeline.class.js +9 -5
- package/dist/components/data/tree/tree-item.class.js +1 -1
- package/dist/components/data/tree/tree.class.d.ts +2 -0
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/forms/button/button.class.d.ts +8 -6
- package/dist/components/forms/button/button.class.js +2 -2
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/color-picker/color-core.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.d.ts +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
- package/dist/components/forms/icon-button/icon-button.class.js +2 -2
- package/dist/components/forms/input/input-shared.js +2 -2
- package/dist/components/forms/input/number-input-locale.js +1 -0
- package/dist/components/forms/input/number-input.class.d.ts +19 -2
- package/dist/components/forms/input/number-input.class.js +2 -2
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -3
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
- package/dist/components/layout/details/accordion-item.class.js +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.d.ts +8 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/tab-group/tab.class.d.ts +7 -1
- package/dist/components/layout/tab-group/tab.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.d.ts +2 -2
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/media/animated-image/animated-image.class.js +1 -1
- package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +21 -14
- package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +36 -12
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
- package/dist/components/media/drop-zone/drop-zone.class.d.ts +23 -5
- package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
- package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/flag/flag-url-resolver.js +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
- package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/media/map/map-owned-features.js +1 -1
- package/dist/components/media/map/map-scene-elevated-lines.js +2 -2
- package/dist/components/media/map/map-scene-render-controller.js +1 -1
- package/dist/components/media/map/map.class.d.ts +5 -5
- package/dist/components/media/map/map.class.js +3 -3
- package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
- package/dist/components/media/video/video.class.d.ts +3 -3
- package/dist/components/media/video/video.class.js +3 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/overlays/chip/chip.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -1
- package/dist/components/overlays/overlay/tooltip.class.js +3 -3
- package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -1
- package/dist/components/retrieval/graph/graph-node-renderer.js +1 -1
- package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.class.d.ts +16 -1
- package/dist/components/utility/json-viewer/json-viewer.class.js +4 -4
- package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
- package/dist/components/utility/known-date/known-date.class.js +1 -1
- package/dist/components/utility/mention-popover/mention-popover.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/csv-viewer/csv-viewer.class.js +1 -1
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +1 -1
- package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/components/viewers/include/include.class.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
- package/dist/components/viewers/table-viewer-shared.js +4 -4
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/anchored-overlay-runtime.js +1 -1
- package/dist/internal/catalog-picker.js +1 -1
- package/dist/internal/document-tokens.js +2 -2
- package/dist/internal/drop-session-controller.js +1 -1
- package/dist/internal/engine-3d.js +1 -1
- package/dist/internal/icon-only-content.js +1 -1
- package/dist/internal/layered-layout.js +1 -1
- package/dist/internal/map-custom-layer-controller.js +1 -1
- package/dist/internal/media-panorama.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/safe-url.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/internal/scroll-overflow.js +1 -1
- package/dist/internal/source-window-controller.js +1 -1
- package/dist/internal/text-quote.js +1 -1
- package/dist/internal/viewer-search.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/sequence-time-binding.js +1 -1
- package/dist/simulation-clock.js +1 -1
- package/dist/styles/reservations.css +1 -1
- package/dist/styles/reservations.styles.js +1 -1
- package/dist/testing/happy-dom-shims.js +1 -1
- package/dist/theme/theme.js +1 -1
- package/llms/components/lr-attachment-chip.md +27 -12
- package/llms/components/lr-attachment-trigger.md +27 -7
- package/llms/components/lr-button.md +6 -4
- package/llms/components/lr-chat-composer.md +13 -7
- package/llms/components/lr-chat-message.md +44 -3
- package/llms/components/lr-chat-viewport.md +39 -2
- package/llms/components/lr-data-grid.md +2 -0
- package/llms/components/lr-dialog.md +10 -0
- package/llms/components/lr-drop-zone.md +26 -2
- package/llms/components/lr-icon-button.md +2 -1
- package/llms/components/lr-json-viewer.md +17 -0
- package/llms/components/lr-locale-picker.md +5 -0
- package/llms/components/lr-markdown-core.md +2 -1
- package/llms/components/lr-markdown.md +20 -4
- package/llms/components/lr-menu.md +3 -1
- package/llms/components/lr-number-input.md +28 -1
- package/llms/components/lr-prompt-input.md +1 -1
- package/llms/components/lr-streaming-text-core.md +3 -2
- package/llms/components/lr-streaming-text.md +4 -1
- package/llms/components/lr-suggestion-chips.md +28 -5
- package/llms/components/lr-tab-group.md +13 -1
- package/llms/components/lr-tab.md +5 -0
- package/llms/components/lr-table.md +25 -4
- package/llms/components/lr-timeline-item.md +1 -1
- package/llms/components/lr-timeline.md +38 -4
- package/llms/components/lr-tooltip.md +3 -1
- package/llms/components/lr-tree.md +4 -0
- package/llms/components/lr-virtual-list.md +1 -0
- package/llms/peers.md +2 -2
- package/llms/shared/forms-and-accessibility.md +21 -4
- package/llms/shared.md +21 -4
- package/package.json +21 -20
- package/registrations.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applySharedStatePatch,parseJsonPatch}from"../runtime.js";import{positiveInteger}from"../../internal/numbers.js";import{createProviderSnapshotBudget,resolveProviderSnapshotLimits,snapshotProviderValue}from"../snapshot.js";const DEFAULT_AG_UI_ADAPTER_LIMITS=Object.freeze({...resolveProviderSnapshotLimits(),maxBufferedTools:256,maxBufferedMessages:512,maxToolArgumentBytes:262144,maxTextDeltaCharacters:32768}),encoder=new TextEncoder;function resolveLimits(limits){return Object.freeze({...resolveProviderSnapshotLimits(limits),maxBufferedTools:positiveInteger(limits.maxBufferedTools,DEFAULT_AG_UI_ADAPTER_LIMITS.maxBufferedTools),maxBufferedMessages:positiveInteger(limits.maxBufferedMessages,DEFAULT_AG_UI_ADAPTER_LIMITS.maxBufferedMessages),maxToolArgumentBytes:positiveInteger(limits.maxToolArgumentBytes,DEFAULT_AG_UI_ADAPTER_LIMITS.maxToolArgumentBytes),maxTextDeltaCharacters:positiveInteger(limits.maxTextDeltaCharacters,DEFAULT_AG_UI_ADAPTER_LIMITS.maxTextDeltaCharacters)})}function record(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function safeType(value){if(record(value))try{const descriptor=Object.getOwnPropertyDescriptor(value,"type");return descriptor&&"value"in descriptor&&typeof descriptor.value=="string"?descriptor.value:void 0}catch{return}}function role(value){return value==="user"||value==="system"?value:"assistant"}function objectArgs(text,limits){try{const parsed=JSON.parse(text),owned=snapshotProviderValue(parsed,createProviderSnapshotBudget(limits));return owned.ok?record(owned.value):null}catch{return null}}function snapshotMessage(value,index){const source=record(value);if(!source)return null;const id=typeof source.id=="string"?source.id:`snapshot-${index}`,content=typeof source.content=="string"?source.content:"";if(source.role==="activity")return typeof source.activityType!="string"||!source.activityType||!record(source.content)?null:{id,role:"assistant",status:"sent",parts:[{id:`${id}:activity`,type:"data",name:source.activityType,data:source.content,state:"complete"}]};const partType=source.role==="reasoning"?"reasoning":"text";return{id,role:role(source.role),status:"sent",parts:content?[{id:`${id}:${partType}`,type:partType,text:content,state:"complete"}]:[]}}class AgUiStreamAdapter{constructor(limits={},options={}){this.tools=new Map,this.messages=new Map,this.activities=new Map,this.activityBytes=0,this.generation=0,this.sequence=0,this.limits=resolveLimits(limits),this.customEventTarget=options.customEventTarget}get bufferedToolCount(){return this.tools.size}reset(){return this.clearBuffers(),this.generation+=1,this.sequence=0,this.emit({type:"reset"})}clearBuffers(){this.tools.clear(),this.messages.clear(),this.activities.clear(),this.activityBytes=0}claimMessage(messageId,kind){const previous=this.messages.get(messageId);return previous&&kind==="custom"?null:previous==="custom"&&kind!=="activity"?(this.messages.set(messageId,kind),null):previous&&previous!==kind?[]:!previous&&this.messages.size>=this.limits.maxBufferedMessages?this.failure("Buffered message count exceeds the configured adapter limit.","stream_limit_exceeded"):(this.messages.set(messageId,kind),null)}activity(messageId,activityType,content,eventId){const snapshot=snapshotProviderValue(content,createProviderSnapshotBudget(this.limits));if(!snapshot.ok)return this.failure("Activity content exceeds the configured adapter limit.","stream_limit_exceeded");const data=record(snapshot.value);if(!data)return[];const previous=this.activities.get(messageId),bytes=this.activityBytes-(previous?.bytes??0)+snapshot.bytes;if(bytes>this.limits.maxBytes)return this.failure("Buffered activity content exceeds the configured adapter limit.","stream_limit_exceeded");const rejected=this.claimMessage(messageId,"activity");return rejected||(this.activities.set(messageId,{activityType,content:data,bytes:snapshot.bytes}),this.activityBytes=bytes,[this.emit({type:"message-part-upsert",messageId,role:"assistant",part:{id:`${messageId}:activity`,type:"data",name:activityType,data:content,state:"complete"}},eventId)])}emit(event,eventId,suffix){this.sequence+=1;const correlatedId=eventId&&suffix?`${eventId}:${suffix}`:eventId;return{...event,generation:this.generation,sequence:this.sequence,...correlatedId?{eventId:correlatedId}:{}}}failure(message,code){return[this.emit({type:"error",message,code})]}toolInvocation(toolCallId,status){const buffer=this.tools.get(toolCallId)??{name:"tool",argsText:"",argsBytes:0,args:{}};return{id:toolCallId,name:buffer.name,args:buffer.args,status}}push(event){const eventType=safeType(event);if(!eventType)return[];const owned=snapshotProviderValue(event,createProviderSnapshotBudget(this.limits));if(!owned.ok)return this.failure(owned.failure==="limit"?"Provider event exceeds the configured adapter limit.":"Provider event is not serializable data.",owned.failure==="limit"?"stream_limit_exceeded":"invalid_provider_event");const source=record(owned.value);if(!source||source.type!==eventType)return[];const eventId=typeof source.eventId=="string"?source.eventId:void 0;switch(eventType){case"RUN_STARTED":return typeof source.runId!="string"||!source.runId?[]:(this.clearBuffers(),this.generation+=1,this.sequence=0,[this.emit({type:"run-start",runId:source.runId},eventId)]);case"RUN_FINISHED":{if(source.runId!==void 0&&typeof source.runId!="string")return[];const output=this.emit({type:"run-status",...source.runId?{runId:source.runId}:{},status:{kind:"done"}},eventId);return this.clearBuffers(),[output]}case"RUN_ERROR":{if(source.message!==void 0&&typeof source.message!="string")return[];if(source.code!==void 0&&typeof source.code!="string")return[];if(source.runId!==void 0&&typeof source.runId!="string")return[];const message=source.message??"Agent run failed",code=source.code,output=[this.emit({type:"error",message,...code?{code}:{}},eventId,"error"),this.emit({type:"run-status",...source.runId?{runId:source.runId}:{},status:{kind:"error",message}},eventId,"status")];return this.clearBuffers(),output}case"TEXT_MESSAGE_START":case"REASONING_MESSAGE_START":{if(typeof source.messageId!="string"||!source.messageId)return[];const reasoning=eventType==="REASONING_MESSAGE_START",rejected=this.claimMessage(source.messageId,reasoning?"reasoning":"text");return rejected||[this.emit({type:"message-start",message:{id:source.messageId,role:reasoning?"assistant":role(source.role),status:"streaming",parts:[]}},eventId)]}case"TEXT_MESSAGE_CONTENT":case"REASONING_MESSAGE_CONTENT":{if(typeof source.messageId!="string"||!source.messageId||typeof source.delta!="string")return[];if(source.delta.length>this.limits.maxTextDeltaCharacters)return this.failure("Text delta exceeds the configured adapter limit.","stream_limit_exceeded");const partType=eventType==="REASONING_MESSAGE_CONTENT"?"reasoning":"text",rejected=this.claimMessage(source.messageId,partType);return rejected||[this.emit({type:"message-part-delta",messageId:source.messageId,role:partType==="reasoning"?"assistant":role(source.role),partId:`${source.messageId}:${partType}`,partType,delta:source.delta},eventId)]}case"TEXT_MESSAGE_END":case"REASONING_MESSAGE_END":return typeof source.messageId!="string"||!source.messageId?[]:this.claimMessage(source.messageId,eventType==="REASONING_MESSAGE_END"?"reasoning":"text")??[this.emit({type:"message-complete",messageId:source.messageId},eventId)];case"TOOL_CALL_START":return typeof source.toolCallId!="string"?[]:!this.tools.has(source.toolCallId)&&this.tools.size>=this.limits.maxBufferedTools?this.failure("Buffered tool count exceeds the configured adapter limit.","stream_limit_exceeded"):source.toolCallName!==void 0&&typeof source.toolCallName!="string"?[]:(this.tools.set(source.toolCallId,{name:source.toolCallName??"tool",argsText:"",argsBytes:0,args:{}}),[this.emit({type:"tool-upsert",invocation:this.toolInvocation(source.toolCallId,"running")},eventId)]);case"TOOL_CALL_ARGS":{if(typeof source.toolCallId!="string"||typeof source.delta!="string")return[];let buffer=this.tools.get(source.toolCallId);if(!buffer){if(this.tools.size>=this.limits.maxBufferedTools)return this.failure("Buffered tool count exceeds the configured adapter limit.","stream_limit_exceeded");buffer={name:"tool",argsText:"",argsBytes:0,args:{}}}const deltaBytes=encoder.encode(source.delta).byteLength;return deltaBytes>this.limits.maxToolArgumentBytes-buffer.argsBytes?(this.tools.delete(source.toolCallId),this.failure("Tool arguments exceed the configured adapter limit.","stream_limit_exceeded")):(buffer.argsText+=source.delta,buffer.argsBytes+=deltaBytes,buffer.args=objectArgs(buffer.argsText,this.limits)??buffer.args,this.tools.set(source.toolCallId,buffer),[this.emit({type:"tool-upsert",invocation:this.toolInvocation(source.toolCallId,"running")},eventId)])}case"TOOL_CALL_END":{if(typeof source.toolCallId!="string")return[];const invocation=this.toolInvocation(source.toolCallId,"running"),buffer=this.tools.get(source.toolCallId);return buffer&&(buffer.argsText="",buffer.argsBytes=0),[this.emit({type:"tool-upsert",invocation},eventId)]}case"TOOL_CALL_RESULT":{if(typeof source.toolCallId!="string")return[];const invocation={...this.toolInvocation(source.toolCallId,"success"),...Object.hasOwn(source,"result")?{result:source.result}:{}};return this.tools.delete(source.toolCallId),[this.emit({type:"tool-upsert",invocation},eventId)]}case"STATE_SNAPSHOT":return Object.hasOwn(source,"snapshot")?[this.emit({type:"state-snapshot",snapshot:source.snapshot},eventId)]:[];case"STATE_DELTA":{const patch=parseJsonPatch(source.delta);return patch?[this.emit({type:"state-delta",patch},eventId)]:[]}case"ACTIVITY_SNAPSHOT":return typeof source.messageId!="string"||!source.messageId||typeof source.activityType!="string"||!source.activityType||!record(source.content)||source.replace!==void 0&&typeof source.replace!="boolean"?[]:source.replace===!1&&this.messages.has(source.messageId)?[]:this.activity(source.messageId,source.activityType,source.content,eventId);case"ACTIVITY_DELTA":{if(typeof source.messageId!="string"||typeof source.activityType!="string")return[];const previous=this.activities.get(source.messageId);if(!previous||previous.activityType!==source.activityType)return[];const patch=parseJsonPatch(source.patch);return patch?this.activity(source.messageId,source.activityType,applySharedStatePatch(previous.content,patch),eventId):[]}case"CUSTOM":{if(!this.customEventTarget||typeof source.name!="string"||!source.name||!Object.hasOwn(source,"value"))return[];let target;try{target=this.customEventTarget({name:source.name,value:source.value})}catch{return this.failure("Custom event routing failed.","invalid_provider_event")}if(target===null)return[];const ownedTarget=snapshotProviderValue(target,createProviderSnapshotBudget(this.limits)),destination=ownedTarget.ok?record(ownedTarget.value):null;if(!destination||typeof destination.messageId!="string"||!destination.messageId||typeof destination.partId!="string"||!destination.partId)return[];const value=snapshotProviderValue(source.value,createProviderSnapshotBudget(this.limits));if(!value.ok)return this.failure("Custom event payload is invalid or exceeds the configured adapter limit.",value.failure==="limit"?"stream_limit_exceeded":"invalid_provider_event");const rejected=this.claimMessage(destination.messageId,"custom");return rejected||[this.emit({type:"message-part-upsert",messageId:destination.messageId,role:"assistant",part:{id:destination.partId,type:"data",name:source.name,data:value.value,state:"complete"}},eventId)]}case"MESSAGES_SNAPSHOT":{if(source.messages!==void 0&&!Array.isArray(source.messages))return[];const messages=(source.messages??[]).map(snapshotMessage).filter(message=>message!==null);if(messages.length>this.limits.maxBufferedMessages)return this.failure("Buffered message count exceeds the configured adapter limit.","stream_limit_exceeded");const activities=new Map,kinds=new Map;let bytes=0;for(const message of messages){const part=message.parts?.[0];if(kinds.set(message.id,part?.type==="data"?"activity":part?.type==="reasoning"?"reasoning":"text"),part?.type!=="data"||!part.name)continue;const ownedContent=snapshotProviderValue(part.data,createProviderSnapshotBudget(this.limits));if(!ownedContent.ok||bytes+ownedContent.bytes>this.limits.maxBytes)return this.failure("Buffered activity content exceeds the configured adapter limit.","stream_limit_exceeded");activities.set(message.id,{activityType:part.name,content:ownedContent.value,bytes:ownedContent.bytes}),bytes+=ownedContent.bytes}this.messages.clear(),this.activities.clear();for(const[id,kind]of kinds)this.messages.set(id,kind);for(const[id,activity]of activities)this.activities.set(id,activity);return this.activityBytes=bytes,[this.emit({type:"messages-snapshot",messages},eventId)]}default:return[]}}}export{AgUiStreamAdapter,DEFAULT_AG_UI_ADAPTER_LIMITS};
|
|
1
|
+
import{applySharedStatePatch,parseJsonPatch}from"../runtime.js";import{positiveInteger}from"../../internal/numbers.js";import{createProviderSnapshotBudget,resolveProviderSnapshotLimits,snapshotProviderValue}from"../snapshot.js";const DEFAULT_AG_UI_ADAPTER_LIMITS=Object.freeze({...resolveProviderSnapshotLimits(),maxBufferedTools:256,maxBufferedMessages:512,maxToolArgumentBytes:262144,maxTextDeltaCharacters:32768}),encoder=new TextEncoder;function resolveLimits(limits){return Object.freeze({...resolveProviderSnapshotLimits(limits),maxBufferedTools:positiveInteger(limits.maxBufferedTools,DEFAULT_AG_UI_ADAPTER_LIMITS.maxBufferedTools),maxBufferedMessages:positiveInteger(limits.maxBufferedMessages,DEFAULT_AG_UI_ADAPTER_LIMITS.maxBufferedMessages),maxToolArgumentBytes:positiveInteger(limits.maxToolArgumentBytes,DEFAULT_AG_UI_ADAPTER_LIMITS.maxToolArgumentBytes),maxTextDeltaCharacters:positiveInteger(limits.maxTextDeltaCharacters,DEFAULT_AG_UI_ADAPTER_LIMITS.maxTextDeltaCharacters)})}function record(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function safeType(value){if(record(value))try{const descriptor=Object.getOwnPropertyDescriptor(value,"type");return descriptor&&"value"in descriptor&&typeof descriptor.value=="string"?descriptor.value:void 0}catch{return}}function role(value){return value==="user"||value==="system"?value:"assistant"}function objectArgs(text,limits){try{const parsed=JSON.parse(text),owned=snapshotProviderValue(parsed,createProviderSnapshotBudget(limits));return owned.ok?record(owned.value):null}catch{return null}}function snapshotMessage(value,index){const source=record(value);if(!source)return null;const id=typeof source.id=="string"?source.id:`snapshot-${index}`,content=typeof source.content=="string"?source.content:"";if(source.role==="activity")return typeof source.activityType!="string"||!source.activityType||!record(source.content)?null:{id,role:"assistant",status:"sent",parts:[{id:`${id}:activity`,type:"data",name:source.activityType,data:source.content,state:"complete"}]};const partType=source.role==="reasoning"?"reasoning":"text";return{id,role:role(source.role),status:"sent",parts:content?[{id:`${id}:${partType}`,type:partType,text:content,state:"complete"}]:[]}}class AgUiStreamAdapter{constructor(limits={},options={}){this.tools=new Map,this.messages=new Map,this.activities=new Map,this.activityBytes=0,this.generation=0,this.sequence=0,this.limits=resolveLimits(limits),this.customEventTarget=options.customEventTarget}get bufferedToolCount(){return this.tools.size}reset(){return this.clearBuffers(),this.generation+=1,this.sequence=0,this.emit({type:"reset"})}clearBuffers(){this.tools.clear(),this.messages.clear(),this.activities.clear(),this.activityBytes=0}claimMessage(messageId,kind){const previous=this.messages.get(messageId);return previous&&kind==="custom"?null:previous==="custom"&&kind!=="activity"?(this.messages.set(messageId,kind),null):previous&&previous!==kind?[]:!previous&&this.messages.size>=this.limits.maxBufferedMessages?this.failure("Buffered message count exceeds the configured adapter limit.","stream_limit_exceeded"):(this.messages.set(messageId,kind),null)}activity(messageId,activityType,content,eventId){const snapshot=snapshotProviderValue(content,createProviderSnapshotBudget(this.limits));if(!snapshot.ok)return this.failure("Activity content exceeds the configured adapter limit.","stream_limit_exceeded");const data=record(snapshot.value);if(!data)return[];const previous=this.activities.get(messageId),bytes=this.activityBytes-(previous?.bytes??0)+snapshot.bytes;if(bytes>this.limits.maxBytes)return this.failure("Buffered activity content exceeds the configured adapter limit.","stream_limit_exceeded");const rejected=this.claimMessage(messageId,"activity");return rejected||(this.activities.set(messageId,{activityType,content:data,bytes:snapshot.bytes}),this.activityBytes=bytes,[this.emit({type:"message-part-upsert",messageId,role:"assistant",part:{id:`${messageId}:activity`,type:"data",name:activityType,data:content,state:"complete"}},eventId)])}emit(event,eventId,suffix){this.sequence+=1;const correlatedId=eventId&&suffix?`${eventId}:${suffix}`:eventId;return{...event,generation:this.generation,sequence:this.sequence,...correlatedId?{eventId:correlatedId}:{}}}failure(message,code){return[this.emit({type:"error",message,code})]}toolInvocation(toolCallId,status){const buffer=this.tools.get(toolCallId)??{name:"tool",argsText:"",argsBytes:0,args:{}};return{id:toolCallId,name:buffer.name,args:buffer.args,status}}push(event){const eventType=safeType(event);if(!eventType)return[];const owned=snapshotProviderValue(event,createProviderSnapshotBudget(this.limits));if(!owned.ok)return this.failure(owned.failure==="limit"?"Provider event exceeds the configured adapter limit.":"Provider event is not serializable data.",owned.failure==="limit"?"stream_limit_exceeded":"invalid_provider_event");const source=record(owned.value);if(!source||source.type!==eventType)return[];const eventId=typeof source.eventId=="string"?source.eventId:void 0;switch(eventType){case"RUN_STARTED":return typeof source.runId!="string"||!source.runId?[]:(this.clearBuffers(),this.generation+=1,this.sequence=0,[this.emit({type:"run-start",runId:source.runId},eventId)]);case"RUN_FINISHED":{if(source.runId!==void 0&&typeof source.runId!="string")return[];const output=this.emit({type:"run-status",...source.runId?{runId:source.runId}:{},status:{kind:"done"}},eventId);return this.clearBuffers(),[output]}case"RUN_ERROR":{if(source.message!==void 0&&typeof source.message!="string")return[];if(source.code!==void 0&&typeof source.code!="string")return[];if(source.runId!==void 0&&typeof source.runId!="string")return[];const message=source.message??"Agent run failed",code=source.code,output=[this.emit({type:"error",message,...code?{code}:{}},eventId,"error"),this.emit({type:"run-status",...source.runId?{runId:source.runId}:{},status:{kind:"error",message}},eventId,"status")];return this.clearBuffers(),output}case"TEXT_MESSAGE_START":case"REASONING_MESSAGE_START":{if(typeof source.messageId!="string"||!source.messageId)return[];const reasoning=eventType==="REASONING_MESSAGE_START",preserveCustomParts=this.messages.get(source.messageId)==="custom",rejected=this.claimMessage(source.messageId,reasoning?"reasoning":"text");return rejected||[this.emit({type:"message-start",message:{id:source.messageId,role:reasoning?"assistant":role(source.role),status:"streaming",...preserveCustomParts?{}:{parts:[]}}},eventId)]}case"TEXT_MESSAGE_CONTENT":case"REASONING_MESSAGE_CONTENT":{if(typeof source.messageId!="string"||!source.messageId||typeof source.delta!="string")return[];if(source.delta.length>this.limits.maxTextDeltaCharacters)return this.failure("Text delta exceeds the configured adapter limit.","stream_limit_exceeded");const partType=eventType==="REASONING_MESSAGE_CONTENT"?"reasoning":"text",rejected=this.claimMessage(source.messageId,partType);return rejected||[this.emit({type:"message-part-delta",messageId:source.messageId,role:partType==="reasoning"?"assistant":role(source.role),partId:`${source.messageId}:${partType}`,partType,delta:source.delta},eventId)]}case"TEXT_MESSAGE_END":case"REASONING_MESSAGE_END":return typeof source.messageId!="string"||!source.messageId?[]:this.claimMessage(source.messageId,eventType==="REASONING_MESSAGE_END"?"reasoning":"text")??[this.emit({type:"message-complete",messageId:source.messageId},eventId)];case"TOOL_CALL_START":return typeof source.toolCallId!="string"?[]:!this.tools.has(source.toolCallId)&&this.tools.size>=this.limits.maxBufferedTools?this.failure("Buffered tool count exceeds the configured adapter limit.","stream_limit_exceeded"):source.toolCallName!==void 0&&typeof source.toolCallName!="string"?[]:(this.tools.set(source.toolCallId,{name:source.toolCallName??"tool",argsText:"",argsBytes:0,args:{}}),[this.emit({type:"tool-upsert",invocation:this.toolInvocation(source.toolCallId,"running")},eventId)]);case"TOOL_CALL_ARGS":{if(typeof source.toolCallId!="string"||typeof source.delta!="string")return[];let buffer=this.tools.get(source.toolCallId);if(!buffer){if(this.tools.size>=this.limits.maxBufferedTools)return this.failure("Buffered tool count exceeds the configured adapter limit.","stream_limit_exceeded");buffer={name:"tool",argsText:"",argsBytes:0,args:{}}}const deltaBytes=encoder.encode(source.delta).byteLength;return deltaBytes>this.limits.maxToolArgumentBytes-buffer.argsBytes?(this.tools.delete(source.toolCallId),this.failure("Tool arguments exceed the configured adapter limit.","stream_limit_exceeded")):(buffer.argsText+=source.delta,buffer.argsBytes+=deltaBytes,buffer.args=objectArgs(buffer.argsText,this.limits)??buffer.args,this.tools.set(source.toolCallId,buffer),[this.emit({type:"tool-upsert",invocation:this.toolInvocation(source.toolCallId,"running")},eventId)])}case"TOOL_CALL_END":{if(typeof source.toolCallId!="string")return[];const invocation=this.toolInvocation(source.toolCallId,"running"),buffer=this.tools.get(source.toolCallId);return buffer&&(buffer.argsText="",buffer.argsBytes=0),[this.emit({type:"tool-upsert",invocation},eventId)]}case"TOOL_CALL_RESULT":{if(typeof source.toolCallId!="string")return[];const invocation={...this.toolInvocation(source.toolCallId,"success"),...Object.hasOwn(source,"result")?{result:source.result}:{}};return this.tools.delete(source.toolCallId),[this.emit({type:"tool-upsert",invocation},eventId)]}case"STATE_SNAPSHOT":return Object.hasOwn(source,"snapshot")?[this.emit({type:"state-snapshot",snapshot:source.snapshot},eventId)]:[];case"STATE_DELTA":{const patch=parseJsonPatch(source.delta);return patch?[this.emit({type:"state-delta",patch},eventId)]:[]}case"ACTIVITY_SNAPSHOT":return typeof source.messageId!="string"||!source.messageId||typeof source.activityType!="string"||!source.activityType||!record(source.content)||source.replace!==void 0&&typeof source.replace!="boolean"?[]:source.replace===!1&&this.messages.has(source.messageId)?[]:this.activity(source.messageId,source.activityType,source.content,eventId);case"ACTIVITY_DELTA":{if(typeof source.messageId!="string"||typeof source.activityType!="string")return[];const previous=this.activities.get(source.messageId);if(!previous||previous.activityType!==source.activityType)return[];const patch=parseJsonPatch(source.patch);return patch?this.activity(source.messageId,source.activityType,applySharedStatePatch(previous.content,patch),eventId):[]}case"CUSTOM":{if(!this.customEventTarget||typeof source.name!="string"||!source.name||!Object.hasOwn(source,"value"))return[];let target;try{target=this.customEventTarget({name:source.name,value:source.value})}catch{return this.failure("Custom event routing failed.","invalid_provider_event")}if(target===null)return[];const ownedTarget=snapshotProviderValue(target,createProviderSnapshotBudget(this.limits)),destination=ownedTarget.ok?record(ownedTarget.value):null;if(!destination||typeof destination.messageId!="string"||!destination.messageId||typeof destination.partId!="string"||!destination.partId)return[];const value=snapshotProviderValue(source.value,createProviderSnapshotBudget(this.limits));if(!value.ok)return this.failure("Custom event payload is invalid or exceeds the configured adapter limit.",value.failure==="limit"?"stream_limit_exceeded":"invalid_provider_event");const rejected=this.claimMessage(destination.messageId,"custom");return rejected||[this.emit({type:"message-part-upsert",messageId:destination.messageId,role:"assistant",part:{id:destination.partId,type:"data",name:source.name,data:value.value,state:"complete"}},eventId)]}case"MESSAGES_SNAPSHOT":{if(source.messages!==void 0&&!Array.isArray(source.messages))return[];const messages=(source.messages??[]).map(snapshotMessage).filter(message=>message!==null);if(messages.length>this.limits.maxBufferedMessages)return this.failure("Buffered message count exceeds the configured adapter limit.","stream_limit_exceeded");const activities=new Map,kinds=new Map;let bytes=0;for(const message of messages){const part=message.parts?.[0];if(kinds.set(message.id,part?.type==="data"?"activity":part?.type==="reasoning"?"reasoning":"text"),part?.type!=="data"||!part.name)continue;const ownedContent=snapshotProviderValue(part.data,createProviderSnapshotBudget(this.limits));if(!ownedContent.ok||bytes+ownedContent.bytes>this.limits.maxBytes)return this.failure("Buffered activity content exceeds the configured adapter limit.","stream_limit_exceeded");activities.set(message.id,{activityType:part.name,content:ownedContent.value,bytes:ownedContent.bytes}),bytes+=ownedContent.bytes}this.messages.clear(),this.activities.clear();for(const[id,kind]of kinds)this.messages.set(id,kind);for(const[id,activity]of activities)this.activities.set(id,activity);return this.activityBytes=bytes,[this.emit({type:"messages-snapshot",messages},eventId)]}default:return[]}}}export{AgUiStreamAdapter,DEFAULT_AG_UI_ADAPTER_LIMITS};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{applyComposedFocusRepair,captureComposedFocusRepair,repairComposedFocus}from"../../../internal/focus-navigation.js";import{chevronIcon}from"../../../internal/icons.js";import{formatTimeOfDay,getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{styles}from"./activity-feed.styles.js";import{literalSetConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{firstByIdentityMemo}from"../collection-identity.js";import{LYRA_DEFAULT_activityFeedCompletedSteps,LYRA_DEFAULT_activityFeedInputLimit,LYRA_DEFAULT_activityFeedLabel}from"../../../internal/default-strings/agent-tools.generated.js";const ACTIVITY_FEED_MODE=literalSetConverter(["live","post-hoc"],"live"),NEAR_BOTTOM_PX=48,entryId=entry=>entry.id;function variantDotPart(variant){return variant==="brand"?"variant-dot variant-dot-brand":variant==="success"?"variant-dot variant-dot-success":variant==="warning"?"variant-dot variant-dot-warning":variant==="danger"?"variant-dot variant-dot-danger":"variant-dot variant-dot-neutral"}class LyraActivityFeed extends LyraElement{constructor(){super(...arguments),this.entries=[],this._mode="live",this.follow=!0,this.expanded=!1,this.size="m",this.frame="card",this.withTimestamps=!1,this.virtualizeAt=199,this.headerId=nextId("activity-feed-header"),this.bodyId=nextId("activity-feed-body"),this.activityEntryKey=item=>item.id,this.isMounting=!0,this.anchoringVirtualTail=!1,this.ownerRealmGeneration=0,this.virtualAnchorRequest=0,this.relationshipSyncRequest=0,this.entryFocusRepairRequest=0,this.explicitRowRefresh=!1,this.toggle=()=>{const expanded=!this.expanded;this.emit("lr-toggle-request",{expanded},{cancelable:!0}).defaultPrevented||(this.expanded=expanded,this.emit("lr-toggle",{expanded}))},this.onBodyScroll=e=>{if(this.isVirtualized||this.mode!=="live")return;const body=e.currentTarget,nearBottom=body.scrollHeight-body.scrollTop-body.clientHeight<=NEAR_BOTTOM_PX;this.setFollowFromUser(nearBottom)},this.onVirtualListRangeChanged=e=>{if(e.stopPropagation(),this.mode!=="live"||this.anchoringVirtualTail)return;const entries=this.normalizedEntries,atBottom=entries.length>0&&e.detail.end>=entries.length-1;this.setFollowFromUser(atBottom)},this.stopOwnedEvent=event=>{event.stopPropagation()},this.renderEntry=item=>this.entryTemplate(item,!1),this.lastInputNotice=""}static{this.defaultStrings={...super.defaultStrings,activityFeedCompletedSteps:LYRA_DEFAULT_activityFeedCompletedSteps,activityFeedInputLimit:LYRA_DEFAULT_activityFeedInputLimit,activityFeedLabel:LYRA_DEFAULT_activityFeedLabel}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["entries"])}static{this.appendOrderedCollectionProperties=Object.freeze(["entries"])}static{this.identityCollectionProperties=Object.freeze(["entries"])}static{this.styles=[LyraElement.styles,styles]}get mode(){return this._mode}set mode(next){const normalized=ACTIVITY_FEED_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.syncListRelationships(),this.scheduleListRelationshipSync()),this.hasUpdated&&this.shouldFollowLiveTail&&this.scrollToLatest()}disconnectedCallback(){this.releaseListRelationships(),this.resetOwnerRealmWork(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseListRelationships(),this.resetOwnerRealmWork(),this.isConnected&&this.hasUpdated&&(this.syncListRelationships(),this.scheduleListRelationshipSync()),this.isConnected&&this.shouldFollowLiveTail&&this.scrollToLatest()}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,199)}get normalizedEntries(){return firstByIdentityMemo(Array.isArray(this.entries)?this.entries:[],entryId)}get isVirtualized(){return this.normalizedEntries.length>this.effectiveVirtualizeAt}get shouldFollowLiveTail(){return this.expanded&&this.mode==="live"&&this.follow}cancelScrollFrame(){this.scrollRafId!==void 0&&this.scrollRafOwner?.cancelAnimationFrame(this.scrollRafId),this.scrollRafId=void 0,this.scrollRafOwner=void 0,this.scrollRafDocument=void 0}cancelVirtualAnchorReleaseFrame(){this.virtualAnchorReleaseRafId!==void 0&&this.virtualAnchorReleaseRafOwner?.cancelAnimationFrame(this.virtualAnchorReleaseRafId),this.virtualAnchorReleaseRafId=void 0,this.virtualAnchorReleaseRafOwner=void 0,this.virtualAnchorReleaseRafDocument=void 0}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.virtualAnchorRequest+=1,this.relationshipSyncRequest+=1,this.entryFocusRepairRequest+=1,this.pendingEntryFocusRepair=void 0,this.cancelScrollFrame(),this.cancelVirtualAnchorReleaseFrame(),this.anchoringVirtualTail=!1}willUpdate(changed){super.willUpdate(changed),(changed.has("expanded")||changed.has("mode"))&&this.expanded&&this.mode==="live"&&(this.follow=!0),changed.has("expanded")&&changed.get("expanded")===!0&&!this.expanded&&this.repairFocusOnCollapse(),changed.has("entries")&&this.captureEntryFocusRepair()}requestUpdate(...args){args[0]===void 0&&(this.explicitRowRefresh=!0),super.requestUpdate(...args)}updated(changed){super.updated(changed);const explicitRefresh=this.explicitRowRefresh;this.explicitRowRefresh=!1,(explicitRefresh||["withTimestamps","formatTimestamp","renderText","locale","strings"].some(name=>changed.has(name)))&&this.virtualListEl?.requestUpdate(),this.syncListRelationships(),this.scheduleListRelationshipSync();const wasMounting=this.isMounting;this.isMounting=!1;const inputNotice=this.inputLimitMessage();if(!wasMounting&&inputNotice&&inputNotice!==this.lastInputNotice&&this.liveRegion?.announce(inputNotice,{force:!0}),this.lastInputNotice=inputNotice,!wasMounting&&changed.has("mode")&&changed.get("mode")==="live"&&this.mode==="post-hoc"){const region=this.liveRegion;region&&(region.mode="polite",region.announce(this.completedStepsSummary(this.normalizedEntries.length),{force:!0}))}const justAnchored=(changed.has("expanded")||changed.has("mode"))&&this.expanded&&this.mode==="live",followingChangedRenderPath=changed.has("virtualizeAt")&&this.expanded&&this.mode==="live"&&this.follow;(justAnchored||followingChangedRenderPath||changed.has("entries")&&this.expanded&&this.mode==="live"&&this.follow)&&this.scrollToLatest(),changed.has("entries")&&this.pendingEntryFocusRepair&&this.settleEntryFocusRepair()}get headerElement(){return this.hasUpdated?this.renderRoot?.querySelector('[part="header"]')??null:null}repairFocusOnCollapse(){repairComposedFocus(this,()=>this.headerElement)}captureEntryFocusRepair(){this.pendingEntryFocusRepair=captureComposedFocusRepair(this,this.headerElement)??void 0}settleEntryFocusRepair(){const pending=this.pendingEntryFocusRepair;if(this.pendingEntryFocusRepair=void 0,!pending)return;const request=++this.entryFocusRepairRequest,generation=this.ownerRealmGeneration,settle=()=>{request!==this.entryFocusRepairRequest||generation!==this.ownerRealmGeneration||!this.isConnected||pending.activeElement.isConnected||applyComposedFocusRepair(pending,()=>this.headerElement)},list=this.virtualListEl;list?list.updateComplete.then(settle):settle()}scrollToLatest(){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected||!this.shouldFollowLiveTail)return;const generation=this.ownerRealmGeneration;if(this.isVirtualized){this.cancelScrollFrame(),this.cancelVirtualAnchorReleaseFrame(),this.anchoringVirtualTail=!0;const request=++this.virtualAnchorRequest;this.updateComplete.then(()=>{const list=this.virtualListEl;if(request!==this.virtualAnchorRequest||generation!==this.ownerRealmGeneration||this.ownerDocument!==ownerDocument||!this.isConnected)return;if(!list||!this.isVirtualized||!this.shouldFollowLiveTail){this.anchoringVirtualTail=!1;return}list.scrollToIndex(this.normalizedEntries.length-1,{align:"end",behavior:"auto"});const firstHandle=ownerWindow.requestAnimationFrame(()=>{if(this.virtualAnchorReleaseRafId!==firstHandle||this.virtualAnchorReleaseRafOwner!==ownerWindow||this.virtualAnchorReleaseRafDocument!==ownerDocument||request!==this.virtualAnchorRequest||generation!==this.ownerRealmGeneration||!this.isConnected||this.ownerDocument!==ownerDocument)return;if(this.virtualAnchorReleaseRafId=void 0,this.virtualAnchorReleaseRafOwner=void 0,this.virtualAnchorReleaseRafDocument=void 0,!this.anchoringVirtualTail||!this.isVirtualized||!this.shouldFollowLiveTail){this.anchoringVirtualTail=!1;return}const secondHandle=ownerWindow.requestAnimationFrame(()=>{this.virtualAnchorReleaseRafId!==secondHandle||this.virtualAnchorReleaseRafOwner!==ownerWindow||this.virtualAnchorReleaseRafDocument!==ownerDocument||request!==this.virtualAnchorRequest||generation!==this.ownerRealmGeneration||!this.isConnected||this.ownerDocument!==ownerDocument||(this.virtualAnchorReleaseRafId=void 0,this.virtualAnchorReleaseRafOwner=void 0,this.virtualAnchorReleaseRafDocument=void 0,this.anchoringVirtualTail=!1)});this.virtualAnchorReleaseRafId=secondHandle,this.virtualAnchorReleaseRafOwner=ownerWindow,this.virtualAnchorReleaseRafDocument=ownerDocument});this.virtualAnchorReleaseRafId=firstHandle,this.virtualAnchorReleaseRafOwner=ownerWindow,this.virtualAnchorReleaseRafDocument=ownerDocument});return}if(this.virtualAnchorRequest+=1,this.cancelVirtualAnchorReleaseFrame(),this.anchoringVirtualTail=!1,this.scrollRafId!==void 0)return;const handle=ownerWindow.requestAnimationFrame(()=>{if(this.scrollRafId!==handle||this.scrollRafOwner!==ownerWindow||this.scrollRafDocument!==ownerDocument||generation!==this.ownerRealmGeneration||!this.isConnected||this.ownerDocument!==ownerDocument||(this.scrollRafId=void 0,this.scrollRafOwner=void 0,this.scrollRafDocument=void 0,!this.shouldFollowLiveTail||this.isVirtualized))return;const body=this.renderRoot.querySelector('[part="body"]');body&&(body.scrollTop=body.scrollHeight)});this.scrollRafId=handle,this.scrollRafOwner=ownerWindow,this.scrollRafDocument=ownerDocument}completedStepsSummary(count){return this.localize("activityFeedCompletedSteps",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count})}get listSemanticOwner(){return this.isVirtualized?this.virtualListEl?.scrollContainer??null:this.renderRoot.querySelector('[part="body"][role="list"]')}syncListRelationships(){const target=this.listSemanticOwner;if(!target){this.releaseListRelationships();return}this.externalLabelledByLease?this.externalLabelledByLease.update(target):this.externalLabelledByLease=acquireResolvedAriaRelationship(this,target,"aria-labelledby"),this.externalDescribedByLease?this.externalDescribedByLease.update(target):this.externalDescribedByLease=acquireResolvedAriaRelationship(this,target,"aria-describedby")}scheduleListRelationshipSync(){const list=this.virtualListEl;if(!this.isVirtualized||!list||!this.isConnected){this.relationshipSyncRequest+=1;return}const request=++this.relationshipSyncRequest,ownerDocument=this.ownerDocument,generation=this.ownerRealmGeneration;list.updateComplete.then(()=>{request!==this.relationshipSyncRequest||generation!==this.ownerRealmGeneration||this.ownerDocument!==ownerDocument||!this.isConnected||!this.isVirtualized||this.virtualListEl!==list||this.syncListRelationships()})}releaseListRelationships(){this.externalLabelledByLease?.release(),this.externalLabelledByLease=void 0,this.externalDescribedByLease?.release(),this.externalDescribedByLease=void 0}setFollowFromUser(following){following!==this.follow&&(this.follow=following,this.emit("lr-follow-change",{following}))}normalizedTimestamp(value){if(value===void 0)return;const date=value instanceof Date?value:new Date(value);return Number.isNaN(date.getTime())?void 0:date}entryTemplate(entry,ownRole){const ts=this.normalizedTimestamp(entry.timestamp),formatter=this.formatTimestamp??(date=>formatTimeOfDay(date,this.effectiveLocale)),variant=entry.variant??"neutral",dotPart=variantDotPart(variant);return html`
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{applyComposedFocusRepair,captureComposedFocusRepair,repairComposedFocus}from"../../../internal/focus-navigation.js";import{chevronIcon}from"../../../internal/icons.js";import{formatTimeOfDay,getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{styles}from"./activity-feed.styles.js";import{literalSetConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{firstByIdentityMemo}from"../collection-identity.js";import{LYRA_DEFAULT_activityFeedCompletedSteps,LYRA_DEFAULT_activityFeedInputLimit,LYRA_DEFAULT_activityFeedLabel}from"../../../internal/default-strings/agent-tools.generated.js";const ACTIVITY_FEED_MODE=literalSetConverter(["live","post-hoc"],"live"),NEAR_BOTTOM_PX=48,entryId=entry=>entry.id;function variantDotPart(variant){return variant==="brand"?"variant-dot variant-dot-brand":variant==="success"?"variant-dot variant-dot-success":variant==="warning"?"variant-dot variant-dot-warning":variant==="danger"?"variant-dot variant-dot-danger":"variant-dot variant-dot-neutral"}class LyraActivityFeed extends LyraElement{constructor(){super(...arguments),this.entries=[],this._mode="live",this.follow=!0,this.expanded=!1,this.size="m",this.frame="card",this.withTimestamps=!1,this.virtualizeAt=199,this.headerId=nextId("activity-feed-header"),this.bodyId=nextId("activity-feed-body"),this.activityEntryKey=item=>item.id,this.isMounting=!0,this.anchoringVirtualTail=!1,this.ownerRealmGeneration=0,this.virtualAnchorRequest=0,this.relationshipSyncRequest=0,this.entryFocusRepairRequest=0,this.explicitRowRefresh=!1,this.toggle=()=>{const expanded=!this.expanded;this.emit("lr-toggle-request",{expanded},{cancelable:!0}).defaultPrevented||(this.expanded=expanded,this.emit("lr-toggle",{expanded}))},this.onBodyScroll=e=>{if(this.isVirtualized||this.mode!=="live")return;const body=e.currentTarget,nearBottom=body.scrollHeight-body.scrollTop-body.clientHeight<=NEAR_BOTTOM_PX;this.setFollowFromUser(nearBottom)},this.onVirtualListRangeChanged=e=>{if(e.stopPropagation(),this.mode!=="live"||this.anchoringVirtualTail)return;const entries=this.normalizedEntries,atBottom=entries.length>0&&e.detail.end>=entries.length-1;this.setFollowFromUser(atBottom)},this.stopOwnedEvent=event=>{event.stopPropagation()},this.renderEntry=item=>this.entryTemplate(item,!1),this.lastInputNotice=""}static{this.defaultStrings={...super.defaultStrings,activityFeedCompletedSteps:LYRA_DEFAULT_activityFeedCompletedSteps,activityFeedInputLimit:LYRA_DEFAULT_activityFeedInputLimit,activityFeedLabel:LYRA_DEFAULT_activityFeedLabel}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["entries"])}static{this.appendOrderedCollectionProperties=Object.freeze(["entries"])}static{this.identityCollectionProperties=Object.freeze(["entries"])}static{this.styles=[LyraElement.styles,styles]}get mode(){return this._mode}set mode(next){const normalized=ACTIVITY_FEED_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.syncListRelationships(),this.scheduleListRelationshipSync()),this.hasUpdated&&this.shouldFollowLiveTail&&this.scrollToLatest()}disconnectedCallback(){this.releaseListRelationships(),this.resetOwnerRealmWork(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseListRelationships(),this.resetOwnerRealmWork(),this.isConnected&&this.hasUpdated&&(this.syncListRelationships(),this.scheduleListRelationshipSync()),this.isConnected&&this.shouldFollowLiveTail&&this.scrollToLatest()}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,199)}get normalizedEntries(){return firstByIdentityMemo(Array.isArray(this.entries)?this.entries:[],entryId)}get isVirtualized(){return this.normalizedEntries.length>this.effectiveVirtualizeAt}get shouldFollowLiveTail(){return this.expanded&&this.mode==="live"&&this.follow}cancelScrollFrame(){this.scrollRafId!==void 0&&this.scrollRafOwner?.cancelAnimationFrame(this.scrollRafId),this.scrollRafId=void 0,this.scrollRafOwner=void 0,this.scrollRafDocument=void 0}cancelVirtualAnchorReleaseFrame(){this.virtualAnchorReleaseRafId!==void 0&&this.virtualAnchorReleaseRafOwner?.cancelAnimationFrame(this.virtualAnchorReleaseRafId),this.virtualAnchorReleaseRafId=void 0,this.virtualAnchorReleaseRafOwner=void 0,this.virtualAnchorReleaseRafDocument=void 0}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.virtualAnchorRequest+=1,this.relationshipSyncRequest+=1,this.entryFocusRepairRequest+=1,this.pendingEntryFocusRepair=void 0,this.cancelScrollFrame(),this.cancelVirtualAnchorReleaseFrame(),this.anchoringVirtualTail=!1}willUpdate(changed){super.willUpdate(changed),(changed.has("expanded")||changed.has("mode"))&&this.expanded&&this.mode==="live"&&(this.follow=!0),changed.has("expanded")&&changed.get("expanded")===!0&&!this.expanded&&this.repairFocusOnCollapse(),changed.has("entries")&&this.captureEntryFocusRepair()}requestUpdate(...args){args[0]===void 0&&(this.explicitRowRefresh=!0),super.requestUpdate(...args)}updated(changed){super.updated(changed);const explicitRefresh=this.explicitRowRefresh;this.explicitRowRefresh=!1,(explicitRefresh||["withTimestamps","formatTimestamp","renderText","locale","strings"].some(name=>changed.has(name)))&&this.virtualListEl?.requestUpdate(),this.syncListRelationships(),this.scheduleListRelationshipSync();const wasMounting=this.isMounting;this.isMounting=!1;const inputNotice=this.inputLimitMessage();if(!wasMounting&&inputNotice&&inputNotice!==this.lastInputNotice&&this.liveRegion?.announce(inputNotice,{force:!0}),this.lastInputNotice=inputNotice,!wasMounting&&changed.has("mode")&&changed.get("mode")==="live"&&this.mode==="post-hoc"){const region=this.liveRegion;region&&(region.mode="polite",region.announce(this.completedStepsSummary(this.normalizedEntries.length),{force:!0}))}const justAnchored=(changed.has("expanded")||changed.has("mode"))&&this.expanded&&this.mode==="live",followingChangedRenderPath=changed.has("virtualizeAt")&&this.expanded&&this.mode==="live"&&this.follow;(justAnchored||followingChangedRenderPath||changed.has("entries")&&this.expanded&&this.mode==="live"&&this.follow)&&this.scrollToLatest(),changed.has("entries")&&this.pendingEntryFocusRepair&&this.settleEntryFocusRepair()}get headerElement(){return this.hasUpdated?this.renderRoot?.querySelector('[part="header"]')??null:null}repairFocusOnCollapse(){repairComposedFocus(this,()=>this.headerElement)}captureEntryFocusRepair(){this.pendingEntryFocusRepair=captureComposedFocusRepair(this,this.headerElement)??void 0}settleEntryFocusRepair(){const pending=this.pendingEntryFocusRepair;if(this.pendingEntryFocusRepair=void 0,!pending)return;const request=++this.entryFocusRepairRequest,generation=this.ownerRealmGeneration,settle=()=>{request!==this.entryFocusRepairRequest||generation!==this.ownerRealmGeneration||!this.isConnected||pending.activeElement.isConnected||applyComposedFocusRepair(pending,()=>this.headerElement)},list=this.virtualListEl;list?list.updateComplete.then(settle):settle()}scrollToLatest(){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected||!this.shouldFollowLiveTail)return;const generation=this.ownerRealmGeneration;if(this.isVirtualized){this.cancelScrollFrame(),this.cancelVirtualAnchorReleaseFrame(),this.anchoringVirtualTail=!0;const request=++this.virtualAnchorRequest;this.updateComplete.then(()=>{const list=this.virtualListEl;if(request!==this.virtualAnchorRequest||generation!==this.ownerRealmGeneration||this.ownerDocument!==ownerDocument||!this.isConnected)return;if(!list||!this.isVirtualized||!this.shouldFollowLiveTail){this.anchoringVirtualTail=!1;return}list.scrollToIndex(this.normalizedEntries.length-1,{align:"end",behavior:"auto"});const firstHandle=ownerWindow.requestAnimationFrame(()=>{if(this.virtualAnchorReleaseRafId!==firstHandle||this.virtualAnchorReleaseRafOwner!==ownerWindow||this.virtualAnchorReleaseRafDocument!==ownerDocument||request!==this.virtualAnchorRequest||generation!==this.ownerRealmGeneration||!this.isConnected||this.ownerDocument!==ownerDocument)return;if(this.virtualAnchorReleaseRafId=void 0,this.virtualAnchorReleaseRafOwner=void 0,this.virtualAnchorReleaseRafDocument=void 0,!this.anchoringVirtualTail||!this.isVirtualized||!this.shouldFollowLiveTail){this.anchoringVirtualTail=!1;return}const secondHandle=ownerWindow.requestAnimationFrame(()=>{this.virtualAnchorReleaseRafId!==secondHandle||this.virtualAnchorReleaseRafOwner!==ownerWindow||this.virtualAnchorReleaseRafDocument!==ownerDocument||request!==this.virtualAnchorRequest||generation!==this.ownerRealmGeneration||!this.isConnected||this.ownerDocument!==ownerDocument||(this.virtualAnchorReleaseRafId=void 0,this.virtualAnchorReleaseRafOwner=void 0,this.virtualAnchorReleaseRafDocument=void 0,this.anchoringVirtualTail=!1)});this.virtualAnchorReleaseRafId=secondHandle,this.virtualAnchorReleaseRafOwner=ownerWindow,this.virtualAnchorReleaseRafDocument=ownerDocument});this.virtualAnchorReleaseRafId=firstHandle,this.virtualAnchorReleaseRafOwner=ownerWindow,this.virtualAnchorReleaseRafDocument=ownerDocument});return}if(this.virtualAnchorRequest+=1,this.cancelVirtualAnchorReleaseFrame(),this.anchoringVirtualTail=!1,this.scrollRafId!==void 0)return;const handle=ownerWindow.requestAnimationFrame(()=>{if(this.scrollRafId!==handle||this.scrollRafOwner!==ownerWindow||this.scrollRafDocument!==ownerDocument||generation!==this.ownerRealmGeneration||!this.isConnected||this.ownerDocument!==ownerDocument||(this.scrollRafId=void 0,this.scrollRafOwner=void 0,this.scrollRafDocument=void 0,!this.shouldFollowLiveTail||this.isVirtualized))return;const body=this.renderRoot.querySelector('[part="body"]');body&&(body.scrollTop=body.scrollHeight)});this.scrollRafId=handle,this.scrollRafOwner=ownerWindow,this.scrollRafDocument=ownerDocument}completedStepsSummary(count){return this.localize("activityFeedCompletedSteps",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count})}get listSemanticOwner(){return this.isVirtualized?this.virtualListEl?.scrollContainer??null:this.renderRoot.querySelector('[part="body"][role="list"]')}syncListRelationships(){const target=this.isConnected?this.listSemanticOwner:null;if(!target){this.releaseListRelationships();return}this.externalLabelledByLease?this.externalLabelledByLease.update(target):this.externalLabelledByLease=acquireResolvedAriaRelationship(this,target,"aria-labelledby"),this.externalDescribedByLease?this.externalDescribedByLease.update(target):this.externalDescribedByLease=acquireResolvedAriaRelationship(this,target,"aria-describedby")}scheduleListRelationshipSync(){const list=this.virtualListEl;if(!this.isVirtualized||!list||!this.isConnected){this.relationshipSyncRequest+=1;return}const request=++this.relationshipSyncRequest,ownerDocument=this.ownerDocument,generation=this.ownerRealmGeneration;list.updateComplete.then(()=>{request!==this.relationshipSyncRequest||generation!==this.ownerRealmGeneration||this.ownerDocument!==ownerDocument||!this.isConnected||!this.isVirtualized||this.virtualListEl!==list||this.syncListRelationships()})}releaseListRelationships(){this.externalLabelledByLease?.release(),this.externalLabelledByLease=void 0,this.externalDescribedByLease?.release(),this.externalDescribedByLease=void 0}setFollowFromUser(following){following!==this.follow&&(this.follow=following,this.emit("lr-follow-change",{following}))}normalizedTimestamp(value){if(value===void 0)return;const date=value instanceof Date?value:new Date(value);return Number.isNaN(date.getTime())?void 0:date}entryTemplate(entry,ownRole){const ts=this.normalizedTimestamp(entry.timestamp),formatter=this.formatTimestamp??(date=>formatTimeOfDay(date,this.effectiveLocale)),variant=entry.variant??"neutral",dotPart=variantDotPart(variant);return html`
|
|
2
2
|
<div part="entry" role=${ownRole?"listitem":nothing} data-variant=${variant}>
|
|
3
3
|
<span part="entry-icon" aria-hidden="true"
|
|
4
4
|
>${entry.icon?entry.icon:html`<span part=${dotPart} data-variant=${variant}></span>`}</span
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{styles}from"./compare-panel.styles.js";import{overallSemanticLabel,overallSemanticRole}from"../semantic-owner.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{LYRA_DEFAULT_compareResponseA,LYRA_DEFAULT_compareResponseB,LYRA_DEFAULT_compareVoteBetter,LYRA_DEFAULT_compareVoteBothBad,LYRA_DEFAULT_compareVoteLabel,LYRA_DEFAULT_compareVoteRecorded,LYRA_DEFAULT_compareVoteTie}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_comparePanel}from"../../../internal/default-strings/shared.generated.js";class LyraComparePanel extends LyraElement{constructor(){super(...arguments),this.hasPromptSlot=!1,this._labelA="",this._labelB="",this._vote=null,this._itemId="",this._syncScroll=!1,this._disabled=!1,this.pendingScrollReset=!1,this.suppressSync=!1,this.ownerRealmGeneration=0,this.voteAssignedInCommit=!1,this.voteWriteVersion=0,this.allowedVotes=["a","b","tie","both-bad"],this.onPromptSlotChange=e=>{this.collectPromptSlotContent(e.target)},this.voteDispatching=!1,this.onPaneScroll=source=>()=>{if(!this.syncScroll||this.suppressSync)return;const from=source==="a"?this.paneAEl:this.paneBEl,to=source==="a"?this.paneBEl:this.paneAEl;if(!from||!to)return;const fromMax=from.scrollHeight-from.clientHeight,toMax=to.scrollHeight-to.clientHeight;if(fromMax<=0)return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{styles}from"./compare-panel.styles.js";import{overallSemanticLabel,overallSemanticRole}from"../semantic-owner.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{LYRA_DEFAULT_compareResponseA,LYRA_DEFAULT_compareResponseB,LYRA_DEFAULT_compareVoteBetter,LYRA_DEFAULT_compareVoteBothBad,LYRA_DEFAULT_compareVoteLabel,LYRA_DEFAULT_compareVoteRecorded,LYRA_DEFAULT_compareVoteTie}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_comparePanel}from"../../../internal/default-strings/shared.generated.js";class LyraComparePanel extends LyraElement{constructor(){super(...arguments),this.hasPromptSlot=!1,this._labelA="",this._labelB="",this._vote=null,this._itemId="",this._syncScroll=!1,this._disabled=!1,this.pendingScrollReset=!1,this.suppressSync=!1,this.ownerRealmGeneration=0,this.voteAssignedInCommit=!1,this.voteWriteVersion=0,this.allowedVotes=["a","b","tie","both-bad"],this.onPromptSlotChange=e=>{this.collectPromptSlotContent(e.target)},this.voteDispatching=!1,this.onPaneScroll=source=>()=>{if(!this.syncScroll||this.suppressSync)return;const from=source==="a"?this.paneAEl:this.paneBEl,to=source==="a"?this.paneBEl:this.paneAEl;if(!from||!to)return;const fromMax=from.scrollHeight-from.clientHeight,toMax=to.scrollHeight-to.clientHeight;if(fromMax<=0)return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const position=from.scrollTop/fromMax*toMax;if(Math.abs(to.scrollTop-position)<=1)return;this.suppressSync=!0,to.scrollTop=position;const generation=this.ownerRealmGeneration,handle=ownerWindow.requestAnimationFrame(()=>{this.syncScrollRafId!==handle||this.syncScrollRafOwner!==ownerWindow||this.syncScrollRafDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.syncScrollRafId=void 0,this.syncScrollRafOwner=void 0,this.syncScrollRafDocument=void 0,this.suppressSync=!1)});this.syncScrollRafId=handle,this.syncScrollRafOwner=ownerWindow,this.syncScrollRafDocument=ownerDocument}}static{this.defaultStrings={...super.defaultStrings,comparePanel:LYRA_DEFAULT_comparePanel,compareResponseA:LYRA_DEFAULT_compareResponseA,compareResponseB:LYRA_DEFAULT_compareResponseB,compareVoteBetter:LYRA_DEFAULT_compareVoteBetter,compareVoteBothBad:LYRA_DEFAULT_compareVoteBothBad,compareVoteLabel:LYRA_DEFAULT_compareVoteLabel,compareVoteRecorded:LYRA_DEFAULT_compareVoteRecorded,compareVoteTie:LYRA_DEFAULT_compareVoteTie}}emitVoteRequest(detail){return this.emit("lr-vote-request",Object.freeze(detail),{cancelable:!0})}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["allowedVotes"])}static{this.styles=[LyraElement.styles,styles]}static{this.properties={labelA:{attribute:"label-a",noAccessor:!0},labelB:{attribute:"label-b",noAccessor:!0},vote:{reflect:!0,noAccessor:!0},itemId:{attribute:"item-id",noAccessor:!0},syncScroll:{type:Boolean,attribute:"sync-scroll",noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}get labelA(){return this._labelA}set labelA(next){const old=this._labelA;this._labelA=next??"",this.requestUpdate("labelA",old)}get labelB(){return this._labelB}set labelB(next){const old=this._labelB;this._labelB=next??"",this.requestUpdate("labelB",old)}get vote(){return this._vote}set vote(next){this.voteWriteVersion++,this.voteAssignedInCommit=!0;const old=this._vote;this._vote=next??null,this._vote?this.setAttribute("vote",this._vote):this.removeAttribute("vote"),this.requestUpdate("vote",old)}get itemId(){return this._itemId}set itemId(next){const old=this._itemId;this._itemId=next??"",old!==this._itemId&&(this.pendingScrollReset=!0),this.requestUpdate("itemId",old)}get syncScroll(){return this._syncScroll}set syncScroll(next){const old=this._syncScroll;this._syncScroll=!!next,this.requestUpdate("syncScroll",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.requestUpdate("disabled",old)}collectPromptSlotContent(slot){this.hasPromptSlot=slot.assignedNodes({flatten:!0}).length>0}disconnectedCallback(){this.resetScrollSyncFrame(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetScrollSyncFrame()}resetScrollSyncFrame(){this.ownerRealmGeneration+=1,this.syncScrollRafId!==void 0&&this.syncScrollRafOwner?.cancelAnimationFrame(this.syncScrollRafId),this.syncScrollRafId=void 0,this.syncScrollRafOwner=void 0,this.syncScrollRafDocument=void 0,this.suppressSync=!1}castVote(choice){if(!this.voteDispatching){this.voteDispatching=!0;try{if(this.disabled)return;const itemId=this.itemId,voteVersion=this.voteWriteVersion,labelAText=this.labelA||this.localize("compareResponseA"),labelBText=this.labelB||this.localize("compareResponseB"),label=choice==="a"?labelAText:choice==="b"?labelBText:choice==="tie"?this.localize("compareVoteTie"):this.localize("compareVoteBothBad");if(this.emitVoteRequest({choice,itemId}).defaultPrevented||this.disabled||this.itemId===itemId&&this.voteWriteVersion!==voteVersion)return;this.itemId===itemId&&(this.vote=choice),this.liveRegion?.announce(this.localize("compareVoteRecorded",void 0,{label}),{force:!0})}finally{this.voteDispatching=!1}}}voteButton(choice,label){return!Array.isArray(this.allowedVotes)||!this.allowedVotes.includes(choice)?nothing:html`<button
|
|
2
2
|
part="vote-button"
|
|
3
3
|
type="button"
|
|
4
4
|
?disabled=${this.disabled}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{SourcePageController}from"../../../internal/source-page-controller.js";import{finiteInteger}from"../../../internal/numbers.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{createHaystackMemo}from"../../../internal/search-haystack.js";import{indexByKey}from"../../../internal/keyed-index.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import"../../forms/input/input.class.js";import{collectionSupport,publicCollectionTruncation}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{getCollator,getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{styles}from"./eval-dataset.styles.js";import{agentActionButtonStyles}from"../agent-action-button.styles.js";import{firstByIdentity}from"../collection-identity.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{LYRA_DEFAULT_evalDatasetAddExample,LYRA_DEFAULT_evalDatasetColumnExpectedOutput,LYRA_DEFAULT_evalDatasetColumnInput,LYRA_DEFAULT_evalDatasetColumnTags,LYRA_DEFAULT_evalDatasetEmpty,LYRA_DEFAULT_evalDatasetImportLabel,LYRA_DEFAULT_evalDatasetLabel,LYRA_DEFAULT_evalDatasetLimit,LYRA_DEFAULT_evalDatasetNoMatches,LYRA_DEFAULT_evalDatasetRemoveExample,LYRA_DEFAULT_evalDatasetSearchLabel,LYRA_DEFAULT_evalDatasetTagFilterLabel}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_tagFacetLimit}from"../../../internal/default-strings/shared.generated.js";const MAX_RENDERED_EXAMPLES=100,MAX_TAG_FACETS=500,rowKey=row=>row.id;class LyraEvalDataset extends LyraElement{constructor(){super(...arguments),this.limitAnnouncements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.examplesTruncated=!1,this.sourceStateVersion=0,this.sourceEpoch=0,this.sourceSyncing=!1,this.sourceRows=[],this.sourceTags=[],this.sourceFacetLabels=new Map,this.sourceSortKey=null,this.sourceSortDir="asc",this.sourcePages=new SourcePageController(this,{normalizeRecord:(record,isCurrent)=>this.projectSourceExample(record,isCurrent),validateMetadata:(result,query)=>{if(!result.tags||query.tags.length>MAX_TAG_FACETS||result.tags.unavailableSelected.some(key=>!query.tags.includes(key)))throw new TypeError("Invalid example source facets");const available=new Set(result.tags.values.map(facet=>facet.key)),missing=new Set(result.tags.unavailableSelected);if(query.tags.some(key=>!available.has(key)&&!missing.has(key)))throw new TypeError("Selected source facet is missing")},onChange:()=>{this.sourceStateVersion++}}),this.sourcePage=0,this.sourcePageSize=100,this.onSourcePage=event=>{event.stopPropagation(),this.sourceMode&&!this.disabled&&(this.sourcePage=event.detail.page-1)},this.onSourceSort=event=>{!this.sourceMode||this.disabled||(this.sourceSortKey=event.detail.sortKey,this.sourceSortDir=event.detail.sortDir,this.syncSource(),this.sourceStateVersion++)},this.onSourceRetry=event=>{event.stopPropagation(),this.sourceMode&&!this.disabled&&this.requestUpdate()},this.examples=[],this.searchable=!1,this.autocomplete="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.inputMode="",this.enterKeyHint="",this.accept="",this.exportFormats=["csv","json"],this.disabled=!1,this.label="",this.searchText="",this.activeTags=new Set,this.selectedId=null,this.normalizedCache=[],this.explicitRefresh=0,this.normalizedRefresh=0,this.searchCorpus=createHaystackMemo((example,locale)=>[example.input,example.expectedOutput??"",...example.tags??[]].join(" ").toLocaleLowerCase(resolveIntlLocale(locale))),this.visibleExamples=[],this.onAddClick=()=>{this.disabled||this.emit("lr-example-add-request")},this.onRemoveClick=()=>{this.disabled||this.sourceBlocked||this.selectedId===null||this.emit("lr-example-remove-request",{exampleId:this.selectedId})},this.onGridRowActivate=e=>{if(e.stopPropagation(),this.disabled||this.sourceBlocked||this.sourceMode&&!this.sourceRows.includes(e.detail.row))return;const id=e.detail.row.id;this.selectedId=id,this.emit("lr-example-select",{exampleId:id})},this.onFiles=e=>{e.stopPropagation(),!(this.disabled||e.detail.files.length===0)&&this.emit("lr-import-request",{files:[...e.detail.files]})},this.onExportButtonExport=e=>{e.preventDefault(),e.stopPropagation(),!this.disabled&&this.emit("lr-export-request",{format:e.detail.format})},this.gateDisabledClear={handleEvent:event=>{this.disabled&&event.stopPropagation()},capture:!0}}static{this.defaultStrings={...super.defaultStrings,evalDatasetAddExample:LYRA_DEFAULT_evalDatasetAddExample,evalDatasetColumnExpectedOutput:LYRA_DEFAULT_evalDatasetColumnExpectedOutput,evalDatasetColumnInput:LYRA_DEFAULT_evalDatasetColumnInput,evalDatasetColumnTags:LYRA_DEFAULT_evalDatasetColumnTags,evalDatasetEmpty:LYRA_DEFAULT_evalDatasetEmpty,evalDatasetImportLabel:LYRA_DEFAULT_evalDatasetImportLabel,evalDatasetLabel:LYRA_DEFAULT_evalDatasetLabel,evalDatasetLimit:LYRA_DEFAULT_evalDatasetLimit,evalDatasetNoMatches:LYRA_DEFAULT_evalDatasetNoMatches,evalDatasetRemoveExample:LYRA_DEFAULT_evalDatasetRemoveExample,evalDatasetSearchLabel:LYRA_DEFAULT_evalDatasetSearchLabel,evalDatasetTagFilterLabel:LYRA_DEFAULT_evalDatasetTagFilterLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,tagFacetLimit:LYRA_DEFAULT_tagFacetLimit}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["examples","exportFormats"])}static{this.identityCollectionProperties=Object.freeze(["examples"])}static{this.styles=[LyraElement.styles,styles,agentActionButtonStyles]}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.sourceMode&&this.selectedId!==null&&this.clearSelection()}adoptedCallback(){super.adoptedCallback(),this.limitAnnouncements.adopted(),this.sourcePages.adopted()}updated(changed){if(super.updated(changed),this.limitAnnouncementInitialized&&this.examplesTruncated&&!this.previouslyTruncated){const truncation=publicCollectionTruncation(this,"examples");truncation&&this.limitAnnouncements.announcePolite(this.localize("evalDatasetLimit",void 0,{count:getNumberFormat(this.effectiveLocale).format(truncation.retained)}))}this.limitAnnouncementInitialized=!0,this.previouslyTruncated=this.examplesTruncated}static{this.immutableEventDetails=Object.freeze(["lr-import-request"])}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.sourcePages.state.pending||!!this.sourcePages.state.error||!!this.sourceFailure)}projectSourceExample(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")throw new TypeError("Invalid source example");const candidate=record.value,read=(key,optional=!1)=>{const descriptor=descriptorOf(candidate,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!optional&&descriptor===MISSING_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid source example");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value},id=read("id"),input=read("input"),expectedOutput=read("expectedOutput",!0),rawTags=read("tags",!0);if(typeof id!="string"||!id.trim()||id!==record.key||typeof input!="string"||expectedOutput!==void 0&&typeof expectedOutput!="string")throw new TypeError("Invalid source example");let units=id.length+input.length+(expectedOutput?.length??0);const tags=[];if(rawTags!==void 0){if(!Array.isArray(rawTags))throw new TypeError("Invalid source tags");const length=descriptorOf(rawTags,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||length.value>MAX_TAG_FACETS)throw new RangeError("Invalid source tags");for(let i=0;i<length.value;i++){const tag=descriptorOf(rawTags,String(i));if(tag===MISSING_OWN_DATA_DESCRIPTOR||tag===UNSAFE_OWN_DATA_DESCRIPTOR||typeof tag.value!="string")throw new TypeError("Invalid source tag");units+=tag.value.length,tags.push(tag.value)}}if(units>65536)throw new RangeError("Source example too large");return{key:record.key,order:record.order,value:Object.freeze({id,input,...expectedOutput===void 0?{}:{expectedOutput},tags:Object.freeze(tags)})}}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.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.searchText,this.activeTags,this.sourceSortKey,this.sourceSortDir,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;this.sourceInputs=inputs,this.sourceFailure=void 0,this.sourceRows=[],this.sourceTags=[],this.sourceResult=void 0,this.selectedId!==null&&this.clearSelection(),this.sourcePages.bind({source,revision,epoch,locale:this.effectiveLocale});const query=Object.freeze({search:this.searchText,tags:Object.freeze([...this.activeTags]),sortKey:this.sourceSortKey,sortDir:this.sourceSortDir});this.sourcePages.request(query,page,size)}catch(error){this.sourcePages.bind(void 0),this.sourceRows=[],this.sourceTags=[],this.sourceResult=void 0,this.sourceFailure=error}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.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.activeTags].some(key=>removed.has(key))){this.activeTags=new Set([...this.activeTags].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)}get normalizedExamples(){if(this.normalizedFor!==this.examples){this.normalizedFor=this.examples;const deduped=firstByIdentity(Array.isArray(this.examples)?this.examples:[],example=>example.id);this.normalizedCache=deduped.map(example=>Array.isArray(example.tags)?example:{...example,tags:void 0})}return this.normalizedCache}requestUpdate(...args){args[0]===void 0&&(this.explicitRefresh=(this.explicitRefresh??0)+1),(args[0]===void 0||["dataSource","sourcePage","sourcePageSize","searchText","activeTags"].includes(String(args[0])))&&this.syncSource(),super.requestUpdate(...args)}willUpdate(changed){if(super.willUpdate(changed),changed.has("searchable")&&!this.searchable&&(this.searchText=""),this.syncSource(),this.sourceMode){this.acceptSourcePage();return}const normalizedChanged=changed.has("dataSource")||this.normalizedFor!==this.examples||this.normalizedRefresh!==this.explicitRefresh;if(this.normalizedRefresh!==this.explicitRefresh&&(this.normalizedRefresh=this.explicitRefresh,this.normalizedFor=void 0),changed.has("searchable")&&!this.searchable&&(this.searchText=""),normalizedChanged){this.selectedId!==null&&!indexByKey(this.normalizedExamples,rowKey).has(this.selectedId)&&this.clearSelection();const available=new Set(this.allTags());[...this.activeTags].some(tag=>!available.has(tag))&&(this.activeTags=new Set([...this.activeTags].filter(tag=>available.has(tag))))}const inputs=[this.normalizedExamples,this.searchText,this.activeTags,this.effectiveLocale],filtersChanged=!this.filterMemo||inputs.some((input,index)=>input!==this.filterMemo.inputs[index]);filtersChanged&&(this.filterMemo={inputs,rows:this.filterExamples()}),this.visibleExamples=this.filterMemo.rows,filtersChanged&&this.selectedId!==null&&!indexByKey(this.visibleExamples,rowKey).has(this.selectedId)&&this.clearSelection()}clearSelection(){this.selectedId=null,this.emit("lr-example-select",{exampleId:null})}allTags(){const examples=this.normalizedExamples,locale=this.effectiveLocale;if(this.tagsMemo?.examples===examples&&this.tagsMemo.locale===locale)return this.tagsMemo.tags;const tags=new Set;for(const example of this.normalizedExamples)for(const tag of example.tags??[])tags.add(tag);const sorted=[...tags].sort(getCollator(locale).compare);return this.tagsMemo={examples,locale,tags:sorted},sorted}filterExamples(){const query=this.searchText.trim().toLocaleLowerCase(this.effectiveLocale),corpus=query?this.searchCorpus(this.normalizedExamples,this.effectiveLocale):void 0;return this.normalizedExamples.filter((example,index)=>this.activeTags.size>0&&!(example.tags??[]).some(tag=>this.activeTags.has(tag))?!1:query===""?!0:corpus[index].includes(query))}buildColumns(){const labels=[this.localize("evalDatasetColumnInput"),this.localize("evalDatasetColumnExpectedOutput"),this.localize("evalDatasetColumnTags")],key=labels.join("\0");return this.columnsCache?.key!==key&&(this.columnsCache={key,columns:this.createColumns(labels)}),this.columnsCache.columns}selectedKeys(){return this.selectedKeysCache?.id!==this.selectedId&&(this.selectedKeysCache={id:this.selectedId,keys:this.selectedId===null?new Set:new Set([this.selectedId])}),this.selectedKeysCache.keys}createColumns([inputLabel,expectedLabel,tagsLabel]){return[{key:"input",label:inputLabel,sortable:!0,sortValue:row=>row.input,cell:row=>row.input},{key:"expectedOutput",label:expectedLabel,sortable:!0,sortValue:row=>row.expectedOutput??"",cell:row=>row.expectedOutput??""},{key:"tags",label:tagsLabel,sortable:!0,sortValue:row=>(row.tags??[]).join(", "),cell:row=>(row.tags??[]).join(", ")}]}onTagChipToggle(tag,e){if(e.stopPropagation(),this.disabled)return;const next=new Set(this.activeTags);e.detail.selected?next.add(tag):next.delete(tag),this.activeTags=next}stopOwnedEvent(event){event.stopPropagation()}renderToolbar(){return html`
|
|
1
|
+
import{__decorate}from"tslib";import{SourcePageController}from"../../../internal/source-page-controller.js";import{finiteInteger}from"../../../internal/numbers.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{createHaystackMemo}from"../../../internal/search-haystack.js";import{indexByKey}from"../../../internal/keyed-index.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import"../../forms/input/input.class.js";import{collectionSupport,publicCollectionTruncation}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{getCollator,getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{styles}from"./eval-dataset.styles.js";import{agentActionButtonStyles}from"../agent-action-button.styles.js";import{firstByIdentity}from"../collection-identity.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{LYRA_DEFAULT_evalDatasetAddExample,LYRA_DEFAULT_evalDatasetColumnExpectedOutput,LYRA_DEFAULT_evalDatasetColumnInput,LYRA_DEFAULT_evalDatasetColumnTags,LYRA_DEFAULT_evalDatasetEmpty,LYRA_DEFAULT_evalDatasetImportLabel,LYRA_DEFAULT_evalDatasetLabel,LYRA_DEFAULT_evalDatasetLimit,LYRA_DEFAULT_evalDatasetNoMatches,LYRA_DEFAULT_evalDatasetRemoveExample,LYRA_DEFAULT_evalDatasetSearchLabel,LYRA_DEFAULT_evalDatasetTagFilterLabel}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_tagFacetLimit}from"../../../internal/default-strings/shared.generated.js";const MAX_RENDERED_EXAMPLES=100,MAX_TAG_FACETS=500,rowKey=row=>row.id;class LyraEvalDataset extends LyraElement{constructor(){super(...arguments),this.limitAnnouncements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.examplesTruncated=!1,this.sourceStateVersion=0,this.sourceEpoch=0,this.sourceSyncing=!1,this.sourceRows=[],this.sourceTags=[],this.sourceFacetLabels=new Map,this.sourceSortKey=null,this.sourceSortDir="asc",this.sourcePages=new SourcePageController(this,{normalizeRecord:(record,isCurrent)=>this.projectSourceExample(record,isCurrent),validateMetadata:(result,query)=>{if(!result.tags||query.tags.length>MAX_TAG_FACETS||result.tags.unavailableSelected.some(key=>!query.tags.includes(key)))throw new TypeError("Invalid example source facets");const available=new Set(result.tags.values.map(facet=>facet.key)),missing=new Set(result.tags.unavailableSelected);if(query.tags.some(key=>!available.has(key)&&!missing.has(key)))throw new TypeError("Selected source facet is missing")},onChange:()=>{this.sourceStateVersion++}}),this.sourcePage=0,this.sourcePageSize=100,this.onSourcePage=event=>{event.stopPropagation(),this.sourceMode&&!this.disabled&&(this.sourcePage=event.detail.page-1)},this.onSourceSort=event=>{!this.sourceMode||this.disabled||(this.sourceSortKey=event.detail.sortKey,this.sourceSortDir=event.detail.sortDir,this.syncSource(),this.sourceStateVersion++)},this.onSourceRetry=event=>{event.stopPropagation(),this.sourceMode&&!this.disabled&&this.requestUpdate()},this.examples=[],this.searchable=!1,this.autocomplete="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.inputMode="",this.enterKeyHint="",this.accept="",this.exportFormats=["csv","json"],this.disabled=!1,this.label="",this.searchText="",this.activeTags=new Set,this.selectedId=null,this.normalizedCache=[],this.explicitRefresh=0,this.normalizedRefresh=0,this.searchCorpus=createHaystackMemo((example,locale)=>[example.input,example.expectedOutput??"",...example.tags??[]].join(" ").toLocaleLowerCase(resolveIntlLocale(locale))),this.visibleExamples=[],this.onAddClick=()=>{this.disabled||this.emit("lr-example-add-request")},this.onRemoveClick=()=>{this.disabled||this.sourceBlocked||this.selectedId===null||this.emit("lr-example-remove-request",{exampleId:this.selectedId})},this.onGridRowActivate=e=>{if(e.stopPropagation(),this.disabled||this.sourceBlocked||this.sourceMode&&!this.sourceRows.includes(e.detail.row))return;const id=e.detail.row.id;this.selectedId=id,this.emit("lr-example-select",{exampleId:id})},this.onFiles=e=>{e.stopPropagation(),!(this.disabled||e.detail.files.length===0)&&this.emit("lr-import-request",{files:[...e.detail.files]})},this.onExportButtonExport=e=>{e.preventDefault(),e.stopPropagation(),!this.disabled&&this.emit("lr-export-request",{format:e.detail.format})},this.gateDisabledClear={handleEvent:event=>{this.disabled&&event.stopPropagation()},capture:!0}}static{this.defaultStrings={...super.defaultStrings,evalDatasetAddExample:LYRA_DEFAULT_evalDatasetAddExample,evalDatasetColumnExpectedOutput:LYRA_DEFAULT_evalDatasetColumnExpectedOutput,evalDatasetColumnInput:LYRA_DEFAULT_evalDatasetColumnInput,evalDatasetColumnTags:LYRA_DEFAULT_evalDatasetColumnTags,evalDatasetEmpty:LYRA_DEFAULT_evalDatasetEmpty,evalDatasetImportLabel:LYRA_DEFAULT_evalDatasetImportLabel,evalDatasetLabel:LYRA_DEFAULT_evalDatasetLabel,evalDatasetLimit:LYRA_DEFAULT_evalDatasetLimit,evalDatasetNoMatches:LYRA_DEFAULT_evalDatasetNoMatches,evalDatasetRemoveExample:LYRA_DEFAULT_evalDatasetRemoveExample,evalDatasetSearchLabel:LYRA_DEFAULT_evalDatasetSearchLabel,evalDatasetTagFilterLabel:LYRA_DEFAULT_evalDatasetTagFilterLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,tagFacetLimit:LYRA_DEFAULT_tagFacetLimit}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["examples","exportFormats"])}static{this.identityCollectionProperties=Object.freeze(["examples"])}static{this.styles=[LyraElement.styles,styles,agentActionButtonStyles]}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.sourceMode&&this.selectedId!==null&&this.clearSelection()}adoptedCallback(){super.adoptedCallback(),this.limitAnnouncements.adopted(),this.sourcePages.adopted()}updated(changed){if(super.updated(changed),this.limitAnnouncementInitialized&&this.examplesTruncated&&!this.previouslyTruncated){const truncation=publicCollectionTruncation(this,"examples");truncation&&this.limitAnnouncements.announcePolite(this.localize("evalDatasetLimit",void 0,{count:getNumberFormat(this.effectiveLocale).format(truncation.retained)}))}this.limitAnnouncementInitialized=!0,this.previouslyTruncated=this.examplesTruncated}static{this.immutableEventDetails=Object.freeze(["lr-import-request"])}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.sourcePages.state.pending||!!this.sourcePages.state.error||!!this.sourceFailure)}projectSourceExample(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")throw new TypeError("Invalid source example");const candidate=record.value,read=(key,optional=!1)=>{const descriptor=descriptorOf(candidate,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!optional&&descriptor===MISSING_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid source example");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value},id=read("id"),input=read("input"),expectedOutput=read("expectedOutput",!0),rawTags=read("tags",!0);if(typeof id!="string"||!id.trim()||id!==record.key||typeof input!="string"||expectedOutput!==void 0&&typeof expectedOutput!="string")throw new TypeError("Invalid source example");let units=id.length+input.length+(expectedOutput?.length??0);const tags=[];if(rawTags!==void 0){if(!Array.isArray(rawTags))throw new TypeError("Invalid source tags");const length=descriptorOf(rawTags,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||length.value>MAX_TAG_FACETS)throw new RangeError("Invalid source tags");for(let i=0;i<length.value;i++){const tag=descriptorOf(rawTags,String(i));if(tag===MISSING_OWN_DATA_DESCRIPTOR||tag===UNSAFE_OWN_DATA_DESCRIPTOR||typeof tag.value!="string")throw new TypeError("Invalid source tag");units+=tag.value.length,tags.push(tag.value)}}if(units>65536)throw new RangeError("Source example too large");return{key:record.key,order:record.order,value:Object.freeze({id,input,...expectedOutput===void 0?{}:{expectedOutput},tags:Object.freeze(tags)})}}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.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.searchText,this.activeTags,this.sourceSortKey,this.sourceSortDir,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;this.sourceInputs=inputs,this.sourceFailure=void 0,this.sourceRows=[],this.sourceTags=[],this.sourceResult=void 0,this.selectedId!==null&&this.clearSelection(),this.sourcePages.bind({source,revision,epoch,locale:this.effectiveLocale});const query=Object.freeze({search:this.searchText,tags:Object.freeze([...this.activeTags]),sortKey:this.sourceSortKey,sortDir:this.sourceSortDir});this.sourcePages.request(query,page,size)}catch(error){this.sourcePages.bind(void 0),this.sourceRows=[],this.sourceTags=[],this.sourceResult=void 0,this.sourceFailure=error}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.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.activeTags].some(key=>removed.has(key))){this.activeTags=new Set([...this.activeTags].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)}get normalizedExamples(){if(this.normalizedFor!==this.examples){this.normalizedFor=this.examples;const deduped=firstByIdentity(Array.isArray(this.examples)?this.examples:[],example=>example.id);this.normalizedCache=deduped.map(example=>Array.isArray(example.tags)?example:{...example,tags:void 0})}return this.normalizedCache}requestUpdate(...args){args[0]===void 0&&(this.explicitRefresh=(this.explicitRefresh??0)+1),(args[0]===void 0||["dataSource","sourcePage","sourcePageSize","searchText","activeTags"].includes(String(args[0])))&&this.syncSource(),super.requestUpdate(...args)}willUpdate(changed){if(super.willUpdate(changed),changed.has("searchable")&&!this.searchable&&(this.searchText=""),this.syncSource(),this.sourceMode){this.acceptSourcePage();return}const normalizedChanged=changed.has("dataSource")||this.normalizedFor!==this.examples||this.normalizedRefresh!==this.explicitRefresh;if(this.normalizedRefresh!==this.explicitRefresh&&(this.normalizedRefresh=this.explicitRefresh,this.normalizedFor=void 0),changed.has("searchable")&&!this.searchable&&(this.searchText=""),normalizedChanged){this.selectedId!==null&&!indexByKey(this.normalizedExamples,rowKey).has(this.selectedId)&&this.clearSelection();const available=new Set(this.allTags());[...this.activeTags].some(tag=>!available.has(tag))&&(this.activeTags=new Set([...this.activeTags].filter(tag=>available.has(tag))))}const inputs=[this.normalizedExamples,this.searchText,this.activeTags,this.effectiveLocale],filtersChanged=!this.filterMemo||inputs.some((input,index)=>input!==this.filterMemo.inputs[index]);filtersChanged&&(this.filterMemo={inputs,rows:this.filterExamples()}),this.visibleExamples=this.filterMemo.rows,filtersChanged&&this.selectedId!==null&&!indexByKey(this.visibleExamples,rowKey).has(this.selectedId)&&this.clearSelection()}clearSelection(){this.selectedId=null,this.emit("lr-example-select",{exampleId:null})}allTags(){const examples=this.normalizedExamples,locale=this.effectiveLocale;if(this.tagsMemo?.examples===examples&&this.tagsMemo.locale===locale)return this.tagsMemo.tags;const tags=new Set;for(const example of this.normalizedExamples)for(const tag of example.tags??[])tags.add(tag);const sorted=[...tags].sort(getCollator(locale).compare);return this.tagsMemo={examples,locale,tags:sorted},sorted}filterExamples(){const query=this.searchText.trim().toLocaleLowerCase(this.effectiveLocale),corpus=query?this.searchCorpus(this.normalizedExamples,this.effectiveLocale):void 0;return this.normalizedExamples.filter((example,index)=>this.activeTags.size>0&&!(example.tags??[]).some(tag=>this.activeTags.has(tag))?!1:query===""?!0:corpus[index].includes(query))}buildColumns(){const labels=[this.localize("evalDatasetColumnInput"),this.localize("evalDatasetColumnExpectedOutput"),this.localize("evalDatasetColumnTags")],key=labels.join("\0");return this.columnsCache?.key!==key&&(this.columnsCache={key,columns:this.createColumns(labels)}),this.columnsCache.columns}selectedKeys(){return this.selectedKeysCache?.id!==this.selectedId&&(this.selectedKeysCache={id:this.selectedId,keys:this.selectedId===null?new Set:new Set([this.selectedId])}),this.selectedKeysCache.keys}createColumns([inputLabel,expectedLabel,tagsLabel]){return[{key:"input",label:inputLabel,sortable:!0,sortValue:row=>row.input,cell:row=>row.input},{key:"expectedOutput",label:expectedLabel,sortable:!0,sortValue:row=>row.expectedOutput??"",cell:row=>row.expectedOutput??""},{key:"tags",label:tagsLabel,sortable:!0,sortValue:row=>(row.tags??[]).join(", "),cell:row=>(row.tags??[]).join(", ")}]}onTagChipToggle(tag,e){if(e.stopPropagation(),this.disabled||e.defaultPrevented){e.preventDefault();return}const next=new Set(this.activeTags);e.detail.selected?next.add(tag):next.delete(tag),this.activeTags=next}stopOwnedEvent(event){event.stopPropagation()}renderToolbar(){return html`
|
|
2
2
|
<div part="toolbar">
|
|
3
3
|
<button part="add-button" data-agent-action="brand" type="button" ?disabled=${this.disabled} @click=${this.onAddClick}>
|
|
4
4
|
${this.localize("evalDatasetAddExample")}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{formatShortDuration,safeDurationMs}from"../../../internal/duration.js";import{literalSetConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{styles}from"./thinking-panel.styles.js";import{LYRA_DEFAULT_thoughtFor}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_thinking,LYRA_DEFAULT_thinkingPanelLabel}from"../../../internal/default-strings/shared.generated.js";const THINKING_PANEL_MODE=literalSetConverter(["live","post-hoc"],"live"),NEAR_BOTTOM_PX=48;class LyraThinkingPanel extends LyraElement{constructor(){super(...arguments),this.size="m",this.frame="card",this.expanded=!1,this._mode="live",this.follow=!0,this.bodyId=nextId("thinking-panel-body"),this.realmGeneration=0,this.onScroll=e=>{const body=e.currentTarget,following=body.scrollHeight-body.scrollTop-body.clientHeight<=NEAR_BOTTOM_PX;following!==this.follow&&(this.follow=following,this.emit("lr-follow-change",{following}))},this.onContentMutated=()=>{if(this.mode!=="live"||!this.expanded||!this.follow||this.scrollRafId!==void 0)return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.realmGeneration,handle=ownerWindow.requestAnimationFrame(()=>{this.scrollRafId!==handle||this.scrollRafOwner!==ownerWindow||this.realmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.scrollRafId=void 0,this.scrollRafOwner=void 0,this.mode==="live"&&this.expanded&&this.follow&&this.scrollToBottom())});this.scrollRafId=handle,this.scrollRafOwner=ownerWindow},this.toggle=()=>{const expanded=!this.expanded;this.emit("lr-toggle-request",{expanded},{cancelable:!0}).defaultPrevented||(this.expanded=expanded,this.emit("lr-toggle",{expanded:this.expanded}))}}static{this.defaultStrings={...super.defaultStrings,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,thinking:LYRA_DEFAULT_thinking,thinkingPanelLabel:LYRA_DEFAULT_thinkingPanelLabel,thoughtFor:LYRA_DEFAULT_thoughtFor}}static{this.styles=[LyraElement.styles,styles]}get mode(){return this._mode}set mode(next){const normalized=THINKING_PANEL_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}connectedCallback(){super.connectedCallback(),this.armContentObserver(),this.addEventListener("lr-content-settled",this.onContentMutated)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("lr-content-settled",this.onContentMutated),this.resetOwnerRealmWork()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork()}willUpdate(changed){super.willUpdate(changed),(changed.has("expanded")||changed.has("mode"))&&this.expanded&&this.mode==="live"&&(this.follow=!0)}armContentObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.contentObserver&&this.contentObserverDocument===ownerDocument)return;this.contentObserver?.disconnect(),this.contentObserver=void 0,this.contentObserverDocument=void 0;const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.realmGeneration,observer=new MutationObserverCtor(()=>{this.contentObserver!==observer||this.contentObserverDocument!==ownerDocument||this.realmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onContentMutated()});this.contentObserver=observer,this.contentObserverDocument=ownerDocument,observer.observe(this,{childList:!0,subtree:!0,characterData:!0})}resetOwnerRealmWork(){this.realmGeneration+=1,this.contentObserver?.disconnect(),this.contentObserver=void 0,this.contentObserverDocument=void 0,this.scrollRafId!==void 0&&this.scrollRafOwner?.cancelAnimationFrame(this.scrollRafId),this.scrollRafId=void 0,this.scrollRafOwner=void 0}updated(changed){super.updated(changed),(changed.has("expanded")||changed.has("mode"))&&this.expanded&&this.mode==="live"&&this.scrollToBottom()}scrollToBottom(){this.follow=!0;const body=this.renderRoot
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{formatShortDuration,safeDurationMs}from"../../../internal/duration.js";import{literalSetConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{styles}from"./thinking-panel.styles.js";import{LYRA_DEFAULT_thoughtFor}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_thinking,LYRA_DEFAULT_thinkingPanelLabel}from"../../../internal/default-strings/shared.generated.js";const THINKING_PANEL_MODE=literalSetConverter(["live","post-hoc"],"live"),NEAR_BOTTOM_PX=48;class LyraThinkingPanel extends LyraElement{constructor(){super(...arguments),this.size="m",this.frame="card",this.expanded=!1,this._mode="live",this.follow=!0,this.bodyId=nextId("thinking-panel-body"),this.realmGeneration=0,this.onScroll=e=>{const body=e.currentTarget,following=body.scrollHeight-body.scrollTop-body.clientHeight<=NEAR_BOTTOM_PX;following!==this.follow&&(this.follow=following,this.emit("lr-follow-change",{following}))},this.onContentMutated=()=>{if(this.mode!=="live"||!this.expanded||!this.follow||this.scrollRafId!==void 0)return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.realmGeneration,handle=ownerWindow.requestAnimationFrame(()=>{this.scrollRafId!==handle||this.scrollRafOwner!==ownerWindow||this.realmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.scrollRafId=void 0,this.scrollRafOwner=void 0,this.mode==="live"&&this.expanded&&this.follow&&this.scrollToBottom())});this.scrollRafId=handle,this.scrollRafOwner=ownerWindow},this.toggle=()=>{const expanded=!this.expanded;this.emit("lr-toggle-request",{expanded},{cancelable:!0}).defaultPrevented||(this.expanded=expanded,this.emit("lr-toggle",{expanded:this.expanded}))}}static{this.defaultStrings={...super.defaultStrings,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,thinking:LYRA_DEFAULT_thinking,thinkingPanelLabel:LYRA_DEFAULT_thinkingPanelLabel,thoughtFor:LYRA_DEFAULT_thoughtFor}}static{this.styles=[LyraElement.styles,styles]}get mode(){return this._mode}set mode(next){const normalized=THINKING_PANEL_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}connectedCallback(){super.connectedCallback(),this.armContentObserver(),this.addEventListener("lr-content-settled",this.onContentMutated)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("lr-content-settled",this.onContentMutated),this.resetOwnerRealmWork()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork()}willUpdate(changed){super.willUpdate(changed),(changed.has("expanded")||changed.has("mode"))&&this.expanded&&this.mode==="live"&&(this.follow=!0)}armContentObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.contentObserver&&this.contentObserverDocument===ownerDocument)return;this.contentObserver?.disconnect(),this.contentObserver=void 0,this.contentObserverDocument=void 0;const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.realmGeneration,observer=new MutationObserverCtor(()=>{this.contentObserver!==observer||this.contentObserverDocument!==ownerDocument||this.realmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onContentMutated()});this.contentObserver=observer,this.contentObserverDocument=ownerDocument,observer.observe(this,{childList:!0,subtree:!0,characterData:!0})}resetOwnerRealmWork(){this.realmGeneration+=1,this.contentObserver?.disconnect(),this.contentObserver=void 0,this.contentObserverDocument=void 0,this.scrollRafId!==void 0&&this.scrollRafOwner?.cancelAnimationFrame(this.scrollRafId),this.scrollRafId=void 0,this.scrollRafOwner=void 0}updated(changed){super.updated(changed),(changed.has("expanded")||changed.has("mode"))&&this.expanded&&this.mode==="live"&&this.scrollToBottom()}scrollToBottom(){this.follow=!0;const body=this.renderRoot?.querySelector('[part="body"]');body&&(body.scrollTop=body.scrollHeight)}get safeDurationMs(){return safeDurationMs(this.durationMs)}get durationDisplay(){const durationMs=this.safeDurationMs;return durationMs!=null?{text:this.localize("thoughtFor",void 0,{duration:formatShortDuration(this.localize.bind(this),this.effectiveLocale,durationMs)}),pending:!1}:this.mode==="live"?{text:this.localize("thinking"),pending:!0}:null}render(){const duration=this.durationDisplay,label=this.label==null?this.localize("thinkingPanelLabel"):this.label;return html`
|
|
2
2
|
<div part="base">
|
|
3
3
|
<button
|
|
4
4
|
part="header"
|
|
@@ -33,7 +33,7 @@ import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/nat
|
|
|
33
33
|
${repeat(group.tools,tool=>tool.id,tool=>this.renderTool(tool,selectedIds))}
|
|
34
34
|
</ul>
|
|
35
35
|
</div>
|
|
36
|
-
`}render(){const projection=this.projection,groups=projection.groups,tools=this.canonicalTools,selectedToolIds=this.canonicalSelectedToolIds,selectedIds=new Set(selectedToolIds),hasTools=tools.length>0,label=this.label
|
|
36
|
+
`}render(){const projection=this.projection,groups=projection.groups,tools=this.canonicalTools,selectedToolIds=this.canonicalSelectedToolIds,selectedIds=new Set(selectedToolIds),hasTools=tools.length>0,label=this.label==null?this.localize("selectTools"):this.label,searchPlaceholder=this.searchPlaceholder==null?this.localize("searchToolsPlaceholder"):this.searchPlaceholder,searchAccessibleName=searchPlaceholder.trim().length>0?searchPlaceholder:this.localize("searchToolsPlaceholder"),knownIds=new Set(tools.map(tool=>tool.id)),selectedCount=selectedToolIds.filter(id=>knownIds.has(id)).length,number=getNumberFormat(this.effectiveLocale),hostLabel=this.getAttribute("aria-label"),panelLabel=(hostLabel?.trim()?hostLabel:typeof this.accessibleLabel=="string"&&this.accessibleLabel.trim()?this.accessibleLabel:null)??(label.trim().length>0?null:this.localize("selectTools"));return this.nativeModal.render(html`
|
|
37
37
|
<div part="backdrop" @click=${this.onBackdropClick}></div>
|
|
38
38
|
<div
|
|
39
39
|
part="panel"
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{positionIndex}from"../../../internal/keyed-index.js";import{collectionSupport,snapshotPublicCollection}from"../../../internal/collection-snapshot.js";import{boundChartSeriesValues}from"./chart-series-bounds.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{createReducedMotionWatch}from"./chart-surface-shared.js";import{loadChartJs}from"./chart-core-loader.js";import{loadBoxPlotAndRegister}from"./box-plot-loader.js";import{loadBoxPlotAndRegister as loadBoxPlotAndRegister2}from"./box-plot-loader.js";import{onAnnotationPluginRegistered}from"../../../internal/chart-annotation-registration.js";import{styles}from"./box-plot.styles.js";import{chartSurfaceStyles}from"./chart-surface.styles.js";import"../../overlays/skeleton/skeleton.class.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatChartValue}from"./chart-number-format.js";import{isKeyboardFocusEvent}from"../../../internal/focus-modality.js";import{showChartActiveDatum}from"./chart-active-datum.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{FALLBACK_GRID_COLOR,FALLBACK_LEGEND_COLOR,FALLBACK_TICK_COLOR,FALLBACK_TICK_FONT_SIZE,FALLBACK_TOOLTIP_BG,FALLBACK_TOOLTIP_TEXT}from"./chart-colors.js";import{ChartTokenCache}from"./chart-token-cache.js";import{chartDataTableVisible,hasSlottedChartDataTable,hasArraySeriesData}from"./chart-data-table.js";import{createForcedColorPattern,forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{legendVisibilityDetail,normalizeHiddenDatasets}from"./chart-legend-visibility.js";import{sampleChartTableIndexes}from"./chart-table-sampling.js";import{canvasSentence,isolateCanvasLabel,isolateScaleTickLabels,tooltipIsolationHook,bidiStyles,isolateHtml}from"./chart-bidi.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{CSS_NUMBER_SOURCE}from"../../../internal/css-number.js";import{LYRA_DEFAULT_boxPlot,LYRA_DEFAULT_boxPlotData,LYRA_DEFAULT_boxPlotMax,LYRA_DEFAULT_boxPlotMedian,LYRA_DEFAULT_boxPlotMin,LYRA_DEFAULT_boxPlotMissingLibrary,LYRA_DEFAULT_boxPlotQ1,LYRA_DEFAULT_boxPlotQ3,LYRA_DEFAULT_boxPlotSeriesSummary,LYRA_DEFAULT_boxPlotSummaryEmpty,LYRA_DEFAULT_boxPlotSummaryWithData,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartPlotSampled,LYRA_DEFAULT_chartPointLabel,LYRA_DEFAULT_chartRenderUnavailable,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartSeriesNoData,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings/charts.generated.js";import{LYRA_DEFAULT_chartSummarySeparator,LYRA_DEFAULT_chartTrendDecreasing,LYRA_DEFAULT_chartTrendFlat,LYRA_DEFAULT_chartTrendIncreasing,LYRA_DEFAULT_chartValueLabel,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";const DIRECT_PIXEL_NUMBER=new RegExp(`^(${CSS_NUMBER_SOURCE})(?:px)?$`,"i");function isBoxPlotSeries(value){return hasArraySeriesData(value)}function normalizeBoxPlotSeries(value){try{return Object.freeze(Array.isArray(value)?value.filter(isBoxPlotSeries):[])}catch{return Object.freeze([])}}function summaryOf(point){return{min:point.min,q1:point.q1,median:point.median,q3:point.q3,max:point.max}}let boxPlotPlugin;function loadBoxPlotPlugin(){return boxPlotPlugin||(boxPlotPlugin=loadBoxPlotAndRegister()),boxPlotPlugin}class LyraBoxPlot extends LyraElement{static{this.defaultStrings={...super.defaultStrings,boxPlot:LYRA_DEFAULT_boxPlot,boxPlotData:LYRA_DEFAULT_boxPlotData,boxPlotMax:LYRA_DEFAULT_boxPlotMax,boxPlotMedian:LYRA_DEFAULT_boxPlotMedian,boxPlotMin:LYRA_DEFAULT_boxPlotMin,boxPlotMissingLibrary:LYRA_DEFAULT_boxPlotMissingLibrary,boxPlotQ1:LYRA_DEFAULT_boxPlotQ1,boxPlotQ3:LYRA_DEFAULT_boxPlotQ3,boxPlotSeriesSummary:LYRA_DEFAULT_boxPlotSeriesSummary,boxPlotSummaryEmpty:LYRA_DEFAULT_boxPlotSummaryEmpty,boxPlotSummaryWithData:LYRA_DEFAULT_boxPlotSummaryWithData,chartCategory:LYRA_DEFAULT_chartCategory,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartPlotSampled:LYRA_DEFAULT_chartPlotSampled,chartPointLabel:LYRA_DEFAULT_chartPointLabel,chartRenderUnavailable:LYRA_DEFAULT_chartRenderUnavailable,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartSeriesNoData:LYRA_DEFAULT_chartSeriesNoData,chartSummarySeparator:LYRA_DEFAULT_chartSummarySeparator,chartTrendDecreasing:LYRA_DEFAULT_chartTrendDecreasing,chartTrendFlat:LYRA_DEFAULT_chartTrendFlat,chartTrendIncreasing:LYRA_DEFAULT_chartTrendIncreasing,chartValueLabel:LYRA_DEFAULT_chartValueLabel,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary,loading:LYRA_DEFAULT_loading}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["labels","hiddenDatasets"])}static{this.styles=[LyraElement.styles,specialistTokens,chartSurfaceStyles,styles,srOnly,bidiStyles]}static{this.immutableEventDetails=Object.freeze(["lr-legend-visibility-change-request","lr-legend-visibility-change"])}constructor(){super(),this.canvasTokens=new ChartTokenCache(this),this.labels=[],this._datasets=Object.freeze([]),this.datasetsSource=this._datasets,this.withLegend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.withoutZeroBaseline=!1,this.label=null,this.description=null,this.withDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("box-plot-data-table"),this.loading=!0,this.loadFailed=!1,this.canvasUnavailable=!1,this.visible=!0,this.keyboardDatumIndex=0,this.keyboardDatumAnnouncement="",this.intersectionGeneration=0,this.reducedMotionWatch=createReducedMotionWatch(this,()=>this.drawIfVisible()),this.loadGeneration=0,this.descriptionId=nextId("box-plot-description"),this.announcements=new AnnouncementSinkController(this),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.forcedColorPatterns=new Map,this.tooltipIsolationPlugin={id:"lyra-box-plot-bidi",beforeTooltipDraw:tooltipIsolationHook(()=>this.effectiveDirection)},this.keyboardBoxShown=!1,this.onCanvasBlur=()=>{this.showKeyboardBox(void 0)},new ThemeWatcher(this,()=>{this.chart&&this.canvasTokens.hasThemeChanged()&&this.refreshTheme()})}get datasets(){return this._datasets}set datasets(value){if(Object.is(value,this.datasetsSource)||Object.is(value,this._datasets))return;const previous=this._datasets;this.datasetsSource=value,this._datasets=normalizeBoxPlotSeries(snapshotPublicCollection(boundChartSeriesValues(value,6)??value,this.ownerDocument?.defaultView)),this.requestUpdate("datasets",previous)}get dataTableVisible(){return chartDataTableVisible(this.withDataTable,this.dataTableToggle,this.dataTableExpandedOverride)}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}connectedCallback(){super.connectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=onAnnotationPluginRegistered(()=>this.rebuildAfterAnnotationRegistration()),this.visible=!this.ownerWindow?.IntersectionObserver,this.armReducedMotionWatcher();const generation=++this.loadGeneration;loadBoxPlotPlugin().then(boxMod=>this.onBoxPlotPluginLoaded(boxMod,generation));const IntersectionObserverCtor=this.ownerWindow?.IntersectionObserver;if(IntersectionObserverCtor){const ownerWindow=this.ownerWindow,observerGeneration=++this.intersectionGeneration,observer=new IntersectionObserverCtor(entries=>{if(observerGeneration!==this.intersectionGeneration||this.intersectionObserver!==observer||!this.isConnected||this.ownerWindow!==ownerWindow)return;const wasVisible=this.visible;this.visible=entries[0]?.isIntersecting??!0,this.visible&&!wasVisible&&this.drawIfVisible()});this.intersectionObserver=observer,observer.observe(this)}}async onBoxPlotPluginLoaded(boxMod,generation=this.loadGeneration){if(generation!==this.loadGeneration||!this.isConnected)return;try{await this.updateComplete}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),generation!==this.loadGeneration||!this.isConnected)return;if(this.loading=!1,!boxMod){this.loadFailed=!0,this.appliedLegendVisibility=void 0,this.chart?.destroy(),this.chart=void 0,this.chartJsModule=void 0;return}this.loadFailed=!1;const chartMod=await loadChartJs();generation!==this.loadGeneration||!this.isConnected||(this.chartJsModule=chartMod??void 0,this.drawIfVisible())}disconnectedCallback(){super.disconnectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=void 0,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.loadGeneration+=1,this.appliedLegendVisibility=void 0,this.chart?.destroy(),this.chart=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.intersectionGeneration+=1,this.visible=!0,this.disarmReducedMotionWatcher()}adoptedCallback(){this.canvasTokens.clear(),super.adoptedCallback(),this.announcements.adopted(),this.disarmReducedMotionWatcher(),this.armReducedMotionWatcher()}armReducedMotionWatcher(){this.reducedMotionWatch.arm()}disarmReducedMotionWatcher(){this.reducedMotionWatch.disarm()}get ownerWindow(){return this.ownerDocument?.defaultView??void 0}effectiveHiddenDatasetIndexes(){return normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length)??[]}applyDatasetVisibility(){if(!this.chart)return!1;const datasetCount=this.chart.data.datasets?.length??0,sourceSeriesIndexes=this.dataTableSample().seriesIndexes,controlled=normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length);if(controlled===void 0){for(let index=0;index<datasetCount;index++){const metadata=this.chart.getDatasetMeta?.(index);metadata&&(metadata.hidden=null)}return datasetCount>0}const hidden=new Set(controlled);for(let index=0;index<datasetCount;index++)this.chart.setDatasetVisibility(index,!hidden.has(sourceSeriesIndexes[index]??index));return datasetCount>0}updated(changed){super.updated(changed);const appliedVisibility=this.appliedLegendVisibility;if(this.appliedLegendVisibility=void 0,!this.isConnected)return;const wasMounting=this.isMounting;this.isMounting=!1,changed.has("keyboardDatumAnnouncement")&&changed.get("keyboardDatumAnnouncement")!==void 0&&this.keyboardDatumAnnouncement!==""&&this.announcements.announcePolite(this.keyboardDatumAnnouncement),changed.has("loadFailed")&&changed.get("loadFailed")!==void 0&&this.loadFailed&&this.announcements.announceAssertive(this.localize("boxPlotMissingLibrary"));const dataTruncation=this.dataTruncationMessage();if(wasMounting&&(this.lastDataTruncationAnnouncement=dataTruncation),!this.loading&&!this.loadFailed&&!wasMounting&&dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.announcements.announcePolite(dataTruncation)),this.setAttribute("aria-busy",String(this.loading)),changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}if(this.loading)return;const visibilityAlreadyApplied=appliedVisibility!==void 0&&appliedVisibility.chart===this.chart&&appliedVisibility.hidden===this.hiddenDatasets,contentChanged=["labels","datasets","hiddenDatasets","withLegend","legendPosition","height","xLabel","yLabel","withoutZeroBaseline","valueFormatter","formatter","locale","strings","loading"].some(name=>changed.has(name)&&(name!=="hiddenDatasets"||!visibilityAlreadyApplied)),direction=this.effectiveDirection,locale=this.effectiveLocale,contextChanged=this.lastDrawnDirection!==void 0&&this.lastDrawnDirection!==direction||this.lastDrawnLocale!==void 0&&this.lastDrawnLocale!==locale;this.lastDrawnDirection=direction,this.lastDrawnLocale=locale,!(!contentChanged&&!contextChanged)&&this.drawIfVisible()}themeColors(){const cs=this.canvasTokens.sync()??this.style;return{grid:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-grid-color").trim()||cs.getPropertyValue("--_lr-chart-grid-color").trim(),FALLBACK_GRID_COLOR),tick:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tick-color").trim()||cs.getPropertyValue("--_lr-chart-tick-color").trim(),FALLBACK_TICK_COLOR),tickFontSize:this.styleNumber("--lr-chart-tick-font-size",FALLBACK_TICK_FONT_SIZE,"--_lr-chart-tick-font-size"),legend:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-legend-color").trim()||cs.getPropertyValue("--_lr-chart-legend-color").trim(),FALLBACK_LEGEND_COLOR),tooltipBg:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-bg").trim()||cs.getPropertyValue("--_lr-chart-tooltip-bg").trim(),FALLBACK_TOOLTIP_BG),tooltipText:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-color").trim()||cs.getPropertyValue("--_lr-chart-tooltip-color").trim(),FALLBACK_TOOLTIP_TEXT)}}seriesColor(index,palette=this.canvasTokens.palette()){const fallback=palette[index%palette.length]??"transparent",series=this.datasets[index];return series?.color?this.canvasTokens.resolve(series.color,fallback):fallback}seriesBorderColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-border-color-${index%8+1}`,base)}seriesFillColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-fill-color-${index%8+1}`,base)}forcedColorFill(index,background){if(!this.ownerWindow||!forcedColorsActive(this.ownerWindow))return background;const surface=this.forcedColorSurface??=this.styleColor("--lr-color-surface",FALLBACK_TOOLTIP_BG),key=`${index%8}/${background}/${surface}`,cached=this.forcedColorPatterns.get(key);if(cached!==void 0)return cached;const value=createForcedColorPattern(this.ownerDocument,index,background,surface);return this.forcedColorPatterns.set(key,value),value}styleColor(name,fallback){const view=this.ownerWindow,value=(view?view.getComputedStyle(this):this.style).getPropertyValue(name).trim();return value?this.canvasTokens.resolve(value,fallback):fallback}styleNumber(name,fallback,fallbackToken){const view=this.ownerWindow,cs=view?view.getComputedStyle(this):this.style,value=cs.getPropertyValue(name).trim()||(fallbackToken?cs.getPropertyValue(fallbackToken).trim():""),direct=DIRECT_PIXEL_NUMBER.exec(value);if(direct){const resolved2=Number.parseFloat(direct[1]);if(Number.isFinite(resolved2)&&resolved2>=0)return resolved2}if(!value||!view)return fallback;const resolved=this.canvasTokens.length(value,()=>{const probe=this.ownerDocument.createElement("span");probe.hidden=!0,probe.setAttribute("aria-hidden","true"),probe.style.inlineSize=value,(this.shadowRoot??this).append(probe);try{return Number.parseFloat(view.getComputedStyle(probe).inlineSize)}finally{probe.remove()}});return Number.isFinite(resolved)&&resolved>=0?resolved:fallback}buildConfig(){this.forcedColorPatterns.clear(),this.forcedColorSurface=void 0;const theme=this.themeColors(),palette=this.canvasTokens.palette(),sample=this.dataTableSample(),direction=this.effectiveDirection==="rtl"?"rtl":"ltr",afterTickToLabelConversion=scale=>isolateScaleTickLabels(scale,direction);return{type:"boxplot",data:{labels:sample.rowIndexes.map(index=>this.labels[index]??""),datasets:sample.seriesIndexes.map(sourceIndex=>{const s=this.datasets[sourceIndex],fillColor=this.seriesFillColor(sourceIndex,palette),borderColor=this.seriesBorderColor(sourceIndex,palette);return{label:s.label,data:sample.rowIndexes.map(index=>{const point=s.data[index];return this.validPoint(point)?summaryOf(point):null}),backgroundColor:this.forcedColorFill(sourceIndex,fillColor),borderColor}})},options:{locale:this.effectiveLocale,responsive:!0,maintainAspectRatio:!1,animation:prefersReducedMotion(this)?!1:void 0,onClick:(event,_elements,chart)=>this.handlePointClick(event,chart),elements:{boxandwhiskers:{borderWidth:this.styleNumber("--lr-box-plot-border-width",1,"--lr-border-width-thin"),itemRadius:this.styleNumber("--lr-box-plot-item-radius",0)}},plugins:{legend:{display:!1,labels:{color:theme.legend}},tooltip:{backgroundColor:theme.tooltipBg,titleColor:theme.tooltipText,bodyColor:theme.tooltipText,...this.formatter||this.valueFormatter?{callbacks:{label:context=>{const raw=context.raw,point=this.validPoint(raw)?raw:void 0;if(!point)return;const datasetIndex=Number.isInteger(context.datasetIndex)?sample.seriesIndexes[context.datasetIndex]:void 0,index=Number.isInteger(context.dataIndex)?sample.rowIndexes[context.dataIndex]:void 0,lines=this.boxStatistics(point).map(([statistic,name,value])=>canvasSentence(sentenceValue=>this.localize("chartValueLabel",void 0,{label:name,value:sentenceValue}),this.formatValue(value,"tooltip",{...datasetIndex===void 0?{}:{datasetIndex},...index===void 0?{}:{index,label:this.labels[index]||void 0},...datasetIndex===void 0?{}:{seriesLabel:this.datasets[datasetIndex]?.label},statistic,axis:"y"}))),label=String(context.dataset?.label??"");return label?[label,...lines]:lines}}}:{}}},scales:{x:{afterTickToLabelConversion,title:{display:!!this.xLabel,text:isolateCanvasLabel(this.xLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize}},grid:{color:theme.grid}},y:{afterTickToLabelConversion,position:this.effectiveDirection==="rtl"?"right":"left",beginAtZero:!this.withoutZeroBaseline,title:{display:!!this.yLabel,text:isolateCanvasLabel(this.yLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize},...this.formatter||this.valueFormatter?{callback:value=>this.formatValue(Number(value),"tick",{axis:"y"})}:{}},grid:{color:theme.grid}}}}}}draw(){if(!this.chartJsModule||!this.canvasEl)return;if(!this.chart&&!this.canvasEl.getContext("2d")){this.setCanvasUnavailable(!0);return}this.canvasTokens.beginThemeDraw();const config=this.buildConfig();if(this.chart){this.chart.data=config.data,this.chart.options=config.options??{},this.applyDatasetVisibility(),this.chart.update("none"),this.canvasTokens.rememberTheme();return}const candidate=new this.chartJsModule.Chart(this.canvasEl,{...config,plugins:[this.tooltipIsolationPlugin]}),context=candidate;if(context.canvas===null||context.ctx===null){candidate.destroy(),this.setCanvasUnavailable(!0);return}this.chart=candidate,this.setCanvasUnavailable(!1),this.hiddenDatasets!==void 0&&(this.applyDatasetVisibility(),this.chart.update("none")),this.canvasTokens.rememberTheme()}setCanvasUnavailable(unavailable){this.canvasUnavailable!==unavailable&&(this.canvasUnavailable=unavailable,queueMicrotask(()=>{this.isConnected&&this.requestUpdate()}),unavailable&&this.announcements.announceAssertive(this.localize("chartRenderUnavailable")))}drawIfVisible(){!this.isConnected||!this.visible||this.draw()}rebuildAfterAnnotationRegistration(){this.chart&&(this.appliedLegendVisibility=void 0,this.chart.destroy(),this.chart=void 0,this.drawIfVisible())}refreshTheme(){this.canvasTokens.clear(),this.drawIfVisible(),this.withLegend&&this.requestUpdate("canvasPresentation",null)}seriesDisplayLabel(series){return series.label||this.localize("chartSeriesLabel")}formatValue(value,surface,metadata={}){const legacyContext=surface==="export"||surface==="spoken"?"table":surface==="visual"?void 0:surface;return this.formatter?.({value,surface,...metadata})??(legacyContext?this.valueFormatter?.(value,legacyContext):void 0)??(surface==="export"?value:formatChartValue(value,this.effectiveLocale))}exportData(format){if(format==="png")return this.chart?.toBase64Image?.()??"";const header=["category","series","min","q1","median","q3","max"].map(escapeCsvField).join(","),rows=[];return this.datasets.forEach((series,datasetIndex)=>{series.data.forEach((point,index)=>{if(!this.validPoint(point))return;const metadata={datasetIndex,index,label:this.labels[index]||void 0,seriesLabel:series.label,axis:"y"};rows.push([this.labels[index]??"",this.seriesDisplayLabel(series),this.formatValue(point.min,"export",{...metadata,statistic:"min"}),this.formatValue(point.q1,"export",{...metadata,statistic:"q1"}),this.formatValue(point.median,"export",{...metadata,statistic:"median"}),this.formatValue(point.q3,"export",{...metadata,statistic:"q3"}),this.formatValue(point.max,"export",{...metadata,statistic:"max"})].map(escapeCsvField).join(","))})}),[header,...rows].join(`\r
|
|
2
|
-
`)}boxPlotDescription(){if(this.description)return this.description;const keys=[this.datasets,this.labels,this.effectiveLocale,this.strings,this.formatter,this.valueFormatter];if(this.descriptionMemo?.keys.every((key,index)=>key===keys[index]))return this.descriptionMemo.value;const value=this.buildBoxPlotDescription();return this.descriptionMemo={keys,value},value}buildBoxPlotDescription(){const summaries=this.dataTableSample().seriesIndexes.map(index=>{const series=this.datasets[index];let count=0,first=0,last=0,min=0,minIndex=0,max=0,maxIndex=0;for(const[pointIndex,point]of series.data.entries())this.validPoint(point)&&(count===0&&(first=point.median,min=point.median,minIndex=pointIndex,max=point.median,maxIndex=pointIndex),last=point.median,point.median<min&&(min=point.median,minIndex=pointIndex),point.median>max&&(max=point.median,maxIndex=pointIndex),count++);if(count===0)return this.localize("chartSeriesNoData",void 0,{label:this.seriesDisplayLabel(series)});const trend=last>first?this.localize("chartTrendIncreasing"):last<first?this.localize("chartTrendDecreasing"):this.localize("chartTrendFlat");return this.localize("boxPlotSeriesSummary",void 0,{label:this.seriesDisplayLabel(series),count:getNumberFormat(this.effectiveLocale).format(count),min:this.formatValue(min,"spoken",{datasetIndex:index,index:minIndex,label:this.labels[minIndex]||void 0,seriesLabel:series.label,statistic:"median",axis:"y"}),max:this.formatValue(max,"spoken",{datasetIndex:index,index:maxIndex,label:this.labels[maxIndex]||void 0,seriesLabel:series.label,statistic:"median",axis:"y"}),trend})});return summaries.length?this.localize("boxPlotSummaryWithData",void 0,{summaries:summaries.join(this.localize("chartSummarySeparator"))}):this.localize("boxPlotSummaryEmpty")}boxDatums(){const sample=this.dataTableSample();if(this.boxDatumsMemo?.sample===sample)return this.boxDatumsMemo.value;const datums=[];for(const datasetIndex of sample.seriesIndexes){const series=this.datasets[datasetIndex];if(series)for(const index of sample.rowIndexes){const point=series.data[index];this.validPoint(point)&&datums.push({datasetIndex,index,label:this.labels[index]||void 0,value:summaryOf(point)})}}return this.boxDatumsMemo={sample,value:datums},datums}boxStatistics(point){return[["min",this.localize("boxPlotMin"),point.min],["q1",this.localize("boxPlotQ1"),point.q1],["median",this.localize("boxPlotMedian"),point.median],["q3",this.localize("boxPlotQ3"),point.q3],["max",this.localize("boxPlotMax"),point.max]]}boxAnnouncement(datum,position,total){const numberFormat=getNumberFormat(this.effectiveLocale),point=datum.value,summary=(point?this.boxStatistics(point):[]).filter(([,,value])=>Number.isFinite(value)).map(([statistic,label,value])=>this.localize("chartValueLabel",void 0,{label,value:this.formatValue(value,"spoken",{datasetIndex:datum.datasetIndex,index:datum.index,label:datum.label,seriesLabel:this.datasets[datum.datasetIndex]?.label,statistic,axis:"y"})})).join(this.localize("chartSummarySeparator"));return this.localize("liteChartMarkSummary",void 0,{series:this.datasets[datum.datasetIndex]?.label||this.localize("chartSeriesLabel"),label:datum.label??this.localize("chartPointLabel",void 0,{n:numberFormat.format(datum.index+1)}),value:summary,index:numberFormat.format(position+1),total:numberFormat.format(total)})}activateBox(datum){const datums=this.boxDatums(),position=datums.findIndex(candidate=>candidate.datasetIndex===datum.datasetIndex&&candidate.index===datum.index);position>=0&&(this.keyboardDatumIndex=position,this.keyboardDatumAnnouncement=this.boxAnnouncement(datum,position,datums.length)),this.emit("lr-datum-activate",{...datum,kind:"box"}),this.emit("lr-point-activate",{...datum})}handlePointClick(event,chart){
|
|
1
|
+
import{__decorate}from"tslib";import{positionIndex}from"../../../internal/keyed-index.js";import{collectionSupport,snapshotPublicCollection}from"../../../internal/collection-snapshot.js";import{boundChartSeriesValues}from"./chart-series-bounds.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{createReducedMotionWatch}from"./chart-surface-shared.js";import{loadChartJs}from"./chart-core-loader.js";import{loadBoxPlotAndRegister}from"./box-plot-loader.js";import{loadBoxPlotAndRegister as loadBoxPlotAndRegister2}from"./box-plot-loader.js";import{onAnnotationPluginRegistered}from"../../../internal/chart-annotation-registration.js";import{styles}from"./box-plot.styles.js";import{chartSurfaceStyles}from"./chart-surface.styles.js";import"../../overlays/skeleton/skeleton.class.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatChartValue}from"./chart-number-format.js";import{isKeyboardFocusEvent}from"../../../internal/focus-modality.js";import{showChartActiveDatum}from"./chart-active-datum.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{FALLBACK_GRID_COLOR,FALLBACK_LEGEND_COLOR,FALLBACK_TICK_COLOR,FALLBACK_TICK_FONT_SIZE,FALLBACK_TOOLTIP_BG,FALLBACK_TOOLTIP_TEXT}from"./chart-colors.js";import{ChartTokenCache}from"./chart-token-cache.js";import{chartDataTableVisible,hasSlottedChartDataTable,hasArraySeriesData}from"./chart-data-table.js";import{createForcedColorPattern,forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{legendVisibilityDetail,normalizeHiddenDatasets}from"./chart-legend-visibility.js";import{sampleChartTableIndexes}from"./chart-table-sampling.js";import{canvasSentence,isolateCanvasLabel,isolateScaleTickLabels,tooltipIsolationHook,bidiStyles,isolateHtml}from"./chart-bidi.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{CSS_NUMBER_SOURCE}from"../../../internal/css-number.js";import{LYRA_DEFAULT_boxPlot,LYRA_DEFAULT_boxPlotData,LYRA_DEFAULT_boxPlotMax,LYRA_DEFAULT_boxPlotMedian,LYRA_DEFAULT_boxPlotMin,LYRA_DEFAULT_boxPlotMissingLibrary,LYRA_DEFAULT_boxPlotQ1,LYRA_DEFAULT_boxPlotQ3,LYRA_DEFAULT_boxPlotSeriesSummary,LYRA_DEFAULT_boxPlotSummaryEmpty,LYRA_DEFAULT_boxPlotSummaryWithData,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartPlotSampled,LYRA_DEFAULT_chartPointLabel,LYRA_DEFAULT_chartRenderUnavailable,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartSeriesNoData,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings/charts.generated.js";import{LYRA_DEFAULT_chartSummarySeparator,LYRA_DEFAULT_chartTrendDecreasing,LYRA_DEFAULT_chartTrendFlat,LYRA_DEFAULT_chartTrendIncreasing,LYRA_DEFAULT_chartValueLabel,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";const DIRECT_PIXEL_NUMBER=new RegExp(`^(${CSS_NUMBER_SOURCE})(?:px)?$`,"i");function isBoxPlotSeries(value){return hasArraySeriesData(value)}function normalizeBoxPlotSeries(value){try{return Object.freeze(Array.isArray(value)?value.filter(isBoxPlotSeries):[])}catch{return Object.freeze([])}}function summaryOf(point){return{min:point.min,q1:point.q1,median:point.median,q3:point.q3,max:point.max}}let boxPlotPlugin;function loadBoxPlotPlugin(){return boxPlotPlugin||(boxPlotPlugin=loadBoxPlotAndRegister()),boxPlotPlugin}class LyraBoxPlot extends LyraElement{static{this.defaultStrings={...super.defaultStrings,boxPlot:LYRA_DEFAULT_boxPlot,boxPlotData:LYRA_DEFAULT_boxPlotData,boxPlotMax:LYRA_DEFAULT_boxPlotMax,boxPlotMedian:LYRA_DEFAULT_boxPlotMedian,boxPlotMin:LYRA_DEFAULT_boxPlotMin,boxPlotMissingLibrary:LYRA_DEFAULT_boxPlotMissingLibrary,boxPlotQ1:LYRA_DEFAULT_boxPlotQ1,boxPlotQ3:LYRA_DEFAULT_boxPlotQ3,boxPlotSeriesSummary:LYRA_DEFAULT_boxPlotSeriesSummary,boxPlotSummaryEmpty:LYRA_DEFAULT_boxPlotSummaryEmpty,boxPlotSummaryWithData:LYRA_DEFAULT_boxPlotSummaryWithData,chartCategory:LYRA_DEFAULT_chartCategory,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartPlotSampled:LYRA_DEFAULT_chartPlotSampled,chartPointLabel:LYRA_DEFAULT_chartPointLabel,chartRenderUnavailable:LYRA_DEFAULT_chartRenderUnavailable,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartSeriesNoData:LYRA_DEFAULT_chartSeriesNoData,chartSummarySeparator:LYRA_DEFAULT_chartSummarySeparator,chartTrendDecreasing:LYRA_DEFAULT_chartTrendDecreasing,chartTrendFlat:LYRA_DEFAULT_chartTrendFlat,chartTrendIncreasing:LYRA_DEFAULT_chartTrendIncreasing,chartValueLabel:LYRA_DEFAULT_chartValueLabel,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary,loading:LYRA_DEFAULT_loading}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["labels","hiddenDatasets"])}static{this.styles=[LyraElement.styles,specialistTokens,chartSurfaceStyles,styles,srOnly,bidiStyles]}static{this.immutableEventDetails=Object.freeze(["lr-legend-visibility-change-request","lr-legend-visibility-change"])}constructor(){super(),this.canvasTokens=new ChartTokenCache(this),this.labels=[],this._datasets=Object.freeze([]),this.datasetsSource=this._datasets,this.withLegend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.withoutZeroBaseline=!1,this.label=null,this.description=null,this.withDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("box-plot-data-table"),this.loading=!0,this.loadFailed=!1,this.canvasUnavailable=!1,this.visible=!0,this.keyboardDatumIndex=0,this.keyboardDatumAnnouncement="",this.intersectionGeneration=0,this.reducedMotionWatch=createReducedMotionWatch(this,()=>this.drawIfVisible()),this.loadGeneration=0,this.descriptionId=nextId("box-plot-description"),this.announcements=new AnnouncementSinkController(this),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.forcedColorPatterns=new Map,this.tooltipIsolationPlugin={id:"lyra-box-plot-bidi",beforeTooltipDraw:tooltipIsolationHook(()=>this.effectiveDirection)},this.keyboardBoxShown=!1,this.onCanvasBlur=()=>{this.showKeyboardBox(void 0)},new ThemeWatcher(this,()=>{this.chart&&this.canvasTokens.hasThemeChanged()&&this.refreshTheme()})}get datasets(){return this._datasets}set datasets(value){if(Object.is(value,this.datasetsSource)||Object.is(value,this._datasets))return;const previous=this._datasets;this.datasetsSource=value,this._datasets=normalizeBoxPlotSeries(snapshotPublicCollection(boundChartSeriesValues(value,6)??value,this.ownerDocument?.defaultView)),this.requestUpdate("datasets",previous)}get dataTableVisible(){return chartDataTableVisible(this.withDataTable,this.dataTableToggle,this.dataTableExpandedOverride)}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}connectedCallback(){super.connectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=onAnnotationPluginRegistered(()=>this.rebuildAfterAnnotationRegistration()),this.visible=!this.ownerWindow?.IntersectionObserver,this.armReducedMotionWatcher();const generation=++this.loadGeneration;loadBoxPlotPlugin().then(boxMod=>this.onBoxPlotPluginLoaded(boxMod,generation));const IntersectionObserverCtor=this.ownerWindow?.IntersectionObserver;if(IntersectionObserverCtor){const ownerWindow=this.ownerWindow,observerGeneration=++this.intersectionGeneration,observer=new IntersectionObserverCtor(entries=>{if(observerGeneration!==this.intersectionGeneration||this.intersectionObserver!==observer||!this.isConnected||this.ownerWindow!==ownerWindow)return;const wasVisible=this.visible;this.visible=entries[0]?.isIntersecting??!0,this.visible&&!wasVisible&&this.drawIfVisible()});this.intersectionObserver=observer,observer.observe(this)}}async onBoxPlotPluginLoaded(boxMod,generation=this.loadGeneration){if(generation!==this.loadGeneration||!this.isConnected)return;try{await this.updateComplete}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),generation!==this.loadGeneration||!this.isConnected)return;if(this.loading=!1,!boxMod){this.loadFailed=!0,this.appliedLegendVisibility=void 0,this.chart?.destroy(),this.chart=void 0,this.chartJsModule=void 0;return}this.loadFailed=!1;const chartMod=await loadChartJs();generation!==this.loadGeneration||!this.isConnected||(this.chartJsModule=chartMod??void 0,this.drawIfVisible())}disconnectedCallback(){super.disconnectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=void 0,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.loadGeneration+=1,this.appliedLegendVisibility=void 0,this.chart?.destroy(),this.chart=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.intersectionGeneration+=1,this.visible=!0,this.disarmReducedMotionWatcher()}adoptedCallback(){this.canvasTokens.clear(),super.adoptedCallback(),this.announcements.adopted(),this.disarmReducedMotionWatcher(),this.armReducedMotionWatcher()}armReducedMotionWatcher(){this.reducedMotionWatch.arm()}disarmReducedMotionWatcher(){this.reducedMotionWatch.disarm()}get ownerWindow(){return this.ownerDocument?.defaultView??void 0}effectiveHiddenDatasetIndexes(){return normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length)??[]}applyDatasetVisibility(){if(!this.chart)return!1;const datasetCount=this.chart.data.datasets?.length??0,sourceSeriesIndexes=this.dataTableSample().seriesIndexes,controlled=normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length);if(controlled===void 0){for(let index=0;index<datasetCount;index++){const metadata=this.chart.getDatasetMeta?.(index);metadata&&(metadata.hidden=null)}return datasetCount>0}const hidden=new Set(controlled);for(let index=0;index<datasetCount;index++)this.chart.setDatasetVisibility(index,!hidden.has(sourceSeriesIndexes[index]??index));return datasetCount>0}updated(changed){super.updated(changed);const appliedVisibility=this.appliedLegendVisibility;if(this.appliedLegendVisibility=void 0,!this.isConnected)return;const wasMounting=this.isMounting;this.isMounting=!1,changed.has("keyboardDatumAnnouncement")&&changed.get("keyboardDatumAnnouncement")!==void 0&&this.keyboardDatumAnnouncement!==""&&this.announcements.announcePolite(this.keyboardDatumAnnouncement),changed.has("loadFailed")&&changed.get("loadFailed")!==void 0&&this.loadFailed&&this.announcements.announceAssertive(this.localize("boxPlotMissingLibrary"));const dataTruncation=this.dataTruncationMessage();if(wasMounting&&(this.lastDataTruncationAnnouncement=dataTruncation),!this.loading&&!this.loadFailed&&!wasMounting&&dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.announcements.announcePolite(dataTruncation)),this.setAttribute("aria-busy",String(this.loading)),changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}if(this.loading)return;const visibilityAlreadyApplied=appliedVisibility!==void 0&&appliedVisibility.chart===this.chart&&appliedVisibility.hidden===this.hiddenDatasets,contentChanged=["labels","datasets","hiddenDatasets","withLegend","legendPosition","height","xLabel","yLabel","withoutZeroBaseline","valueFormatter","formatter","locale","strings","loading"].some(name=>changed.has(name)&&(name!=="hiddenDatasets"||!visibilityAlreadyApplied)),direction=this.effectiveDirection,locale=this.effectiveLocale,contextChanged=this.lastDrawnDirection!==void 0&&this.lastDrawnDirection!==direction||this.lastDrawnLocale!==void 0&&this.lastDrawnLocale!==locale;this.lastDrawnDirection=direction,this.lastDrawnLocale=locale,!(!contentChanged&&!contextChanged)&&this.drawIfVisible()}themeColors(){const cs=this.canvasTokens.sync()??this.style;return{grid:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-grid-color").trim()||cs.getPropertyValue("--_lr-chart-grid-color").trim(),FALLBACK_GRID_COLOR),tick:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tick-color").trim()||cs.getPropertyValue("--_lr-chart-tick-color").trim(),FALLBACK_TICK_COLOR),tickFontSize:this.styleNumber("--lr-chart-tick-font-size",FALLBACK_TICK_FONT_SIZE,"--_lr-chart-tick-font-size"),legend:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-legend-color").trim()||cs.getPropertyValue("--_lr-chart-legend-color").trim(),FALLBACK_LEGEND_COLOR),tooltipBg:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-bg").trim()||cs.getPropertyValue("--_lr-chart-tooltip-bg").trim(),FALLBACK_TOOLTIP_BG),tooltipText:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-color").trim()||cs.getPropertyValue("--_lr-chart-tooltip-color").trim(),FALLBACK_TOOLTIP_TEXT)}}seriesColor(index,palette=this.canvasTokens.palette()){const fallback=palette[index%palette.length]??"transparent",series=this.datasets[index];return series?.color?this.canvasTokens.resolve(series.color,fallback):fallback}seriesBorderColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-border-color-${index%8+1}`,base)}seriesFillColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-fill-color-${index%8+1}`,base)}forcedColorFill(index,background){if(!this.ownerWindow||!forcedColorsActive(this.ownerWindow))return background;const surface=this.forcedColorSurface??=this.styleColor("--lr-color-surface",FALLBACK_TOOLTIP_BG),key=`${index%8}/${background}/${surface}`,cached=this.forcedColorPatterns.get(key);if(cached!==void 0)return cached;const value=createForcedColorPattern(this.ownerDocument,index,background,surface);return this.forcedColorPatterns.set(key,value),value}styleColor(name,fallback){const view=this.ownerWindow,value=(view?view.getComputedStyle(this):this.style).getPropertyValue(name).trim();return value?this.canvasTokens.resolve(value,fallback):fallback}styleNumber(name,fallback,fallbackToken){const view=this.ownerWindow,cs=view?view.getComputedStyle(this):this.style,value=cs.getPropertyValue(name).trim()||(fallbackToken?cs.getPropertyValue(fallbackToken).trim():""),direct=DIRECT_PIXEL_NUMBER.exec(value);if(direct){const resolved2=Number.parseFloat(direct[1]);if(Number.isFinite(resolved2)&&resolved2>=0)return resolved2}if(!value||!view)return fallback;const resolved=this.canvasTokens.length(value,()=>{const probe=this.ownerDocument.createElement("span");probe.hidden=!0,probe.setAttribute("aria-hidden","true"),probe.style.inlineSize=value,(this.shadowRoot??this).append(probe);try{return Number.parseFloat(view.getComputedStyle(probe).inlineSize)}finally{probe.remove()}});return Number.isFinite(resolved)&&resolved>=0?resolved:fallback}buildConfig(){this.forcedColorPatterns.clear(),this.forcedColorSurface=void 0;const theme=this.themeColors(),palette=this.canvasTokens.palette(),sample=this.dataTableSample(),direction=this.effectiveDirection==="rtl"?"rtl":"ltr",afterTickToLabelConversion=scale=>isolateScaleTickLabels(scale,direction);return{type:"boxplot",data:{labels:sample.rowIndexes.map(index=>this.labels[index]??""),datasets:sample.seriesIndexes.map(sourceIndex=>{const s=this.datasets[sourceIndex],fillColor=this.seriesFillColor(sourceIndex,palette),borderColor=this.seriesBorderColor(sourceIndex,palette);return{label:s.label,data:sample.rowIndexes.map(index=>{const point=s.data[index];return this.validPoint(point)?summaryOf(point):null}),backgroundColor:this.forcedColorFill(sourceIndex,fillColor),borderColor}})},options:{locale:this.effectiveLocale,responsive:!0,maintainAspectRatio:!1,animation:prefersReducedMotion(this)?!1:void 0,onClick:(event,_elements,chart)=>this.handlePointClick(event,chart),elements:{boxandwhiskers:{borderWidth:this.styleNumber("--lr-box-plot-border-width",1,"--lr-border-width-thin"),itemRadius:this.styleNumber("--lr-box-plot-item-radius",0)}},plugins:{legend:{display:!1,labels:{color:theme.legend}},tooltip:{backgroundColor:theme.tooltipBg,titleColor:theme.tooltipText,bodyColor:theme.tooltipText,...this.formatter||this.valueFormatter?{callbacks:{label:context=>{const raw=context.raw,point=this.validPoint(raw)?raw:void 0;if(!point)return;const datasetIndex=Number.isInteger(context.datasetIndex)?sample.seriesIndexes[context.datasetIndex]:void 0,index=Number.isInteger(context.dataIndex)?sample.rowIndexes[context.dataIndex]:void 0,lines=this.boxStatistics(point).map(([statistic,name,value])=>canvasSentence(sentenceValue=>this.localize("chartValueLabel",void 0,{label:name,value:sentenceValue}),this.formatValue(value,"tooltip",{...datasetIndex===void 0?{}:{datasetIndex},...index===void 0?{}:{index,label:this.labels[index]||void 0},...datasetIndex===void 0?{}:{seriesLabel:this.datasets[datasetIndex]?.label},statistic,axis:"y"}))),label=String(context.dataset?.label??"");return label?[label,...lines]:lines}}}:{}}},scales:{x:{afterTickToLabelConversion,title:{display:!!this.xLabel,text:isolateCanvasLabel(this.xLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize}},grid:{color:theme.grid}},y:{afterTickToLabelConversion,position:this.effectiveDirection==="rtl"?"right":"left",beginAtZero:!this.withoutZeroBaseline,title:{display:!!this.yLabel,text:isolateCanvasLabel(this.yLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize},...this.formatter||this.valueFormatter?{callback:value=>this.formatValue(Number(value),"tick",{axis:"y"})}:{}},grid:{color:theme.grid}}}}}}draw(){if(!this.chartJsModule||!this.canvasEl||!this.ownerWindow)return;if(!this.chart&&!this.canvasEl.getContext("2d")){this.setCanvasUnavailable(!0);return}this.canvasTokens.beginThemeDraw();const config=this.buildConfig();if(this.chart){this.chart.data=config.data,this.chart.options=config.options??{},this.applyDatasetVisibility(),this.chart.update("none"),this.canvasTokens.rememberTheme();return}const candidate=new this.chartJsModule.Chart(this.canvasEl,{...config,plugins:[this.tooltipIsolationPlugin]}),context=candidate;if(context.canvas===null||context.ctx===null){candidate.destroy(),this.setCanvasUnavailable(!0);return}this.chart=candidate,this.setCanvasUnavailable(!1),this.hiddenDatasets!==void 0&&(this.applyDatasetVisibility(),this.chart.update("none")),this.canvasTokens.rememberTheme()}setCanvasUnavailable(unavailable){this.canvasUnavailable!==unavailable&&(this.canvasUnavailable=unavailable,queueMicrotask(()=>{this.isConnected&&this.requestUpdate()}),unavailable&&this.announcements.announceAssertive(this.localize("chartRenderUnavailable")))}drawIfVisible(){!this.isConnected||!this.visible||this.draw()}rebuildAfterAnnotationRegistration(){this.chart&&(this.appliedLegendVisibility=void 0,this.chart.destroy(),this.chart=void 0,this.drawIfVisible())}refreshTheme(){this.canvasTokens.clear(),this.drawIfVisible(),this.withLegend&&this.requestUpdate("canvasPresentation",null)}seriesDisplayLabel(series){return series.label||this.localize("chartSeriesLabel")}formatValue(value,surface,metadata={}){const legacyContext=surface==="export"||surface==="spoken"?"table":surface==="visual"?void 0:surface;return this.formatter?.({value,surface,...metadata})??(legacyContext?this.valueFormatter?.(value,legacyContext):void 0)??(surface==="export"?value:formatChartValue(value,this.effectiveLocale))}exportData(format){if(format==="png")return this.chart?.toBase64Image?.()??"";const header=["category","series","min","q1","median","q3","max"].map(escapeCsvField).join(","),rows=[];return this.datasets.forEach((series,datasetIndex)=>{series.data.forEach((point,index)=>{if(!this.validPoint(point))return;const metadata={datasetIndex,index,label:this.labels[index]||void 0,seriesLabel:series.label,axis:"y"};rows.push([this.labels[index]??"",this.seriesDisplayLabel(series),this.formatValue(point.min,"export",{...metadata,statistic:"min"}),this.formatValue(point.q1,"export",{...metadata,statistic:"q1"}),this.formatValue(point.median,"export",{...metadata,statistic:"median"}),this.formatValue(point.q3,"export",{...metadata,statistic:"q3"}),this.formatValue(point.max,"export",{...metadata,statistic:"max"})].map(escapeCsvField).join(","))})}),[header,...rows].join(`\r
|
|
2
|
+
`)}boxPlotDescription(){if(this.description)return this.description;const keys=[this.datasets,this.labels,this.effectiveLocale,this.strings,this.formatter,this.valueFormatter];if(this.descriptionMemo?.keys.every((key,index)=>key===keys[index]))return this.descriptionMemo.value;const value=this.buildBoxPlotDescription();return this.descriptionMemo={keys,value},value}buildBoxPlotDescription(){const summaries=this.dataTableSample().seriesIndexes.map(index=>{const series=this.datasets[index];let count=0,first=0,last=0,min=0,minIndex=0,max=0,maxIndex=0;for(const[pointIndex,point]of series.data.entries())this.validPoint(point)&&(count===0&&(first=point.median,min=point.median,minIndex=pointIndex,max=point.median,maxIndex=pointIndex),last=point.median,point.median<min&&(min=point.median,minIndex=pointIndex),point.median>max&&(max=point.median,maxIndex=pointIndex),count++);if(count===0)return this.localize("chartSeriesNoData",void 0,{label:this.seriesDisplayLabel(series)});const trend=last>first?this.localize("chartTrendIncreasing"):last<first?this.localize("chartTrendDecreasing"):this.localize("chartTrendFlat");return this.localize("boxPlotSeriesSummary",void 0,{label:this.seriesDisplayLabel(series),count:getNumberFormat(this.effectiveLocale).format(count),min:this.formatValue(min,"spoken",{datasetIndex:index,index:minIndex,label:this.labels[minIndex]||void 0,seriesLabel:series.label,statistic:"median",axis:"y"}),max:this.formatValue(max,"spoken",{datasetIndex:index,index:maxIndex,label:this.labels[maxIndex]||void 0,seriesLabel:series.label,statistic:"median",axis:"y"}),trend})});return summaries.length?this.localize("boxPlotSummaryWithData",void 0,{summaries:summaries.join(this.localize("chartSummarySeparator"))}):this.localize("boxPlotSummaryEmpty")}boxDatums(){const sample=this.dataTableSample();if(this.boxDatumsMemo?.sample===sample)return this.boxDatumsMemo.value;const datums=[];for(const datasetIndex of sample.seriesIndexes){const series=this.datasets[datasetIndex];if(series)for(const index of sample.rowIndexes){const point=series.data[index];this.validPoint(point)&&datums.push({datasetIndex,index,label:this.labels[index]||void 0,value:summaryOf(point)})}}return this.boxDatumsMemo={sample,value:datums},datums}boxStatistics(point){return[["min",this.localize("boxPlotMin"),point.min],["q1",this.localize("boxPlotQ1"),point.q1],["median",this.localize("boxPlotMedian"),point.median],["q3",this.localize("boxPlotQ3"),point.q3],["max",this.localize("boxPlotMax"),point.max]]}boxAnnouncement(datum,position,total){const numberFormat=getNumberFormat(this.effectiveLocale),point=datum.value,summary=(point?this.boxStatistics(point):[]).filter(([,,value])=>Number.isFinite(value)).map(([statistic,label,value])=>this.localize("chartValueLabel",void 0,{label,value:this.formatValue(value,"spoken",{datasetIndex:datum.datasetIndex,index:datum.index,label:datum.label,seriesLabel:this.datasets[datum.datasetIndex]?.label,statistic,axis:"y"})})).join(this.localize("chartSummarySeparator"));return this.localize("liteChartMarkSummary",void 0,{series:this.datasets[datum.datasetIndex]?.label||this.localize("chartSeriesLabel"),label:datum.label??this.localize("chartPointLabel",void 0,{n:numberFormat.format(datum.index+1)}),value:summary,index:numberFormat.format(position+1),total:numberFormat.format(total)})}activateBox(datum){const datums=this.boxDatums(),position=datums.findIndex(candidate=>candidate.datasetIndex===datum.datasetIndex&&candidate.index===datum.index);position>=0&&(this.keyboardDatumIndex=position,this.keyboardDatumAnnouncement=this.boxAnnouncement(datum,position,datums.length)),this.emit("lr-datum-activate",{...datum,kind:"box"}),this.emit("lr-point-activate",{...datum})}handlePointClick(event,chart){if(!this.isConnected||chart!==this.chart)return;let hit;try{hit=chart.getElementsAtEventForMode?.(event,"nearest",{intersect:!0},!0)?.[0]}catch{return}if(!hit||!this.isConnected||chart!==this.chart)return;const sample=this.dataTableSample(),datasetIndex=sample.seriesIndexes[hit.datasetIndex],index=sample.rowIndexes[hit.index];if(datasetIndex===void 0||index===void 0||!this.isConnected||chart!==this.chart)return;const point=this.datasets[datasetIndex]?.data[index];this.activateBox({datasetIndex,index,label:this.labels[index]||void 0,value:this.validPoint(point)?summaryOf(point):null})}showKeyboardBox(datum){if(!this.chart||!datum&&!this.keyboardBoxShown)return;const sample=this.dataTableSample();this.keyboardBoxShown=showChartActiveDatum(this.chart,datum&&{datasetIndex:positionIndex(sample.seriesIndexes).get(datum.datasetIndex)??-1,index:positionIndex(sample.rowIndexes).get(datum.index)??-1})}onCanvasFocus(event){const datums=this.boxDatums();datums.length&&(this.keyboardDatumIndex=Math.min(this.keyboardDatumIndex,datums.length-1),isKeyboardFocusEvent(event)&&this.showKeyboardBox(datums[this.keyboardDatumIndex]),this.keyboardDatumAnnouncement=this.boxAnnouncement(datums[this.keyboardDatumIndex],this.keyboardDatumIndex,datums.length))}onCanvasKeyDown(event){const datums=this.boxDatums();if(!datums.length)return;if(this.keyboardDatumIndex=Math.min(this.keyboardDatumIndex,datums.length-1),event.key==="Enter"||event.key===" "){event.preventDefault(),this.activateBox(datums[this.keyboardDatumIndex]);return}const rtl=this.effectiveDirection==="rtl",forward=rtl?"ArrowLeft":"ArrowRight",backward=rtl?"ArrowRight":"ArrowLeft";let next=this.keyboardDatumIndex;if(event.key===forward||event.key==="ArrowDown")next=Math.min(datums.length-1,next+1);else if(event.key===backward||event.key==="ArrowUp")next=Math.max(0,next-1);else if(event.key==="Home")next=0;else if(event.key==="End")next=datums.length-1;else return;event.preventDefault(),this.keyboardDatumIndex=next,this.showKeyboardBox(datums[next]),this.keyboardDatumAnnouncement=this.boxAnnouncement(datums[next],next,datums.length)}validPoint(point){return!!point&&[point.min,point.q1,point.median,point.q3,point.max].every(Number.isFinite)&&point.min<=point.q1&&point.q1<=point.median&&point.median<=point.q3&&point.q3<=point.max}accessibleName(fallback){return this.getAttribute("aria-label")??this.label??fallback}dataTableSample(){if(this.sampleMemo?.datasets===this.datasets&&this.sampleMemo.labels===this.labels)return this.sampleMemo.value;let rowCount=this.labels.length;for(const series of this.datasets)rowCount=Math.max(rowCount,series.data.length);const indexes=sampleChartTableIndexes(rowCount,this.datasets.length),value={rowCount,seriesCount:this.datasets.length,...indexes};return this.sampleMemo={datasets:this.datasets,labels:this.labels,value},value}generatedDataIsSampled(){const sample=this.dataTableSample();return sample.rowCount===0||sample.seriesCount===0?!1:sample.rowIndexes.length<sample.rowCount||sample.seriesIndexes.length<sample.seriesCount}dataTruncationMessage(){return this.generatedDataIsSampled()?this.hasCustomDataTable()?this.localize("chartPlotSampled"):this.localize("chartDataSampled"):""}requestUpdate(...args){const key=args[0];key===void 0&&(this.descriptionMemo=void 0),(key===void 0||["datasets","labels","formatter","valueFormatter","locale","strings","withDataTable","dataTableToggle","dataTableExpandedOverride"].includes(String(key)))&&(this.dataTableRows=void 0),super.requestUpdate(...args)}renderDataTableRows(){if(this.dataTableRows)return this.dataTableRows;const numberFormat=getNumberFormat(this.effectiveLocale),direction=this.effectiveDirection==="rtl"?"rtl":"ltr",sample=this.dataTableSample();return this.dataTableRows=sample.seriesIndexes.flatMap(seriesIndex=>{const series=this.datasets[seriesIndex];return sample.rowIndexes.map(index=>{const point=series.data[index],metadata={datasetIndex:seriesIndex,index,label:this.labels[index]||void 0,seriesLabel:series.label,axis:"y"};return this.validPoint(point)?html`
|
|
3
3
|
<tr>
|
|
4
4
|
<th scope="row">${isolateHtml(this.labels[index]||this.localize("chartPointLabel",void 0,{n:numberFormat.format(index+1)}),direction)}</th>
|
|
5
5
|
<td>${isolateHtml(this.seriesDisplayLabel(series),direction)}</td>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{adoptChartSyncStyles}from"./chart-sync-style-adoption.js";const documents=new WeakMap;class ChartSyncController{constructor(host,project,reset,isNavigationTarget){this.host=host,this.project=project,this.reset=reset,this.isNavigationTarget=isNavigationTarget,this.groupName="",this.scrollTargets=[],this.shown=!1,this.onLeave=()=>{this.clear()},this.onKeyDown=event=>{event.key==="Escape"&&this.clear()},this.onScroll=event=>{if(!this.shown&&(!this.group?.active||this.group.frame!==void 0))return;const target=event.target;target&&typeof target.nodeType=="number"&&(target===this.document||this.includesComposed(target,this.host)||this.includesComposed(this.host,target))&&(this.clear(),this.receive())},this.onBlur=event=>{const target=event.relatedTarget;target&&typeof target.nodeType=="number"&&(this.isNavigationTarget?this.isNavigationTarget(target):this.includesComposed(this.host,target))||this.clear()}}get enabled(){return this.group!==void 0}update(name,compatible,invalidateOwner=!1){const normalized=typeof name=="string"&&compatible?name.trim():"";if(!this.host.isConnected||!normalized){this.disconnect();return}const doc=this.host.ownerDocument;if(doc!==this.document||normalized!==this.groupName){this.disconnect();let groups=documents.get(doc);groups||(groups=new Map,documents.set(doc,groups));let group=groups.get(normalized);group||(group={members:new Set},groups.set(normalized,group)),this.document=doc,this.groupName=normalized,this.group=group,group.members.add(this),this.host.addEventListener("pointerleave",this.onLeave),this.host.addEventListener("pointercancel",this.onLeave),this.host.addEventListener("focusout",this.onBlur),this.host.shadowRoot?.addEventListener("focusout",this.onBlur),this.host.addEventListener("keydown",this.onKeyDown);const roots=new Set([doc]);this.host.shadowRoot&&roots.add(this.host.shadowRoot);for(let node=this.host;node;node=this.composedParent(node))roots.add(node.getRootNode());this.scrollTargets=[...roots];for(const root of this.scrollTargets)root.addEventListener("scroll",this.onScroll,!0)}this.releaseStyles??=adoptChartSyncStyles(this.host),invalidateOwner&&this.group?.active?.owner===this&&this.clear(),this.receive()}publish(label,index){if(!label||!this.group){this.clear();return}const active=this.group.active;if(this.shown&&active?.owner===this&&active.label===label&&active.index===index)return;const group=this.group;if(group.active={owner:this,label,index},group.frame!==void 0)return;const view=this.document?.defaultView;view&&(group.frame=view.requestAnimationFrame(()=>{group.frame=void 0;const current=group.active;if(!current)return;const presentations=[...group.members].map(member=>({member,presentation:member.host.isConnected?member.
|
|
1
|
+
import{adoptChartSyncStyles}from"./chart-sync-style-adoption.js";const documents=new WeakMap;class ChartSyncController{constructor(host,project,reset,isNavigationTarget){this.host=host,this.project=project,this.reset=reset,this.isNavigationTarget=isNavigationTarget,this.groupName="",this.scrollTargets=[],this.shown=!1,this.onLeave=()=>{this.clear()},this.onKeyDown=event=>{event.key==="Escape"&&this.clear()},this.onScroll=event=>{if(!this.shown&&(!this.group?.active||this.group.frame!==void 0))return;const target=event.target;target&&typeof target.nodeType=="number"&&(target===this.document||this.includesComposed(target,this.host)||this.includesComposed(this.host,target))&&(this.clear(),this.receive())},this.onBlur=event=>{const target=event.relatedTarget;target&&typeof target.nodeType=="number"&&(this.isNavigationTarget?this.isNavigationTarget(target):this.includesComposed(this.host,target))||this.clear()}}get enabled(){return this.group!==void 0}update(name,compatible,invalidateOwner=!1){const normalized=typeof name=="string"&&compatible?name.trim():"";if(!this.host.isConnected||!normalized){this.disconnect();return}const doc=this.host.ownerDocument;if(doc!==this.document||normalized!==this.groupName){this.disconnect();let groups=documents.get(doc);groups||(groups=new Map,documents.set(doc,groups));let group=groups.get(normalized);group||(group={members:new Set},groups.set(normalized,group)),this.document=doc,this.groupName=normalized,this.group=group,group.members.add(this),this.host.addEventListener("pointerleave",this.onLeave),this.host.addEventListener("pointercancel",this.onLeave),this.host.addEventListener("focusout",this.onBlur),this.host.shadowRoot?.addEventListener("focusout",this.onBlur),this.host.addEventListener("keydown",this.onKeyDown);const roots=new Set([doc]);this.host.shadowRoot&&roots.add(this.host.shadowRoot);for(let node=this.host;node;node=this.composedParent(node))roots.add(node.getRootNode());this.scrollTargets=[...roots];for(const root of this.scrollTargets)root.addEventListener("scroll",this.onScroll,!0)}this.releaseStyles??=adoptChartSyncStyles(this.host),invalidateOwner&&this.group?.active?.owner===this&&this.clear(),this.receive()}publish(label,index){if(!label||!this.group){this.clear();return}const active=this.group.active;if(this.shown&&!this.group.retry&&active?.owner===this&&active.label===label&&active.index===index)return;const group=this.group;if(group.active={owner:this,label,index},group.frame!==void 0)return;const view=this.document?.defaultView;view&&(group.frame=view.requestAnimationFrame(()=>{group.frame=void 0;const current=group.active;if(!current)return;group.retry=!1;const presentations=[...group.members].map(member=>({member,presentation:member.host.isConnected?member.presentation(current.label,member===current.owner?current.index:void 0):void 0}));if(!presentations.find(item=>item.member===current.owner)?.presentation){current.owner.clear();return}const widths=presentations.map(({presentation})=>presentation?.container.clientWidth??0),writes=presentations.map(({member,presentation},index2)=>member.show(presentation,widths[index2])).map(measure=>measure?.());for(const write of writes)write?.()}))}clear(){if(this.group?.active?.owner===this){this.group.active=void 0,this.group.frame!==void 0&&this.document?.defaultView?.cancelAnimationFrame(this.group.frame),this.group.frame=void 0;for(const member of[...this.group.members])member.hide()}}disconnect(){if(this.releaseStyles?.(),this.releaseStyles=void 0,!this.group){this.hide(!1);return}this.clear();const group=this.group;if(group?.members.delete(this),group&&group.members.size===0&&this.document){const groups=documents.get(this.document);groups?.delete(this.groupName),groups?.size===0&&documents.delete(this.document)}this.host.removeEventListener("pointerleave",this.onLeave),this.host.removeEventListener("pointercancel",this.onLeave),this.host.removeEventListener("focusout",this.onBlur),this.host.shadowRoot?.removeEventListener("focusout",this.onBlur),this.host.removeEventListener("keydown",this.onKeyDown);for(const root of this.scrollTargets)root.removeEventListener("scroll",this.onScroll,!0);this.scrollTargets=[],this.group=void 0,this.document=void 0,this.groupName="",this.hide()}composedParent(node){return node.assignedSlot??node.parentNode??(node.nodeType===11?node.host??null:null)}includesComposed(ancestor,descendant){for(let node=descendant;node;node=this.composedParent(node))if(node===ancestor)return!0;return!1}hide(reset=!0){const wasShown=this.shown;this.shown=!1,this.crosshair?.remove(),this.tooltip?.remove(),this.crosshair=void 0,this.tooltip=void 0,reset&&wasShown&&this.resetRenderer()}resetRenderer(){try{this.reset?.()}catch{}}presentation(label,sourceIndex){try{return this.project(label,sourceIndex)}catch{this.group&&(this.group.retry=!0);return}}receive(){const active=this.group?.active,presentation=active&&this.host.isConnected?this.presentation(active.label,active.owner===this?active.index:void 0):void 0;this.show(presentation)?.()?.()}show(presentation,containerWidth=presentation?.container.clientWidth??0){const wasShown=this.shown;if(this.hide(!1),!presentation){wasShown&&this.resetRenderer();return}this.shown=!0;const{container,x,top,height}=presentation;if(![x,top,height].every(Number.isFinite)||height<=0||containerWidth<=0)return;const doc=this.host.ownerDocument,crosshair=doc.createElement("div");crosshair.setAttribute("part","sync-crosshair"),crosshair.setAttribute("aria-hidden","true"),crosshair.style.left=`${x}px`,crosshair.style.top=`${top}px`,crosshair.style.height=`${height}px`,container.append(crosshair),this.crosshair=crosshair;const content=presentation.tooltip;if(!content||!content.rows.length&&!content.title)return;const tooltip=doc.createElement("div");tooltip.setAttribute("part","sync-tooltip"),tooltip.setAttribute("aria-hidden","true");for(const text of[content.title,...content.rows]){if(!text)continue;const line=doc.createElement("div"),isolated=doc.createElement("bdi");isolated.textContent=text,line.append(isolated),tooltip.append(line)}return container.append(tooltip),this.tooltip=tooltip,()=>{const rect=tooltip.getBoundingClientRect(),width=container.clientWidth,height2=container.clientHeight,left=container.scrollLeft,topEdge=container.scrollTop,inlineSize=Math.min(rect.width,width),xPosition=Math.max(left,Math.min(x,left+width-inlineSize)),yPosition=Math.max(topEdge,Math.min(top,topEdge+height2-rect.height));return()=>{tooltip.style.left=`${xPosition}px`,tooltip.style.top=`${yPosition}px`}}}}export{ChartSyncController};
|
|
@@ -316,7 +316,7 @@ protected preparedDataInput():LyraChartPreparedData|null;
|
|
|
316
316
|
/** Full spatial viewport; null retains the exact global source bounds.*/
|
|
317
317
|
viewport:LyraSpatialBounds|null;
|
|
318
318
|
/** Controlled exact spatial selection, independent of reveal focus.*/
|
|
319
|
-
selectedPointId:string;private spatialActive;private spatial;private spatialWaiters;private spatialRevealToken;private preparedGeneration;private spatialKeyboardIndex;private spatialChanged;private wakeSpatialWaiters;private spatialPoints;private spatialSeriesPoints;private spatialGuard;private spatialPointText;private spatialBinText;private activateSpatialPoint;private activateSpatialBin;private revealSpatialPoint;private spatialKeyboardItems;private spatialKeyDown;private renderSpatialTable;private preparedDirty;private preparedActive;private preparedChanged;private preparedInvalid;private preparedPending;private preparedRequestFailed;private announcedPreparedInvalid;private preparedBaseModel?;private preparedModel?;private preparedEffective?;private readonly preparedRequests;private refreshPreparedModel;
|
|
319
|
+
selectedPointId:string;private spatialActive;private spatial;private spatialWaiters;private spatialRevealToken;private preparedGeneration;private legendDataGeneration;private spatialKeyboardIndex;private spatialChanged;private wakeSpatialWaiters;private spatialPoints;private spatialSeriesPoints;private spatialGuard;private spatialPointText;private spatialBinText;private activateSpatialPoint;private activateSpatialBin;private revealSpatialPoint;private spatialKeyboardItems;private spatialKeyDown;private renderSpatialTable;private preparedDirty;private preparedActive;private preparedChanged;private preparedInvalid;private preparedPending;private preparedRequestFailed;private announcedPreparedInvalid;private preparedBaseModel?;private preparedModel?;private preparedEffective?;private readonly preparedRequests;private refreshPreparedModel;
|
|
320
320
|
/**
|
|
321
321
|
* Resolves one original source position and adds a bounded isolated overlay. Returns false for
|
|
322
322
|
* missing, invalid, canceled or obsolete points. It never interprets sourceIndex as a peer index
|