@aceshooting/lyra-ui 14.3.2 → 15.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 +103 -0
- package/custom-elements.json +1 -1
- package/design-tokens.json +1 -1
- package/dist/cli/migration-contract.json +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.d.ts +4 -0
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +3 -3
- package/dist/components/agent-tools/approval-queue/approval-queue.class.js +3 -2
- package/dist/components/agent-tools/artifact-panel/artifact-panel.styles.js +1 -1
- package/dist/components/agent-tools/commit-card/commit-card.styles.js +1 -1
- package/dist/components/agent-tools/compare-panel/compare-panel.styles.js +1 -1
- package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +8 -3
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.d.ts +3 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +10 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.styles.js +1 -1
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.class.d.ts +19 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +4 -4
- package/dist/components/agent-tools/subagent-panel/subagent-panel.styles.js +1 -1
- package/dist/components/agent-tools/task-list/task-list.class.d.ts +5 -0
- package/dist/components/agent-tools/task-list/task-list.class.js +3 -3
- package/dist/components/agent-tools/terminal/terminal.class.d.ts +1 -1
- package/dist/components/agent-tools/terminal/terminal.styles.js +1 -1
- package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +10 -7
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +15 -14
- package/dist/components/agent-tools/tool-param-form/tool-param-form.d.ts +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.styles.js +1 -1
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.d.ts +5 -2
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +1 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.d.ts +3 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +9 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.styles.js +1 -1
- package/dist/components/charts/chart/box-plot.class.d.ts +64 -4
- package/dist/components/charts/chart/box-plot.class.js +5 -5
- package/dist/components/charts/chart/chart-colors.d.ts +10 -0
- package/dist/components/charts/chart/chart-colors.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +35 -10
- package/dist/components/charts/chart/chart.class.js +4 -4
- package/dist/components/charts/chart/lite-chart.class.d.ts +10 -2
- package/dist/components/charts/chart/lite-chart.styles.js +1 -1
- package/dist/components/conversation/markdown/markdown.class.d.ts +9 -1
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +18 -1
- package/dist/components/conversation/message-parts/message-parts.class.js +4 -4
- package/dist/components/conversation/model-select/model-select.class.d.ts +6 -2
- package/dist/components/conversation/model-select/model-select.class.js +3 -3
- package/dist/components/conversation/prompt-input/prompt-input.styles.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +5 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/data/calendar/calendar.class.js +2 -2
- package/dist/components/data/context-meter/context-meter.styles.js +1 -1
- package/dist/components/data/data-grid/data-grid-types.d.ts +8 -2
- package/dist/components/data/data-grid/data-grid.class.d.ts +16 -3
- package/dist/components/data/data-grid/data-grid.class.js +3 -2
- package/dist/components/data/env-list/env-list.styles.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +22 -2
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.class.d.ts +12 -4
- package/dist/components/data/flow-minimap/flow-minimap.class.js +2 -2
- package/dist/components/data/flow-minimap/flow-minimap.styles.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +5 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +12 -1
- package/dist/components/data/heatmap/heatmap.class.js +3 -3
- package/dist/components/data/heatmap/heatmap.styles.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/combobox/combobox.styles.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/date-picker/date-picker.class.d.ts +12 -1
- package/dist/components/forms/date-picker/date-picker.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +27 -5
- package/dist/components/forms/icon-button/icon-button.class.js +7 -3
- package/dist/components/forms/input/input.styles.js +1 -1
- package/dist/components/forms/input/time-input.class.d.ts +13 -2
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/otp-input/otp-input.class.d.ts +8 -1
- package/dist/components/forms/otp-input/otp-input.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +1 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/slider/slider.class.d.ts +4 -1
- package/dist/components/forms/slider/slider.class.js +1 -1
- package/dist/components/forms/textarea/textarea.class.d.ts +9 -4
- package/dist/components/forms/textarea/textarea.class.js +1 -1
- package/dist/components/forms/time-range/time-range.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail.class.d.ts +7 -2
- package/dist/components/layout/app-rail/app-rail.class.js +1 -1
- package/dist/components/layout/card/card.class.js +2 -2
- package/dist/components/layout/card/card.styles.js +1 -1
- package/dist/components/layout/control-group/control-group.class.js +1 -1
- package/dist/components/layout/dashboard-grid/dashboard-grid.styles.js +1 -1
- package/dist/components/layout/details/details.styles.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.d.ts +13 -3
- package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
- package/dist/components/layout/menu/dropdown-item.class.d.ts +2 -0
- package/dist/components/layout/menu/menu-item.class.d.ts +28 -1
- package/dist/components/layout/menu/menu-item.class.js +45 -35
- package/dist/components/layout/menu/menu-item.styles.js +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.d.ts +12 -2
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/page/page.class.js +2 -1
- package/dist/components/layout/page/page.styles.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.d.ts +6 -4
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +2 -2
- package/dist/components/layout/responsive-panel/responsive-panel.styles.js +1 -1
- package/dist/components/layout/stepper/stepper.class.js +2 -2
- package/dist/components/layout/virtual-list/virtual-list.class.js +2 -2
- package/dist/components/layout/widget/widget.class.d.ts +12 -2
- package/dist/components/layout/widget/widget.class.js +2 -2
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
- package/dist/components/media/file-icon/file-icon.class.d.ts +3 -1
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.d.ts +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/flag/flag.styles.js +1 -1
- package/dist/components/media/image-comparer/image-comparer.class.d.ts +5 -5
- package/dist/components/media/image-comparer/image-comparer.class.js +1 -1
- package/dist/components/media/image-comparer/image-comparer.styles.js +1 -1
- package/dist/components/media/lightbox/lightbox.styles.js +1 -1
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.styles.js +1 -1
- package/dist/components/overlays/alert/alert.class.d.ts +6 -0
- package/dist/components/overlays/alert/alert.styles.js +1 -1
- package/dist/components/overlays/empty/empty.class.js +2 -2
- package/dist/components/overlays/kbd/kbd.styles.js +1 -1
- package/dist/components/overlays/progress/progress-ring.class.d.ts +4 -1
- package/dist/components/overlays/progress/progress.styles.js +1 -1
- package/dist/components/overlays/toast/toast.styles.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +10 -3
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/graph/graph.styles.js +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +6 -6
- package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.js +2 -2
- package/dist/components/retrieval/mind-map/mind-map.styles.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +3 -3
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
- package/dist/components/retrieval/node-palette/node-palette.class.d.ts +7 -1
- package/dist/components/retrieval/node-palette/node-palette.class.js +23 -13
- package/dist/components/retrieval/node-palette/node-palette.styles.js +1 -1
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.d.ts +4 -1
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
- package/dist/components/retrieval/retrieval-search/retrieval-search.class.js +4 -3
- package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
- package/dist/components/retrieval/source-list/source-list.class.d.ts +7 -1
- package/dist/components/retrieval/source-list/source-list.class.js +1 -1
- package/dist/components/utility/export-button/export-button.class.d.ts +14 -2
- package/dist/components/utility/export-button/export-button.class.js +3 -3
- package/dist/components/utility/export-button/export-button.styles.js +1 -1
- 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.d.ts +4 -2
- package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.class.d.ts +9 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.class.js +4 -4
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.d.ts +1 -1
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +4 -4
- package/dist/components/viewers/document-compare/document-compare.class.d.ts +5 -0
- package/dist/components/viewers/document-compare/document-compare.class.js +9 -4
- package/dist/components/viewers/document-compare/document-compare.styles.js +1 -1
- package/dist/components/viewers/document-preview/document-preview.class.d.ts +9 -1
- package/dist/components/viewers/document-preview/document-preview.class.js +2 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.d.ts +5 -0
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +5 -0
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.d.ts +1 -1
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +3 -3
- package/dist/components/viewers/xml-viewer/xml-viewer.styles.js +1 -1
- package/dist/custom-elements-jsx.d.ts +1 -1
- package/dist/events.d.ts +5 -4
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/vue.d.ts +1 -1
- package/llms/components/lr-alert.md +11 -3
- package/llms/components/lr-box-plot.md +21 -4
- package/llms/components/lr-chart.md +13 -4
- package/llms/components/lr-code-block.md +5 -4
- package/llms/components/lr-data-grid.md +24 -10
- package/llms/components/lr-document-compare.md +5 -0
- package/llms/components/lr-dropdown-item.md +24 -0
- package/llms/components/lr-eval-dataset.md +5 -4
- package/llms/components/lr-export-button.md +10 -5
- package/llms/components/lr-filter-bar.md +4 -1
- package/llms/components/lr-flow-minimap.md +7 -1
- package/llms/components/lr-icon-button.md +6 -1
- package/llms/components/lr-lite-chart.md +2 -1
- package/llms/components/lr-markdown.md +2 -2
- package/llms/components/lr-menu-item.md +24 -0
- package/llms/components/lr-menu.md +24 -0
- package/llms/components/lr-message-parts.md +7 -0
- package/llms/components/lr-model-settings-panel.md +4 -1
- package/llms/components/lr-node-palette.md +5 -4
- package/llms/components/lr-pdf-viewer.md +7 -0
- package/llms/components/lr-responsive-panel.md +2 -2
- package/llms/components/lr-subagent-panel.md +17 -2
- package/llms/components/lr-thinking-panel.md +4 -0
- package/llms/components/lr-timeline-item.md +1 -1
- package/llms/components/lr-timeline.md +1 -1
- package/llms/components/lr-tool-select-dialog.md +4 -3
- package/llms/components/lr-virtual-list.md +11 -11
- package/llms-full.txt +205 -59
- package/package.json +3 -3
- package/vscode-css-data.json +1 -1
- package/vscode-html-data.json +1 -1
- package/web-types.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{composedParentElement,isAccessibilitySubtreeExcluded,isAccessibilityVisible,isAccessibilityVisibilityHidden,nextId}from"../../../internal/a11y.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./known-date.styles.js";import{getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{activeElementIn}from"../../../internal/active-element.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{setCustomState}from"../../../internal/custom-states.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{currentValidityValidator}from"../../forms/form-validator.js";import{LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_knownDateDay,LYRA_DEFAULT_knownDateMonth,LYRA_DEFAULT_knownDateYear}from"../../../internal/default-strings.generated.js";const EMPTY_PARTS={day:"",month:"",year:""};function localDate(year,month,day){const date=new Date(0);return date.setHours(0,0,0,0),date.setFullYear(year,month,day),date}function parseISO(value){const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(value);if(!match)return null;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=localDate(year,month-1,day);return isNaN(date.getTime())||date.getFullYear()!==year||date.getMonth()!==month-1||date.getDate()!==day?null:date}function formatISO(date){const mm=String(date.getMonth()+1).padStart(2,"0"),dd=String(date.getDate()).padStart(2,"0");return`${String(date.getFullYear()).padStart(4,"0")}-${mm}-${dd}`}function localeDateOrder(locale){try{const order=getDateTimeFormat(locale||void 0,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2026,0,2)).filter(p=>p.type==="day"||p.type==="month"||p.type==="year").map(p=>p.type);return order.length===3?order:["month","day","year"]}catch{return["month","day","year"]}}class LyraKnownDateBase extends LyraElement{}function addCompatibilityDetail(event,detail){return Object.defineProperty(event,"detail",{configurable:!0,value:detail}),event}class LyraKnownDate extends FormAssociated(LyraKnownDateBase){static{this.defaultStrings={...super.defaultStrings,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,fieldRequired:LYRA_DEFAULT_fieldRequired,knownDateDay:LYRA_DEFAULT_knownDateDay,knownDateMonth:LYRA_DEFAULT_knownDateMonth,knownDateYear:LYRA_DEFAULT_knownDateYear}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max")]}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={min:{reflect:!0,noAccessor:!0},max:{reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},parts:{attribute:!1,noAccessor:!0}}}constructor(){super(),this.size="m",this.appearance="outlined",this.pill=!1,this.label="",this.hint="",this.errorText="",this.locale="",this.autocomplete="",this.withLabel=!1,this.withHint=!1,this.accessibleLabel=null,this._parts={...EMPTY_PARTS},this.touched=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this._min="",this._max="",this._readonly=!1,this.lastCommittedValue="",this.lastEditedField="day",this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.connectionGeneration=0,this.onForwardedSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||(this.bindErrorObserverTargets(),this.announceVisibleError())},this.hintId=nextId("known-date-hint"),this.errorId=nextId("known-date-error"),this.dayId=nextId("known-date-day"),this.monthId=nextId("known-date-month"),this.yearId=nextId("known-date-year"),this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onFieldInput=(field,e)=>{e.stopPropagation();const input=e.target,maxLength=field==="year"?4:2,digits=this.normalizeFieldDigits(input.value).slice(0,maxLength);input.value!==digits&&(input.value=digits),this.setFieldText(field,digits),this.lastEditedField=field,this.commitFromFields();const InputEventConstructor=this.ownerDocument.defaultView?.InputEvent??InputEvent,event=addCompatibilityDetail(new InputEventConstructor("input",{bubbles:!0,composed:!0,inputType:e.inputType||"insertText"}),this.detailFor(field));this.dispatchEvent(event),field!=="year"&&digits.length===maxLength&&this.focusAdjacentField(field,1)},this.onFieldKeydown=(field,e)=>{const input=e.currentTarget;if(isImplicitSubmission(e)){if(this.effectiveDisabled||this.readonly)return;submitOnEnter(this,e,{beforeSubmit:()=>this.commitChangeIfNeeded()});return}if(e.key==="Backspace"&&this.textFor(field)===""){e.preventDefault(),this.focusAdjacentField(field,-1);return}if(e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;const atStart=input.selectionStart===0&&input.selectionEnd===0,atEnd=input.selectionStart===input.value.length&&input.selectionEnd===input.value.length,rtl=this.effectiveDirection==="rtl";e.key==="ArrowLeft"&&atStart?(e.preventDefault(),this.focusAdjacentField(field,rtl?1:-1)):e.key==="ArrowRight"&&atEnd&&(e.preventDefault(),this.focusAdjacentField(field,rtl?-1:1))},this.onFieldFocus=e=>{e.stopPropagation(),this.emit("focus")},this.onFieldBlur=e=>{e.stopPropagation(),this.commitChangeIfNeeded();const related=e.relatedTarget,active=activeElementIn(this.shadowRoot);e.isTrusted&&(this.isRenderedFieldTarget(related)||active!==e.target&&this.isRenderedFieldTarget(active))||(this.effectiveDisabled||(this.touched=!0),this.emit("blur"))},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this});const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.errorObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindErrorObserverTargets(),this.announceVisibleError()}):void 0,this.addEventListener("slotchange",this.onForwardedSlotChange),this.bindErrorObserverTargets(),this.errorAnnouncementsArmed=!1;const generation=++this.connectionGeneration;this.updateComplete.then(()=>{const view=this.ownerDocument.defaultView;return typeof view?.requestAnimationFrame=="function"?new Promise(resolve=>view.requestAnimationFrame(()=>resolve())):Promise.resolve()}).then(()=>this.updateComplete).then(()=>{!this.isConnected||generation!==this.connectionGeneration||(this.lastVisibleError=this.visibleErrorText(),this.errorAnnouncementsArmed=!0)})}observeErrorNode(node){if(this.errorObserver){if(node.nodeType===3){this.errorObserver.observe(node,{characterData:!0});return}node.nodeType===1&&this.errorObserver.observe(node,{attributes:!0,attributeFilter:["aria-hidden","aria-label","class","hidden","inert","slot","style"],characterData:!0,childList:!0,subtree:!0})}}bindErrorObserverTargets(){if(!this.errorObserver)return;this.errorObserver.disconnect(),this.observeErrorNode(this);let ancestor=composedParentElement(this);for(;ancestor;)this.errorObserver.observe(ancestor,{attributes:!0,attributeFilter:["aria-hidden","class","hidden","inert","style"]}),ancestor=composedParentElement(ancestor);const forwardedSlots=Array.from(this.children).filter(element=>element.getAttribute("slot")==="error").flatMap(branch=>[...branch.localName==="slot"?[branch]:[],...branch.querySelectorAll("slot")]);for(const slot of forwardedSlots)for(const assigned of slot.assignedNodes({flatten:!0}))this.observeErrorNode(assigned)}disconnectedCallback(){this.releaseExternalDescription(),this.connectionGeneration+=1,this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.removeEventListener("slotchange",this.onForwardedSlotChange),this.errorObserver?.disconnect(),this.errorObserver=void 0,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription()}syncExternalDescription(){if(!this.isConnected)return;const owner=this.renderRoot.querySelector('[part="fieldset"]');owner&&(this.externalDescriptionLease?this.externalDescriptionLease.update(owner):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,owner,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}get min(){return this._min}set min(next){const old=this._min;this._min=next??"",this.updateValidity(),this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"",this.updateValidity(),this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this.updateValidity(),this.requestUpdate("readonly",old)}get parts(){return this._parts}set parts(next){this.setParts(next,!0)}setParts(next,programmatic){const old=this._parts;this._parts={day:String(next?.day??""),month:String(next?.month??""),year:String(next?.year??"")},programmatic&&(this.commitFromFields(),this.lastCommittedValue=this.value),this.requestUpdate("parts",old)}get value(){return super.value}set value(next){const parsed=this.parseStrictISO(next??"");parsed?(this.setParts({day:String(parsed.getDate()),month:String(parsed.getMonth()+1),year:String(parsed.getFullYear())},!1),super.value=formatISO(parsed)):(this.setParts({day:"",month:"",year:""},!1),super.value=""),this.lastCommittedValue=super.value}get valueAsDate(){return this.value?parseISO(this.value):null}set valueAsDate(next){this.value=next?formatISO(next):""}parseStrictISO(value){return/^\d{4}-\d{2}-\d{2}$/.test(value)?parseISO(value):null}get fieldOrder(){return localeDateOrder(this.effectiveLocale)}textFor(field){return this._parts[field]}setFieldText(field,text){this.setParts({...this._parts,[field]:text},!1)}idFor(field){return field==="day"?this.dayId:field==="month"?this.monthId:this.yearId}get effectiveDayLabel(){return this.dayLabel??this.localize("knownDateDay")}get effectiveMonthLabel(){return this.monthLabel??this.localize("knownDateMonth")}get effectiveYearLabel(){return this.yearLabel??this.localize("knownDateYear")}labelFor(field){return field==="day"?this.effectiveDayLabel:field==="month"?this.effectiveMonthLabel:this.effectiveYearLabel}autocompleteFor(field){return this.autocomplete?this.autocomplete==="bday"?`bday-${field}`:this.autocomplete==="on"||this.autocomplete==="off"?this.autocomplete:field==="year"?this.autocomplete:"":""}computeCanonicalValue(){if(!this._parts.day||!this._parts.month||!this._parts.year)return"";const iso=`${this._parts.year.padStart(4,"0")}-${this._parts.month.padStart(2,"0")}-${this._parts.day.padStart(2,"0")}`;return parseISO(iso)?iso:""}commitFromFields(){super.value=this.computeCanonicalValue()}get eventDetail(){return{value:this.value,...this._parts}}detailFor(field){return{...this.eventDetail,field}}commitChangeIfNeeded(){if(this.value===this.lastCommittedValue)return;this.lastCommittedValue=this.value;const EventConstructor=this.ownerDocument.defaultView?.Event??Event,event=addCompatibilityDetail(new EventConstructor("change",{bubbles:!0,composed:!0}),this.detailFor(this.lastEditedField));this.dispatchEvent(event)}fieldInputElement(field){return this.renderRoot?.querySelector(`input[data-field="${field}"]`)??null}isRenderedFieldTarget(target){if(!target||typeof target!="object")return!1;const field=target.dataset?.field;return field!=="day"&&field!=="month"&&field!=="year"?!1:this.fieldInputElement(field)===target}focusAdjacentField(field,delta){const order=this.fieldOrder,targetIndex=order.indexOf(field)+delta;targetIndex<0||targetIndex>=order.length||this.fieldInputElement(order[targetIndex])?.focus()}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";const blank=this._parts.day===""&&this._parts.month===""&&this._parts.year==="";if(this.value==="")this.required&&blank?(flags.valueMissing=!0,message=this.localize("fieldRequired")):blank||(flags.badInput=!0,message=this.localize("dateInputInvalid"));else{const date=parseISO(this.value),min=this.parseStrictISO(this.min),max=this.parseStrictISO(this.max);min&&date<min&&(flags.rangeUnderflow=!0,message=this.localize("dateInputMinMessage",void 0,{min:this.min})),max&&date>max&&(flags.rangeOverflow=!0,message||=this.localize("dateInputMaxMessage",void 0,{max:this.max}))}this[SET_ANCHORED_VALIDITY](flags,message)}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error"))}updated(changed){super.updated(changed),this.syncExternalDescription(),setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("min")||changed.has("max")||changed.has("readonly"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.announceVisibleError()}formResetCallback(){super.formResetCallback(),this.touched=!1}formStateRestoreCallback(state2){this.value=typeof state2=="string"?state2:""}setCustomValidity(message){super.setCustomValidity(message),this.requestUpdate()}get validationTarget(){return this.validationTargetOverride??this.fieldInputElement(this.fieldOrder[0])??void 0}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0,this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity(""),this.updateValidity()}visibleErrorText(){const slottedElements=Array.from(this.children).filter(element=>element.getAttribute("slot")==="error");return slottedElements.length>0?slottedElements.map(element=>this.accessibleVisibleText(element)).join(" ").replace(/\s+/g," ").trim():(this.errorText||(this.touched?this.validationMessage:"")).trim()}accessibleVisibleText(node){if(node.nodeType===3)return node.textContent??"";if(node.nodeType!==1)return"";const element=node;if(isAccessibilitySubtreeExcluded(element))return"";const visibilityHidden=isAccessibilityVisibilityHidden(element),accessibleLabel=visibilityHidden?null:element.getAttribute("aria-label");if(accessibleLabel?.trim())return accessibleLabel;const assigned=element.localName==="slot"?element.assignedNodes({flatten:!0}):[];return(assigned.length>0?assigned:Array.from(element.childNodes)).map(child=>child.nodeType===3&&visibilityHidden?"":this.accessibleVisibleText(child)).join(" ")}announceVisibleError(){if(!this.errorAnnouncementsArmed||!isAccessibilityVisible(this))return;const message=this.visibleErrorText();message!==this.lastVisibleError&&(this.lastVisibleError=message,message&&this.errorAnnouncementSink?.announce(message))}normalizeFieldDigits(value){const digitMap=new Map([["٠","0"],["١","1"],["٢","2"],["٣","3"],["٤","4"],["٥","5"],["٦","6"],["٧","7"],["٨","8"],["٩","9"],["۰","0"],["۱","1"],["۲","2"],["۳","3"],["۴","4"],["۵","5"],["۶","6"],["۷","7"],["۸","8"],["۹","9"]]);try{const formatter=getNumberFormat(this.effectiveLocale||void 0,{useGrouping:!1});for(let digit=0;digit<=9;digit++)digitMap.set(formatter.format(digit),String(digit))}catch{}let normalized="";for(const character of value)character>="0"&&character<="9"?normalized+=character:normalized+=digitMap.get(character)??"";return normalized}focus(options){const target=this.fieldOrder.find(field=>this.textFor(field)==="")??this.fieldOrder[0];this.fieldInputElement(target)?.focus(options)}blur(){this.renderRoot.querySelector("input:focus")?.blur()}click(){this.fieldInputElement(this.fieldOrder[0])?.click()}renderField(field,describedBy,invalid){const id=this.idFor(field),maxLength=field==="year"?4:2;return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{composedParentElement,isAccessibilitySubtreeExcluded,isAccessibilityVisible,isAccessibilityVisibilityHidden,nextId}from"../../../internal/a11y.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./known-date.styles.js";import{getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{activeElementIn}from"../../../internal/active-element.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{setCustomState}from"../../../internal/custom-states.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{currentValidityValidator}from"../../forms/form-validator.js";import{LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_knownDateDay,LYRA_DEFAULT_knownDateMonth,LYRA_DEFAULT_knownDateYear}from"../../../internal/default-strings.generated.js";const EMPTY_PARTS={day:"",month:"",year:""};function localDate(year,month,day){const date=new Date(0);return date.setHours(0,0,0,0),date.setFullYear(year,month,day),date}function parseISO(value){const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(value);if(!match)return null;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=localDate(year,month-1,day);return isNaN(date.getTime())||date.getFullYear()!==year||date.getMonth()!==month-1||date.getDate()!==day?null:date}function formatISO(date){if(!Number.isFinite(date.getTime())||date.getFullYear()<0||date.getFullYear()>9999)return"";const mm=String(date.getMonth()+1).padStart(2,"0"),dd=String(date.getDate()).padStart(2,"0");return`${String(date.getFullYear()).padStart(4,"0")}-${mm}-${dd}`}function localeDateOrder(locale){try{const order=getDateTimeFormat(locale||void 0,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2026,0,2)).filter(p=>p.type==="day"||p.type==="month"||p.type==="year").map(p=>p.type);return order.length===3?order:["month","day","year"]}catch{return["month","day","year"]}}class LyraKnownDateBase extends LyraElement{}function addCompatibilityDetail(event,detail){return Object.defineProperty(event,"detail",{configurable:!0,value:detail}),event}class LyraKnownDate extends FormAssociated(LyraKnownDateBase){static{this.defaultStrings={...super.defaultStrings,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,fieldRequired:LYRA_DEFAULT_fieldRequired,knownDateDay:LYRA_DEFAULT_knownDateDay,knownDateMonth:LYRA_DEFAULT_knownDateMonth,knownDateYear:LYRA_DEFAULT_knownDateYear}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max")]}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={min:{reflect:!0,noAccessor:!0},max:{reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},parts:{attribute:!1,noAccessor:!0}}}constructor(){super(),this.size="m",this.appearance="outlined",this.pill=!1,this.label="",this.hint="",this.errorText="",this.locale="",this.autocomplete="",this.withLabel=!1,this.withHint=!1,this.accessibleLabel=null,this._parts={...EMPTY_PARTS},this.touched=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this._min="",this._max="",this._readonly=!1,this.lastCommittedValue="",this.lastEditedField="day",this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.connectionGeneration=0,this.onForwardedSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||(this.bindErrorObserverTargets(),this.announceVisibleError())},this.hintId=nextId("known-date-hint"),this.errorId=nextId("known-date-error"),this.dayId=nextId("known-date-day"),this.monthId=nextId("known-date-month"),this.yearId=nextId("known-date-year"),this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onFieldInput=(field,e)=>{e.stopPropagation();const input=e.target,maxLength=field==="year"?4:2,digits=this.normalizeFieldDigits(input.value).slice(0,maxLength);input.value!==digits&&(input.value=digits),this.setFieldText(field,digits),this.lastEditedField=field,this.commitFromFields();const InputEventConstructor=this.ownerDocument.defaultView?.InputEvent??InputEvent,event=addCompatibilityDetail(new InputEventConstructor("input",{bubbles:!0,composed:!0,inputType:e.inputType||"insertText"}),this.detailFor(field));this.dispatchEvent(event),field!=="year"&&digits.length===maxLength&&this.focusAdjacentField(field,1)},this.onFieldKeydown=(field,e)=>{const input=e.currentTarget;if(isImplicitSubmission(e)){if(this.effectiveDisabled||this.readonly)return;submitOnEnter(this,e,{beforeSubmit:()=>this.commitChangeIfNeeded()});return}if(e.key==="Backspace"&&this.textFor(field)===""){e.preventDefault(),this.focusAdjacentField(field,-1);return}if(e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;const atStart=input.selectionStart===0&&input.selectionEnd===0,atEnd=input.selectionStart===input.value.length&&input.selectionEnd===input.value.length,rtl=this.effectiveDirection==="rtl";e.key==="ArrowLeft"&&atStart?(e.preventDefault(),this.focusAdjacentField(field,rtl?1:-1)):e.key==="ArrowRight"&&atEnd&&(e.preventDefault(),this.focusAdjacentField(field,rtl?-1:1))},this.onFieldFocus=e=>{e.stopPropagation(),this.emit("focus")},this.onFieldBlur=e=>{e.stopPropagation(),this.commitChangeIfNeeded();const related=e.relatedTarget,active=activeElementIn(this.shadowRoot);e.isTrusted&&(this.isRenderedFieldTarget(related)||active!==e.target&&this.isRenderedFieldTarget(active))||(this.effectiveDisabled||(this.touched=!0),this.emit("blur"))},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this});const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.errorObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindErrorObserverTargets(),this.announceVisibleError()}):void 0,this.addEventListener("slotchange",this.onForwardedSlotChange),this.bindErrorObserverTargets(),this.errorAnnouncementsArmed=!1;const generation=++this.connectionGeneration;this.updateComplete.then(()=>{const view=this.ownerDocument.defaultView;return typeof view?.requestAnimationFrame=="function"?new Promise(resolve=>view.requestAnimationFrame(()=>resolve())):Promise.resolve()}).then(()=>this.updateComplete).then(()=>{!this.isConnected||generation!==this.connectionGeneration||(this.lastVisibleError=this.visibleErrorText(),this.errorAnnouncementsArmed=!0)})}observeErrorNode(node){if(this.errorObserver){if(node.nodeType===3){this.errorObserver.observe(node,{characterData:!0});return}node.nodeType===1&&this.errorObserver.observe(node,{attributes:!0,attributeFilter:["aria-hidden","aria-label","class","hidden","inert","slot","style"],characterData:!0,childList:!0,subtree:!0})}}bindErrorObserverTargets(){if(!this.errorObserver)return;this.errorObserver.disconnect(),this.observeErrorNode(this);let ancestor=composedParentElement(this);for(;ancestor;)this.errorObserver.observe(ancestor,{attributes:!0,attributeFilter:["aria-hidden","class","hidden","inert","style"]}),ancestor=composedParentElement(ancestor);const forwardedSlots=Array.from(this.children).filter(element=>element.getAttribute("slot")==="error").flatMap(branch=>[...branch.localName==="slot"?[branch]:[],...branch.querySelectorAll("slot")]);for(const slot of forwardedSlots)for(const assigned of slot.assignedNodes({flatten:!0}))this.observeErrorNode(assigned)}disconnectedCallback(){this.releaseExternalDescription(),this.connectionGeneration+=1,this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.removeEventListener("slotchange",this.onForwardedSlotChange),this.errorObserver?.disconnect(),this.errorObserver=void 0,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription()}syncExternalDescription(){if(!this.isConnected)return;const owner=this.renderRoot.querySelector('[part="fieldset"]');owner&&(this.externalDescriptionLease?this.externalDescriptionLease.update(owner):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,owner,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}get min(){return this._min}set min(next){const old=this._min;this._min=next??"",this.updateValidity(),this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"",this.updateValidity(),this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this.updateValidity(),this.requestUpdate("readonly",old)}get parts(){return this._parts}set parts(next){this.setParts(next,!0)}setParts(next,programmatic){const old=this._parts;this._parts={day:String(next?.day??""),month:String(next?.month??""),year:String(next?.year??"")},programmatic&&(this.commitFromFields(),this.lastCommittedValue=this.value),this.requestUpdate("parts",old)}get value(){return super.value}set value(next){const parsed=this.parseStrictISO(next??"");parsed?(this.setParts({day:String(parsed.getDate()),month:String(parsed.getMonth()+1),year:String(parsed.getFullYear())},!1),super.value=formatISO(parsed)):(this.setParts({day:"",month:"",year:""},!1),super.value=""),this.lastCommittedValue=super.value}get valueAsDate(){return this.value?parseISO(this.value):null}set valueAsDate(next){this.value=next?formatISO(next):""}parseStrictISO(value){return/^\d{4}-\d{2}-\d{2}$/.test(value)?parseISO(value):null}get fieldOrder(){return localeDateOrder(this.effectiveLocale)}textFor(field){return this._parts[field]}setFieldText(field,text){this.setParts({...this._parts,[field]:text},!1)}idFor(field){return field==="day"?this.dayId:field==="month"?this.monthId:this.yearId}get effectiveDayLabel(){return this.dayLabel??this.localize("knownDateDay")}get effectiveMonthLabel(){return this.monthLabel??this.localize("knownDateMonth")}get effectiveYearLabel(){return this.yearLabel??this.localize("knownDateYear")}labelFor(field){return field==="day"?this.effectiveDayLabel:field==="month"?this.effectiveMonthLabel:this.effectiveYearLabel}autocompleteFor(field){return this.autocomplete?this.autocomplete==="bday"?`bday-${field}`:this.autocomplete==="on"||this.autocomplete==="off"?this.autocomplete:field==="year"?this.autocomplete:"":""}computeCanonicalValue(){if(!this._parts.day||!this._parts.month||!this._parts.year)return"";const iso=`${this._parts.year.padStart(4,"0")}-${this._parts.month.padStart(2,"0")}-${this._parts.day.padStart(2,"0")}`;return parseISO(iso)?iso:""}commitFromFields(){super.value=this.computeCanonicalValue()}get eventDetail(){return{value:this.value,...this._parts}}detailFor(field){return{...this.eventDetail,field}}commitChangeIfNeeded(){if(this.value===this.lastCommittedValue)return;this.lastCommittedValue=this.value;const EventConstructor=this.ownerDocument.defaultView?.Event??Event,event=addCompatibilityDetail(new EventConstructor("change",{bubbles:!0,composed:!0}),this.detailFor(this.lastEditedField));this.dispatchEvent(event)}fieldInputElement(field){return this.renderRoot?.querySelector(`input[data-field="${field}"]`)??null}isRenderedFieldTarget(target){if(!target||typeof target!="object")return!1;const field=target.dataset?.field;return field!=="day"&&field!=="month"&&field!=="year"?!1:this.fieldInputElement(field)===target}focusAdjacentField(field,delta){const order=this.fieldOrder,targetIndex=order.indexOf(field)+delta;targetIndex<0||targetIndex>=order.length||this.fieldInputElement(order[targetIndex])?.focus()}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";const blank=this._parts.day===""&&this._parts.month===""&&this._parts.year==="";if(this.value==="")this.required&&blank?(flags.valueMissing=!0,message=this.localize("fieldRequired")):blank||(flags.badInput=!0,message=this.localize("dateInputInvalid"));else{const date=parseISO(this.value),min=this.parseStrictISO(this.min),max=this.parseStrictISO(this.max);min&&date<min&&(flags.rangeUnderflow=!0,message=this.localize("dateInputMinMessage",void 0,{min:this.min})),max&&date>max&&(flags.rangeOverflow=!0,message||=this.localize("dateInputMaxMessage",void 0,{max:this.max}))}this[SET_ANCHORED_VALIDITY](flags,message)}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error"))}updated(changed){super.updated(changed),this.syncExternalDescription(),setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("min")||changed.has("max")||changed.has("readonly"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.announceVisibleError()}formResetCallback(){super.formResetCallback(),this.touched=!1}formStateRestoreCallback(state2){this.value=typeof state2=="string"?state2:""}setCustomValidity(message){super.setCustomValidity(message),this.requestUpdate()}get validationTarget(){return this.validationTargetOverride??this.fieldInputElement(this.fieldOrder[0])??void 0}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0,this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity(""),this.updateValidity()}visibleErrorText(){const slottedElements=Array.from(this.children).filter(element=>element.getAttribute("slot")==="error");return slottedElements.length>0?slottedElements.map(element=>this.accessibleVisibleText(element)).join(" ").replace(/\s+/g," ").trim():(this.errorText||(this.touched?this.validationMessage:"")).trim()}accessibleVisibleText(node){if(node.nodeType===3)return node.textContent??"";if(node.nodeType!==1)return"";const element=node;if(isAccessibilitySubtreeExcluded(element))return"";const visibilityHidden=isAccessibilityVisibilityHidden(element),accessibleLabel=visibilityHidden?null:element.getAttribute("aria-label");if(accessibleLabel?.trim())return accessibleLabel;const assigned=element.localName==="slot"?element.assignedNodes({flatten:!0}):[];return(assigned.length>0?assigned:Array.from(element.childNodes)).map(child=>child.nodeType===3&&visibilityHidden?"":this.accessibleVisibleText(child)).join(" ")}announceVisibleError(){if(!this.errorAnnouncementsArmed||!isAccessibilityVisible(this))return;const message=this.visibleErrorText();message!==this.lastVisibleError&&(this.lastVisibleError=message,message&&this.errorAnnouncementSink?.announce(message))}normalizeFieldDigits(value){const digitMap=new Map([["٠","0"],["١","1"],["٢","2"],["٣","3"],["٤","4"],["٥","5"],["٦","6"],["٧","7"],["٨","8"],["٩","9"],["۰","0"],["۱","1"],["۲","2"],["۳","3"],["۴","4"],["۵","5"],["۶","6"],["۷","7"],["۸","8"],["۹","9"]]);try{const formatter=getNumberFormat(this.effectiveLocale||void 0,{useGrouping:!1});for(let digit=0;digit<=9;digit++)digitMap.set(formatter.format(digit),String(digit))}catch{}let normalized="";for(const character of value)character>="0"&&character<="9"?normalized+=character:normalized+=digitMap.get(character)??"";return normalized}focus(options){const target=this.fieldOrder.find(field=>this.textFor(field)==="")??this.fieldOrder[0];this.fieldInputElement(target)?.focus(options)}blur(){this.renderRoot.querySelector("input:focus")?.blur()}click(){this.fieldInputElement(this.fieldOrder[0])?.click()}renderField(field,describedBy,invalid){const id=this.idFor(field),maxLength=field==="year"?4:2;return html`
|
|
2
2
|
<div part=${field==="day"?"field field-day":field==="month"?"field field-month":"field field-year"} data-field=${field}>
|
|
3
3
|
<label part="field-label" for=${id}>${this.labelFor(field)}</label>
|
|
4
4
|
<input
|
|
@@ -160,8 +160,10 @@ emptyText?:string;
|
|
|
160
160
|
* this property when present -- matches `<lr-combobox>`'s/`<lr-table>`'s identical host
|
|
161
161
|
* `aria-label` fallback. */
|
|
162
162
|
label?:string;private activeIndex;private readonly _listId;private cleanup?;private virtualAnchor;private _isFirstUpdate;private _silentClose;private _ownsFocus;private _focusOwnerPredicate?;private _focusTransferGeneration;private anchorRelationship?;private announcementSink?;private announcedResultCount?;private announcedResultPosition?;connectedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;disconnectedCallback():void;adoptedCallback():void;private syncAnnouncementSink;private resetResultAnnouncements;private announceResultState;private snapshotAttribute;private restoreAttribute;private captureAnchorCaret;private restoreRelationshipFocus;private restoreAnchorFocus;private attachAnchorRelationship;private detachAnchorRelationship;private syncAnchorRelationship;
|
|
163
|
-
/** The current candidate set: runtime rows without a string `label` are omitted
|
|
164
|
-
*
|
|
163
|
+
/** The current candidate set: runtime rows without a non-blank string `label` are omitted (a
|
|
164
|
+
* blank/whitespace-only label would otherwise render a focusable `role="option"` with no
|
|
165
|
+
* accessible name), then the remaining `items` are filtered by `query` via `filter` (or the
|
|
166
|
+
* built-in default). */
|
|
165
167
|
get filteredItems():readonly Readonly<LyraMentionItem>[];
|
|
166
168
|
/** The internal id of the currently highlighted row, for same-tree consumers only. */
|
|
167
169
|
get activeDescendantId():string|null;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./mention-popover.styles.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_mentionResultCount,LYRA_DEFAULT_mentionResultPosition,LYRA_DEFAULT_mentionSuggestions,LYRA_DEFAULT_noMatches}from"../../../internal/default-strings.generated.js";function isTextControl(el){const view=el.ownerDocument.defaultView;return view?el instanceof view.HTMLTextAreaElement?!0:el instanceof view.HTMLInputElement&&(el.type==="text"||el.type==="search"):!1}function isTextareaAnchor(el){const view=el.ownerDocument.defaultView;return!!(view&&el instanceof view.HTMLTextAreaElement)}const MIRROR_CSS_PROPS=["box-sizing","width","padding-top","padding-right","padding-bottom","padding-left","border-top-width","border-right-width","border-bottom-width","border-left-width","border-style","font-family","font-size","font-style","font-variant","font-weight","font-stretch","letter-spacing","word-spacing","line-height","text-align","text-indent","text-transform","tab-size","direction"];function caretClientRect(el){const owner=el.ownerDocument,view=owner.defaultView;if(!view)return null;const elRect=el.getBoundingClientRect();if(elRect.width===0||elRect.height===0)return null;const computed=view.getComputedStyle(el),mirror=owner.createElement("div");mirror.style.position="absolute",mirror.style.visibility="hidden",mirror.style.top="0",mirror.style.left="-9999px",mirror.style.whiteSpace=el instanceof view.HTMLTextAreaElement?"pre-wrap":"pre",mirror.style.overflowWrap="break-word";for(const prop of MIRROR_CSS_PROPS)mirror.style.setProperty(prop,computed.getPropertyValue(prop));const index=el.selectionStart??el.value.length;mirror.append(owner.createTextNode(el.value.slice(0,index)));const marker=owner.createElement("span");marker.textContent=el.value.slice(index)||"",mirror.appendChild(marker),owner.body.appendChild(mirror);const mirrorRect=mirror.getBoundingClientRect(),markerRect=marker.getBoundingClientRect();mirror.remove();const lineHeight=parseFloat(computed.lineHeight)||markerRect.height||16;return new view.DOMRect(elRect.left+(markerRect.left-mirrorRect.left)-el.scrollLeft,elRect.top+(markerRect.top-mirrorRect.top)-el.scrollTop,1,lineHeight)}class LyraMentionPopover extends LyraElement{constructor(){super(...arguments),this._textareaFocusSessionGeneration=0,this._items=Object.freeze([]),this.query="",this.open=!1,this.filter=null,this.activeIndex=0,this._listId=nextId("mention-popover-listbox"),this.virtualAnchor=null,this._isFirstUpdate=!0,this._silentClose=!1,this._ownsFocus=!1,this._focusTransferGeneration=0,this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index)||index<0)return;const item=this.filteredItems[index];item&&this.commit(item)},this.onListboxKeyDown=e=>{e.defaultPrevented||!this._ownsFocus||this.handleKeyDown(e)&&this.open&&this.focusActiveOption()}}static{this.defaultStrings={...super.defaultStrings,mentionResultCount:LYRA_DEFAULT_mentionResultCount,mentionResultPosition:LYRA_DEFAULT_mentionResultPosition,mentionSuggestions:LYRA_DEFAULT_mentionSuggestions,noMatches:LYRA_DEFAULT_noMatches}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={items:{attribute:!1,noAccessor:!0}}}requestUpdate(name,oldValue,options){(name==="open"||name==="anchor"||name==="query"||name==="items"||name==="filter")&&this.hasTextareaFocusSession()&&(this._textareaFocusSessionGeneration+=1),super.requestUpdate(name,oldValue,options)}hasTextareaFocusSession(){const relationshipControl=this.anchorRelationship?.control;return this.anchor!==void 0&&isTextareaAnchor(this.anchor)||relationshipControl!==void 0&&isTextareaAnchor(relationshipControl)}get items(){return this._items}set items(next){const previous=this._items,source=Array.isArray(next)?next:[];this._items=Object.freeze(source.map(item=>Object.freeze({...item}))),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.announceResultState()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._ownsFocus&&!this.fallbackFocusIsStillOwned()&&(this._ownsFocus=!1,this._focusOwnerPredicate=void 0),(changed.has("query")||changed.has("items")||changed.has("filter"))&&(this.activeIndex=0);const candidatesChanged=changed.has("query")||changed.has("items")||changed.has("filter");this._ownsFocus&&changed.has("open")&&!this.open?(this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0):this._ownsFocus&&this.open&&candidatesChanged&&this.filteredItems.length===0&&(this.anchor?.isConnected?this.restoreAnchorFocus():this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0}),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),this._ownsFocus&&changed.has("anchor")&&this.anchorRelationship?.control!==this.anchor&&this.detachAnchorRelationship()}updated(changed){if(super.updated(changed),changed.has("open"))if(this.open)this.reposition();else{this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove();const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),!this._isFirstUpdate&&!this._silentClose&&queueMicrotask(()=>this.emit("lr-mention-close")),this._silentClose=!1}else this.open&&(changed.has("anchor")||changed.has("query"))&&this.reposition();if(changed.has("activeIndex")||changed.has("query")||changed.has("items")||changed.has("filter")){const active=this.renderRoot.querySelector('[part="option"][data-active]');active?.scrollIntoView({block:"nearest"}),this._ownsFocus&&(!active&&this.anchor?.isConnected?this.restoreFocus():this.restoreFocus(!0))}this.syncAnchorRelationship(),this.open?this.announceResultState():this.resetResultAnnouncements()}disconnectedCallback(){this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.announcementSink?.release(),this.announcementSink=void 0,this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.open=!1}adoptedCallback(){super.adoptedCallback(),this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.syncAnnouncementSink(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),this.open=!1}syncAnnouncementSink(){this.announcementSink?.element?.ownerDocument!==this.ownerDocument&&(this.announcementSink?.release(),this.announcementSink=this.isConnected?acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}):void 0)}resetResultAnnouncements(){this.announcedResultCount=void 0,this.announcedResultPosition=void 0}announceResultState(){if(!this.open||!this.announcementSink)return;const rows=this.filteredItems,resultState=rows.length===0?this.localize("noMatches"):this.localize("mentionResultCount",void 0,{count:rows.length}),index=this.clampedIndex(rows),position=index<0?void 0:this.localize("mentionResultPosition",void 0,{current:index+1,total:rows.length});if(this._isFirstUpdate){this.announcedResultCount=resultState,this.announcedResultPosition=position;return}if(resultState!==this.announcedResultCount&&(this.announcementSink.announce(resultState),this.announcedResultCount=resultState),position===void 0){this.announcedResultPosition=void 0;return}position!==this.announcedResultPosition&&(this.announcementSink.announce(position),this.announcedResultPosition=position)}snapshotAttribute(control,name){return{present:control.hasAttribute(name),value:control.getAttribute(name)}}restoreAttribute(control,name,snapshot){snapshot.present?control.setAttribute(name,snapshot.value??""):control.removeAttribute(name)}captureAnchorCaret(relationship=this.anchorRelationship){if(!relationship||!isTextareaAnchor(relationship.control))return;const{control}=relationship;relationship.selectionStart=control.selectionStart,relationship.selectionEnd=control.selectionEnd,relationship.selectionDirection=control.selectionDirection}restoreRelationshipFocus(relationship){const{control}=relationship;if(control.isConnected)try{control.focus({preventScroll:!0}),isTextareaAnchor(control)&&relationship.selectionStart!==null&&relationship.selectionStart!==void 0&&relationship.selectionEnd!==null&&relationship.selectionEnd!==void 0&&control.setSelectionRange(relationship.selectionStart,relationship.selectionEnd,relationship.selectionDirection??void 0)}catch{}}restoreAnchorFocus(){const relationship=this.anchorRelationship;if(relationship){this.restoreRelationshipFocus(relationship);return}const anchor=this.anchor;if(anchor?.isConnected)try{anchor.focus({preventScroll:!0})}catch{}}attachAnchorRelationship(control){const reflected=control,textarea=isTextareaAnchor(control),attributes=new Map((textarea?["role","aria-expanded","aria-haspopup","aria-autocomplete","aria-controls","aria-activedescendant"]:["role","aria-expanded","aria-haspopup","aria-controls","aria-activedescendant"]).map(name=>[name,this.snapshotAttribute(control,name)])),activeElement="ariaActiveDescendantElement"in control?reflected.ariaActiveDescendantElement??null:void 0,controlsElements="ariaControlsElements"in control?reflected.ariaControlsElements??null:void 0,capturedTextareaActiveElement=textarea&&attributes.get("aria-activedescendant")?.present&&attributes.get("aria-activedescendant")?.value===""?activeElement??void 0:void 0,capturedTextareaControlsElements=textarea&&attributes.get("aria-controls")?.present&&attributes.get("aria-controls")?.value===""&&controlsElements?.length?controlsElements:void 0,relationship={control,attributes,activeElement:textarea?capturedTextareaActiveElement:activeElement,controlsElements:textarea?capturedTextareaControlsElements:controlsElements,selectionStart:textarea?control.selectionStart:void 0,selectionEnd:textarea?control.selectionEnd:void 0,selectionDirection:textarea?control.selectionDirection:void 0};return this.anchorRelationship=relationship,relationship}detachAnchorRelationship(){const relationship=this.anchorRelationship;if(!relationship)return;if(this.anchorRelationship=void 0,this._ownsFocus&&(this.restoreRelationshipFocus(relationship),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),!isTextareaAnchor(relationship.control)){const reflected2=relationship.control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=relationship.controlsElements}catch{}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);return}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);const reflected=relationship.control;if(relationship.activeElement!==void 0)try{reflected.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected.ariaControlsElements=relationship.controlsElements}catch{}}syncAnchorRelationship(){const next=this.open&&this.anchor&&isTextControl(this.anchor)?this.anchor:void 0;if(this.anchorRelationship?.control!==next&&this.detachAnchorRelationship(),!next)return;const relationship=this.anchorRelationship??this.attachAnchorRelationship(next),control=relationship.control;if(isTextareaAnchor(control)){control.removeAttribute("role"),control.removeAttribute("aria-expanded"),control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant");const reflected2=control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=null}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=null}catch{}control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant"),control.setAttribute("aria-haspopup","listbox"),control.setAttribute("aria-autocomplete","list");return}relationship.attributes.get("role")?.present||control.setAttribute("role","combobox"),control.setAttribute("aria-expanded","true"),control.setAttribute("aria-haspopup","listbox");const listbox=this.renderRoot.querySelector('[part="listbox"]'),reflected=control;if(listbox&&"ariaControlsElements"in control)try{control.removeAttribute("aria-controls"),reflected.ariaControlsElements=[listbox],reflected.ariaControlsElements?.[0]!==listbox&&(reflected.ariaControlsElements=[this],reflected.ariaControlsElements?.[0]!==this&&control.removeAttribute("aria-controls"))}catch{control.removeAttribute("aria-controls")}else control.removeAttribute("aria-controls");control.removeAttribute("aria-activedescendant"),this.syncActiveDescendant(control)}get filteredItems(){const locale=this.effectiveLocale,q=(this.query??"").trim().toLocaleLowerCase(locale);return this.items.filter(item=>typeof item.label!="string"?!1:q?this.filter?this.filter(item,q):item.label.toLocaleLowerCase(locale).includes(q)||(typeof item.description=="string"?item.description:"").toLocaleLowerCase(locale).includes(q):!0)}get activeDescendantId(){if(!this.open)return null;const idx=this.clampedIndex(this.filteredItems);return idx>=0?this.rowId(idx):null}get activeDescendantElement(){const id=this.activeDescendantId,escape=this.ownerDocument.defaultView?.CSS.escape;return id&&escape?this.renderRoot.querySelector(`#${escape(id)}`):null}syncActiveDescendant(_control){if(isTextareaAnchor(_control)||(_control.removeAttribute("aria-activedescendant"),!("ariaActiveDescendantElement"in _control)))return!1;const active=this.activeDescendantElement;try{const reflected=_control;reflected.ariaActiveDescendantElement=active;const accepted=reflected.ariaActiveDescendantElement===active;return accepted||(reflected.ariaActiveDescendantElement=null,_control.removeAttribute("aria-activedescendant")),accepted}catch{return _control.removeAttribute("aria-activedescendant"),!1}}async focusActiveOption(options={}){const ownsFocus=options.ownsFocus??(this._ownsFocus?this._focusOwnerPredicate:void 0);if(!this.open||!this.isConnected||!this.activeDescendantElement||!this.callFocusOwner(ownsFocus))return!1;const generation=++this._focusTransferGeneration,textareaSession=this.anchor!==void 0&&isTextareaAnchor(this.anchor),textareaSessionGeneration=this._textareaFocusSessionGeneration,snapshot={ownerDocument:this.ownerDocument,anchor:this.anchor,items:this.items,query:this.query,filter:this.filter,activeIndex:this.activeIndex};if(await this.updateComplete,await this.cleanup?.ready===!1||generation!==this._focusTransferGeneration||textareaSession&&textareaSessionGeneration!==this._textareaFocusSessionGeneration||!this.isConnected||!this.open||this.ownerDocument!==snapshot.ownerDocument||this.anchor!==snapshot.anchor||this.items!==snapshot.items||this.query!==snapshot.query||this.filter!==snapshot.filter||this.activeIndex!==snapshot.activeIndex||!this.callFocusOwner(ownsFocus))return!1;const active=this.activeDescendantElement;return!active?.isConnected||!this.callFocusOwner(ownsFocus)||(this.captureAnchorCaret(),active.focus({preventScroll:!0}),activeElementIn(this.shadowRoot)!==active)?!1:(this._focusOwnerPredicate=ownsFocus,this._ownsFocus=!0,!0)}async restoreFocus(waitForPlacement=!1){if(waitForPlacement){if(await this.cleanup?.ready===!1||!this._ownsFocus||!this.open)return;if(this.hasTextareaFocusSession()&&!this.fallbackFocusIsStillOwned()){this._ownsFocus=!1,this._focusOwnerPredicate=void 0;return}}const active=this.renderRoot.querySelector('[part="option"][data-active]');active?active.focus({preventScroll:!0}):this.anchor?.isConnected?(this.renderRoot.querySelector('[part="listbox"]')?.setAttribute("tabindex","-1"),this.restoreAnchorFocus(),this.scheduleAfterUpdate(()=>{this._ownsFocus=!1,this._focusOwnerPredicate=void 0})):this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0})}callFocusOwner(predicate){try{return predicate?.()??!0}catch{return!1}}fallbackFocusIsStillOwned(){return this.callFocusOwner(this._focusOwnerPredicate)&&activeElementIn(this.shadowRoot)!==null}get listboxId(){return this._listId}handleKeyDown(e){if(!this.open||e.isComposing||e.keyCode===229)return!1;const rows=this.filteredItems;switch(e.key){case"ArrowDown":return rows.length?(e.preventDefault(),this.activeIndex=Math.min(rows.length-1,this.clampedIndex(rows)+1),!0):!1;case"ArrowUp":return rows.length?(e.preventDefault(),this.activeIndex=Math.max(0,this.clampedIndex(rows)-1),!0):!1;case"Enter":case"Tab":{const idx=this.clampedIndex(rows);return idx<0?!1:(e.preventDefault(),this.commit(rows[idx]),!0)}case"Escape":return e.preventDefault(),this.open=!1,!0;default:return!1}}clampedIndex(rows){return rows.length?Math.min(Math.max(this.activeIndex,0),rows.length-1):-1}rowId(index){return`${this._listId}-opt-${index}`}commit(item){const index=this.items.indexOf(item);if(index<0)return;const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),this.emit("lr-mention-select",Object.freeze({suggestionId:item.suggestionId,index,label:item.label})),this._silentClose=!0,this.open=!1}reposition(){this.cleanup?.(),this.cleanup=void 0;const anchorEl=this.resolveAnchorElement(),popup=this.renderRoot.querySelector('[part="listbox"]');if(anchorEl&&popup){const placement=place(anchorEl,popup,{placement:"bottom-start"});this.cleanup=placement,placement.ready.then(positioned=>{positioned||this.cleanup!==placement||!this.open||(this._silentClose=!0,this.open=!1)})}}resolveAnchorElement(){const anchor=this.anchor;if(!anchor)return null;if(isTextControl(anchor)){const rect=caretClientRect(anchor);if(rect){const owner=anchor.ownerDocument;this.virtualAnchor&&this.virtualAnchor.ownerDocument!==owner&&(this.virtualAnchor.remove(),this.virtualAnchor=null);const virtual=this.virtualAnchor??(this.virtualAnchor=owner.createElement("div"));return virtual.style.position="fixed",virtual.style.left=`${rect.left}px`,virtual.style.top=`${rect.top}px`,virtual.style.width="0",virtual.style.height=`${rect.height}px`,virtual.style.pointerEvents="none",virtual.isConnected||owner.body.appendChild(virtual),virtual}}return anchor}get effectiveEmptyText(){return this.emptyText===void 0?this.localize("noMatches"):this.emptyText}get effectiveLabel(){return hostAriaLabel(this)??(this.label===void 0?this.localize("mentionSuggestions"):this.label)}renderRow(item,index,activeId){const id=this.rowId(index),active=id===activeId;return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./mention-popover.styles.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_mentionResultCount,LYRA_DEFAULT_mentionResultPosition,LYRA_DEFAULT_mentionSuggestions,LYRA_DEFAULT_noMatches}from"../../../internal/default-strings.generated.js";function isTextControl(el){const view=el.ownerDocument.defaultView;return view?el instanceof view.HTMLTextAreaElement?!0:el instanceof view.HTMLInputElement&&(el.type==="text"||el.type==="search"):!1}function isTextareaAnchor(el){const view=el.ownerDocument.defaultView;return!!(view&&el instanceof view.HTMLTextAreaElement)}const MIRROR_CSS_PROPS=["box-sizing","width","padding-top","padding-right","padding-bottom","padding-left","border-top-width","border-right-width","border-bottom-width","border-left-width","border-style","font-family","font-size","font-style","font-variant","font-weight","font-stretch","letter-spacing","word-spacing","line-height","text-align","text-indent","text-transform","tab-size","direction"];function caretClientRect(el){const owner=el.ownerDocument,view=owner.defaultView;if(!view)return null;const elRect=el.getBoundingClientRect();if(elRect.width===0||elRect.height===0)return null;const computed=view.getComputedStyle(el),mirror=owner.createElement("div");mirror.style.position="absolute",mirror.style.visibility="hidden",mirror.style.top="0",mirror.style.left="-9999px",mirror.style.whiteSpace=el instanceof view.HTMLTextAreaElement?"pre-wrap":"pre",mirror.style.overflowWrap="break-word";for(const prop of MIRROR_CSS_PROPS)mirror.style.setProperty(prop,computed.getPropertyValue(prop));const index=el.selectionStart??el.value.length;mirror.append(owner.createTextNode(el.value.slice(0,index)));const marker=owner.createElement("span");marker.textContent=el.value.slice(index)||"",mirror.appendChild(marker),owner.body.appendChild(mirror);const mirrorRect=mirror.getBoundingClientRect(),markerRect=marker.getBoundingClientRect();mirror.remove();const lineHeight=parseFloat(computed.lineHeight)||markerRect.height||16;return new view.DOMRect(elRect.left+(markerRect.left-mirrorRect.left)-el.scrollLeft,elRect.top+(markerRect.top-mirrorRect.top)-el.scrollTop,1,lineHeight)}class LyraMentionPopover extends LyraElement{constructor(){super(...arguments),this._textareaFocusSessionGeneration=0,this._items=Object.freeze([]),this.query="",this.open=!1,this.filter=null,this.activeIndex=0,this._listId=nextId("mention-popover-listbox"),this.virtualAnchor=null,this._isFirstUpdate=!0,this._silentClose=!1,this._ownsFocus=!1,this._focusTransferGeneration=0,this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index)||index<0)return;const item=this.filteredItems[index];item&&this.commit(item)},this.onListboxKeyDown=e=>{e.defaultPrevented||!this._ownsFocus||this.handleKeyDown(e)&&this.open&&this.focusActiveOption()}}static{this.defaultStrings={...super.defaultStrings,mentionResultCount:LYRA_DEFAULT_mentionResultCount,mentionResultPosition:LYRA_DEFAULT_mentionResultPosition,mentionSuggestions:LYRA_DEFAULT_mentionSuggestions,noMatches:LYRA_DEFAULT_noMatches}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={items:{attribute:!1,noAccessor:!0}}}requestUpdate(name,oldValue,options){(name==="open"||name==="anchor"||name==="query"||name==="items"||name==="filter")&&this.hasTextareaFocusSession()&&(this._textareaFocusSessionGeneration+=1),super.requestUpdate(name,oldValue,options)}hasTextareaFocusSession(){const relationshipControl=this.anchorRelationship?.control;return this.anchor!==void 0&&isTextareaAnchor(this.anchor)||relationshipControl!==void 0&&isTextareaAnchor(relationshipControl)}get items(){return this._items}set items(next){const previous=this._items,source=Array.isArray(next)?next:[];this._items=Object.freeze(source.map(item=>Object.freeze({...item}))),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.announceResultState()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._ownsFocus&&!this.fallbackFocusIsStillOwned()&&(this._ownsFocus=!1,this._focusOwnerPredicate=void 0),(changed.has("query")||changed.has("items")||changed.has("filter"))&&(this.activeIndex=0);const candidatesChanged=changed.has("query")||changed.has("items")||changed.has("filter");this._ownsFocus&&changed.has("open")&&!this.open?(this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0):this._ownsFocus&&this.open&&candidatesChanged&&this.filteredItems.length===0&&(this.anchor?.isConnected?this.restoreAnchorFocus():this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0}),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),this._ownsFocus&&changed.has("anchor")&&this.anchorRelationship?.control!==this.anchor&&this.detachAnchorRelationship()}updated(changed){if(super.updated(changed),changed.has("open"))if(this.open)this.reposition();else{this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove();const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),!this._isFirstUpdate&&!this._silentClose&&queueMicrotask(()=>this.emit("lr-mention-close")),this._silentClose=!1}else this.open&&(changed.has("anchor")||changed.has("query"))&&this.reposition();if(changed.has("activeIndex")||changed.has("query")||changed.has("items")||changed.has("filter")){const active=this.renderRoot.querySelector('[part="option"][data-active]');active?.scrollIntoView({block:"nearest"}),this._ownsFocus&&(!active&&this.anchor?.isConnected?this.restoreFocus():this.restoreFocus(!0))}this.syncAnchorRelationship(),this.open?this.announceResultState():this.resetResultAnnouncements()}disconnectedCallback(){this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.announcementSink?.release(),this.announcementSink=void 0,this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.open=!1}adoptedCallback(){super.adoptedCallback(),this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.syncAnnouncementSink(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),this.open=!1}syncAnnouncementSink(){this.announcementSink?.element?.ownerDocument!==this.ownerDocument&&(this.announcementSink?.release(),this.announcementSink=this.isConnected?acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}):void 0)}resetResultAnnouncements(){this.announcedResultCount=void 0,this.announcedResultPosition=void 0}announceResultState(){if(!this.open||!this.announcementSink)return;const rows=this.filteredItems,resultState=rows.length===0?this.localize("noMatches"):this.localize("mentionResultCount",void 0,{count:rows.length}),index=this.clampedIndex(rows),position=index<0?void 0:this.localize("mentionResultPosition",void 0,{current:index+1,total:rows.length});if(this._isFirstUpdate){this.announcedResultCount=resultState,this.announcedResultPosition=position;return}if(resultState!==this.announcedResultCount&&(this.announcementSink.announce(resultState),this.announcedResultCount=resultState),position===void 0){this.announcedResultPosition=void 0;return}position!==this.announcedResultPosition&&(this.announcementSink.announce(position),this.announcedResultPosition=position)}snapshotAttribute(control,name){return{present:control.hasAttribute(name),value:control.getAttribute(name)}}restoreAttribute(control,name,snapshot){snapshot.present?control.setAttribute(name,snapshot.value??""):control.removeAttribute(name)}captureAnchorCaret(relationship=this.anchorRelationship){if(!relationship||!isTextareaAnchor(relationship.control))return;const{control}=relationship;relationship.selectionStart=control.selectionStart,relationship.selectionEnd=control.selectionEnd,relationship.selectionDirection=control.selectionDirection}restoreRelationshipFocus(relationship){const{control}=relationship;if(control.isConnected)try{control.focus({preventScroll:!0}),isTextareaAnchor(control)&&relationship.selectionStart!==null&&relationship.selectionStart!==void 0&&relationship.selectionEnd!==null&&relationship.selectionEnd!==void 0&&control.setSelectionRange(relationship.selectionStart,relationship.selectionEnd,relationship.selectionDirection??void 0)}catch{}}restoreAnchorFocus(){const relationship=this.anchorRelationship;if(relationship){this.restoreRelationshipFocus(relationship);return}const anchor=this.anchor;if(anchor?.isConnected)try{anchor.focus({preventScroll:!0})}catch{}}attachAnchorRelationship(control){const reflected=control,textarea=isTextareaAnchor(control),attributes=new Map((textarea?["role","aria-expanded","aria-haspopup","aria-autocomplete","aria-controls","aria-activedescendant"]:["role","aria-expanded","aria-haspopup","aria-controls","aria-activedescendant"]).map(name=>[name,this.snapshotAttribute(control,name)])),activeElement="ariaActiveDescendantElement"in control?reflected.ariaActiveDescendantElement??null:void 0,controlsElements="ariaControlsElements"in control?reflected.ariaControlsElements??null:void 0,capturedTextareaActiveElement=textarea&&attributes.get("aria-activedescendant")?.present&&attributes.get("aria-activedescendant")?.value===""?activeElement??void 0:void 0,capturedTextareaControlsElements=textarea&&attributes.get("aria-controls")?.present&&attributes.get("aria-controls")?.value===""&&controlsElements?.length?controlsElements:void 0,relationship={control,attributes,activeElement:textarea?capturedTextareaActiveElement:activeElement,controlsElements:textarea?capturedTextareaControlsElements:controlsElements,selectionStart:textarea?control.selectionStart:void 0,selectionEnd:textarea?control.selectionEnd:void 0,selectionDirection:textarea?control.selectionDirection:void 0};return this.anchorRelationship=relationship,relationship}detachAnchorRelationship(){const relationship=this.anchorRelationship;if(!relationship)return;if(this.anchorRelationship=void 0,this._ownsFocus&&(this.restoreRelationshipFocus(relationship),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),!isTextareaAnchor(relationship.control)){const reflected2=relationship.control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=relationship.controlsElements}catch{}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);return}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);const reflected=relationship.control;if(relationship.activeElement!==void 0)try{reflected.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected.ariaControlsElements=relationship.controlsElements}catch{}}syncAnchorRelationship(){const next=this.open&&this.anchor&&isTextControl(this.anchor)?this.anchor:void 0;if(this.anchorRelationship?.control!==next&&this.detachAnchorRelationship(),!next)return;const relationship=this.anchorRelationship??this.attachAnchorRelationship(next),control=relationship.control;if(isTextareaAnchor(control)){control.removeAttribute("role"),control.removeAttribute("aria-expanded"),control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant");const reflected2=control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=null}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=null}catch{}control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant"),control.setAttribute("aria-haspopup","listbox"),control.setAttribute("aria-autocomplete","list");return}relationship.attributes.get("role")?.present||control.setAttribute("role","combobox"),control.setAttribute("aria-expanded","true"),control.setAttribute("aria-haspopup","listbox");const listbox=this.renderRoot.querySelector('[part="listbox"]'),reflected=control;if(listbox&&"ariaControlsElements"in control)try{control.removeAttribute("aria-controls"),reflected.ariaControlsElements=[listbox],reflected.ariaControlsElements?.[0]!==listbox&&(reflected.ariaControlsElements=[this],reflected.ariaControlsElements?.[0]!==this&&control.removeAttribute("aria-controls"))}catch{control.removeAttribute("aria-controls")}else control.removeAttribute("aria-controls");control.removeAttribute("aria-activedescendant"),this.syncActiveDescendant(control)}get filteredItems(){const locale=this.effectiveLocale,q=(this.query??"").trim().toLocaleLowerCase(locale);return this.items.filter(item=>typeof item.label!="string"||item.label.trim().length===0?!1:q?this.filter?this.filter(item,q):item.label.toLocaleLowerCase(locale).includes(q)||(typeof item.description=="string"?item.description:"").toLocaleLowerCase(locale).includes(q):!0)}get activeDescendantId(){if(!this.open)return null;const idx=this.clampedIndex(this.filteredItems);return idx>=0?this.rowId(idx):null}get activeDescendantElement(){const id=this.activeDescendantId,escape=this.ownerDocument.defaultView?.CSS.escape;return id&&escape?this.renderRoot.querySelector(`#${escape(id)}`):null}syncActiveDescendant(_control){if(isTextareaAnchor(_control)||(_control.removeAttribute("aria-activedescendant"),!("ariaActiveDescendantElement"in _control)))return!1;const active=this.activeDescendantElement;try{const reflected=_control;reflected.ariaActiveDescendantElement=active;const accepted=reflected.ariaActiveDescendantElement===active;return accepted||(reflected.ariaActiveDescendantElement=null,_control.removeAttribute("aria-activedescendant")),accepted}catch{return _control.removeAttribute("aria-activedescendant"),!1}}async focusActiveOption(options={}){const ownsFocus=options.ownsFocus??(this._ownsFocus?this._focusOwnerPredicate:void 0);if(!this.open||!this.isConnected||!this.activeDescendantElement||!this.callFocusOwner(ownsFocus))return!1;const generation=++this._focusTransferGeneration,textareaSession=this.anchor!==void 0&&isTextareaAnchor(this.anchor),textareaSessionGeneration=this._textareaFocusSessionGeneration,snapshot={ownerDocument:this.ownerDocument,anchor:this.anchor,items:this.items,query:this.query,filter:this.filter,activeIndex:this.activeIndex};if(await this.updateComplete,await this.cleanup?.ready===!1||generation!==this._focusTransferGeneration||textareaSession&&textareaSessionGeneration!==this._textareaFocusSessionGeneration||!this.isConnected||!this.open||this.ownerDocument!==snapshot.ownerDocument||this.anchor!==snapshot.anchor||this.items!==snapshot.items||this.query!==snapshot.query||this.filter!==snapshot.filter||this.activeIndex!==snapshot.activeIndex||!this.callFocusOwner(ownsFocus))return!1;const active=this.activeDescendantElement;return!active?.isConnected||!this.callFocusOwner(ownsFocus)||(this.captureAnchorCaret(),active.focus({preventScroll:!0}),activeElementIn(this.shadowRoot)!==active)?!1:(this._focusOwnerPredicate=ownsFocus,this._ownsFocus=!0,!0)}async restoreFocus(waitForPlacement=!1){if(waitForPlacement){if(await this.cleanup?.ready===!1||!this._ownsFocus||!this.open)return;if(this.hasTextareaFocusSession()&&!this.fallbackFocusIsStillOwned()){this._ownsFocus=!1,this._focusOwnerPredicate=void 0;return}}const active=this.renderRoot.querySelector('[part="option"][data-active]');active?active.focus({preventScroll:!0}):this.anchor?.isConnected?(this.renderRoot.querySelector('[part="listbox"]')?.setAttribute("tabindex","-1"),this.restoreAnchorFocus(),this.scheduleAfterUpdate(()=>{this._ownsFocus=!1,this._focusOwnerPredicate=void 0})):this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0})}callFocusOwner(predicate){try{return predicate?.()??!0}catch{return!1}}fallbackFocusIsStillOwned(){return this.callFocusOwner(this._focusOwnerPredicate)&&activeElementIn(this.shadowRoot)!==null}get listboxId(){return this._listId}handleKeyDown(e){if(!this.open||e.isComposing||e.keyCode===229)return!1;const rows=this.filteredItems;switch(e.key){case"ArrowDown":return rows.length?(e.preventDefault(),this.activeIndex=Math.min(rows.length-1,this.clampedIndex(rows)+1),!0):!1;case"ArrowUp":return rows.length?(e.preventDefault(),this.activeIndex=Math.max(0,this.clampedIndex(rows)-1),!0):!1;case"Enter":case"Tab":{const idx=this.clampedIndex(rows);return idx<0?!1:(e.preventDefault(),this.commit(rows[idx]),!0)}case"Escape":return e.preventDefault(),this.open=!1,!0;default:return!1}}clampedIndex(rows){return rows.length?Math.min(Math.max(this.activeIndex,0),rows.length-1):-1}rowId(index){return`${this._listId}-opt-${index}`}commit(item){const index=this.items.indexOf(item);if(index<0)return;const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),this.emit("lr-mention-select",Object.freeze({suggestionId:item.suggestionId,index,label:item.label})),this._silentClose=!0,this.open=!1}reposition(){this.cleanup?.(),this.cleanup=void 0;const anchorEl=this.resolveAnchorElement(),popup=this.renderRoot.querySelector('[part="listbox"]');if(anchorEl&&popup){const placement=place(anchorEl,popup,{placement:"bottom-start"});this.cleanup=placement,placement.ready.then(positioned=>{positioned||this.cleanup!==placement||!this.open||(this._silentClose=!0,this.open=!1)})}}resolveAnchorElement(){const anchor=this.anchor;if(!anchor)return null;if(isTextControl(anchor)){const rect=caretClientRect(anchor);if(rect){const owner=anchor.ownerDocument;this.virtualAnchor&&this.virtualAnchor.ownerDocument!==owner&&(this.virtualAnchor.remove(),this.virtualAnchor=null);const virtual=this.virtualAnchor??(this.virtualAnchor=owner.createElement("div"));return virtual.style.position="fixed",virtual.style.left=`${rect.left}px`,virtual.style.top=`${rect.top}px`,virtual.style.width="0",virtual.style.height=`${rect.height}px`,virtual.style.pointerEvents="none",virtual.isConnected||owner.body.appendChild(virtual),virtual}}return anchor}get effectiveEmptyText(){return this.emptyText===void 0?this.localize("noMatches"):this.emptyText}get effectiveLabel(){return hostAriaLabel(this)??(this.label===void 0?this.localize("mentionSuggestions"):this.label)}renderRow(item,index,activeId){const id=this.rowId(index),active=id===activeId;return html`
|
|
2
2
|
<div
|
|
3
3
|
part="option"
|
|
4
4
|
id=${id}
|
|
@@ -93,4 +93,12 @@ searchNext():Promise<boolean>;
|
|
|
93
93
|
searchPrevious():Promise<boolean>;
|
|
94
94
|
/** Clears the query, matches, and active index, and resets `lr-search-change` to a
|
|
95
95
|
* 0-match/no-active-index state. */
|
|
96
|
-
clearSearch():void;private emitSearchChange;private stopInternalEvent;
|
|
96
|
+
clearSearch():void;private emitSearchChange;private stopInternalEvent;
|
|
97
|
+
/** Memoized `<lr-virtual-list>.items`/`.renderItem` inputs, keyed on the exact `rows` array
|
|
98
|
+
* reference and `hasHeaderRow` -- a fresh `body` array and `renderItem` closure on every
|
|
99
|
+
* render() (a search keystroke, active-row change, locale change, all unrelated to the data
|
|
100
|
+
* itself) would otherwise defeat the virtual list's own offset-cache memoization on every one
|
|
101
|
+
* of those, forcing its O(n) `recomputeOffsets()` and clearing measured row heights. `renderItem`
|
|
102
|
+
* still reads live `this` state (highlights, etc.) on every call -- only its own identity is
|
|
103
|
+
* cached, not its output. */
|
|
104
|
+
private virtualListInputsCache?;private virtualListInputs;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-csv-viewer':LyraCsvViewer;}}export{};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{parseCellRange}from"../../../internal/cell-range.js";import{loadPapaParseCached}from"../../../internal/papaparse-loader.js";import{styles}from"./csv-viewer.styles.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{delimitedCellText as cell,delimitedColumnCount as columns,parseDelimitedGrid}from"../../../internal/delimited-data.js";import{LatestTask}from"../../../internal/latest-task.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_cellHighlightWithLabel,LYRA_DEFAULT_csvViewerLabel,LYRA_DEFAULT_csvViewerUnavailable,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_noData}from"../../../internal/default-strings.generated.js";const MAX_SEARCH_MATCHES=1e3;function headerOffset(hasHeaderRow){return hasHeaderRow?1:0}class LyraCsvViewerBase extends LyraElement{}class LyraCsvViewer extends DocumentAnchorTarget(LyraCsvViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.hasHeaderRow=!0,this.maxHeight="",this.anchorKinds=["cell-range"],this.fetchState={kind:"idle"},this.activeRowKey="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.loadTask=new LatestTask,this.loadLibrary=loadPapaParseCached,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.pendingAnimationFrames=new Set,this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,cellHighlightWithLabel:LYRA_DEFAULT_cellHighlightWithLabel,csvViewerLabel:LYRA_DEFAULT_csvViewerLabel,csvViewerUnavailable:LYRA_DEFAULT_csvViewerUnavailable,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument,noData:LYRA_DEFAULT_noData}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.loadTask.next(),this.cancelPendingAnimationFrames(),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelPendingAnimationFrames(),this.announcements.adopted()}waitForOwnerAnimationFrame(){const owner=this.ownerDocument.defaultView;return!owner||!this.isConnected?Promise.resolve(!1):new Promise(resolve=>{const pending={owner,resolve};this.pendingAnimationFrames.add(pending),pending.handle=owner.requestAnimationFrame(()=>{this.pendingAnimationFrames.delete(pending)&&resolve(this.isConnected&&this.ownerDocument.defaultView===owner)})})}cancelPendingAnimationFrames(){const pendingFrames=[...this.pendingAnimationFrames];this.pendingAnimationFrames.clear();for(const pending of pendingFrames)pending.handle!==void 0&&pending.owner.cancelAnimationFrame(pending.handle),pending.resolve(!1)}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.activeRowKey="")}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=!!this.searchQuery;this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}async load(){this.lastLoadSrc=this.src;const generation=this.loadTask.next(),signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const library=await this.loadLibrary();if(!this.isConnected||!this.loadTask.isCurrent(generation))return;if(!library){const error=new LyraUserFacingError(this.localize("csvViewerUnavailable"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}const source=await readResponseText(response);if(!this.isConnected||!this.loadTask.isCurrent(generation))return;const result=parseDelimitedGrid(library,source);if(!this.isConnected||!this.loadTask.isCurrent(generation)||(this.fetchState={kind:"loaded",rows:result.data},this.searchQuery&&await this.search(this.searchQuery),!this.isConnected||!this.loadTask.isCurrent(generation)))return;result.errors.length&&this.emit("lr-render-error",{error:result.errors})}catch(error){if(isAbortError(error)||!this.isConnected||!this.loadTask.isCurrent(generation))return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}cellHighlightsForRow(rawRow){const seen=new Set;return this.highlights.filter(highlight=>seen.has(highlight.id)?!1:(seen.add(highlight.id),!0)).flatMap(highlight=>{if(highlight.anchor.kind!=="cell-range"||highlight.anchor.sheet)return[];const parsed=parseCellRange(highlight.anchor.range);return parsed?rawRow-1>=parsed.startRow&&rawRow-1<=parsed.endRow?[{highlight,parsed}]:[]:[]})}renderCell(value,colIndex,rowHighlights,role){const colHighlights=rowHighlights.filter(entry=>colIndex>=entry.parsed.startCol&&colIndex<=entry.parsed.endCol);if(!colHighlights.length)return html`<div part="cell" role=${role}>${cell(value)}</div>`;const active=colHighlights.find(entry=>entry.highlight.id===this.activeHighlightId),primary=active??colHighlights[0],text=cell(value),accessibleLabel=primary.highlight.label?this.localize("cellHighlightWithLabel",void 0,{value:text,label:primary.highlight.label}):this.localize("highlightWithLabel",void 0,{label:text});return html`<div
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{parseCellRange}from"../../../internal/cell-range.js";import{loadPapaParseCached}from"../../../internal/papaparse-loader.js";import{styles}from"./csv-viewer.styles.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{delimitedCellText as cell,delimitedColumnCount as columns,parseDelimitedGrid}from"../../../internal/delimited-data.js";import{LatestTask}from"../../../internal/latest-task.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_cellHighlightWithLabel,LYRA_DEFAULT_csvViewerLabel,LYRA_DEFAULT_csvViewerUnavailable,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_noData}from"../../../internal/default-strings.generated.js";const MAX_SEARCH_MATCHES=1e3;function headerOffset(hasHeaderRow){return hasHeaderRow?1:0}function indexKeyFunction(_item,index){return index}class LyraCsvViewerBase extends LyraElement{}class LyraCsvViewer extends DocumentAnchorTarget(LyraCsvViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.hasHeaderRow=!0,this.maxHeight="",this.anchorKinds=["cell-range"],this.fetchState={kind:"idle"},this.activeRowKey="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.loadTask=new LatestTask,this.loadLibrary=loadPapaParseCached,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.pendingAnimationFrames=new Set,this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,cellHighlightWithLabel:LYRA_DEFAULT_cellHighlightWithLabel,csvViewerLabel:LYRA_DEFAULT_csvViewerLabel,csvViewerUnavailable:LYRA_DEFAULT_csvViewerUnavailable,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument,noData:LYRA_DEFAULT_noData}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.loadTask.next(),this.cancelPendingAnimationFrames(),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelPendingAnimationFrames(),this.announcements.adopted()}waitForOwnerAnimationFrame(){const owner=this.ownerDocument.defaultView;return!owner||!this.isConnected?Promise.resolve(!1):new Promise(resolve=>{const pending={owner,resolve};this.pendingAnimationFrames.add(pending),pending.handle=owner.requestAnimationFrame(()=>{this.pendingAnimationFrames.delete(pending)&&resolve(this.isConnected&&this.ownerDocument.defaultView===owner)})})}cancelPendingAnimationFrames(){const pendingFrames=[...this.pendingAnimationFrames];this.pendingAnimationFrames.clear();for(const pending of pendingFrames)pending.handle!==void 0&&pending.owner.cancelAnimationFrame(pending.handle),pending.resolve(!1)}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.activeRowKey="")}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=!!this.searchQuery;this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}async load(){this.lastLoadSrc=this.src;const generation=this.loadTask.next(),signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const library=await this.loadLibrary();if(!this.isConnected||!this.loadTask.isCurrent(generation))return;if(!library){const error=new LyraUserFacingError(this.localize("csvViewerUnavailable"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}const source=await readResponseText(response);if(!this.isConnected||!this.loadTask.isCurrent(generation))return;const result=parseDelimitedGrid(library,source);if(!this.isConnected||!this.loadTask.isCurrent(generation)||(this.fetchState={kind:"loaded",rows:result.data},this.searchQuery&&await this.search(this.searchQuery),!this.isConnected||!this.loadTask.isCurrent(generation)))return;result.errors.length&&this.emit("lr-render-error",{error:result.errors})}catch(error){if(isAbortError(error)||!this.isConnected||!this.loadTask.isCurrent(generation))return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}cellHighlightsForRow(rawRow){const seen=new Set;return this.highlights.filter(highlight=>seen.has(highlight.id)?!1:(seen.add(highlight.id),!0)).flatMap(highlight=>{if(highlight.anchor.kind!=="cell-range"||highlight.anchor.sheet)return[];const parsed=parseCellRange(highlight.anchor.range);return parsed?rawRow-1>=parsed.startRow&&rawRow-1<=parsed.endRow?[{highlight,parsed}]:[]:[]})}renderCell(value,colIndex,rowHighlights,role){const colHighlights=rowHighlights.filter(entry=>colIndex>=entry.parsed.startCol&&colIndex<=entry.parsed.endCol);if(!colHighlights.length)return html`<div part="cell" role=${role}>${cell(value)}</div>`;const active=colHighlights.find(entry=>entry.highlight.id===this.activeHighlightId),primary=active??colHighlights[0],text=cell(value),accessibleLabel=primary.highlight.label?this.localize("cellHighlightWithLabel",void 0,{value:text,label:primary.highlight.label}):this.localize("highlightWithLabel",void 0,{label:text});return html`<div
|
|
2
2
|
part="cell cell-highlight"
|
|
3
3
|
role=${role}
|
|
4
4
|
?data-active=${!!active}
|
|
@@ -19,7 +19,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
19
19
|
style=${`grid-template-columns:repeat(${count},minmax(var(--lr-size-8rem),1fr))`}
|
|
20
20
|
>
|
|
21
21
|
${Array.from({length:count},(_unused,index)=>this.renderCell(row[index],index,rowHighlights,header?"columnheader":"cell"))}
|
|
22
|
-
</div>`}async jumpToCell(rawRow,col){const loadedState=this.fetchState;if(loadedState.kind!=="loaded")return!1;const{rows}=loadedState;if(rawRow<1||rawRow>rows.length||col<0||col>=columns(rows))return!1;const bodyIndex=rawRow-1-headerOffset(this.hasHeaderRow);if(bodyIndex<0){const target=this.renderRoot.querySelector('[part="header-row"]')?.querySelectorAll('[part~="cell"]')[col];return target?.scrollIntoView({behavior:prefersReducedMotion(this.ownerDocument.defaultView)?"auto":"smooth",block:"nearest",inline:"nearest"}),!!target}return this.activeRowKey=bodyIndex,await this.updateComplete,await this.scrollColumnIntoView(col),this.fetchState===loadedState}async applyAnchor(anchor){if(anchor.kind!=="cell-range"||anchor.sheet)return!1;const parsed=parseCellRange(anchor.range);return parsed?this.jumpToCell(parsed.startRow+1,parsed.startCol):!1}async scrollColumnIntoView(col){const list=this.renderRoot.querySelector("lr-virtual-list");if(list?.updateComplete&&await list.updateComplete,!await this.waitForOwnerAnimationFrame())return;list?.shadowRoot?.querySelector('[part="row"][aria-current="true"]')?.querySelectorAll('[part~="cell"]')[col]?.scrollIntoView({behavior:prefersReducedMotion(this.ownerDocument.defaultView)?"auto":"smooth",block:"nearest",inline:"nearest"})}async search(query){this.searchQuery=query,this.lastSearchLocale=this.effectiveLocale;const boundedQuery=boundedViewerSearchQuery(query,this.effectiveLocale),trimmed=boundedQuery.needle,matches=[];let matchCountExact=boundedQuery.accepted;if(boundedQuery.accepted&&trimmed&&this.fetchState.kind==="loaded"){const budget=new ViewerSearchWorkBudget,{rows}=this.fetchState;searchRows:for(let r=0;r<rows.length;r++){const row=rows[r];for(let c=0;c<row.length;c++){if(budget.includes(cell(row[c]),trimmed,this.effectiveLocale)){if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1;break searchRows}matches.push({row:r+1,col:c})}if(!budget.complete){matchCountExact=!1;break searchRows}}}}return this.searchMatches=matches,this.searchMatchCountExact=matchCountExact,this.searchActiveIndex=matches.length>0?0:-1,this.emitSearchChange(),this.searchActiveIndex>=0&&await this.jumpToCell(matches[0].row,matches[0].col),matches.length}async searchNext(){if(!this.searchMatches.length)return!1;this.searchActiveIndex=(this.searchActiveIndex+1)%this.searchMatches.length,this.emitSearchChange();const match=this.searchMatches[this.searchActiveIndex];return await this.jumpToCell(match.row,match.col),!0}async searchPrevious(){if(!this.searchMatches.length)return!1;this.searchActiveIndex=(this.searchActiveIndex-1+this.searchMatches.length)%this.searchMatches.length,this.emitSearchChange();const match=this.searchMatches[this.searchActiveIndex];return await this.jumpToCell(match.row,match.col),!0}clearSearch(){this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emit("lr-search-change",{query:"",matchCount:0,matchCountExact:!0,activeIndex:-1})}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.searchActiveIndex})}render(){const label=viewerSemanticLabel(this,this.name||this.localize("csvViewerLabel"));let content;if(this.fetchState.kind==="loaded"){const rows=this.fetchState.rows;if(!rows.length)content=html`<p class="empty-note">${this.localize("noData")}</p>`;else{const header=this.hasHeaderRow?rows[0]:void 0,body=this.
|
|
22
|
+
</div>`}async jumpToCell(rawRow,col){const loadedState=this.fetchState;if(loadedState.kind!=="loaded")return!1;const{rows}=loadedState;if(rawRow<1||rawRow>rows.length||col<0||col>=columns(rows))return!1;const bodyIndex=rawRow-1-headerOffset(this.hasHeaderRow);if(bodyIndex<0){const target=this.renderRoot.querySelector('[part="header-row"]')?.querySelectorAll('[part~="cell"]')[col];return target?.scrollIntoView({behavior:prefersReducedMotion(this.ownerDocument.defaultView)?"auto":"smooth",block:"nearest",inline:"nearest"}),!!target}return this.activeRowKey=bodyIndex,await this.updateComplete,await this.scrollColumnIntoView(col),this.fetchState===loadedState}async applyAnchor(anchor){if(anchor.kind!=="cell-range"||anchor.sheet)return!1;const parsed=parseCellRange(anchor.range);return parsed?this.jumpToCell(parsed.startRow+1,parsed.startCol):!1}async scrollColumnIntoView(col){const list=this.renderRoot.querySelector("lr-virtual-list");if(list?.updateComplete&&await list.updateComplete,!await this.waitForOwnerAnimationFrame())return;list?.shadowRoot?.querySelector('[part="row"][aria-current="true"]')?.querySelectorAll('[part~="cell"]')[col]?.scrollIntoView({behavior:prefersReducedMotion(this.ownerDocument.defaultView)?"auto":"smooth",block:"nearest",inline:"nearest"})}async search(query){this.searchQuery=query,this.lastSearchLocale=this.effectiveLocale;const boundedQuery=boundedViewerSearchQuery(query,this.effectiveLocale),trimmed=boundedQuery.needle,matches=[];let matchCountExact=boundedQuery.accepted;if(boundedQuery.accepted&&trimmed&&this.fetchState.kind==="loaded"){const budget=new ViewerSearchWorkBudget,{rows}=this.fetchState;searchRows:for(let r=0;r<rows.length;r++){const row=rows[r];for(let c=0;c<row.length;c++){if(budget.includes(cell(row[c]),trimmed,this.effectiveLocale)){if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1;break searchRows}matches.push({row:r+1,col:c})}if(!budget.complete){matchCountExact=!1;break searchRows}}}}return this.searchMatches=matches,this.searchMatchCountExact=matchCountExact,this.searchActiveIndex=matches.length>0?0:-1,this.emitSearchChange(),this.searchActiveIndex>=0&&await this.jumpToCell(matches[0].row,matches[0].col),matches.length}async searchNext(){if(!this.searchMatches.length)return!1;this.searchActiveIndex=(this.searchActiveIndex+1)%this.searchMatches.length,this.emitSearchChange();const match=this.searchMatches[this.searchActiveIndex];return await this.jumpToCell(match.row,match.col),!0}async searchPrevious(){if(!this.searchMatches.length)return!1;this.searchActiveIndex=(this.searchActiveIndex-1+this.searchMatches.length)%this.searchMatches.length,this.emitSearchChange();const match=this.searchMatches[this.searchActiveIndex];return await this.jumpToCell(match.row,match.col),!0}clearSearch(){this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emit("lr-search-change",{query:"",matchCount:0,matchCountExact:!0,activeIndex:-1})}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.searchActiveIndex})}virtualListInputs(rows,hasHeaderRow){const cached=this.virtualListInputsCache;if(cached&&cached.rows===rows&&cached.hasHeaderRow===hasHeaderRow)return cached;const body=hasHeaderRow?rows.slice(1):rows,count=columns(rows),next={rows,hasHeaderRow,body,renderItem:(row,index)=>this.renderRow(row,count,"data-row",index+1+headerOffset(hasHeaderRow))};return this.virtualListInputsCache=next,next}render(){const label=viewerSemanticLabel(this,this.name||this.localize("csvViewerLabel"));let content;if(this.fetchState.kind==="loaded"){const rows=this.fetchState.rows;if(!rows.length)content=html`<p class="empty-note">${this.localize("noData")}</p>`;else{const header=this.hasHeaderRow?rows[0]:void 0,count=columns(rows),{body,renderItem}=this.virtualListInputs(rows,this.hasHeaderRow),tableLabel=hostAriaLabel(this)??(this.name||this.localize("csvViewerLabel"));content=html`<div
|
|
23
23
|
part="sheet"
|
|
24
24
|
role="table"
|
|
25
25
|
aria-label=${tableLabel}
|
|
@@ -30,8 +30,8 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
30
30
|
part="rows"
|
|
31
31
|
exportparts="data-row:data-row, cell:cell, cell-highlight:cell-highlight, cell-highlight-action:cell-highlight-action"
|
|
32
32
|
.items=${body}
|
|
33
|
-
.renderItem=${
|
|
34
|
-
.keyFunction=${
|
|
33
|
+
.renderItem=${renderItem}
|
|
34
|
+
.keyFunction=${indexKeyFunction}
|
|
35
35
|
.activeItemId=${this.activeRowKey}
|
|
36
36
|
item-role="row"
|
|
37
37
|
row-index-offset=${this.hasHeaderRow?"1":"0"}
|
|
@@ -113,4 +113,4 @@ searchNext():Promise<boolean>;
|
|
|
113
113
|
searchPrevious():Promise<boolean>;
|
|
114
114
|
/** Clears the query, matches, and active index, and resets `lr-search-change` to a
|
|
115
115
|
* 0-match/no-active-index state. */
|
|
116
|
-
clearSearch():void;private emitSearchChange;private stopInternalEvent;private renderBody;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-dataset-viewer':LyraDatasetViewer;}}export{};
|
|
116
|
+
clearSearch():void;private emitSearchChange;private stopInternalEvent;private readonly virtualListKeyFunction;private renderBody;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-dataset-viewer':LyraDatasetViewer;}}export{};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{loadPapaParseCached}from"../../../internal/papaparse-loader.js";import{parseCellRange}from"../../../internal/cell-range.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{styles}from"./dataset-viewer.styles.js";import{parseDelimitedRecords}from"../../../internal/delimited-data.js";import{LatestTask}from"../../../internal/latest-task.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{literalSetConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_cellHighlightWithLabel,LYRA_DEFAULT_datasetViewerCaption,LYRA_DEFAULT_datasetViewerCaptionNamed,LYRA_DEFAULT_datasetViewerEmpty,LYRA_DEFAULT_datasetViewerMissingParser,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDataset,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings.generated.js";const MAX_SEARCH_MATCHES=1e3,DATASET_VIEWER_SCROLL_MODE=literalSetConverter(["self","page"],"self");class LyraDatasetViewerBase extends LyraElement{}class LyraDatasetViewer extends DocumentAnchorTarget(LyraDatasetViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this._scrollMode="self",this.anchorKinds=["cell-range"],this.fetchState={kind:"idle"},this.activeRowKey="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.loadTask=new LatestTask,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.pendingAnimationFrames=new Set,this.renderRow=(row,index,fields)=>{const rawRow=index+2,rowHighlights=this.cellHighlightsForRow(rawRow);return html`<div part="data-row" role="presentation">
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{loadPapaParseCached}from"../../../internal/papaparse-loader.js";import{parseCellRange}from"../../../internal/cell-range.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{styles}from"./dataset-viewer.styles.js";import{parseDelimitedRecords}from"../../../internal/delimited-data.js";import{LatestTask}from"../../../internal/latest-task.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{literalSetConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_cellHighlightWithLabel,LYRA_DEFAULT_datasetViewerCaption,LYRA_DEFAULT_datasetViewerCaptionNamed,LYRA_DEFAULT_datasetViewerEmpty,LYRA_DEFAULT_datasetViewerMissingParser,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDataset,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings.generated.js";const MAX_SEARCH_MATCHES=1e3,DATASET_VIEWER_SCROLL_MODE=literalSetConverter(["self","page"],"self");class LyraDatasetViewerBase extends LyraElement{}class LyraDatasetViewer extends DocumentAnchorTarget(LyraDatasetViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this._scrollMode="self",this.anchorKinds=["cell-range"],this.fetchState={kind:"idle"},this.activeRowKey="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.loadTask=new LatestTask,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.pendingAnimationFrames=new Set,this.renderRow=(row,index,fields)=>{const rawRow=index+2,rowHighlights=this.cellHighlightsForRow(rawRow);return html`<div part="data-row" role="presentation">
|
|
2
2
|
${fields.map((field,col)=>this.renderCell(row[field]??"",col,rowHighlights))}
|
|
3
|
-
</div>`},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,cellHighlightWithLabel:LYRA_DEFAULT_cellHighlightWithLabel,datasetViewerCaption:LYRA_DEFAULT_datasetViewerCaption,datasetViewerCaptionNamed:LYRA_DEFAULT_datasetViewerCaptionNamed,datasetViewerEmpty:LYRA_DEFAULT_datasetViewerEmpty,datasetViewerMissingParser:LYRA_DEFAULT_datasetViewerMissingParser,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDataset:LYRA_DEFAULT_documentPreviewTypeDataset,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}get scrollMode(){return this._scrollMode}set scrollMode(next){const normalized=DATASET_VIEWER_SCROLL_MODE.normalizeReflected(this,"scroll-mode",next),previous=this._scrollMode;previous!==normalized&&(this._scrollMode=normalized,this.requestUpdate("scrollMode",previous))}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.loadTask.next(),this.cancelPendingAnimationFrames(),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelPendingAnimationFrames(),this.announcements.adopted()}waitForOwnerAnimationFrame(){const owner=this.ownerDocument.defaultView;return!owner||!this.isConnected?Promise.resolve(!1):new Promise(resolve=>{const pending={owner,resolve};this.pendingAnimationFrames.add(pending),pending.handle=owner.requestAnimationFrame(()=>{this.pendingAnimationFrames.delete(pending)&&resolve(this.isConnected&&this.ownerDocument.defaultView===owner)})})}cancelPendingAnimationFrames(){const pendingFrames=[...this.pendingAnimationFrames];this.pendingAnimationFrames.clear();for(const pending of pendingFrames)pending.handle!==void 0&&pending.owner.cancelAnimationFrame(pending.handle),pending.resolve(!1)}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.activeRowKey="")}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=!!this.searchQuery;this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}async load(){this.lastLoadSrc=this.src;const generation=this.loadTask.next(),signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const source=await readResponseText(response);if(!this.isConnected||!this.loadTask.isCurrent(generation))return;const parsed=await this.parse(source,generation);if(parsed===void 0)return;if(this.isConnected&&this.loadTask.isCurrent(generation)){const{table}=parsed;this.fetchState=table?{kind:"loaded",table}:{kind:"empty"},table&&this.searchQuery&&await this.search(this.searchQuery),parsed.errors.length&&this.isConnected&&this.loadTask.isCurrent(generation)&&this.emit("lr-render-error",{error:parsed.errors})}}catch(error){if(isAbortError(error)||!this.isConnected||!this.loadTask.isCurrent(generation))return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}async parse(text,generation){const papa=await loadPapaParseCached();if(!this.isConnected||!this.loadTask.isCurrent(generation))return;if(!papa)throw new LyraUserFacingError(this.localize("datasetViewerMissingParser"));const result=parseDelimitedRecords(papa,text);return!result.fields.length||!result.rows.length?{table:null,errors:result.errors}:{table:{fields:result.fields,rows:result.rows},errors:result.errors}}cellHighlightsForRow(rawRow){const seen=new Set;return this.highlights.filter(highlight=>seen.has(highlight.id)?!1:(seen.add(highlight.id),!0)).flatMap(highlight=>{if(highlight.anchor.kind!=="cell-range"||highlight.anchor.sheet)return[];const parsed=parseCellRange(highlight.anchor.range);return parsed?rawRow-1>=parsed.startRow&&rawRow-1<=parsed.endRow?[{highlight,parsed}]:[]:[]})}renderCell(value,colIndex,rowHighlights,role="cell"){const colHighlights=rowHighlights.filter(entry=>colIndex>=entry.parsed.startCol&&colIndex<=entry.parsed.endCol),part=role==="columnheader"?"header-cell":"cell";if(!colHighlights.length)return html`<div part=${part} role=${role}>${value}</div>`;const active=colHighlights.find(entry=>entry.highlight.id===this.activeHighlightId),primary=active??colHighlights[0],accessibleLabel=primary.highlight.label?this.localize("cellHighlightWithLabel",void 0,{value,label:primary.highlight.label}):this.localize("highlightWithLabel",void 0,{label:value});return html`<div
|
|
3
|
+
</div>`},this.stopInternalEvent=event=>{event.stopPropagation()},this.virtualListKeyFunction=(_item,index)=>index}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,cellHighlightWithLabel:LYRA_DEFAULT_cellHighlightWithLabel,datasetViewerCaption:LYRA_DEFAULT_datasetViewerCaption,datasetViewerCaptionNamed:LYRA_DEFAULT_datasetViewerCaptionNamed,datasetViewerEmpty:LYRA_DEFAULT_datasetViewerEmpty,datasetViewerMissingParser:LYRA_DEFAULT_datasetViewerMissingParser,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDataset:LYRA_DEFAULT_documentPreviewTypeDataset,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}get scrollMode(){return this._scrollMode}set scrollMode(next){const normalized=DATASET_VIEWER_SCROLL_MODE.normalizeReflected(this,"scroll-mode",next),previous=this._scrollMode;previous!==normalized&&(this._scrollMode=normalized,this.requestUpdate("scrollMode",previous))}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.loadTask.next(),this.cancelPendingAnimationFrames(),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelPendingAnimationFrames(),this.announcements.adopted()}waitForOwnerAnimationFrame(){const owner=this.ownerDocument.defaultView;return!owner||!this.isConnected?Promise.resolve(!1):new Promise(resolve=>{const pending={owner,resolve};this.pendingAnimationFrames.add(pending),pending.handle=owner.requestAnimationFrame(()=>{this.pendingAnimationFrames.delete(pending)&&resolve(this.isConnected&&this.ownerDocument.defaultView===owner)})})}cancelPendingAnimationFrames(){const pendingFrames=[...this.pendingAnimationFrames];this.pendingAnimationFrames.clear();for(const pending of pendingFrames)pending.handle!==void 0&&pending.owner.cancelAnimationFrame(pending.handle),pending.resolve(!1)}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.activeRowKey="")}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=!!this.searchQuery;this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}async load(){this.lastLoadSrc=this.src;const generation=this.loadTask.next(),signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const source=await readResponseText(response);if(!this.isConnected||!this.loadTask.isCurrent(generation))return;const parsed=await this.parse(source,generation);if(parsed===void 0)return;if(this.isConnected&&this.loadTask.isCurrent(generation)){const{table}=parsed;this.fetchState=table?{kind:"loaded",table}:{kind:"empty"},table&&this.searchQuery&&await this.search(this.searchQuery),parsed.errors.length&&this.isConnected&&this.loadTask.isCurrent(generation)&&this.emit("lr-render-error",{error:parsed.errors})}}catch(error){if(isAbortError(error)||!this.isConnected||!this.loadTask.isCurrent(generation))return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}async parse(text,generation){const papa=await loadPapaParseCached();if(!this.isConnected||!this.loadTask.isCurrent(generation))return;if(!papa)throw new LyraUserFacingError(this.localize("datasetViewerMissingParser"));const result=parseDelimitedRecords(papa,text);return!result.fields.length||!result.rows.length?{table:null,errors:result.errors}:{table:{fields:result.fields,rows:result.rows},errors:result.errors}}cellHighlightsForRow(rawRow){const seen=new Set;return this.highlights.filter(highlight=>seen.has(highlight.id)?!1:(seen.add(highlight.id),!0)).flatMap(highlight=>{if(highlight.anchor.kind!=="cell-range"||highlight.anchor.sheet)return[];const parsed=parseCellRange(highlight.anchor.range);return parsed?rawRow-1>=parsed.startRow&&rawRow-1<=parsed.endRow?[{highlight,parsed}]:[]:[]})}renderCell(value,colIndex,rowHighlights,role="cell"){const colHighlights=rowHighlights.filter(entry=>colIndex>=entry.parsed.startCol&&colIndex<=entry.parsed.endCol),part=role==="columnheader"?"header-cell":"cell";if(!colHighlights.length)return html`<div part=${part} role=${role}>${value}</div>`;const active=colHighlights.find(entry=>entry.highlight.id===this.activeHighlightId),primary=active??colHighlights[0],accessibleLabel=primary.highlight.label?this.localize("cellHighlightWithLabel",void 0,{value,label:primary.highlight.label}):this.localize("highlightWithLabel",void 0,{label:value});return html`<div
|
|
4
4
|
part="${part} cell-highlight"
|
|
5
5
|
role=${role}
|
|
6
6
|
?data-active=${!!active}
|
|
@@ -27,9 +27,9 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
27
27
|
</div>
|
|
28
28
|
<lr-virtual-list
|
|
29
29
|
exportparts="data-row:data-row, cell:cell, cell-highlight:cell-highlight, cell-highlight-action:cell-highlight-action"
|
|
30
|
-
.items=${rows}
|
|
30
|
+
.items=${guard([rows],()=>rows)}
|
|
31
31
|
.renderItem=${(row,index)=>this.renderRow(row,index,fields)}
|
|
32
|
-
.keyFunction=${
|
|
32
|
+
.keyFunction=${this.virtualListKeyFunction}
|
|
33
33
|
.activeItemId=${this.activeRowKey}
|
|
34
34
|
item-role="row"
|
|
35
35
|
row-index-offset="1"
|
|
@@ -115,6 +115,11 @@ languages?:Readonly<Record<string,ShikiLanguageInput>>;
|
|
|
115
115
|
/** Whether scrolling one `view="side-by-side"` pane proportionally scrolls the other. See the
|
|
116
116
|
* class doc's "Synchronized anchors" section. */
|
|
117
117
|
syncScroll:boolean;
|
|
118
|
+
/** A CSS length (e.g. `"30rem"`); once set, overrides `--lr-document-compare-pane-max-height` --
|
|
119
|
+
* the max block size of each `view="side-by-side"` pane -- declaratively, the same `max-height`
|
|
120
|
+
* attribute every other content-viewer sibling exposes, rather than requiring a consumer to set
|
|
121
|
+
* the differently-named CSS custom property inline. Invalid values are ignored. */
|
|
122
|
+
maxHeight:string;
|
|
118
123
|
/** A shared scroll-to-anchor target forwarded to both `view="side-by-side"` panes'
|
|
119
124
|
* `scrollToAnchor()`. `hasChanged: () => true` so re-assigning the same value (e.g. re-clicking
|
|
120
125
|
* the same source reference) still re-fires, mirroring `<lr-document-viewer>`'s identical
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{styles}from"./document-compare.styles.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentCompareLabel,LYRA_DEFAULT_documentCompareNewVersion,LYRA_DEFAULT_documentCompareNoVersion,LYRA_DEFAULT_documentCompareOldVersion,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const DOCUMENT_COMPARE_VIEW=literalSetConverter(["diff","side-by-side"],"diff"),DOCUMENT_COMPARE_DIFF_LAYOUT=literalSetConverter(["unified","split"],"unified"),DOCUMENT_COMPARE_VERSION_FIELDS=["id","name","mimeType","uri","version","text","highlights"];function projectDocumentCompareVersion(value){try{if(value===null||typeof value!="object"||Array.isArray(value))return;const descriptors=new Map;for(const field of DOCUMENT_COMPARE_VERSION_FIELDS)descriptors.set(field,getOwnDataDescriptor(value,field));const fieldValue=field=>{const descriptor=descriptors.get(field);if(!(descriptor===void 0||descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR))return descriptor.value},idDescriptor=descriptors.get("id"),nameDescriptor=descriptors.get("name");if(idDescriptor===void 0||idDescriptor===MISSING_OWN_DATA_DESCRIPTOR||idDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||nameDescriptor===void 0||nameDescriptor===MISSING_OWN_DATA_DESCRIPTOR||nameDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR)return;const id=fieldValue("id"),name=fieldValue("name");if(typeof id!="string"||typeof name!="string")return;const mimeType=fieldValue("mimeType"),uri=fieldValue("uri"),version=fieldValue("version"),text=fieldValue("text"),highlights=fieldValue("highlights");return Object.freeze({id,name,...typeof mimeType=="string"?{mimeType}:{},...typeof uri=="string"?{uri}:{},...typeof version=="string"?{version}:{},...typeof text=="string"?{text}:{},...highlights===void 0?{}:{highlights:snapshotLyraHighlights(highlights)}})}catch{return}}function versionSourceIdentity(version){return version?JSON.stringify([version.id??"",version.uri??"",version.version??"",version.mimeType??"",version.name??""]):""}class LyraDocumentCompare extends LyraElement{constructor(){super(...arguments),this._view="diff",this._diffLayout="unified",this.copyable=!1,this._language="",this.syncScroll=!0,this.anchor=null,this.suppressSync=!1,this.onPaneScroll=source=>()=>{if(!this.syncScroll||this.suppressSync)return;const from=source==="old"?this.paneOldEl:this.paneNewEl,to=source==="old"?this.paneNewEl:this.paneOldEl;if(!from||!to)return;const fromMax=from.scrollHeight-from.clientHeight,toMax=to.scrollHeight-to.clientHeight;if(fromMax<=0)return;const fraction=from.scrollTop/fromMax;this.suppressSync=!0,to.scrollTop=fraction*toMax,this.scheduleSyncRelease()}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentCompareLabel:LYRA_DEFAULT_documentCompareLabel,documentCompareNewVersion:LYRA_DEFAULT_documentCompareNewVersion,documentCompareNoVersion:LYRA_DEFAULT_documentCompareNoVersion,documentCompareOldVersion:LYRA_DEFAULT_documentCompareOldVersion,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get view(){return this._view}set view(next){const normalized=DOCUMENT_COMPARE_VIEW.normalizeReflected(this,"view",next),old=this._view;old!==normalized&&(this._view=normalized,this.requestUpdate("view",old))}get oldVersion(){return this._oldVersion}set oldVersion(value){const previous=this._oldVersion;this._oldVersion=projectDocumentCompareVersion(value),this.requestUpdate("oldVersion",previous)}get newVersion(){return this._newVersion}set newVersion(value){const previous=this._newVersion;this._newVersion=projectDocumentCompareVersion(value),this.requestUpdate("newVersion",previous)}get diffLayout(){return this._diffLayout}set diffLayout(next){const normalized=DOCUMENT_COMPARE_DIFF_LAYOUT.normalizeReflected(this,"diff-layout",next),old=this._diffLayout;old!==normalized&&(this._diffLayout=normalized,this.requestUpdate("diffLayout",old))}get language(){return this._language}set language(value){const normalized=typeof value=="string"?value:"",previous=this._language;previous!==normalized&&(this._language=normalized,this.requestUpdate("language",previous))}disconnectedCallback(){this.cancelSyncRelease(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelSyncRelease()}cancelSyncRelease(){this.syncReleaseFrame!==void 0&&this.syncReleaseView?.cancelAnimationFrame(this.syncReleaseFrame),this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1}scheduleSyncRelease(){const view=this.ownerDocument.defaultView;if(!view){this.suppressSync=!1;return}const frame=view.requestAnimationFrame(()=>{this.syncReleaseView!==view||this.syncReleaseFrame!==frame||(this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1)});this.syncReleaseView=view,this.syncReleaseFrame=frame}updated(changed){super.updated(changed);const anchor=this.anchor,sourceChanged=property2=>changed.has(property2)&&versionSourceIdentity(changed.get(property2))!==versionSourceIdentity(this[property2]),oldSourceChanged=sourceChanged("oldVersion"),newSourceChanged=sourceChanged("newVersion");if(anchor!=null){(changed.has("anchor")||this.view==="side-by-side"&&(changed.has("view")||changed.has("oldVersion")||changed.has("newVersion")))&&(this.previewOldEl?.scrollToAnchor(anchor),this.previewNewEl?.scrollToAnchor(anchor));return}this.view!=="side-by-side"||!oldSourceChanged&&!newSourceChanged||(this.cancelSyncRelease(),(this.syncScroll||oldSourceChanged)&&this.paneOldEl&&(this.paneOldEl.scrollTop=0),(this.syncScroll||newSourceChanged)&&this.paneNewEl&&(this.paneNewEl.scrollTop=0))}onHighlightActivate(side,event){const{highlightId}=event.detail,otherPreview=side==="old"?this.previewNewEl:this.previewOldEl;otherPreview?.highlights.some(highlight=>highlight.id===highlightId)&&otherPreview?.scrollToAnchor(highlightId)}versionLabel(version,fallbackKey){return version?.name||version?.version||this.localize(fallbackKey)}renderDiff(){return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{literalSetConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{styles}from"./document-compare.styles.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentCompareLabel,LYRA_DEFAULT_documentCompareNewVersion,LYRA_DEFAULT_documentCompareNoVersion,LYRA_DEFAULT_documentCompareOldVersion,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const DOCUMENT_COMPARE_VIEW=literalSetConverter(["diff","side-by-side"],"diff"),DOCUMENT_COMPARE_DIFF_LAYOUT=literalSetConverter(["unified","split"],"unified"),DOCUMENT_COMPARE_VERSION_FIELDS=["id","name","mimeType","uri","version","text","highlights"];function projectDocumentCompareVersion(value){try{if(value===null||typeof value!="object"||Array.isArray(value))return;const descriptors=new Map;for(const field of DOCUMENT_COMPARE_VERSION_FIELDS)descriptors.set(field,getOwnDataDescriptor(value,field));const fieldValue=field=>{const descriptor=descriptors.get(field);if(!(descriptor===void 0||descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR))return descriptor.value},idDescriptor=descriptors.get("id"),nameDescriptor=descriptors.get("name");if(idDescriptor===void 0||idDescriptor===MISSING_OWN_DATA_DESCRIPTOR||idDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||nameDescriptor===void 0||nameDescriptor===MISSING_OWN_DATA_DESCRIPTOR||nameDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR)return;const id=fieldValue("id"),name=fieldValue("name");if(typeof id!="string"||typeof name!="string")return;const mimeType=fieldValue("mimeType"),uri=fieldValue("uri"),version=fieldValue("version"),text=fieldValue("text"),highlights=fieldValue("highlights");return Object.freeze({id,name,...typeof mimeType=="string"?{mimeType}:{},...typeof uri=="string"?{uri}:{},...typeof version=="string"?{version}:{},...typeof text=="string"?{text}:{},...highlights===void 0?{}:{highlights:snapshotLyraHighlights(highlights)}})}catch{return}}function versionSourceIdentity(version){return version?JSON.stringify([version.id??"",version.uri??"",version.version??"",version.mimeType??"",version.name??""]):""}class LyraDocumentCompare extends LyraElement{constructor(){super(...arguments),this._view="diff",this._diffLayout="unified",this.copyable=!1,this._language="",this.syncScroll=!0,this.maxHeight="",this.anchor=null,this.suppressSync=!1,this.onPaneScroll=source=>()=>{if(!this.syncScroll||this.suppressSync)return;const from=source==="old"?this.paneOldEl:this.paneNewEl,to=source==="old"?this.paneNewEl:this.paneOldEl;if(!from||!to)return;const fromMax=from.scrollHeight-from.clientHeight,toMax=to.scrollHeight-to.clientHeight;if(fromMax<=0)return;const fraction=from.scrollTop/fromMax;this.suppressSync=!0,to.scrollTop=fraction*toMax,this.scheduleSyncRelease()}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentCompareLabel:LYRA_DEFAULT_documentCompareLabel,documentCompareNewVersion:LYRA_DEFAULT_documentCompareNewVersion,documentCompareNoVersion:LYRA_DEFAULT_documentCompareNoVersion,documentCompareOldVersion:LYRA_DEFAULT_documentCompareOldVersion,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get view(){return this._view}set view(next){const normalized=DOCUMENT_COMPARE_VIEW.normalizeReflected(this,"view",next),old=this._view;old!==normalized&&(this._view=normalized,this.requestUpdate("view",old))}get oldVersion(){return this._oldVersion}set oldVersion(value){const previous=this._oldVersion;this._oldVersion=projectDocumentCompareVersion(value),this.requestUpdate("oldVersion",previous)}get newVersion(){return this._newVersion}set newVersion(value){const previous=this._newVersion;this._newVersion=projectDocumentCompareVersion(value),this.requestUpdate("newVersion",previous)}get diffLayout(){return this._diffLayout}set diffLayout(next){const normalized=DOCUMENT_COMPARE_DIFF_LAYOUT.normalizeReflected(this,"diff-layout",next),old=this._diffLayout;old!==normalized&&(this._diffLayout=normalized,this.requestUpdate("diffLayout",old))}get language(){return this._language}set language(value){const normalized=typeof value=="string"?value:"",previous=this._language;previous!==normalized&&(this._language=normalized,this.requestUpdate("language",previous))}disconnectedCallback(){this.cancelSyncRelease(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelSyncRelease()}cancelSyncRelease(){this.syncReleaseFrame!==void 0&&this.syncReleaseView?.cancelAnimationFrame(this.syncReleaseFrame),this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1}scheduleSyncRelease(){const view=this.ownerDocument.defaultView;if(!view){this.suppressSync=!1;return}const frame=view.requestAnimationFrame(()=>{this.syncReleaseView!==view||this.syncReleaseFrame!==frame||(this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1)});this.syncReleaseView=view,this.syncReleaseFrame=frame}updated(changed){super.updated(changed);const anchor=this.anchor,sourceChanged=property2=>changed.has(property2)&&versionSourceIdentity(changed.get(property2))!==versionSourceIdentity(this[property2]),oldSourceChanged=sourceChanged("oldVersion"),newSourceChanged=sourceChanged("newVersion");if(anchor!=null){(changed.has("anchor")||this.view==="side-by-side"&&(changed.has("view")||changed.has("oldVersion")||changed.has("newVersion")))&&(this.previewOldEl?.scrollToAnchor(anchor),this.previewNewEl?.scrollToAnchor(anchor));return}this.view!=="side-by-side"||!oldSourceChanged&&!newSourceChanged||(this.cancelSyncRelease(),(this.syncScroll||oldSourceChanged)&&this.paneOldEl&&(this.paneOldEl.scrollTop=0),(this.syncScroll||newSourceChanged)&&this.paneNewEl&&(this.paneNewEl.scrollTop=0))}onHighlightActivate(side,event){const{highlightId}=event.detail,otherPreview=side==="old"?this.previewNewEl:this.previewOldEl;otherPreview?.highlights.some(highlight=>highlight.id===highlightId)&&otherPreview?.scrollToAnchor(highlightId)}versionLabel(version,fallbackKey){return version?.name||version?.version||this.localize(fallbackKey)}renderDiff(){return html`
|
|
2
2
|
<lr-diff-view
|
|
3
3
|
part="diff"
|
|
4
4
|
.oldText=${this.oldVersion?.text??""}
|
|
@@ -27,8 +27,13 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
27
27
|
${this.renderVersionPane(this.newVersion,"new")}
|
|
28
28
|
</div>
|
|
29
29
|
</div>
|
|
30
|
-
`}render(){return html`
|
|
31
|
-
<div
|
|
30
|
+
`}render(){const maxHeight=sanitizeCssLength(this.maxHeight);return html`
|
|
31
|
+
<div
|
|
32
|
+
part="base"
|
|
33
|
+
role=${viewerSemanticRole(this,"group")??nothing}
|
|
34
|
+
aria-label=${viewerSemanticLabel(this,this.localize("documentCompareLabel"))??nothing}
|
|
35
|
+
style=${maxHeight?styleMap({"--_lr-document-compare-pane-max-height-attr":maxHeight}):nothing}
|
|
36
|
+
>
|
|
32
37
|
${this.view==="side-by-side"?this.renderSideBySide():this.renderDiff()}
|
|
33
38
|
</div>
|
|
34
|
-
`}}__decorate([property({reflect:!0,converter:DOCUMENT_COMPARE_VIEW})],LyraDocumentCompare.prototype,"view",null),__decorate([property({attribute:!1})],LyraDocumentCompare.prototype,"oldVersion",null),__decorate([property({attribute:!1})],LyraDocumentCompare.prototype,"newVersion",null),__decorate([property({attribute:"diff-layout",reflect:!0,converter:DOCUMENT_COMPARE_DIFF_LAYOUT})],LyraDocumentCompare.prototype,"diffLayout",null),__decorate([property({type:Boolean})],LyraDocumentCompare.prototype,"copyable",void 0),__decorate([property()],LyraDocumentCompare.prototype,"language",null),__decorate([property({attribute:!1})],LyraDocumentCompare.prototype,"languages",void 0),__decorate([property({attribute:"sync-scroll",converter:trueDefaultBooleanConverter})],LyraDocumentCompare.prototype,"syncScroll",void 0),__decorate([property({attribute:!1,hasChanged:()=>!0})],LyraDocumentCompare.prototype,"anchor",void 0),__decorate([query('[part="pane-old"]')],LyraDocumentCompare.prototype,"paneOldEl",void 0),__decorate([query('[part="pane-new"]')],LyraDocumentCompare.prototype,"paneNewEl",void 0),__decorate([query('[part="pane-old"] lr-document-preview')],LyraDocumentCompare.prototype,"previewOldEl",void 0),__decorate([query('[part="pane-new"] lr-document-preview')],LyraDocumentCompare.prototype,"previewNewEl",void 0);export{LyraDocumentCompare};
|
|
39
|
+
`}}__decorate([property({reflect:!0,converter:DOCUMENT_COMPARE_VIEW})],LyraDocumentCompare.prototype,"view",null),__decorate([property({attribute:!1})],LyraDocumentCompare.prototype,"oldVersion",null),__decorate([property({attribute:!1})],LyraDocumentCompare.prototype,"newVersion",null),__decorate([property({attribute:"diff-layout",reflect:!0,converter:DOCUMENT_COMPARE_DIFF_LAYOUT})],LyraDocumentCompare.prototype,"diffLayout",null),__decorate([property({type:Boolean})],LyraDocumentCompare.prototype,"copyable",void 0),__decorate([property()],LyraDocumentCompare.prototype,"language",null),__decorate([property({attribute:!1})],LyraDocumentCompare.prototype,"languages",void 0),__decorate([property({attribute:"sync-scroll",converter:trueDefaultBooleanConverter})],LyraDocumentCompare.prototype,"syncScroll",void 0),__decorate([property({attribute:"max-height"})],LyraDocumentCompare.prototype,"maxHeight",void 0),__decorate([property({attribute:!1,hasChanged:()=>!0})],LyraDocumentCompare.prototype,"anchor",void 0),__decorate([query('[part="pane-old"]')],LyraDocumentCompare.prototype,"paneOldEl",void 0),__decorate([query('[part="pane-new"]')],LyraDocumentCompare.prototype,"paneNewEl",void 0),__decorate([query('[part="pane-old"] lr-document-preview')],LyraDocumentCompare.prototype,"previewOldEl",void 0),__decorate([query('[part="pane-new"] lr-document-preview')],LyraDocumentCompare.prototype,"previewNewEl",void 0);export{LyraDocumentCompare};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{css}from"lit";const styles=css`:host{contain-intrinsic-inline-size:var(--lr-size-20rem);--_lr-document-compare-pane-max-height:var(--lr-size-24rem);display:block;container-type:inline-size}[part=base]{gap:var(--lr-space-m);color:var(--lr-color-text);flex-direction:column;display:flex}[part=diff]{display:block}[part=panes]{gap:var(--lr-space-m);align-items:stretch;display:flex}[part=pane-old],[part=pane-new]{gap:var(--lr-space-xs);border:var(--lr-border-width-thin) solid var(--lr-color-border);border-radius:var(--lr-radius);min-inline-size:0;padding:var(--lr-space-m);max-block-size:var(--lr-document-compare-pane-max-height,var(--_lr-document-compare-pane-max-height));flex-direction:column;flex:1 1 0;display:flex;overflow:hidden auto}[part=pane-old]:focus-visible,[part=pane-new]:focus-visible{outline:var(--lr-focus-ring);outline-offset:calc(-1 * var(--lr-focus-ring-width))}[part=pane-old]:hover,[part=pane-new]:hover{border-color:var(--lr-color-border-strong)}[part=pane-header]{font-weight:var(--lr-font-weight-semibold);font-size:var(--lr-font-size-xs);color:var(--lr-color-text-quiet);text-transform:uppercase;letter-spacing:var(--lr-size-0-02em)}[part=pane-empty]{color:var(--lr-color-text-quiet);font-size:var(--lr-font-size-sm);margin:0}@container (inline-size<=639.98px){[part=panes]{flex-direction:column}}`;export{styles};
|
|
1
|
+
import{css}from"lit";const styles=css`:host{contain-intrinsic-inline-size:var(--lr-size-20rem);--_lr-document-compare-pane-max-height:var(--lr-size-24rem);display:block;container-type:inline-size}[part=base]{gap:var(--lr-space-m);color:var(--lr-color-text);flex-direction:column;display:flex}[part=diff]{display:block}[part=panes]{gap:var(--lr-space-m);align-items:stretch;display:flex}[part=pane-old],[part=pane-new]{gap:var(--lr-space-xs);border:var(--lr-border-width-thin) solid var(--lr-color-border);border-radius:var(--lr-radius);min-inline-size:0;padding:var(--lr-space-m);max-block-size:var(--_lr-document-compare-pane-max-height-attr,var(--lr-document-compare-pane-max-height,var(--_lr-document-compare-pane-max-height)));flex-direction:column;flex:1 1 0;display:flex;overflow:hidden auto}[part=pane-old]:focus-visible,[part=pane-new]:focus-visible{outline:var(--lr-focus-ring);outline-offset:calc(-1 * var(--lr-focus-ring-width))}[part=pane-old]:hover,[part=pane-new]:hover{border-color:var(--lr-color-border-strong)}[part=pane-header]{font-weight:var(--lr-font-weight-semibold);font-size:var(--lr-font-size-xs);color:var(--lr-color-text-quiet);text-transform:uppercase;letter-spacing:var(--lr-size-0-02em)}[part=pane-empty]{color:var(--lr-color-text-quiet);font-size:var(--lr-font-size-sm);margin:0}@container (inline-size<=639.98px){[part=panes]{flex-direction:column}[part=pane-old],[part=pane-new]{flex-basis:auto}}`;export{styles};
|
|
@@ -89,6 +89,9 @@ import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from
|
|
|
89
89
|
* @csspart highlight-actions - Non-overlapping actions used when multiple region highlights would
|
|
90
90
|
* otherwise create overlapping minimum hit areas (image format only).
|
|
91
91
|
* @csspart region-highlight-action - One action in the non-overlapping highlight action list.
|
|
92
|
+
* ArrowDown/ArrowUp (or ArrowLeft/ArrowRight under RTL) plus Home/End move focus across this
|
|
93
|
+
* list, matching `<lr-highlight-layer>`'s roving shortcut; every action keeps its own native
|
|
94
|
+
* tabindex, so Tab still steps through each one individually.
|
|
92
95
|
* @cssprop [--lr-document-preview-max-height=none] - Maximum body block size before the preview scrolls internally.
|
|
93
96
|
* @cssprop [--lr-document-preview-font=var(--lr-font-mono)] - Font used for plain-text previews.
|
|
94
97
|
* @cssprop [--lr-document-preview-download-link-hover-bg=color-mix(in oklab, var(--lr-color-brand), var(--lr-color-mix-partner) var(--lr-color-mix-hover))] - Hover background of the generic download link.
|
|
@@ -163,7 +166,12 @@ private renderSpinner;private renderError;private renderTextPreview;private rend
|
|
|
163
166
|
* (plus the highlight layer, which needs the same relatively-positioned sibling context either
|
|
164
167
|
* way) unwrapped, preserving pre-`zoomable` DOM exactly. Mirrors `<lr-svg-viewer>`'s identical
|
|
165
168
|
* helper. */
|
|
166
|
-
private renderZoomableWrapper;private projectRegionHighlights;private regionHighlights;private highlightActionLabel;private renderHighlightLayer;
|
|
169
|
+
private renderZoomableWrapper;private projectRegionHighlights;private regionHighlights;private highlightActionLabel;private renderHighlightLayer;
|
|
170
|
+
/** Moves focus among the `region-highlight-action` list to match `<lr-highlight-layer>`'s
|
|
171
|
+
* roving arrow-key shortcut. Every action button keeps its own native tabindex (this list
|
|
172
|
+
* isn't a roving-tabindex widget), so this only offers ArrowDown/ArrowUp/Home/End as a
|
|
173
|
+
* faster alternative to repeated Tab, direction-aware under RTL. */
|
|
174
|
+
private onHighlightActionKeyDown;private renderHighlightActions;
|
|
167
175
|
/** Scrolls a `region` highlight into view (image format only). See `<lr-svg-viewer>`'s
|
|
168
176
|
* identical method for the id/anchor-reference resolution and no-retry-loop rationale. */
|
|
169
177
|
scrollToAnchor(target:LyraAnchor|string):Promise<boolean>;private renderDownloadFallback;
|
|
@@ -57,7 +57,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
57
57
|
style=${styleMap({left:`${h.anchor.rect.x}%`,top:`${h.anchor.rect.y}%`,width:`${h.anchor.rect.width}%`,height:`${h.anchor.rect.height}%`})}
|
|
58
58
|
></div>
|
|
59
59
|
`)}
|
|
60
|
-
</div>`:nothing}renderHighlightActions(regionHighlights){return regionHighlights.length<2?nothing:html`<div part="highlight-actions">
|
|
60
|
+
</div>`:nothing}onHighlightActionKeyDown(e,index,total){const rtl=this.effectiveDirection==="rtl",forward=e.key==="ArrowDown"||(rtl?e.key==="ArrowLeft":e.key==="ArrowRight"),backward=e.key==="ArrowUp"||(rtl?e.key==="ArrowRight":e.key==="ArrowLeft");let nextIndex;forward?nextIndex=Math.min(total-1,index+1):backward?nextIndex=Math.max(0,index-1):e.key==="Home"?nextIndex=0:e.key==="End"&&(nextIndex=total-1),!(nextIndex===void 0||nextIndex===index)&&(e.preventDefault(),this.renderRoot.querySelectorAll('[part="region-highlight-action"]')[nextIndex]?.focus())}renderHighlightActions(regionHighlights){return regionHighlights.length<2?nothing:html`<div part="highlight-actions">
|
|
61
61
|
${regionHighlights.map((highlight,index)=>{const label=this.highlightActionLabel(highlight,index,regionHighlights.length);return html`
|
|
62
62
|
<button
|
|
63
63
|
part="region-highlight-action"
|
|
@@ -65,6 +65,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
65
65
|
data-highlight-id=${highlight.id}
|
|
66
66
|
aria-label=${label}
|
|
67
67
|
@click=${()=>this.emit("lr-highlight-activate",{highlightId:highlight.id})}
|
|
68
|
+
@keydown=${e=>this.onHighlightActionKeyDown(e,index,regionHighlights.length)}
|
|
68
69
|
>
|
|
69
70
|
${highlight.label||label}
|
|
70
71
|
</button>
|
|
@@ -122,6 +122,11 @@ src:string;
|
|
|
122
122
|
get notebook():NotebookDoc|string|undefined;set notebook(value:NotebookDoc|string|undefined);private _notebook?;
|
|
123
123
|
/** Readonly discriminated snapshot of the effective source authority. */
|
|
124
124
|
get source():LyraNotebookViewerSource;
|
|
125
|
+
/** Intentionally inert -- `source` is always derived live from `src`/`notebook`. A getter with
|
|
126
|
+
* no setter throws (in strict-mode module code, which every consumer runs) the moment
|
|
127
|
+
* anything assigns to it, including a stray `.source=${x}` template binding; this no-op keeps
|
|
128
|
+
* that assignment harmless instead of throwing from inside framework internals. */
|
|
129
|
+
set source(_value:LyraNotebookViewerSource);
|
|
125
130
|
/** Display name used as the viewer's accessible label, and matched against a `fragment` anchor's
|
|
126
131
|
* cell id. */
|
|
127
132
|
name:string;
|