@aceshooting/lyra-ui 30.9.0 → 31.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +361 -335
- package/dist/ai/adapters/ag-ui.js +1 -1
- package/dist/autoloader-cdn.js +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/budget-meter/budget-meter.class.d.ts +12 -1
- package/dist/components/agent-tools/budget-meter/budget-meter.class.js +4 -4
- package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
- package/dist/components/charts/chart/box-plot.class.js +2 -2
- package/dist/components/charts/chart/chart-sync.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +1 -1
- package/dist/components/charts/chart/chart.class.js +4 -4
- package/dist/components/charts/chart/lite-chart-axis-layout.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +2 -2
- package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +26 -11
- package/dist/components/conversation/chat-composer/chat-composer.class.js +11 -9
- package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
- package/dist/components/conversation/chat-message/chat-message.class.d.ts +27 -3
- package/dist/components/conversation/chat-message/chat-message.class.js +14 -12
- package/dist/components/conversation/chat-message/chat-message.styles.js +1 -1
- package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +29 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +2 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +1 -1
- package/dist/components/conversation/code-block/code-block-shared.js +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.d.ts +10 -0
- package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
- package/dist/components/conversation/markdown/markdown-shared.js +3 -3
- package/dist/components/conversation/markdown/markdown.class.d.ts +10 -0
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-feedback/message-feedback.class.d.ts +11 -3
- package/dist/components/conversation/message-feedback/message-feedback.class.js +12 -6
- package/dist/components/conversation/message-feedback/message-feedback.styles.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +8 -4
- package/dist/components/conversation/prompt-input/prompt-input.class.js +3 -2
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +4 -0
- package/dist/components/conversation/streaming-text/streaming-text-base.class.js +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
- package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +17 -3
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +3 -3
- package/dist/components/conversation/suggestion-chips/suggestion-chips.d.ts +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.js +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.d.ts +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.js +3 -3
- package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.d.ts +10 -10
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/document-library/document-library-cursor.js +1 -0
- package/dist/components/data/document-library/document-library-types.d.ts +20 -0
- package/dist/components/data/document-library/document-library.class.d.ts +37 -26
- package/dist/components/data/document-library/document-library.class.js +20 -11
- package/dist/components/data/document-library/document-library.styles.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +2 -2
- package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/pagination/pagination.class.js +1 -1
- package/dist/components/data/table/table.class.d.ts +31 -2
- package/dist/components/data/table/table.class.js +3 -3
- package/dist/components/data/table/table.styles.js +1 -1
- package/dist/components/data/timeline/timeline-cluster.js +1 -1
- package/dist/components/data/timeline/timeline-item.class.d.ts +10 -3
- package/dist/components/data/timeline/timeline-item.class.js +16 -12
- package/dist/components/data/timeline/timeline-item.styles.js +1 -1
- package/dist/components/data/timeline/timeline.class.d.ts +14 -2
- package/dist/components/data/timeline/timeline.class.js +9 -5
- package/dist/components/data/tree/tree-item.class.js +1 -1
- package/dist/components/data/tree/tree.class.d.ts +2 -0
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/forms/button/button.class.d.ts +8 -6
- package/dist/components/forms/button/button.class.js +2 -2
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/color-picker/color-core.js +1 -1
- package/dist/components/forms/combobox/combobox.class.d.ts +20 -12
- package/dist/components/forms/combobox/combobox.class.js +2 -2
- package/dist/components/forms/date-picker/date-input.class.d.ts +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
- package/dist/components/forms/icon-button/icon-button.class.js +2 -2
- package/dist/components/forms/input/input-shared.js +2 -2
- package/dist/components/forms/input/number-input-locale.js +1 -0
- package/dist/components/forms/input/number-input.class.d.ts +19 -2
- package/dist/components/forms/input/number-input.class.js +2 -2
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -3
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
- package/dist/components/layout/details/accordion-item.class.js +1 -1
- package/dist/components/layout/dock-panel/dock-panel.class.d.ts +1 -1
- package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +3 -3
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/segmented/segmented.class.d.ts +20 -7
- package/dist/components/layout/segmented/segmented.class.js +34 -24
- package/dist/components/layout/segmented/segmented.styles.js +1 -1
- package/dist/components/layout/stepper/stepper.styles.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.d.ts +8 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/tab-group/tab.class.d.ts +7 -1
- package/dist/components/layout/tab-group/tab.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.d.ts +2 -2
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/media/animated-image/animated-image.class.js +1 -1
- package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +21 -14
- package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +36 -12
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
- package/dist/components/media/drop-zone/drop-zone.class.d.ts +23 -5
- package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
- package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/flag/flag-url-resolver.js +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
- package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/media/map/map-anchor-controller.js +1 -1
- package/dist/components/media/map/map-canvas-target.js +1 -0
- package/dist/components/media/map/map-owned-features.js +1 -1
- package/dist/components/media/map/map-scene-elevated-lines.js +2 -2
- package/dist/components/media/map/map-scene-render-controller.js +1 -1
- package/dist/components/media/map/map.class.d.ts +15 -6
- package/dist/components/media/map/map.class.js +4 -4
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +21 -9
- package/dist/components/media/sequence-playback/sequence-playback.class.js +7 -6
- package/dist/components/media/sequence-playback/sequence-playback.styles.js +1 -1
- package/dist/components/media/video/video.class.d.ts +3 -3
- package/dist/components/media/video/video.class.js +3 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/overlays/chip/chip.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.js +1 -1
- package/dist/components/overlays/overlay/overlay.styles.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -1
- package/dist/components/overlays/overlay/tooltip.class.js +3 -3
- package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -1
- package/dist/components/retrieval/graph/graph-node-renderer.js +1 -1
- package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.d.ts +11 -0
- package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.js +1 -0
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +18 -7
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +13 -26
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.styles.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
- package/dist/components/utility/diff-view/diff-view.class.d.ts +5 -5
- package/dist/components/utility/diff-view/diff-view.class.js +1 -1
- package/dist/components/utility/icon/icon.class.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.class.d.ts +16 -1
- package/dist/components/utility/json-viewer/json-viewer.class.js +4 -4
- package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
- package/dist/components/utility/known-date/known-date.class.js +1 -1
- package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
- package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
- package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
- package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +1 -1
- package/dist/components/viewers/document-preview/document-preview.class.js +2 -2
- package/dist/components/viewers/docx-viewer/docx-viewer.class.d.ts +1 -1
- package/dist/components/viewers/docx-viewer/docx-viewer.class.js +2 -2
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.d.ts +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
- package/dist/components/viewers/html-viewer/html-viewer.class.js +1 -1
- package/dist/components/viewers/include/include.class.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
- package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
- package/dist/components/viewers/table-viewer-shared.js +4 -4
- package/dist/components/viewers/xml-viewer/xml-viewer.class.js +2 -2
- package/dist/data-sources.d.ts +10 -0
- package/dist/events.d.ts +9 -4
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/anchored-overlay-runtime.js +1 -1
- package/dist/internal/catalog-picker.js +1 -1
- package/dist/internal/default-strings/conversation.generated.js +1 -1
- package/dist/internal/default-strings/data.generated.js +1 -1
- package/dist/internal/default-strings/retrieval.generated.js +1 -1
- package/dist/internal/document-tokens.js +2 -2
- package/dist/internal/drop-session-controller.js +1 -1
- package/dist/internal/engine-3d.js +1 -1
- package/dist/internal/icon-only-content.js +1 -1
- package/dist/internal/layered-layout.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.js +2 -2
- package/dist/internal/map-custom-layer-controller.js +1 -1
- package/dist/internal/media-panorama.js +1 -1
- package/dist/internal/native-modal-context.js +1 -1
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/overlay-order.js +1 -1
- package/dist/internal/overlay-stack.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/runtime-diagnostics.js +1 -0
- package/dist/internal/safe-url.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/internal/scroll-overflow.js +1 -1
- package/dist/internal/source-cursor-controller.js +1 -0
- package/dist/internal/source-cursor-projection.js +1 -0
- package/dist/internal/source-page-scope.js +1 -1
- package/dist/internal/source-window-controller.js +1 -1
- package/dist/internal/text-quote.js +1 -1
- package/dist/internal/viewer-search.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/sequence-time-binding.js +1 -1
- package/dist/simulation-clock.js +1 -1
- package/dist/styles/reservations.css +1 -1
- package/dist/styles/reservations.styles.js +1 -1
- package/dist/testing/happy-dom-shims.js +1 -1
- package/dist/theme/theme-bootstrap.js +1 -1
- package/dist/theme/theme.js +1 -1
- package/dist/utilities/overlay-manager.d.ts +2 -0
- package/llms/components/lr-attachment-chip.md +27 -12
- package/llms/components/lr-attachment-trigger.md +27 -7
- package/llms/components/lr-budget-meter.md +31 -0
- package/llms/components/lr-button.md +6 -4
- package/llms/components/lr-chat-composer.md +26 -9
- package/llms/components/lr-chat-message.md +44 -3
- package/llms/components/lr-chat-viewport.md +39 -2
- package/llms/components/lr-combobox.md +27 -1
- package/llms/components/lr-data-grid.md +2 -0
- package/llms/components/lr-dialog.md +10 -0
- package/llms/components/lr-diff-view.md +6 -0
- package/llms/components/lr-document-library.md +90 -6
- package/llms/components/lr-drop-zone.md +26 -2
- package/llms/components/lr-graph.md +5 -0
- package/llms/components/lr-icon-button.md +2 -1
- package/llms/components/lr-ingestion-queue.md +76 -8
- package/llms/components/lr-json-viewer.md +51 -0
- package/llms/components/lr-lite-chart.md +2 -1
- package/llms/components/lr-locale-picker.md +5 -0
- package/llms/components/lr-map.md +33 -0
- package/llms/components/lr-markdown-core.md +2 -1
- package/llms/components/lr-markdown.md +20 -4
- package/llms/components/lr-menu.md +3 -1
- package/llms/components/lr-message-feedback.md +38 -3
- package/llms/components/lr-number-input.md +28 -1
- package/llms/components/lr-page.md +4 -2
- package/llms/components/lr-prompt-input.md +6 -3
- package/llms/components/lr-segmented.md +30 -10
- package/llms/components/lr-sequence-playback.md +47 -12
- package/llms/components/lr-streaming-text-core.md +3 -2
- package/llms/components/lr-streaming-text.md +4 -1
- package/llms/components/lr-suggestion-chips.md +28 -5
- package/llms/components/lr-tab-group.md +13 -1
- package/llms/components/lr-tab.md +5 -0
- package/llms/components/lr-table.md +25 -4
- package/llms/components/lr-timeline-item.md +1 -1
- package/llms/components/lr-timeline.md +38 -4
- package/llms/components/lr-tooltip.md +3 -1
- package/llms/components/lr-tree.md +4 -0
- package/llms/components/lr-virtual-list.md +4 -1
- package/llms/peers.md +2 -2
- package/llms/shared/events-and-types.md +61 -2
- package/llms/shared/forms-and-accessibility.md +46 -4
- package/llms/shared/imports-and-registration.md +154 -110
- package/llms/shared/testing-and-utilities.md +5 -1
- package/llms/shared.md +266 -117
- package/locales.json +1 -1
- package/package.json +22 -21
- package/registrations.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{combineShikiLanguageSources}from"../../../internal/shiki-language-sources.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink,Announcer}from"../../../internal/announcer.js";import{advanceViewerSearchIndex,announceSearchResult,viewerSearchDetail}from"../../../internal/viewer-search.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../../viewers/viewer-search-limits.js";import{ViewerAnnouncementController}from"../../viewers/viewer-announcements.js";import{commonAffix,computeLineDiff,pairOpsForSplit}from"./diff-line-diff.js";import{loadShikiHighlighterCore,SHIKI_THEMES,SHIKI_SOURCE_MAX_CODE_UNITS,resolvedShikiLanguages,ensureShikiLanguageLoaded}from"../../conversation/code-block/shiki-types.js";import{styles}from"./diff-view.styles.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_remove,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_copyDiff,LYRA_DEFAULT_diffViewHiddenLines,LYRA_DEFAULT_diffViewHighlightLimit,LYRA_DEFAULT_diffViewNewLabel,LYRA_DEFAULT_diffViewOldLabel,LYRA_DEFAULT_diffViewTooLarge}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,splitLines=text=>text===""?[]:text.split(/\r\n|\r|\n/),MAX_DIFF_RENDERED_LINES=1e4,MAX_DIFF_CHARACTERS=1e6,MAX_DIFF_COMPARISONS=4e6,MAX_DIFF_LANGUAGES=1e4,MAX_DIFF_LANGUAGE_INSPECTIONS=MAX_DIFF_LANGUAGES*2,MAX_PAINTED_HIGHLIGHTS=100;function projectLanguages(value){if(!(value===null||typeof value!="object"))try{if(Array.isArray(value))return;const projected=Object.create(null),keys=Object.getOwnPropertyNames(value);let inspected=0,admitted=0;for(const key of keys){if(inspected>=MAX_DIFF_LANGUAGE_INSPECTIONS||admitted>=MAX_DIFF_LANGUAGES)break;inspected+=1;const descriptor=getOwnDataDescriptor(value,key);descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable||(Object.defineProperty(projected,key,{value:descriptor.value,enumerable:!0,configurable:!1,writable:!1}),admitted+=1)}return Object.freeze(projected)}catch{return}}const DIFF_VIEW_LAYOUT=literalSetConverter(["unified","split"],"unified");class LyraDiffViewBase extends LyraElement{}class LyraDiffView extends DocumentAnchorTarget(LyraDiffViewBase){constructor(){super(...arguments),this.oldText="",this.newText="",this.copyable=!1,this.maxHeight="",this._layout="unified",this.language="",this.maxLines=5e3,this.anchorKinds=["line-range"],this.copyStatus="rest",this.diffTooLarge=!1,this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.forcedVisibleOps=new Set,this.searchAnnouncements=new ViewerAnnouncementController(this),this.searchAnnouncer=new Announcer({onFlush:text=>this.searchAnnouncements.announcePolite(text)}),this.highlightedOldLines=null,this.highlightedNewLines=null,this.highlightToken=0,this.loadHighlighterCore=loadShikiHighlighterCore,this.copyGeneration=0,this.oldTextSnapshot="",this.newTextSnapshot="",this.languageSnapshot="",this.diffOps=[],this.opIndexMap=new Map,this.onCopyClick=()=>{this.copy()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyDiff:LYRA_DEFAULT_copyDiff,copyFailed:LYRA_DEFAULT_copyFailed,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,diffViewHiddenLines:LYRA_DEFAULT_diffViewHiddenLines,diffViewHighlightLimit:LYRA_DEFAULT_diffViewHighlightLimit,diffViewNewLabel:LYRA_DEFAULT_diffViewNewLabel,diffViewOldLabel:LYRA_DEFAULT_diffViewOldLabel,diffViewTooLarge:LYRA_DEFAULT_diffViewTooLarge,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,remove:LYRA_DEFAULT_remove,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,srOnly]}get layout(){return this._layout}set layout(next){const normalized=DIFF_VIEW_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated||changed.has("oldText")||changed.has("newText")){const oldText=this.oldText,newText=this.newText;this.oldTextSnapshot=typeof oldText=="string"?oldText:"",this.newTextSnapshot=typeof newText=="string"?newText:""}if(!this.hasUpdated||changed.has("language")||changed.has("languages")||changed.has("languageLoaders")){const language=this.language;this.languageSnapshot=typeof language=="string"?language:"";const languages=projectLanguages(this.languages);if(this.languageLoaders===void 0)this.languagesSnapshot=languages;else{const loaders=projectLanguages(this.languageLoaders);this.languagesSnapshot=projectLanguages(combineShikiLanguageSources(languages,loaders))}}if(this.hasUpdated&&(changed.has("oldText")||changed.has("newText")||changed.has("copyable")||changed.has("maxLines"))&&this.resetCopyFeedback(),changed.has("oldText")||changed.has("newText")||changed.has("maxLines")){const oldLines=splitLines(this.oldTextSnapshot),newLines=splitLines(this.newTextSnapshot),maxLines=this.maxLines===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:finiteCount(this.maxLines,5e3),characterCount=this.oldTextSnapshot.length+this.newTextSnapshot.length,[head,tail]=commonAffix(oldLines,newLines),comparisons=(oldLines.length-head-tail)*(newLines.length-head-tail);this.diffTooLarge=oldLines.length>maxLines||newLines.length>maxLines||characterCount>MAX_DIFF_CHARACTERS||comparisons>MAX_DIFF_COMPARISONS,this.diffOps=this.diffTooLarge?[]:computeLineDiff(oldLines,newLines),this.diffOps.length>MAX_DIFF_RENDERED_LINES&&(this.diffTooLarge=!0,this.diffOps=[]),this.opIndexMap=new Map(this.diffOps.map((op,index)=>[op,index])),this.pendingSearchResetEvent||=this.hasSearchState(),this.forcedVisibleOps=new Set,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1}(changed.has("oldText")||changed.has("newText")||changed.has("language")||changed.has("languages")||changed.has("languageLoaders")||changed.has("maxLines"))&&this.syncHighlight()}updated(changed){super.updated(changed),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")}}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncHighlight(),this.copyAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.connect();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}disconnectedCallback(){this.highlightToken++,super.disconnectedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncer.cancel(),this.searchAnnouncements.disconnect()}adoptedCallback(){this.highlightToken++,super.adoptedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncements.adopted();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetCopyFeedback(){this.copyGeneration+=1,this.cancelCopyTimer(),this.copyStatus="rest"}get highlightLimited(){return this.oldTextSnapshot.length>SHIKI_SOURCE_MAX_CODE_UNITS||this.newTextSnapshot.length>SHIKI_SOURCE_MAX_CODE_UNITS}syncHighlight(){const token=++this.highlightToken;if(this.diffTooLarge||this.highlightLimited){this.highlightedOldLines=null,this.highlightedNewLines=null;return}const lang=this.languageSnapshot,languages=this.languagesSnapshot;if(!lang||!languages||!Object.hasOwn(languages,lang)){this.highlightedOldLines=null,this.highlightedNewLines=null;return}this.highlightedOldLines=null,this.highlightedNewLines=null;let loading;try{loading=this.loadHighlighterCore(resolvedShikiLanguages(languages))}catch{this.highlightedOldLines=null,this.highlightedNewLines=null;return}loading.then(async hl=>{if(token!==this.highlightToken||!this.isConnected)return;if(!hl){this.highlightedOldLines=null,this.highlightedNewLines=null;return}const loaded=await ensureShikiLanguageLoaded(hl,lang,languages[lang]);if(!(token!==this.highlightToken||!this.isConnected)){if(!loaded){this.highlightedOldLines=null,this.highlightedNewLines=null;return}this.highlightedOldLines=this.tokenizeLines(hl,this.oldTextSnapshot,lang),this.highlightedNewLines=this.tokenizeLines(hl,this.newTextSnapshot,lang)}},()=>{token===this.highlightToken&&(this.highlightedOldLines=null,this.highlightedNewLines=null)})}tokenizeLines(hl,text,lang){if(text.length>SHIKI_SOURCE_MAX_CODE_UNITS)return null;try{const html2=hl.codeToHtml(text,{lang,themes:SHIKI_THEMES}),DOMParserCtor=this.ownerDocument.defaultView?.DOMParser;if(!DOMParserCtor)return null;const doc=new DOMParserCtor().parseFromString(html2,"text/html"),lines=Array.from(doc.querySelectorAll("code > .line")).map(line=>line.innerHTML),expected=splitLines(text).length;for(;lines.length>expected;)lines.pop();for(;lines.length<expected;)lines.push("");return lines}catch{return null}}computeFolds(){const ops=this.diffOps,visible=new Set(ops),foldBefore=new Map;let trailingFold=0;const ctx=this.contextLines==null||!Number.isFinite(this.contextLines)||this.contextLines<0?void 0:finiteCount(this.contextLines);if(ctx===void 0)return{visible,foldBefore,trailingFold};let i=0;for(;i<ops.length;){if(ops[i].type!=="equal"){i++;continue}let j=i;for(;j<ops.length&&ops[j].type==="equal";)j++;const runLength=j-i,isLeading=i===0,isTrailing=j===ops.length;let runHasForcedReveal=!1;if(this.forcedVisibleOps.size>0){for(let k=i;k<j;k++)if(this.forcedVisibleOps.has(ops[k])){runHasForcedReveal=!0;break}}if(!(isLeading&&isTrailing)){if(!runHasForcedReveal){if(isLeading){const hidden=Math.max(0,runLength-ctx);if(hidden>0){for(let k=i;k<i+hidden;k++)visible.delete(ops[k]);foldBefore.set(ops[i+hidden],hidden)}}else if(isTrailing){const shown=Math.min(ctx,runLength),hidden=runLength-shown;if(hidden>0){for(let k=i+shown;k<j;k++)visible.delete(ops[k]);trailingFold=hidden}}else if(runLength>ctx*2){const hiddenStart=i+ctx,hiddenEnd=j-ctx;for(let k=hiddenStart;k<hiddenEnd;k++)visible.delete(ops[k]);foldBefore.set(ops[hiddenStart],hiddenEnd-hiddenStart)}}}i=j}return{visible,foldBefore,trailingFold}}foldMarker(count){const text=this.localize("diffViewHiddenLines",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count});return html`<div part="line" data-type="fold">${text}</div>`}async revealOp(op){if(!this.forcedVisibleOps.has(op)){const next=new Set(this.forcedVisibleOps);next.add(op),this.forcedVisibleOps=next}await this.updateComplete}lineElementForOpIndex(index){return this.renderRoot.querySelector(`[data-op-index="${index}"]`)}async scrollOpIndexIntoView(index){const op=this.diffOps[index];if(!op)return!1;await this.revealOp(op);const target=this.lineElementForOpIndex(index);return target?(target.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"nearest"}),!0):!1}async applyAnchor(anchor){if(anchor.kind!=="line-range")return!1;const index=anchor.start;return!Number.isInteger(index)||index<0||index>=this.diffOps.length?!1:this.scrollOpIndexIntoView(index)}resolvedHighlightOps(){const perOp=new Map,owners=new Map,order=new Map,ops=this.diffOps;if(ops.length===0)return{perOp,owners,order,total:0};const seen=new Set;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(order.size>=MAX_PAINTED_HIGHLIGHTS)break;if(seen.has(highlight.id)||(seen.add(highlight.id),highlight.anchor.kind!=="line-range"))continue;const start=Math.max(0,Math.min(highlight.anchor.start,ops.length-1)),end=Math.max(start,Math.min(highlight.anchor.end??highlight.anchor.start,ops.length-1));let resolvedAny=!1;for(let index=start;index<=end;index++){const op=ops[index];resolvedAny=!0,!perOp.has(op)&&(perOp.set(op,highlight),owners.has(highlight)||owners.set(highlight,op))}resolvedAny&&order.set(highlight,order.size)}return{perOp,owners,order,total:order.size}}highlightActionLabel(highlight,index,total){if(highlight.label)return this.localize("highlightWithLabel",void 0,{label:highlight.label});const numberFormat=getNumberFormat(this.effectiveLocale);return this.localize("highlightOfTotal",void 0,{index:numberFormat.format(index+1),total:numberFormat.format(total)})}activateHighlight(highlight){this.emit("lr-highlight-activate",{highlightId:highlight.id})}emitSearchChange(){this.emit("lr-search-change",viewerSearchDetail(this.searchQuery,this.searchMatches.length,this.searchMatchCountExact,this.searchActiveIndex)),announceSearchResult((key,fallback,values)=>this.localize(key,fallback,values),this.searchAnnouncer,this.effectiveLocale,this.searchMatches.length,this.searchActiveIndex)}recomputeSearchMatches(){this.lastSearchLocale=this.effectiveLocale;const boundedQuery=boundedViewerSearchQuery(this.searchQuery,this.effectiveLocale),needle=boundedQuery.needle,matches=[];let matchCountExact=boundedQuery.accepted;if(boundedQuery.accepted&&needle){const budget=new ViewerSearchWorkBudget;for(let index=0;index<this.diffOps.length;index++)if(budget.includes(this.diffOps[index].text,needle,this.effectiveLocale)&&matches.push({opIndex:index}),!budget.complete){matchCountExact=!1;break}}this.searchMatches=matches,this.searchMatchCountExact=matchCountExact}async search(query){this.searchQuery=query,this.recomputeSearchMatches(),this.searchActiveIndex=this.searchMatches.length>0?0:-1,this.emitSearchChange();const active=this.searchMatches[this.searchActiveIndex];return active&&await this.scrollOpIndexIntoView(active.opIndex),this.searchMatches.length}async searchNext(){return this.searchMatches.length?(this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,1),this.emitSearchChange(),await this.scrollOpIndexIntoView(this.searchMatches[this.searchActiveIndex].opIndex),!0):!1}async searchPrevious(){return this.searchMatches.length?(this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,-1),this.emitSearchChange(),await this.scrollOpIndexIntoView(this.searchMatches[this.searchActiveIndex].opIndex),!0):!1}clearSearch(){this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange()}get unifiedText(){return this.diffOps.map(op=>`${op.type==="add"?"+":op.type==="remove"?"-":" "} ${op.text}`).join(`
|
|
1
|
+
import{__decorate}from"tslib";import{combineShikiLanguageSources}from"../../../internal/shiki-language-sources.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink,Announcer}from"../../../internal/announcer.js";import{advanceViewerSearchIndex,announceSearchResult,viewerSearchDetail}from"../../../internal/viewer-search.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../../viewers/viewer-search-limits.js";import{ViewerAnnouncementController}from"../../viewers/viewer-announcements.js";import{commonAffix,computeLineDiff,pairOpsForSplit}from"./diff-line-diff.js";import{loadShikiHighlighterCore,SHIKI_THEMES,SHIKI_SOURCE_MAX_CODE_UNITS,resolvedShikiLanguages,ensureShikiLanguageLoaded}from"../../conversation/code-block/shiki-types.js";import{styles}from"./diff-view.styles.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_remove,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_copyDiff,LYRA_DEFAULT_diffViewHiddenLines,LYRA_DEFAULT_diffViewHighlightLimit,LYRA_DEFAULT_diffViewNewLabel,LYRA_DEFAULT_diffViewOldLabel,LYRA_DEFAULT_diffViewTooLarge}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,splitLines=text=>text===""?[]:text.split(/\r\n|\r|\n/),MAX_DIFF_RENDERED_LINES=1e4,MAX_DIFF_CHARACTERS=1e6,MAX_DIFF_COMPARISONS=4e6,MAX_DIFF_LANGUAGES=1e4,MAX_DIFF_LANGUAGE_INSPECTIONS=MAX_DIFF_LANGUAGES*2,MAX_PAINTED_HIGHLIGHTS=100;function projectLanguages(value){if(!(value===null||typeof value!="object"))try{if(Array.isArray(value))return;const projected=Object.create(null),keys=Object.getOwnPropertyNames(value);let inspected=0,admitted=0;for(const key of keys){if(inspected>=MAX_DIFF_LANGUAGE_INSPECTIONS||admitted>=MAX_DIFF_LANGUAGES)break;inspected+=1;const descriptor=getOwnDataDescriptor(value,key);descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable||(Object.defineProperty(projected,key,{value:descriptor.value,enumerable:!0,configurable:!1,writable:!1}),admitted+=1)}return Object.freeze(projected)}catch{return}}const DIFF_VIEW_LAYOUT=literalSetConverter(["unified","split"],"unified");class LyraDiffViewBase extends LyraElement{}class LyraDiffView extends DocumentAnchorTarget(LyraDiffViewBase){constructor(){super(...arguments),this.oldText="",this.newText="",this.copyable=!1,this.maxHeight="",this._layout="unified",this.language="",this.maxLines=5e3,this.anchorKinds=["line-range"],this.copyStatus="rest",this.diffTooLarge=!1,this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.forcedVisibleOps=new Set,this.searchAnnouncements=new ViewerAnnouncementController(this),this.searchAnnouncer=new Announcer({onFlush:text=>this.searchAnnouncements.announcePolite(text)}),this.highlightedOldLines=null,this.highlightedNewLines=null,this.highlightToken=0,this.loadHighlighterCore=loadShikiHighlighterCore,this.copyGeneration=0,this.scrollGeneration=0,this.searchGeneration=0,this.oldTextSnapshot="",this.newTextSnapshot="",this.languageSnapshot="",this.diffOps=[],this.opIndexMap=new Map,this.onCopyClick=()=>{this.copy()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyDiff:LYRA_DEFAULT_copyDiff,copyFailed:LYRA_DEFAULT_copyFailed,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,diffViewHiddenLines:LYRA_DEFAULT_diffViewHiddenLines,diffViewHighlightLimit:LYRA_DEFAULT_diffViewHighlightLimit,diffViewNewLabel:LYRA_DEFAULT_diffViewNewLabel,diffViewOldLabel:LYRA_DEFAULT_diffViewOldLabel,diffViewTooLarge:LYRA_DEFAULT_diffViewTooLarge,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,remove:LYRA_DEFAULT_remove,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,srOnly]}get layout(){return this._layout}set layout(next){const normalized=DIFF_VIEW_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}willUpdate(changed){if((changed.has("oldText")||changed.has("newText")||changed.has("maxLines"))&&(this.scrollGeneration++,this.searchGeneration++,this.cancelPendingAnchor()),super.willUpdate(changed),!this.hasUpdated||changed.has("oldText")||changed.has("newText")){const oldText=this.oldText,newText=this.newText;this.oldTextSnapshot=typeof oldText=="string"?oldText:"",this.newTextSnapshot=typeof newText=="string"?newText:""}if(!this.hasUpdated||changed.has("language")||changed.has("languages")||changed.has("languageLoaders")){const language=this.language;this.languageSnapshot=typeof language=="string"?language:"";const languages=projectLanguages(this.languages);if(this.languageLoaders===void 0)this.languagesSnapshot=languages;else{const loaders=projectLanguages(this.languageLoaders);this.languagesSnapshot=projectLanguages(combineShikiLanguageSources(languages,loaders))}}if(this.hasUpdated&&(changed.has("oldText")||changed.has("newText")||changed.has("copyable")||changed.has("maxLines"))&&this.resetCopyFeedback(),changed.has("oldText")||changed.has("newText")||changed.has("maxLines")){const oldLines=splitLines(this.oldTextSnapshot),newLines=splitLines(this.newTextSnapshot),maxLines=this.maxLines===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:finiteCount(this.maxLines,5e3),characterCount=this.oldTextSnapshot.length+this.newTextSnapshot.length,[head,tail]=commonAffix(oldLines,newLines),comparisons=(oldLines.length-head-tail)*(newLines.length-head-tail);this.diffTooLarge=oldLines.length>maxLines||newLines.length>maxLines||characterCount>MAX_DIFF_CHARACTERS||comparisons>MAX_DIFF_COMPARISONS,this.diffOps=this.diffTooLarge?[]:computeLineDiff(oldLines,newLines),this.diffOps.length>MAX_DIFF_RENDERED_LINES&&(this.diffTooLarge=!0,this.diffOps=[]),this.opIndexMap=new Map(this.diffOps.map((op,index)=>[op,index])),this.pendingSearchResetEvent||=this.hasSearchState(),this.forcedVisibleOps=new Set,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1}(changed.has("oldText")||changed.has("newText")||changed.has("language")||changed.has("languages")||changed.has("languageLoaders")||changed.has("maxLines"))&&this.syncHighlight()}updated(changed){super.updated(changed),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")}}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncHighlight(),this.copyAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.connect();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}disconnectedCallback(){this.highlightToken++,this.scrollGeneration++,this.searchGeneration++,super.disconnectedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncer.cancel(),this.searchAnnouncements.disconnect()}adoptedCallback(){this.highlightToken++,this.scrollGeneration++,this.searchGeneration++,super.adoptedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncements.adopted();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetCopyFeedback(){this.copyGeneration+=1,this.cancelCopyTimer(),this.copyStatus="rest"}get highlightLimited(){return this.oldTextSnapshot.length>SHIKI_SOURCE_MAX_CODE_UNITS||this.newTextSnapshot.length>SHIKI_SOURCE_MAX_CODE_UNITS}syncHighlight(){const token=++this.highlightToken;if(this.diffTooLarge||this.highlightLimited){this.highlightedOldLines=null,this.highlightedNewLines=null;return}const lang=this.languageSnapshot,languages=this.languagesSnapshot;if(!lang||!languages||!Object.hasOwn(languages,lang)){this.highlightedOldLines=null,this.highlightedNewLines=null;return}this.highlightedOldLines=null,this.highlightedNewLines=null;let loading;try{loading=this.loadHighlighterCore(resolvedShikiLanguages(languages))}catch{this.highlightedOldLines=null,this.highlightedNewLines=null;return}loading.then(async hl=>{if(token!==this.highlightToken||!this.isConnected)return;if(!hl){this.highlightedOldLines=null,this.highlightedNewLines=null;return}const loaded=await ensureShikiLanguageLoaded(hl,lang,languages[lang]);if(!(token!==this.highlightToken||!this.isConnected)){if(!loaded){this.highlightedOldLines=null,this.highlightedNewLines=null;return}this.highlightedOldLines=this.tokenizeLines(hl,this.oldTextSnapshot,lang),this.highlightedNewLines=this.tokenizeLines(hl,this.newTextSnapshot,lang)}},()=>{token===this.highlightToken&&(this.highlightedOldLines=null,this.highlightedNewLines=null)})}tokenizeLines(hl,text,lang){if(text.length>SHIKI_SOURCE_MAX_CODE_UNITS)return null;try{const html2=hl.codeToHtml(text,{lang,themes:SHIKI_THEMES}),DOMParserCtor=this.ownerDocument.defaultView?.DOMParser;if(!DOMParserCtor)return null;const doc=new DOMParserCtor().parseFromString(html2,"text/html"),lines=Array.from(doc.querySelectorAll("code > .line")).map(line=>line.innerHTML),expected=splitLines(text).length;for(;lines.length>expected;)lines.pop();for(;lines.length<expected;)lines.push("");return lines}catch{return null}}computeFolds(){const ops=this.diffOps,visible=new Set(ops),foldBefore=new Map;let trailingFold=0;const ctx=this.contextLines==null||!Number.isFinite(this.contextLines)||this.contextLines<0?void 0:finiteCount(this.contextLines);if(ctx===void 0)return{visible,foldBefore,trailingFold};let i=0;for(;i<ops.length;){if(ops[i].type!=="equal"){i++;continue}let j=i;for(;j<ops.length&&ops[j].type==="equal";)j++;const runLength=j-i,isLeading=i===0,isTrailing=j===ops.length;let runHasForcedReveal=!1;if(this.forcedVisibleOps.size>0){for(let k=i;k<j;k++)if(this.forcedVisibleOps.has(ops[k])){runHasForcedReveal=!0;break}}if(!(isLeading&&isTrailing)){if(!runHasForcedReveal){if(isLeading){const hidden=Math.max(0,runLength-ctx);if(hidden>0){for(let k=i;k<i+hidden;k++)visible.delete(ops[k]);foldBefore.set(ops[i+hidden],hidden)}}else if(isTrailing){const shown=Math.min(ctx,runLength),hidden=runLength-shown;if(hidden>0){for(let k=i+shown;k<j;k++)visible.delete(ops[k]);trailingFold=hidden}}else if(runLength>ctx*2){const hiddenStart=i+ctx,hiddenEnd=j-ctx;for(let k=hiddenStart;k<hiddenEnd;k++)visible.delete(ops[k]);foldBefore.set(ops[hiddenStart],hiddenEnd-hiddenStart)}}}i=j}return{visible,foldBefore,trailingFold}}foldMarker(count){const text=this.localize("diffViewHiddenLines",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count});return html`<div part="line" data-type="fold">${text}</div>`}async revealOp(op){if(!this.forcedVisibleOps.has(op)){const next=new Set(this.forcedVisibleOps);next.add(op),this.forcedVisibleOps=next}await this.updateComplete}lineElementForOpIndex(index){return this.renderRoot.querySelector(`[data-op-index="${index}"]`)}scrollAuthority(){const generation=this.scrollGeneration,document=this.ownerDocument,ops=this.diffOps,oldText=this.oldText,newText=this.newText,maxLines=this.maxLines;return()=>this.isConnected&&this.ownerDocument===document&&this.scrollGeneration===generation&&this.diffOps===ops&&this.oldText===oldText&&this.newText===newText&&Object.is(this.maxLines,maxLines)}async scrollOpIndexIntoView(index,isCurrent=this.scrollAuthority()){const op=this.diffOps[index];if(!op||!isCurrent()||(await this.revealOp(op),!isCurrent()))return!1;const target=this.lineElementForOpIndex(index);return target?(target.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"nearest"}),!0):!1}async applyAnchor(anchor){if(anchor.kind!=="line-range")return!1;const index=anchor.start;return!Number.isInteger(index)||index<0||index>=this.diffOps.length?!1:this.scrollOpIndexIntoView(index)}resolvedHighlightOps(){const perOp=new Map,owners=new Map,order=new Map,ops=this.diffOps;if(ops.length===0)return{perOp,owners,order,total:0};const seen=new Set;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(order.size>=MAX_PAINTED_HIGHLIGHTS)break;if(seen.has(highlight.id)||(seen.add(highlight.id),highlight.anchor.kind!=="line-range"))continue;const start=Math.max(0,Math.min(highlight.anchor.start,ops.length-1)),end=Math.max(start,Math.min(highlight.anchor.end??highlight.anchor.start,ops.length-1));let resolvedAny=!1;for(let index=start;index<=end;index++){const op=ops[index];resolvedAny=!0,!perOp.has(op)&&(perOp.set(op,highlight),owners.has(highlight)||owners.set(highlight,op))}resolvedAny&&order.set(highlight,order.size)}return{perOp,owners,order,total:order.size}}highlightActionLabel(highlight,index,total){if(highlight.label)return this.localize("highlightWithLabel",void 0,{label:highlight.label});const numberFormat=getNumberFormat(this.effectiveLocale);return this.localize("highlightOfTotal",void 0,{index:numberFormat.format(index+1),total:numberFormat.format(total)})}activateHighlight(highlight){this.emit("lr-highlight-activate",{highlightId:highlight.id})}emitSearchChange(){const generation=this.searchGeneration,isCurrent=this.scrollAuthority();this.emit("lr-search-change",viewerSearchDetail(this.searchQuery,this.searchMatches.length,this.searchMatchCountExact,this.searchActiveIndex)),!(generation!==this.searchGeneration||!isCurrent())&&announceSearchResult((key,fallback,values)=>this.localize(key,fallback,values),this.searchAnnouncer,this.effectiveLocale,this.searchMatches.length,this.searchActiveIndex)}recomputeSearchMatches(){this.lastSearchLocale=this.effectiveLocale;const boundedQuery=boundedViewerSearchQuery(this.searchQuery,this.effectiveLocale),needle=boundedQuery.needle,matches=[];let matchCountExact=boundedQuery.accepted;if(boundedQuery.accepted&&needle){const budget=new ViewerSearchWorkBudget;for(let index=0;index<this.diffOps.length;index++)if(budget.includes(this.diffOps[index].text,needle,this.effectiveLocale)&&matches.push({opIndex:index}),!budget.complete){matchCountExact=!1;break}}this.searchMatches=matches,this.searchMatchCountExact=matchCountExact}async search(query){const generation=++this.searchGeneration,ownsSource=this.scrollAuthority(),isCurrent=()=>generation===this.searchGeneration&&ownsSource();this.searchQuery=query,this.recomputeSearchMatches(),this.searchActiveIndex=this.searchMatches.length>0?0:-1;const active=this.searchMatches[this.searchActiveIndex],count=this.searchMatches.length;return this.emitSearchChange(),!isCurrent()||active&&!await this.scrollOpIndexIntoView(active.opIndex,isCurrent)?0:isCurrent()?count:0}async searchNext(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration,ownsSource=this.scrollAuthority(),isCurrent=()=>generation===this.searchGeneration&&ownsSource();this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,1);const active=this.searchMatches[this.searchActiveIndex];return this.emitSearchChange(),isCurrent()?this.scrollOpIndexIntoView(active.opIndex,isCurrent):!1}async searchPrevious(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration,ownsSource=this.scrollAuthority(),isCurrent=()=>generation===this.searchGeneration&&ownsSource();this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,-1);const active=this.searchMatches[this.searchActiveIndex];return this.emitSearchChange(),isCurrent()?this.scrollOpIndexIntoView(active.opIndex,isCurrent):!1}clearSearch(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange()}get unifiedText(){return this.diffOps.map(op=>`${op.type==="add"?"+":op.type==="remove"?"-":" "} ${op.text}`).join(`
|
|
2
2
|
`)}isCurrentCopy(generation,owner){return this.isConnected&&this.copyable&&!this.diffTooLarge&&generation===this.copyGeneration&&this.ownerDocument.defaultView===owner}showCopyStatus(status,generation){const owner=this.ownerDocument.defaultView;if(!owner||!this.isCurrentCopy(generation,owner))return;this.copyStatus=status,this.copyAnnouncementSink?.announce(status==="success"?this.localize("copied"):this.localize("copyFailed")),this.cancelCopyTimer();let handle=0;handle=owner.setTimeout(()=>{const timer=this.copyTimer;timer?.owner!==owner||timer.handle!==handle||timer.generation!==generation||!this.isCurrentCopy(generation,owner)||(this.copyTimer=void 0,this.copyStatus="rest")},COPY_CONFIRM_MS),this.copyTimer={owner,handle,generation}}async copy(){if(!this.copyable||this.diffTooLarge)return;const generation=++this.copyGeneration;this.cancelCopyTimer(),this.copyStatus="rest";const text=this.unifiedText,owner=this.isConnected?this.ownerDocument.defaultView:null;if(!owner)return;const outcome=await writeClipboardText(owner,text);if(this.isCurrentCopy(generation,owner)){if(!outcome.ok){this.showCopyStatus("error",generation),this.emit("lr-error"),this.emit("lr-copy-error",outcome);return}this.showCopyStatus("success",generation),this.emit("lr-copy",outcome)}}lineRenderContext(){const{perOp,owners,order,total}=this.resolvedHighlightOps();return{perOp,owners,order,total,matchedOpIndexes:new Set(this.searchMatches.map(match=>match.opIndex)),activeMatchOpIndex:this.searchMatches[this.searchActiveIndex]?.opIndex??-1}}renderDiffLine(op,marker,content,context){const index=this.opIndexMap.get(op),isMatch=index!==void 0&&context.matchedOpIndexes.has(index),isActiveMatch=index!==void 0&&index===context.activeMatchOpIndex,highlight=context.perOp.get(op),owner=highlight&&context.owners.get(highlight)===op?highlight:void 0,ownerLabel=owner?this.highlightActionLabel(owner,context.order.get(owner)??0,context.total):"",text=html`${marker} ${content}`;return html`<div
|
|
3
3
|
part="line"
|
|
4
4
|
data-type=${op.type}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeFetchUrl}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement}from"../../../internal/safe-svg.js";import{
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeFetchUrl}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement}from"../../../internal/safe-svg.js";import{resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getIconLibrary,subscribeIconLibrary}from"./icon-library.js";import{acquireSanitizedIconResource,IconResourceError}from"./icon-resource.js";import{styles}from"./icon.styles.js";import{LYRA_DEFAULT_iconLoadError,LYRA_DEFAULT_iconSanitizerMissing,LYRA_DEFAULT_iconTooLarge}from"../../../internal/default-strings/utility.generated.js";const PATHS={add:"M12 5v14M5 12h14",check:"m5 12 4 4L19 6",close:"m6 6 12 12M18 6 6 18",refresh:"M20 11a8 8 0 0 0-14.9-4M4 5v4h4m-4 4a8 8 0 0 0 14.9 4M20 19v-4h-4",search:"m21 21-4.35-4.35M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z",menu:"M4 6h16M4 12h16M4 18h16","chevron-left":"m15 18-6-6 6-6","chevron-right":"m9 18 6-6-6-6","chevron-down":"m6 9 6 6 6-6",calendar:"M6 3v3M18 3v3M4 9h16M5 5h14a1 1 0 0 1 1 1v13H4V6a1 1 0 0 1 1-1Z",command:"M6 6h4v4H6zM14 6h4v4h-4zM6 14h4v4H6zM14 14h4v4h-4z",trash:"M4 7h16M10 11v6M14 11v6M6 7l1 14h10l1-14M9 7V4h6v3"};class LyraIcon extends LyraElement{constructor(){super(...arguments),this._name="",this.path="",this.label="",this.library="default",this.family="",this.variant="",this._src="",this.rotate=0,this.swapOpacity=!1,this.fetchState={kind:"idle"},this.generation=0,this.onCustomSlotChange=()=>{this.syncCustomNodes()}}static{this.defaultStrings={...super.defaultStrings,iconLoadError:LYRA_DEFAULT_iconLoadError,iconSanitizerMissing:LYRA_DEFAULT_iconSanitizerMissing,iconTooLarge:LYRA_DEFAULT_iconTooLarge}}static{this.styles=[LyraElement.styles,styles,srOnly]}get name(){return this._name}set name(value){const old=this._name;this._name=value??"",this.requestUpdate("name",old)}get src(){return this._src}set src(value){const old=this._src;this._src=value??"",this.requestUpdate("src",old)}connectedCallback(){super.connectedCallback(),this.stopLibrarySubscription??=subscribeIconLibrary(name=>{name===this.library&&this.load()}),this.hasUpdated&&(queueMicrotask(()=>{this.isConnected&&this.syncCustomNodes()}),this.hasRemoteSource()&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.generation++,this.releaseResourceLease(),this.stopLibrarySubscription?.(),this.stopLibrarySubscription=void 0,this.customContentObserver?.disconnect(),this.customContentObserver=void 0,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"}),super.disconnectedCallback()}updated(changed){if(super.updated(changed),changed.has("rotate")){const angle=finiteNumber(this.rotate??0,0);angle?this.style.setProperty("--lr-icon-rotate",`${angle}deg`):this.style.removeProperty("--lr-icon-rotate")}this.applyRemoteA11y(),this.syncCustomNodes(),(changed.has("src")||changed.has("library")||changed.has("name")||changed.has("family")||changed.has("variant"))&&this.scheduleAfterUpdate(()=>{this.load()})}syncCustomNodes(){if(this.fetchState.kind!=="idle")return;const svgEl=this.svgEl;if(!svgEl)return;svgEl.querySelectorAll("[data-lr-custom-copy]").forEach(node=>node.remove()),this.customContentObserver?.disconnect();const slot=this.customSlot;if(slot){for(const node of slot.assignedNodes({flatten:!0})){const copy=this.cloneSvgNode(node);copy&&(copy.setAttribute("data-lr-custom-copy",""),svgEl.append(copy))}this.observeCustomContent(slot)}}observeCustomContent(slot){if(this.customContentObserver?.disconnect(),!this.isConnected)return;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){this.customContentObserver??=new MutationObserverCtor(()=>{this.isConnected&&this.syncCustomNodes()});for(const node of slot.assignedNodes({flatten:!0}))node.nodeType===1&&this.customContentObserver.observe(node,{attributes:!0,childList:!0,subtree:!0})}}cloneSvgNode(node){if(node.nodeType!==1)return null;const element=node;if(element.localName.includes("-")||isUnsafeSvgCloneElement(element.localName))return null;const copy=this.ownerDocument.createElementNS("http://www.w3.org/2000/svg",element.localName);for(const attribute of element.attributes)isUnsafeSvgCloneAttribute(attribute.name,attribute.value,element.localName)||copy.setAttribute(attribute.name==="xlink:href"?"href":attribute.name,attribute.value);for(const child of element.childNodes){const childCopy=this.cloneSvgNode(child);childCopy?copy.append(childCopy):child.nodeType===3&©.append(this.ownerDocument.createTextNode(child.textContent??""))}return copy}accessibleLabel(){return this.getAttribute("aria-label")??this.label}hasRemoteSource(){return!!(this.src||this.name&&this.library&&getIconLibrary(this.library))}releaseResourceLease(){this.resourceLease?.release(),this.resourceLease=void 0}async load(){const generation=++this.generation;this.releaseResourceLease();const library=this.name&&this.library?getIconLibrary(this.library):void 0;if(!library&&!this.src){this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"});return}this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.fetchState={kind:"loading"};let source=this.src;try{if(library){if(source=await library.resolver(this.name,this.family,this.variant),!this.isConnected||generation!==this.generation)return;if(typeof source!="string")throw new TypeError("icon resolver did not return a URL")}}catch(error){await this.fail("load",generation,this.name,error);return}if(!source){this.isConnected&&generation===this.generation&&(this.fetchState={kind:"idle"});return}const safeSource=safeFetchUrl(source);if(!safeSource){await this.fail("load",generation,source,new Error("icon URL is not allowed"));return}const fetchTarget=resolveOwnerFetchTarget(this,safeSource);if(!fetchTarget){await this.fail("load",generation,safeSource,new Error("icon URL is not available"));return}let lease;try{lease=acquireSanitizedIconResource(fetchTarget),this.resourceLease=lease;const canonical=await lease.promise;if(!this.isConnected||generation!==this.generation)return;if(!canonical){if(this.fetchState={kind:"empty"},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource});return}const node=this.ownerDocument.importNode(canonical,!0);if(library?.mutator?.(node),!this.isConnected||generation!==this.generation||(this.fetchState={kind:"loaded",node},await this.updateComplete,!this.isConnected||generation!==this.generation))return;this.emit("lr-load",{src:safeSource})}catch(error){const reason=error instanceof IconResourceError?error.reason:"load";await this.fail(reason,generation,safeSource,error)}finally{this.resourceLease===lease&&(this.resourceLease=void 0),lease?.release()}}async fail(reason,generation,src,error){!this.isConnected||generation!==this.generation||(this.fetchState={kind:"error",reason},await this.updateComplete,!(!this.isConnected||generation!==this.generation)&&(isAccessibilityVisible(this)&&this.errorAnnouncementSink?.announce(this.errorMessage(reason)),this.emit("lr-error",{src,error})))}errorMessage(reason){return reason==="sanitizer"?this.localize("iconSanitizerMissing"):reason==="too-large"?this.localize("iconTooLarge"):this.localize("iconLoadError")}applyRemoteA11y(){const state2=this.fetchState;if(state2.kind==="loaded"){state2.node.setAttribute("part","svg"),state2.node.setAttribute("focusable","false"),state2.node.setAttribute("aria-hidden","true"),state2.node.removeAttribute("aria-label");for(const use of state2.node.querySelectorAll("use")){const parts=new Set((use.getAttribute("part")??"").split(/\s+/).filter(Boolean));parts.add("use"),use.setAttribute("part",[...parts].join(" "))}}}renderBuiltIn(){const path=this.path||PATHS[this.name]||"";return html`<svg
|
|
2
2
|
part="svg"
|
|
3
3
|
viewBox="0 0 24 24"
|
|
4
4
|
fill="none"
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraSearchChangeDetail}from'../../../internal/text-viewer-target.js';import type{LyraHierarchySource,LyraHierarchyQuery,LyraInspectionNode}from'../../../data-sources.js';export type JsonViewerTreeSource=LyraHierarchySource<LyraInspectionNode,LyraHierarchyQuery>;import{type LyraClipboardWriteFailure,type LyraClipboardWriteSuccess}from'../../../internal/clipboard.js';
|
|
1
|
+
import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraSearchChangeDetail}from'../../../internal/text-viewer-target.js';import type{LyraHierarchySource,LyraHierarchyQuery,LyraInspectionNode}from'../../../data-sources.js';export type JsonViewerTreeSource=LyraHierarchySource<LyraInspectionNode,LyraHierarchyQuery>;import{type LyraClipboardWriteFailure,type LyraClipboardWriteSuccess}from'../../../internal/clipboard.js';
|
|
2
|
+
/** How a scalar row places its key and value; see `LyraJsonViewer.layout`.*/
|
|
3
|
+
export type LyraJsonViewerLayout='auto'|'inline'|'stacked';export interface LyraJsonViewerEventMap{'lr-copy':CustomEvent<LyraClipboardWriteSuccess>;'lr-error':CustomEvent<null>;'lr-copy-error':CustomEvent<LyraClipboardWriteFailure>;'lr-search-change':CustomEvent<LyraSearchChangeDetail>;}
|
|
2
4
|
/**
|
|
3
5
|
* `<lr-json-viewer>` — a collapsible, copyable tree view for an arbitrary
|
|
4
6
|
* JSON-serializable value (object/array/string/number/boolean/null/
|
|
@@ -85,6 +87,19 @@ expandDepth?:number;
|
|
|
85
87
|
/** A CSS length (e.g. `"20rem"`); once set, the viewer scrolls internally past this height
|
|
86
88
|
* instead of growing the page. Invalid values are ignored. */
|
|
87
89
|
maxHeight:string;
|
|
90
|
+
/**
|
|
91
|
+
* How a scalar row places its key and value.
|
|
92
|
+
*
|
|
93
|
+
* `'auto'` (the default) keeps them side by side while the viewer's own inline size is at least
|
|
94
|
+
* 30rem and switches to the stacked layout below that, through a container query on the
|
|
95
|
+
* viewer's allocation, not the viewport. `'stacked'` always puts the value on its own line under
|
|
96
|
+
* its key and tightens rows: leaf rows lose the icon-button-sized floor their hidden toggle
|
|
97
|
+
* spacer otherwise imposes, and lines use the snug line height. Real expand/collapse toggles keep
|
|
98
|
+
* their full hit area. `'inline'` keeps the side-by-side row at every width. Unknown values
|
|
99
|
+
* fall back to `'auto'`. Applies to the `data` tree; `treeSource` rows keep their fixed
|
|
100
|
+
* virtualized layout.
|
|
101
|
+
*/
|
|
102
|
+
layout:LyraJsonViewerLayout;
|
|
88
103
|
/** Shows copy-to-clipboard affordances: one for the whole value, plus one per node.*/
|
|
89
104
|
copyable:boolean;
|
|
90
105
|
/** Removing the attribute clears search without changing its null readback. Case-insensitive substring match against keys/values; matches are highlighted and their ancestors auto-expanded. See also `runSearch()`/`searchNext()`/`searchPrevious()`/`clearSearch()` for imperative, cursor-navigable search built on top of this property.*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{ref}from"lit/directives/ref.js";import{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount}from"../../../internal/numbers.js";import{viewerSearchDetail}from"../../../internal/viewer-search.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{styles}from"./json-viewer.styles.js";import{HierarchySourceController,hierarchyField}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";const INSPECTION_KINDS=new Set(["object","array","scalar","element","attribute","text","comment","processing-instruction"]);import{sanitizeCssLength}from"../../../internal/safe-css.js";import{writeClipboardText,clipboardFailureReason}from"../../../internal/clipboard.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_sourceSearchUnavailable,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_circularReference,LYRA_DEFAULT_copyJson,LYRA_DEFAULT_jsonArray,LYRA_DEFAULT_jsonCollapseLabel,LYRA_DEFAULT_jsonCopyLabel,LYRA_DEFAULT_jsonExpandLabel,LYRA_DEFAULT_jsonItemCount,LYRA_DEFAULT_jsonKeyCount,LYRA_DEFAULT_jsonObject,LYRA_DEFAULT_jsonValue,LYRA_DEFAULT_jsonViewerLimit}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,MAX_JSON_NODES=5e3,MAX_JSON_DEPTH=100,OMIT_JSON_SNAPSHOT=Symbol("omit-json-viewer-snapshot"),EMPTY_SEARCH={keyMatches:new Set,valueMatches:new Set,forceExpand:new Set,paths:new Set,orderedMatches:[],truncated:!1};function isArrayContainer(value){try{return Array.isArray(value)}catch{return!1}}function isSnapshotArray(value){return Array.isArray(value)}function snapshotJsonData(value,maxNodes){const budget={remainingNodes:maxNodes,remainingInspections:maxNodes*2,truncated:!1},projected=snapshotJsonValue(value,budget,new WeakMap,0);return Object.freeze({value:projected===OMIT_JSON_SNAPSHOT?void 0:projected,truncated:budget.truncated||projected===OMIT_JSON_SNAPSHOT})}function snapshotJsonValue(value,budget,copies,depth){if(budget.remainingNodes-=1,value==null||typeof value=="string"||typeof value=="number"||typeof value=="boolean"||typeof value=="bigint")return value;if(typeof value!="object")return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const source=value,existing=copies.get(source);if(existing)return existing;const array=isArrayContainer(source);if(depth>=MAX_JSON_DEPTH){budget.truncated=!0;const shell=array?[]:Object.create(null);return copies.set(source,shell),Object.freeze(shell)}return array?snapshotJsonArray(source,budget,copies,depth):snapshotJsonObject(source,budget,copies,depth)}function snapshotJsonArray(source,budget,copies,depth){const length=getOwnDataDescriptor(source,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const projected=[];copies.set(source,projected);let retainedLength=0;const count=Math.min(length.value,budget.remainingInspections);count<length.value&&(budget.truncated=!0);for(let index=0;index<count;index+=1){if(budget.remainingNodes<=0||budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1,retainedLength=index+1;const descriptor=getOwnDataDescriptor(source,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){budget.truncated=!0;continue}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}projected[index]=child}return projected.length=retainedLength,Object.freeze(projected)}function snapshotJsonObject(source,budget,copies,depth){const projected=Object.create(null);copies.set(source,projected);let keys;try{keys=Object.getOwnPropertyNames(source)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}try{for(const key of keys){if(budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1;const descriptor=getOwnDataDescriptor(source,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable){descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&(budget.truncated=!0);continue}if(budget.remainingNodes<=0){budget.truncated=!0;break}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}Object.defineProperty(projected,key,{value:child,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function entriesOf(value,limit){const entries=[];if(isSnapshotArray(value)){const total2=value.length,count=Math.min(total2,limit);for(let index=0;index<count;index+=1)entries.push([index,Object.hasOwn(value,index)?value[index]:void 0]);return{entries,truncated:total2>count,total:total2,exact:!0}}const record=value;let total=0;for(const key in record)total+=1,entries.length<limit&&entries.push([key,record[key]]);return{entries,truncated:total>entries.length,total,exact:!0}}function valueType(value){if(value===null)return"null";if(value===void 0)return"undefined";if(isSnapshotArray(value))return"array";const t=typeof value;return t==="string"||t==="number"||t==="boolean"?t:t==="object"?"object":"string"}function formatPrimitive(value,type){return type==="string"&&typeof value=="string"?JSON.stringify(value):String(value)}class LyraJsonViewer extends LyraElement{constructor(){super(...arguments),this.sourceMode=!1,this.sourceSearchDirty=!0,this.sourceSearchIntent=0,this.sourceCopyIntent=0,this.sourceNavigationIntent=0,this.sourceSearchTask=Promise.resolve(0),this.sourceHitKeys=new Set,this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.hierarchy=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceNode(value,key),onChange:()=>this.requestUpdate("sourceState",null),accepted:()=>{},payload:{maxUnits:2e6,maxRowUnits:327702,unitsOf:node=>node.name.length+node.path.length+(node.value?.length??0)+node.kind.length}}),this.maxNodes=5e3,this.maxHeight="",this.copyable=!1,this.query="",this.expandedOverrides=new Map,this.activeSearchIndex=-1,this.searchState=EMPTY_SEARCH,this.searchLocale="",this.dataSnapshot=void 0,this.dataSnapshotTruncated=!1,this.explicitRefresh=0,this.matchElements=new Map,this.searchAnnouncementsArmed=!1,this.searchAnnouncementGeneration=0,this.copyFeedback=null}static{this.defaultStrings={...super.defaultStrings,circularReference:LYRA_DEFAULT_circularReference,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,copyJson:LYRA_DEFAULT_copyJson,expand:LYRA_DEFAULT_expand,jsonArray:LYRA_DEFAULT_jsonArray,jsonCollapseLabel:LYRA_DEFAULT_jsonCollapseLabel,jsonCopyLabel:LYRA_DEFAULT_jsonCopyLabel,jsonExpandLabel:LYRA_DEFAULT_jsonExpandLabel,jsonItemCount:LYRA_DEFAULT_jsonItemCount,jsonKeyCount:LYRA_DEFAULT_jsonKeyCount,jsonObject:LYRA_DEFAULT_jsonObject,jsonValue:LYRA_DEFAULT_jsonValue,jsonViewerLimit:LYRA_DEFAULT_jsonViewerLimit,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,sourceSearchUnavailable:LYRA_DEFAULT_sourceSearchUnavailable,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,hierarchySourceStyles,styles,srOnly]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.invalidateSourceSearch(),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.sourceNavigationIntent++,this.treeSource===void 0?Promise.resolve(!1):this.hierarchy.reveal(key)}syncSource(force=!1){if(!this.hierarchy)return;const source=this.treeSource,query=this.query??"",locale=this.effectiveLocale,binding=this.sourceBinding;source===void 0&&!this.sourceMode&&binding?.source===void 0||!force&&binding&&binding.source===source&&binding.query===query&&binding.locale===locale||(this.invalidateSourceSearch(),this.hierarchy.update(source,locale,force,{search:query,hiddenKinds:[]}),source===this.treeSource&&query===(this.query??"")&&locale===this.effectiveLocale&&(this.sourceBinding={source,query,locale}))}normalizeSourceNode(value,key){const name=hierarchyField(value,"name"),path=hierarchyField(value,"path"),kind=hierarchyField(value,"kind"),text=hierarchyField(value,"value");if(typeof name!="string"||name.length>65536||typeof path!="string"||path.length>65536||path!==key||typeof kind!="string"||!INSPECTION_KINDS.has(kind)||text!==void 0&&(typeof text!="string"||text.length>65536))throw new TypeError("Invalid inspection node");return Object.freeze({name,path,kind,...text===void 0?{}:{value:text}})}invalidateSourceSearch(){this.sourceSearchIntent=(this.sourceSearchIntent??0)+1,this.sourceCopyIntent=(this.sourceCopyIntent??0)+1,this.sourceNavigationIntent=(this.sourceNavigationIntent??0)+1,this.sourceHits=void 0,this.sourceHitKeys?.clear(),this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.sourceSearchDirty=!0,this.activeSearchIndex!==void 0&&(this._treeSource!==void 0||this.sourceMode)&&(this.activeSearchIndex=-1),this.copyFeedback!==void 0&&this.clearCopyFeedback()}async searchSource(){this.sourceSearchDirty=!1;const intent=this.sourceSearchIntent,provider=this.treeSource;if(!(this.query??""))return this.hierarchy.cancelSearch(),this.hasUpdated&&this.emitSearchChange(),0;const result=await this.hierarchy.search();return intent!==this.sourceSearchIntent||provider!==this.treeSource||!this.isConnected||result.status==="stale"||result.status==="ready"&&!result.isCurrent()?0:(this.sourceHits=result.status==="ready"?result:void 0,this.sourceHitKeys=new Set(this.sourceHits?.value.hits.map(hit=>hit.key)??[]),this.sourceSearchExact=result.status==="ready"&&result.value.exhaustive,this.sourceSearchUnavailable=result.status!=="ready",this.requestUpdate("sourceSearchResult",null),this.emitSearchChange(),await this.updateComplete,intent===this.sourceSearchIntent?this.sourceHitKeys.size:0)}async stepSourceSearch(direction){const navigation=++this.sourceNavigationIntent,hits=this.sourceHits;if(!hits?.isCurrent()||!hits.value.hits.length)return!1;const size=hits.value.hits.length;this.activeSearchIndex=this.activeSearchIndex<0?direction===1?0:size-1:(this.activeSearchIndex+direction+size)%size;const found=await this.hierarchy.reveal(hits.value.hits[this.activeSearchIndex].key);return!found||navigation!==this.sourceNavigationIntent||!hits.isCurrent()||this.sourceHits!==hits?!1:(this.emitSearchChange(),found)}sourceSummary(){const projection=this.hierarchy.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}hasSourceCopy(){const source=this.treeSource;try{const available=typeof source?.copy=="function";return source===this.treeSource&&available}catch{return!1}}async copySource(key,scope){const source=this.treeSource,epoch=this.hierarchy.epoch,owner=this.ownerDocument,intent=++this.sourceCopyIntent,current=()=>this.treeSource===source&&this.hierarchy.epoch===epoch&&this.ownerDocument===owner&&this.isConnected&&intent===this.sourceCopyIntent;this.clearCopyFeedback();const result=await this.hierarchy.copy(key,scope,25*1024*1024);if(!current()||result.status==="stale")return;const feedback=key??"toolbar";if(result.status!=="ready"){this.showCopyFeedback(feedback,!1);const message=this.localize("copyFailed");current()&&this.searchAnnouncementSink?.announce(message);return}const accepted=()=>current()&&result.isCurrent();if(!accepted())return;let outcome;try{const clipboard=owner.defaultView?.navigator.clipboard,write=clipboard?.writeText;if(!accepted())return;typeof write!="function"?outcome=Object.freeze({ok:!1,text:result.value,reason:"unsupported",error:new Error("Clipboard is unavailable")}):(await write.call(clipboard,result.value),outcome=Object.freeze({ok:!0,text:result.value}))}catch(error){outcome=Object.freeze({ok:!1,text:result.value,reason:clipboardFailureReason(error),error})}if(accepted())if(this.showCopyFeedback(feedback,outcome.ok),outcome.ok){const message=this.localize("copied");if(!accepted())return;this.searchAnnouncementSink?.announce(message),accepted()&&this.emit("lr-copy",outcome)}else{const message=this.localize("copyFailed");if(!accepted()||(this.searchAnnouncementSink?.announce(message),!accepted()))return;this.emit("lr-error"),accepted()&&this.emit("lr-copy-error",outcome)}}sourceCopyButton(node){if(!this.copyable||!this.hasSourceCopy())return nothing;const source=this.treeSource,epoch=this.hierarchy.epoch,key=node?.path??null,projection=this.hierarchy.projection,label=node?this.localize("jsonCopyLabel",void 0,{label:node.name}):this.localize("copyJson");return html`<button part="copy-button" type="button" aria-label=${this.copyLabel(key??"toolbar",label)}
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{ref}from"lit/directives/ref.js";import{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{viewerSearchDetail}from"../../../internal/viewer-search.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{styles}from"./json-viewer.styles.js";import{HierarchySourceController,hierarchyField}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";const INSPECTION_KINDS=new Set(["object","array","scalar","element","attribute","text","comment","processing-instruction"]);import{sanitizeCssLength}from"../../../internal/safe-css.js";import{writeClipboardText,clipboardFailureReason}from"../../../internal/clipboard.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_sourceSearchUnavailable,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_circularReference,LYRA_DEFAULT_copyJson,LYRA_DEFAULT_jsonArray,LYRA_DEFAULT_jsonCollapseLabel,LYRA_DEFAULT_jsonCopyLabel,LYRA_DEFAULT_jsonExpandLabel,LYRA_DEFAULT_jsonItemCount,LYRA_DEFAULT_jsonKeyCount,LYRA_DEFAULT_jsonObject,LYRA_DEFAULT_jsonValue,LYRA_DEFAULT_jsonViewerLimit}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,MAX_JSON_NODES=5e3,MAX_JSON_DEPTH=100,OMIT_JSON_SNAPSHOT=Symbol("omit-json-viewer-snapshot"),EMPTY_SEARCH={keyMatches:new Set,valueMatches:new Set,forceExpand:new Set,paths:new Set,orderedMatches:[],truncated:!1};function isArrayContainer(value){try{return Array.isArray(value)}catch{return!1}}function isSnapshotArray(value){return Array.isArray(value)}function snapshotJsonData(value,maxNodes){const budget={remainingNodes:maxNodes,remainingInspections:maxNodes*2,truncated:!1},projected=snapshotJsonValue(value,budget,new WeakMap,0);return Object.freeze({value:projected===OMIT_JSON_SNAPSHOT?void 0:projected,truncated:budget.truncated||projected===OMIT_JSON_SNAPSHOT})}function snapshotJsonValue(value,budget,copies,depth){if(budget.remainingNodes-=1,value==null||typeof value=="string"||typeof value=="number"||typeof value=="boolean"||typeof value=="bigint")return value;if(typeof value!="object")return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const source=value,existing=copies.get(source);if(existing)return existing;const array=isArrayContainer(source);if(depth>=MAX_JSON_DEPTH){budget.truncated=!0;const shell=array?[]:Object.create(null);return copies.set(source,shell),Object.freeze(shell)}return array?snapshotJsonArray(source,budget,copies,depth):snapshotJsonObject(source,budget,copies,depth)}function snapshotJsonArray(source,budget,copies,depth){const length=getOwnDataDescriptor(source,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const projected=[];copies.set(source,projected);let retainedLength=0;const count=Math.min(length.value,budget.remainingInspections);count<length.value&&(budget.truncated=!0);for(let index=0;index<count;index+=1){if(budget.remainingNodes<=0||budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1,retainedLength=index+1;const descriptor=getOwnDataDescriptor(source,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){budget.truncated=!0;continue}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}projected[index]=child}return projected.length=retainedLength,Object.freeze(projected)}function snapshotJsonObject(source,budget,copies,depth){const projected=Object.create(null);copies.set(source,projected);let keys;try{keys=Object.getOwnPropertyNames(source)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}try{for(const key of keys){if(budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1;const descriptor=getOwnDataDescriptor(source,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable){descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&(budget.truncated=!0);continue}if(budget.remainingNodes<=0){budget.truncated=!0;break}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}Object.defineProperty(projected,key,{value:child,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function entriesOf(value,limit){const entries=[];if(isSnapshotArray(value)){const total2=value.length,count=Math.min(total2,limit);for(let index=0;index<count;index+=1)entries.push([index,Object.hasOwn(value,index)?value[index]:void 0]);return{entries,truncated:total2>count,total:total2,exact:!0}}const record=value;let total=0;for(const key in record)total+=1,entries.length<limit&&entries.push([key,record[key]]);return{entries,truncated:total>entries.length,total,exact:!0}}function valueType(value){if(value===null)return"null";if(value===void 0)return"undefined";if(isSnapshotArray(value))return"array";const t=typeof value;return t==="string"||t==="number"||t==="boolean"?t:t==="object"?"object":"string"}const JSON_VIEWER_LAYOUT=literalSetConverter(["auto","inline","stacked"],"auto"),KEY_BREAK_POINT=/(?<=[_\-./:@])(?=.)|(?<=\p{Ll})(?=\p{Lu})/u;function keyWithBreaks(label){const segments=label.split(KEY_BREAK_POINT);return segments.length<2?label:segments.map((segment,index)=>index===0?segment:html`<wbr>${segment}`)}function formatPrimitive(value,type){return type==="string"&&typeof value=="string"?JSON.stringify(value):String(value)}class LyraJsonViewer extends LyraElement{constructor(){super(...arguments),this.sourceMode=!1,this.sourceSearchDirty=!0,this.sourceSearchIntent=0,this.sourceCopyIntent=0,this.sourceNavigationIntent=0,this.sourceSearchTask=Promise.resolve(0),this.sourceHitKeys=new Set,this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.hierarchy=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceNode(value,key),onChange:()=>this.requestUpdate("sourceState",null),accepted:()=>{},payload:{maxUnits:2e6,maxRowUnits:327702,unitsOf:node=>node.name.length+node.path.length+(node.value?.length??0)+node.kind.length}}),this.maxNodes=5e3,this.maxHeight="",this.layout="auto",this.copyable=!1,this.query="",this.expandedOverrides=new Map,this.activeSearchIndex=-1,this.searchState=EMPTY_SEARCH,this.searchLocale="",this.dataSnapshot=void 0,this.dataSnapshotTruncated=!1,this.explicitRefresh=0,this.matchElements=new Map,this.searchAnnouncementsArmed=!1,this.searchAnnouncementGeneration=0,this.copyFeedback=null}static{this.defaultStrings={...super.defaultStrings,circularReference:LYRA_DEFAULT_circularReference,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,copyJson:LYRA_DEFAULT_copyJson,expand:LYRA_DEFAULT_expand,jsonArray:LYRA_DEFAULT_jsonArray,jsonCollapseLabel:LYRA_DEFAULT_jsonCollapseLabel,jsonCopyLabel:LYRA_DEFAULT_jsonCopyLabel,jsonExpandLabel:LYRA_DEFAULT_jsonExpandLabel,jsonItemCount:LYRA_DEFAULT_jsonItemCount,jsonKeyCount:LYRA_DEFAULT_jsonKeyCount,jsonObject:LYRA_DEFAULT_jsonObject,jsonValue:LYRA_DEFAULT_jsonValue,jsonViewerLimit:LYRA_DEFAULT_jsonViewerLimit,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,sourceSearchUnavailable:LYRA_DEFAULT_sourceSearchUnavailable,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,hierarchySourceStyles,styles,srOnly]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.invalidateSourceSearch(),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.sourceNavigationIntent++,this.treeSource===void 0?Promise.resolve(!1):this.hierarchy.reveal(key)}syncSource(force=!1){if(!this.hierarchy)return;const source=this.treeSource,query=this.query??"",locale=this.effectiveLocale,binding=this.sourceBinding;source===void 0&&!this.sourceMode&&binding?.source===void 0||!force&&binding&&binding.source===source&&binding.query===query&&binding.locale===locale||(this.invalidateSourceSearch(),this.hierarchy.update(source,locale,force,{search:query,hiddenKinds:[]}),source===this.treeSource&&query===(this.query??"")&&locale===this.effectiveLocale&&(this.sourceBinding={source,query,locale}))}normalizeSourceNode(value,key){const name=hierarchyField(value,"name"),path=hierarchyField(value,"path"),kind=hierarchyField(value,"kind"),text=hierarchyField(value,"value");if(typeof name!="string"||name.length>65536||typeof path!="string"||path.length>65536||path!==key||typeof kind!="string"||!INSPECTION_KINDS.has(kind)||text!==void 0&&(typeof text!="string"||text.length>65536))throw new TypeError("Invalid inspection node");return Object.freeze({name,path,kind,...text===void 0?{}:{value:text}})}invalidateSourceSearch(){this.sourceSearchIntent=(this.sourceSearchIntent??0)+1,this.sourceCopyIntent=(this.sourceCopyIntent??0)+1,this.sourceNavigationIntent=(this.sourceNavigationIntent??0)+1,this.sourceHits=void 0,this.sourceHitKeys?.clear(),this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.sourceSearchDirty=!0,this.activeSearchIndex!==void 0&&(this._treeSource!==void 0||this.sourceMode)&&(this.activeSearchIndex=-1),this.copyFeedback!==void 0&&this.clearCopyFeedback()}async searchSource(){this.sourceSearchDirty=!1;const intent=this.sourceSearchIntent,provider=this.treeSource;if(!(this.query??""))return this.hierarchy.cancelSearch(),this.hasUpdated&&this.emitSearchChange(),0;const result=await this.hierarchy.search();return intent!==this.sourceSearchIntent||provider!==this.treeSource||!this.isConnected||result.status==="stale"||result.status==="ready"&&!result.isCurrent()?0:(this.sourceHits=result.status==="ready"?result:void 0,this.sourceHitKeys=new Set(this.sourceHits?.value.hits.map(hit=>hit.key)??[]),this.sourceSearchExact=result.status==="ready"&&result.value.exhaustive,this.sourceSearchUnavailable=result.status!=="ready",this.requestUpdate("sourceSearchResult",null),this.emitSearchChange(),await this.updateComplete,intent===this.sourceSearchIntent?this.sourceHitKeys.size:0)}async stepSourceSearch(direction){const navigation=++this.sourceNavigationIntent,hits=this.sourceHits;if(!hits?.isCurrent()||!hits.value.hits.length)return!1;const size=hits.value.hits.length;this.activeSearchIndex=this.activeSearchIndex<0?direction===1?0:size-1:(this.activeSearchIndex+direction+size)%size;const found=await this.hierarchy.reveal(hits.value.hits[this.activeSearchIndex].key);return!found||navigation!==this.sourceNavigationIntent||!hits.isCurrent()||this.sourceHits!==hits?!1:(this.emitSearchChange(),found)}sourceSummary(){const projection=this.hierarchy.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}hasSourceCopy(){const source=this.treeSource;try{const available=typeof source?.copy=="function";return source===this.treeSource&&available}catch{return!1}}async copySource(key,scope){const source=this.treeSource,epoch=this.hierarchy.epoch,owner=this.ownerDocument,intent=++this.sourceCopyIntent,current=()=>this.treeSource===source&&this.hierarchy.epoch===epoch&&this.ownerDocument===owner&&this.isConnected&&intent===this.sourceCopyIntent;this.clearCopyFeedback();const result=await this.hierarchy.copy(key,scope,25*1024*1024);if(!current()||result.status==="stale")return;const feedback=key??"toolbar";if(result.status!=="ready"){this.showCopyFeedback(feedback,!1);const message=this.localize("copyFailed");current()&&this.searchAnnouncementSink?.announce(message);return}const accepted=()=>current()&&result.isCurrent();if(!accepted())return;let outcome;try{const clipboard=owner.defaultView?.navigator.clipboard,write=clipboard?.writeText;if(!accepted())return;typeof write!="function"?outcome=Object.freeze({ok:!1,text:result.value,reason:"unsupported",error:new Error("Clipboard is unavailable")}):(await write.call(clipboard,result.value),outcome=Object.freeze({ok:!0,text:result.value}))}catch(error){outcome=Object.freeze({ok:!1,text:result.value,reason:clipboardFailureReason(error),error})}if(accepted())if(this.showCopyFeedback(feedback,outcome.ok),outcome.ok){const message=this.localize("copied");if(!accepted())return;this.searchAnnouncementSink?.announce(message),accepted()&&this.emit("lr-copy",outcome)}else{const message=this.localize("copyFailed");if(!accepted()||(this.searchAnnouncementSink?.announce(message),!accepted()))return;this.emit("lr-error"),accepted()&&this.emit("lr-copy-error",outcome)}}sourceCopyButton(node){if(!this.copyable||!this.hasSourceCopy())return nothing;const source=this.treeSource,epoch=this.hierarchy.epoch,key=node?.path??null,projection=this.hierarchy.projection,label=node?this.localize("jsonCopyLabel",void 0,{label:node.name}):this.localize("copyJson");return html`<button part="copy-button" type="button" aria-label=${this.copyLabel(key??"toolbar",label)}
|
|
2
2
|
@keydown=${event=>event.stopPropagation()}
|
|
3
3
|
@click=${event=>{event.stopPropagation();const button=event.currentTarget;button.isConnected&&button.getRootNode()===this.renderRoot&&!this.hierarchy.loading&&projection===this.hierarchy.projection&&source===this.treeSource&&epoch===this.hierarchy.epoch&&this.copySource(key,node?node.kind==="object"||node.kind==="array"||node.kind==="element"?"subtree":"node":"document")}}>${this.copyLabel(key??"toolbar",this.localize("copy"))}</button>`}renderSourceNode(node){const match=this.sourceHits?.isCurrent()&&this.sourceHitKeys.has(node.path),active=this.sourceHits?.value.hits[this.activeSearchIndex]?.key===node.path;return html`<span part="key" ?data-match=${match} ?data-active=${active}>${node.name}</span><span aria-hidden="true">:</span><span
|
|
4
4
|
part="value" data-type=${node.kind==="scalar"?"string":node.kind} ?data-match=${match} ?data-active=${active}>${node.value??node.kind}</span>${this.sourceCopyButton(node)}`}renderSource(){const partial=!this.sourceSearchExact&&!!this.query,count=this.sourceHitKeys.size;return html`<div class="source-shell" style=${styleMap({"--lr-json-viewer-max-height":sanitizeCssLength(this.maxHeight)??"var(--lr-size-20rem)"})}>
|
|
@@ -34,7 +34,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
|
|
|
34
34
|
?data-match=${search.keyMatches.has(pathKey)}
|
|
35
35
|
?data-active=${!!activeMatch&&activeMatch.pathKey===pathKey&&activeMatch.kind==="key"}
|
|
36
36
|
aria-current=${activeMatch&&activeMatch.pathKey===pathKey&&activeMatch.kind==="key"?"true":"false"}
|
|
37
|
-
>${keyLabel}</span
|
|
37
|
+
>${keyWithBreaks(keyLabel)}</span
|
|
38
38
|
><span class="colon">:</span>`:nothing}
|
|
39
39
|
${isCircular?html`
|
|
40
40
|
<span part="bracket">${openBracket}</span>
|
|
@@ -83,8 +83,8 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
|
|
|
83
83
|
${this.copyLabel("toolbar",this.localize("copy"))}
|
|
84
84
|
</button>
|
|
85
85
|
</div>`:nothing}
|
|
86
|
-
<div part="tree" role="list" aria-label=${hostAriaLabel(this)??nothing}>${tree}</div>
|
|
86
|
+
<div part="tree" role="list" data-layout=${JSON_VIEWER_LAYOUT.normalize(this.layout)} aria-label=${hostAriaLabel(this)??nothing}>${tree}</div>
|
|
87
87
|
${limited?html`<p part="limit">${this.localize("jsonViewerLimit",void 0,{count:getNumberFormat(this.effectiveLocale).format(this.effectiveMaxNodes),depth:getNumberFormat(this.effectiveLocale).format(MAX_JSON_DEPTH)})}</p>`:nothing}
|
|
88
88
|
<span class="sr-only" aria-hidden="true">${this.activeSearchAnnouncement()}</span>
|
|
89
89
|
</div>
|
|
90
|
-
`}}__decorate([property({attribute:!1})],LyraJsonViewer.prototype,"treeSource",null),__decorate([property({type:Number,attribute:"max-nodes"})],LyraJsonViewer.prototype,"maxNodes",void 0),__decorate([property({attribute:!1})],LyraJsonViewer.prototype,"data",void 0),__decorate([property({type:Number,attribute:"expand-depth"})],LyraJsonViewer.prototype,"expandDepth",void 0),__decorate([property({attribute:"max-height"})],LyraJsonViewer.prototype,"maxHeight",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraJsonViewer.prototype,"copyable",void 0),__decorate([property()],LyraJsonViewer.prototype,"query",void 0),__decorate([state()],LyraJsonViewer.prototype,"expandedOverrides",void 0),__decorate([state()],LyraJsonViewer.prototype,"activeSearchIndex",void 0),__decorate([state()],LyraJsonViewer.prototype,"copyFeedback",void 0);export{LyraJsonViewer};
|
|
90
|
+
`}}__decorate([property({attribute:!1})],LyraJsonViewer.prototype,"treeSource",null),__decorate([property({type:Number,attribute:"max-nodes"})],LyraJsonViewer.prototype,"maxNodes",void 0),__decorate([property({attribute:!1})],LyraJsonViewer.prototype,"data",void 0),__decorate([property({type:Number,attribute:"expand-depth"})],LyraJsonViewer.prototype,"expandDepth",void 0),__decorate([property({attribute:"max-height"})],LyraJsonViewer.prototype,"maxHeight",void 0),__decorate([property({converter:JSON_VIEWER_LAYOUT})],LyraJsonViewer.prototype,"layout",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraJsonViewer.prototype,"copyable",void 0),__decorate([property()],LyraJsonViewer.prototype,"query",void 0),__decorate([state()],LyraJsonViewer.prototype,"expandedOverrides",void 0),__decorate([state()],LyraJsonViewer.prototype,"activeSearchIndex",void 0),__decorate([state()],LyraJsonViewer.prototype,"copyFeedback",void 0);export{LyraJsonViewer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; --_lr-json-viewer-max-height: none; --_lr-json-viewer-font: var(--lr-font-mono); --_lr-json-viewer-active-outline: var(--lr-focus-ring-color); --_lr-json-viewer-string-color: var(--lr-color-success); --_lr-json-viewer-number-color: var(--lr-color-brand); --_lr-json-viewer-boolean-color: var(--lr-color-warning); --_lr-json-viewer-null-color: var(--lr-color-text-quiet); font-family: var(--lr-json-viewer-font, var(--_lr-json-viewer-font)); font-size: var(--lr-font-size-sm); line-height: var(--lr-line-height-loose); white-space: normal; } .source-shell { min-inline-size: 0; } .source-shell .source-tree { block-size: var(--lr-json-viewer-max-height, var(--lr-size-20rem)); max-block-size: var(--lr-json-viewer-max-height, var(--lr-size-20rem)); } .source-shell [part~='source-list'] { block-size: 100%; } [part='search-status'] { padding: var(--lr-space-xs); color: var(--lr-color-text-quiet); } [part="base"] { display: block; max-block-size: var( --lr-json-viewer-max-height, var(--_lr-json-viewer-max-height) ); overflow: auto; border: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); border-radius: var(--lr-radius); background: var(--lr-color-surface); } [part="toolbar"] { position: sticky; inset-block-start: 0; z-index: var(--lr-layer-content); display: flex; justify-content: flex-end; padding: var(--lr-space-xs) var(--lr-space-s); border-block-end: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); background: var(--lr-color-surface); } [part="tree"] { padding: var(--lr-space-s); direction: ltr; } .row { display: flex; align-items: flex-start; gap: var(--lr-space-xs); min-inline-size: 0; border-radius: var(--lr-radius); } .row:hover { background: var(--lr-json-viewer-row-hover-bg, var(--lr-color-brand-quiet)); } .row:hover [part="copy-button"], .row:focus-within [part="copy-button"] { opacity: 1; } [part="toggle"] { inline-size: var(--lr-size-1-25rem); block-size: var(--lr-size-1-25rem); ${iconHitTarget} margin-block-start: var(--lr-size-0-1875rem); flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; padding: 0; border: none; background: none; color: var(--lr-color-text-quiet); border-radius: var(--lr-radius); cursor: pointer; transition: var(--lr-transition-interactive); font: inherit; } [part="toggle"][hidden] { visibility: hidden; } [part="toggle"] .chevron { display: inline-flex; transform: rotate(0deg); transition: transform var(--lr-transition-fast); } [part="toggle"][aria-expanded="true"] .chevron { transform: rotate(90deg); } :where([part="toggle"]):hover:where(:not([hidden])) { background: var(--lr-color-brand-quiet); color: var(--lr-color-brand); } :where([part="toggle"]):active:where(:not([hidden])) { background: color-mix( in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); color: var(--lr-color-brand); } [part="toggle"]:focus-visible, [part="copy-button"]:focus-visible { ${focusRing} } .toggle-space { inline-size: var(--lr-icon-button-size); flex: 0 0 auto; } [part="key"] { flex: 0 1 auto; min-inline-size: 0; overflow-wrap: anywhere; font-weight: var(--lr-font-weight-semibold); color: var(--lr-color-text); } .colon { flex: 0 0 auto; color: var(--lr-color-text-quiet); margin-inline-end: var(--lr-space-xs); } [part="bracket"] { flex: 0 0 auto; color: var(--lr-color-text-quiet); } [part="key"][data-match], [part="value"][data-match] { background: var(--lr-json-viewer-match-bg, var(--lr-color-warning-quiet)); border-radius: var(--lr-size-0-1875rem); box-shadow: 0 0 0 var(--lr-size-0-125rem) var(--lr-json-viewer-match-bg, var(--lr-color-warning-quiet)); } [part="value"] { min-inline-size: 0; overflow-wrap: anywhere; word-break: break-word; white-space: pre-wrap; } [part="value"][data-type="string"] { color: var( --lr-json-viewer-string-color, var(--_lr-json-viewer-string-color) ); } [part="value"][data-type="number"] { color: var( --lr-json-viewer-number-color, var(--_lr-json-viewer-number-color) ); } [part="value"][data-type="boolean"] { color: var( --lr-json-viewer-boolean-color, var(--_lr-json-viewer-boolean-color) ); } [part="value"][data-type="null"], [part="value"][data-type="undefined"], [part="value"][data-type="circular"] { color: var(--lr-json-viewer-null-color, var(--_lr-json-viewer-null-color)); font-style: italic; } [part="key"][data-active], [part="value"][data-active] { outline: var(--lr-focus-ring-width) solid var( --lr-json-viewer-active-outline, var(--_lr-json-viewer-active-outline) ); outline-offset: var(--lr-focus-ring-offset); } .preview { flex: 0 0 auto; color: var(--lr-color-text-quiet); font-style: italic; margin-inline: var(--lr-space-xs); } [part="copy-button"] { flex: 0 0 auto; margin-inline-start: auto; border: none; background: none; color: var(--lr-color-text-quiet); font: inherit; font-size: var(--lr-font-size-xs); line-height: var(--lr-line-height-none); ${iconHitTarget} padding: var(--lr-size-0-125rem) var(--lr-space-xs); border-radius: var(--lr-radius); cursor: pointer; transition: var(--lr-transition-interactive); } [part="copy-button"]:hover { background: var(--lr-color-brand-quiet); color: var(--lr-color-brand); } [part="copy-button"]:active { background: color-mix( in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); color: var(--lr-color-brand); } .row [part="copy-button"] { opacity: 0; } .row [part="copy-button"]:focus-visible { opacity: 1; } @media (hover: none), (pointer: coarse) { .row [part="copy-button"] { opacity: 1; } } @media (prefers-reduced-motion: reduce) { [part="toggle"], [part="copy-button"], [part="toggle"] .chevron { transition: none !important; } } `;export{styles};
|
|
1
|
+
import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{mediumContainerQuery}from"../../../internal/container-breakpoints.styles.js";const styles=css` :host { display: block; --_lr-json-viewer-max-height: none; --_lr-json-viewer-font: var(--lr-font-mono); --_lr-json-viewer-active-outline: var(--lr-focus-ring-color); --_lr-json-viewer-string-color: var(--lr-color-success); --_lr-json-viewer-number-color: var(--lr-color-brand); --_lr-json-viewer-boolean-color: var(--lr-color-warning); --_lr-json-viewer-null-color: var(--lr-color-text-quiet); font-family: var(--lr-json-viewer-font, var(--_lr-json-viewer-font)); font-size: var(--lr-font-size-sm); line-height: var(--lr-line-height-loose); white-space: normal; container-type: inline-size; contain-intrinsic-inline-size: var(--lr-size-20rem); } .source-shell { min-inline-size: 0; } .source-shell .source-tree { block-size: var(--lr-json-viewer-max-height, var(--lr-size-20rem)); max-block-size: var(--lr-json-viewer-max-height, var(--lr-size-20rem)); } .source-shell [part~='source-list'] { block-size: 100%; } [part='search-status'] { padding: var(--lr-space-xs); color: var(--lr-color-text-quiet); } [part="base"] { display: block; max-block-size: var( --lr-json-viewer-max-height, var(--_lr-json-viewer-max-height) ); overflow: auto; border: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); border-radius: var(--lr-radius); background: var(--lr-color-surface); } [part="toolbar"] { position: sticky; inset-block-start: 0; z-index: var(--lr-layer-content); display: flex; justify-content: flex-end; padding: var(--lr-space-xs) var(--lr-space-s); border-block-end: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); background: var(--lr-color-surface); } [part="tree"] { padding: var(--lr-space-s); direction: ltr; } .row { display: flex; flex-wrap: var(--_lr-json-viewer-row-wrap, nowrap); align-items: flex-start; gap: var(--lr-space-xs); row-gap: 0; min-inline-size: 0; border-radius: var(--lr-radius); } [part='tree'][data-layout='stacked'] { --_lr-json-viewer-row-wrap: wrap; --_lr-json-viewer-value-basis: 100%; --_lr-json-viewer-value-indent: calc(var(--lr-icon-button-size) + var(--lr-space-xs)); --_lr-json-viewer-value-order: 1; --_lr-json-viewer-spacer-margin-block: calc(var(--lr-icon-button-size) / -2); line-height: var(--lr-line-height-snug); } @container ${mediumContainerQuery} { [part='tree'][data-layout='auto'] { --_lr-json-viewer-row-wrap: wrap; --_lr-json-viewer-value-basis: 100%; --_lr-json-viewer-value-indent: calc(var(--lr-icon-button-size) + var(--lr-space-xs)); --_lr-json-viewer-value-order: 1; --_lr-json-viewer-spacer-margin-block: calc(var(--lr-icon-button-size) / -2); line-height: var(--lr-line-height-snug); } } [part='key'] ~ [part='value'] { flex-basis: var(--_lr-json-viewer-value-basis, auto); order: var(--_lr-json-viewer-value-order, 0); margin-inline-start: var(--_lr-json-viewer-value-indent, 0); } .row:hover { background: var(--lr-json-viewer-row-hover-bg, var(--lr-color-brand-quiet)); } .row:hover [part="copy-button"], .row:focus-within [part="copy-button"] { opacity: 1; } [part="toggle"] { inline-size: var(--lr-size-1-25rem); block-size: var(--lr-size-1-25rem); ${iconHitTarget} margin-block-start: var(--lr-size-0-1875rem); flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; padding: 0; border: none; background: none; color: var(--lr-color-text-quiet); border-radius: var(--lr-radius); cursor: pointer; transition: var(--lr-transition-interactive); font: inherit; } [part="toggle"][hidden] { visibility: hidden; margin-block: var(--_lr-json-viewer-spacer-margin-block, var(--lr-size-0-1875rem) 0); } [part="toggle"] .chevron { display: inline-flex; transform: rotate(0deg); transition: transform var(--lr-transition-fast); } [part="toggle"][aria-expanded="true"] .chevron { transform: rotate(90deg); } :where([part="toggle"]):hover:where(:not([hidden])) { background: var(--lr-color-brand-quiet); color: var(--lr-color-brand); } :where([part="toggle"]):active:where(:not([hidden])) { background: color-mix( in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); color: var(--lr-color-brand); } [part="toggle"]:focus-visible, [part="copy-button"]:focus-visible { ${focusRing} } .toggle-space { inline-size: var(--lr-icon-button-size); flex: 0 0 auto; } [part="key"] { flex: 0 1 auto; min-inline-size: 0; overflow-wrap: anywhere; font-weight: var(--lr-font-weight-semibold); color: var(--lr-color-text); } .colon { flex: 0 0 auto; color: var(--lr-color-text-quiet); margin-inline-end: var(--lr-space-xs); } [part="bracket"] { flex: 0 0 auto; color: var(--lr-color-text-quiet); } [part="key"][data-match], [part="value"][data-match] { background: var(--lr-json-viewer-match-bg, var(--lr-color-warning-quiet)); border-radius: var(--lr-size-0-1875rem); box-shadow: 0 0 0 var(--lr-size-0-125rem) var(--lr-json-viewer-match-bg, var(--lr-color-warning-quiet)); } [part="value"] { min-inline-size: 0; overflow-wrap: anywhere; word-break: break-word; white-space: pre-wrap; } [part="value"][data-type="string"] { color: var( --lr-json-viewer-string-color, var(--_lr-json-viewer-string-color) ); } [part="value"][data-type="number"] { color: var( --lr-json-viewer-number-color, var(--_lr-json-viewer-number-color) ); } [part="value"][data-type="boolean"] { color: var( --lr-json-viewer-boolean-color, var(--_lr-json-viewer-boolean-color) ); } [part="value"][data-type="null"], [part="value"][data-type="undefined"], [part="value"][data-type="circular"] { color: var(--lr-json-viewer-null-color, var(--_lr-json-viewer-null-color)); font-style: italic; } [part="key"][data-active], [part="value"][data-active] { outline: var(--lr-focus-ring-width) solid var( --lr-json-viewer-active-outline, var(--_lr-json-viewer-active-outline) ); outline-offset: var(--lr-focus-ring-offset); } .preview { flex: 0 0 auto; color: var(--lr-color-text-quiet); font-style: italic; margin-inline: var(--lr-space-xs); } [part="copy-button"] { flex: 0 0 auto; margin-inline-start: auto; border: none; background: none; color: var(--lr-color-text-quiet); font: inherit; font-size: var(--lr-font-size-xs); line-height: var(--lr-line-height-none); ${iconHitTarget} padding: var(--lr-size-0-125rem) var(--lr-space-xs); border-radius: var(--lr-radius); cursor: pointer; transition: var(--lr-transition-interactive); } [part="copy-button"]:hover { background: var(--lr-color-brand-quiet); color: var(--lr-color-brand); } [part="copy-button"]:active { background: color-mix( in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); color: var(--lr-color-brand); } .row [part="copy-button"] { opacity: 0; } .row [part="copy-button"]:focus-visible { opacity: 1; } @media (hover: none), (pointer: coarse) { .row [part="copy-button"] { opacity: 1; } } @media (prefers-reduced-motion: reduce) { [part="toggle"], [part="copy-button"], [part="toggle"] .chevron { transition: none !important; } } `;export{styles};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{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{localeDateOrder,localeDigitMap,normalizeLocaleDigits}from"../../../internal/locale-date.js";import{shadowFocusTarget}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{formatISO,parseISO}from"../../forms/date-picker/calendar-core.js";import{currentValidityValidator}from"../../forms/form-validator.js";import{LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_knownDateDay,LYRA_DEFAULT_knownDateMonth,LYRA_DEFAULT_knownDateYear}from"../../../internal/default-strings/utility.generated.js";const EMPTY_PARTS={day:"",month:"",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}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}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.slotPresence=new SlotPresenceController(this),this._min="",this._max="",this._readonly=!1,this.lastCommittedValue="",this.lastEditedField="day",this.errorTextObserver=new AccessibleTextController(this,["error"],()=>this.announceVisibleError(),["slot"]),this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.connectionGeneration=0,this.onForwardedSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||(this.errorTextObserver.bind(),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.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,detail=this.detailFor(field),event=addCompatibilityDetail(new InputEventConstructor("input",{bubbles:!0,composed:!0,inputType:e.inputType||"insertText"}),detail);this.dispatchEvent(event),this.emit("lr-input",detail),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(),relayNativeEvent(this,e,{relatedTarget:this.isRenderedFieldTarget(e.relatedTarget)?null:e.relatedTarget})},this.onFieldBlur=e=>{e.stopPropagation(),this.commitChangeIfNeeded();const related=e.relatedTarget,active=shadowFocusTarget(this);e.isTrusted&&(this.isRenderedFieldTarget(related)||active!==e.target&&this.isRenderedFieldTarget(active))||(this.effectiveDisabled||(this.touched=!0),relayNativeEvent(this,e))},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.addEventListener("slotchange",this.onForwardedSlotChange),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)})}disconnectedCallback(){this.releaseExternalDescription(),this.connectionGeneration+=1,this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.removeEventListener("slotchange",this.onForwardedSlotChange),this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.errorTextObserver.adopted(),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){next!==this.partsSource&&(this.partsSource=next,this.setParts(next,!0))}setParts(next,programmatic){const old=this._parts,parts={day:String(next?.day??""),month:String(next?.month??""),year:String(next?.year??"")};programmatic&&parts.day===old.day&&parts.month===old.month&&parts.year===old.year||(this._parts=parts,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&&formatISO(parsed)===super.value||(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(){const locale=this.effectiveLocale;return this.fieldOrderCache?.locale!==locale&&(this.fieldOrderCache={locale,order:localeDateOrder(locale)}),this.fieldOrderCache.order}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,detail=this.detailFor(this.lastEditedField),event=addCompatibilityDetail(new EventConstructor("change",{bubbles:!0,composed:!0}),detail);this.dispatchEvent(event),this.emit("lr-change",detail)}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)}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 locale=this.effectiveLocale;return this.digitMapCache?.locale!==locale&&(this.digitMapCache={locale,map:localeDigitMap(locale)}),normalizeLocaleDigits(value,locale,this.digitMapCache.map).replace(/\D/g,"")}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
|
+
import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{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{localeDateOrder,localeDigitMap,normalizeLocaleDigits}from"../../../internal/locale-date.js";import{shadowFocusTarget}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{formatISO,parseISO}from"../../forms/date-picker/calendar-core.js";import{currentValidityValidator}from"../../forms/form-validator.js";import{LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_knownDateDay,LYRA_DEFAULT_knownDateMonth,LYRA_DEFAULT_knownDateYear}from"../../../internal/default-strings/utility.generated.js";const EMPTY_PARTS={day:"",month:"",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}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}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.slotPresence=new SlotPresenceController(this),this._min="",this._max="",this._readonly=!1,this.lastCommittedValue="",this.lastEditedField="day",this.errorTextObserver=new AccessibleTextController(this,["error"],()=>this.announceVisibleError(),["slot"]),this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.connectionGeneration=0,this.onForwardedSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||(this.errorTextObserver.bind(),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.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,detail=this.detailFor(field),event=addCompatibilityDetail(new InputEventConstructor("input",{bubbles:!0,composed:!0,inputType:e.inputType||"insertText"}),detail);this.dispatchEvent(event),this.emit("lr-input",detail),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(),relayNativeEvent(this,e,{relatedTarget:this.isRenderedFieldTarget(e.relatedTarget)?null:e.relatedTarget})},this.onFieldBlur=e=>{e.stopPropagation(),this.commitChangeIfNeeded();const related=e.relatedTarget,active=shadowFocusTarget(this);e.isTrusted&&(this.isRenderedFieldTarget(related)||active!==e.target&&this.isRenderedFieldTarget(active))||(this.effectiveDisabled||(this.touched=!0),relayNativeEvent(this,e))},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.addEventListener("slotchange",this.onForwardedSlotChange),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)})}disconnectedCallback(){this.releaseExternalDescription(),this.connectionGeneration+=1,this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.removeEventListener("slotchange",this.onForwardedSlotChange),this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.errorTextObserver.adopted(),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){next!==this.partsSource&&(this.partsSource=next,this.setParts(next,!0))}setParts(next,programmatic){const old=this._parts,parts={day:String(next?.day??""),month:String(next?.month??""),year:String(next?.year??"")};programmatic&&parts.day===old.day&&parts.month===old.month&&parts.year===old.year||(this._parts=parts,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&&formatISO(parsed)===super.value||(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(){const locale=this.effectiveLocale;return this.fieldOrderCache?.locale!==locale&&(this.fieldOrderCache={locale,order:localeDateOrder(locale)}),this.fieldOrderCache.order}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,detail=this.detailFor(this.lastEditedField),event=addCompatibilityDetail(new EventConstructor("change",{bubbles:!0,composed:!0}),detail);this.dispatchEvent(event),this.emit("lr-change",detail)}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)}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 locale=this.effectiveLocale;return this.digitMapCache?.locale!==locale&&(this.digitMapCache={locale,map:localeDigitMap(locale)}),normalizeLocaleDigits(value,locale,this.digitMapCache.map).replace(/\D/g,"")}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
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{createHaystackMemo}from"../../../internal/search-haystack.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{waitForTransitionSettle}from"../../../internal/css-motion-time.js";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{AnnouncementSinkController}from"../../../internal/announcer.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{styles}from"./mention-popover.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_noMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_mentionInputLimit,LYRA_DEFAULT_mentionMoreResults,LYRA_DEFAULT_mentionResultCount,LYRA_DEFAULT_mentionResultPosition,LYRA_DEFAULT_mentionSuggestions}from"../../../internal/default-strings/utility.generated.js";const MAX_VISIBLE_MENTION_ITEMS=50,MAX_MENTION_ITEMS=1e4;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"],caretMirrors=new WeakMap;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);let cached=caretMirrors.get(el);if(!cached||cached.mirror.ownerDocument!==owner){const mirror2=owner.createElement("div"),prefix2=owner.createTextNode(""),marker2=owner.createElement("span"),suffix2=owner.createTextNode("");marker2.append(suffix2),mirror2.append(prefix2,marker2),cached={mirror:mirror2,prefix:prefix2,marker:marker2,suffix:suffix2},caretMirrors.set(el,cached)}const{mirror,prefix,marker,suffix}=cached;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,before=el.value.slice(0,index),after=el.value.slice(index)||"";prefix.textContent!==before&&(prefix.textContent=before),suffix.textContent!==after&&(suffix.textContent=after),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{static{this.defaultStrings={...super.defaultStrings,mentionInputLimit:LYRA_DEFAULT_mentionInputLimit,mentionMoreResults:LYRA_DEFAULT_mentionMoreResults,mentionResultCount:LYRA_DEFAULT_mentionResultCount,mentionResultPosition:LYRA_DEFAULT_mentionResultPosition,mentionSuggestions:LYRA_DEFAULT_mentionSuggestions,noMatches:LYRA_DEFAULT_noMatches}}constructor(){super(),this._textareaFocusSessionGeneration=0,this.itemPositions=new WeakMap,this._items=Object.freeze([]),this.query="",this.open=!1,this.filter=null,this.activeIndex=0,this.listboxHidden=!0,this.listboxHideToken=0,this._listId=nextId("mention-popover-listbox"),this.virtualAnchor=null,this._isFirstUpdate=!0,this._silentClose=!1,this._ownsFocus=!1,this._focusTransferGeneration=0,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitMounted=!1,this.labelKeys=createHaystackMemo((item,locale)=>typeof item.label=="string"?item.label.toLocaleLowerCase(resolveIntlLocale(locale)):""),this.descriptionKeys=createHaystackMemo((item,locale)=>typeof item.description=="string"?item.description.toLocaleLowerCase(resolveIntlLocale(locale)):""),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.visibleItems[index];item&&this.commit(item)},this.onListboxKeyDown=e=>{e.defaultPrevented||!this._ownsFocus||this.handleKeyDown(e)&&this.open&&this.focusActiveOption()},this.inputLimited=!1,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open)}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),name===void 0&&(this.filteredMemo=void 0),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;if(next===this.itemsSource||next===previous)return;this.itemsSource=next;const source=Array.isArray(next)?next:[];this.inputLimited=source.length>MAX_MENTION_ITEMS;const rows=new Array(Math.min(source.length,MAX_MENTION_ITEMS));this.itemPositions=new WeakMap;for(let index=0;index<Math.min(source.length,MAX_MENTION_ITEMS);index++){const descriptor=getOwnDataDescriptor(source,String(index));if(typeof descriptor=="symbol")continue;const item=descriptor.value,copy={};if(item&&typeof item=="object"){let keys=[];try{keys=Object.keys(item)}catch{}for(const key of keys){const field=getOwnDataDescriptor(item,key);typeof field!="symbol"&&Object.defineProperty(copy,key,{value:field.value,enumerable:!0})}}const snapshot=Object.freeze(copy);rows[index]=snapshot,this.itemPositions.set(snapshot,index)}this._items=Object.freeze(rows),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback(),this.announceResultState()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,changed.has("open")&&this.open&&(this.listboxHidden=!1),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.visibleItems.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),this.limitMounted&&changed.has("inputLimited")&&this.inputLimited&&this.announcements.announcePolite(this.localize("mentionInputLimit")),this.limitMounted=!0,changed.has("open"))if(this.open)this.reposition();else{this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.settleListboxHidden();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]'),list=active?.parentElement;if(active&&list){const top=active.offsetTop,bottom=top+active.offsetHeight;top<list.scrollTop?list.scrollTop=top:bottom>list.scrollTop+list.clientHeight&&(list.scrollTop=bottom-list.clientHeight)}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._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.listboxHideToken++,this.listboxHidden=!0,this.open=!1}adoptedCallback(){super.adoptedCallback(),this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.announcements.adopted(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),this.open=!1}resetResultAnnouncements(){this.announcedResultCount=void 0,this.announcedResultPosition=void 0}announceResultState(){if(!this.open)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.announcements.announcePolite(resultState),this.announcedResultCount=resultState),position===void 0){this.announcedResultPosition=void 0;return}position!==this.announcedResultPosition&&(this.announcements.announcePolite(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,{items,query,filter}=this,memo=this.filteredMemo;if(memo&&memo[0]===items&&memo[1]===query&&memo[2]===filter&&memo[3]===locale)return memo[4];const q=(query??"").trim().toLocaleLowerCase(locale),labels=filter?void 0:this.labelKeys(items,locale),descriptions=filter?void 0:this.descriptionKeys(items,locale),rows=items.filter((item,index)=>typeof item.label!="string"||item.label.trim().length===0?!1:q?this.filter?this.filter(item,q):labels[index].includes(q)||descriptions[index].includes(q):!0);return this.filteredMemo=[items,query,filter,locale,rows],rows}get visibleItems(){const filtered=this.filteredItems;if(this.visibleMemo?.[0]===filtered)return this.visibleMemo[1];const visible=filtered.length>MAX_VISIBLE_MENTION_ITEMS?filtered.slice(0,MAX_VISIBLE_MENTION_ITEMS):filtered;return this.visibleMemo=[filtered,visible],visible}get activeDescendantId(){if(!this.open)return null;const idx=this.clampedIndex(this.visibleItems);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}),shadowFocusTarget(this)!==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)&&shadowFocusTarget(this)!==null}get listboxId(){return this._listId}handleKeyDown(e){if(!this.open||e.isComposing||e.keyCode===229)return!1;const rows=this.visibleItems;switch(e.key){case"ArrowDown":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),1),!0):!1;case"ArrowUp":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,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"Home":case"End":return!this._ownsFocus||!rows.length?!1:(e.preventDefault(),this.activeIndex=e.key==="Home"?this.stepEnabledIndex(rows,-1,1):this.stepEnabledIndex(rows,rows.length,-1),!0);case"Escape":return e.preventDefault(),this.open=!1,!0;default:return!1}}clampedIndex(rows){const count=rows.length;if(!count)return-1;const clamped=Math.min(Math.max(this.activeIndex,0),count-1);if(!rows[clamped]?.disabled)return clamped;for(let forward=clamped+1;forward<count;forward+=1)if(!rows[forward]?.disabled)return forward;for(let backward=clamped-1;backward>=0;backward-=1)if(!rows[backward]?.disabled)return backward;return-1}stepEnabledIndex(rows,from,direction){const count=rows.length;if(!count)return 0;let index=Math.min(Math.max(from+direction,0),count-1);for(let steps=0;steps<count;steps+=1){if(!rows[index]?.disabled)return index;if(index+=direction,index<0||index>=count)break}return from>=0&&from<count&&!rows[from]?.disabled?from:this.activeIndex}rowId(index){return`${this._listId}-opt-${index}`}commit(item){if(item.disabled)return;const index=this.itemPositions.get(item)??-1;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",strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});this.cleanup=placement,placement.ready.then(positioned=>{positioned||this.cleanup!==placement||!this.open||(this._silentClose=!0,this.open=!1)})}}async settleListboxHidden(){const token=++this.listboxHideToken;await this.updateComplete,!(token!==this.listboxHideToken||this.open)&&(await waitForTransitionSettle(this.renderRoot.querySelector('[part="listbox"]'),this,{reducedMotion:prefersReducedMotion(this)}).finished,!(token!==this.listboxHideToken||this.open)&&(this.listboxHidden=!0))}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
|
+
import{__decorate}from"tslib";import{getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{createHaystackMemo}from"../../../internal/search-haystack.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{waitForTransitionSettle}from"../../../internal/css-motion-time.js";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{AnnouncementSinkController}from"../../../internal/announcer.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{styles}from"./mention-popover.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_noMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_mentionInputLimit,LYRA_DEFAULT_mentionMoreResults,LYRA_DEFAULT_mentionResultCount,LYRA_DEFAULT_mentionResultPosition,LYRA_DEFAULT_mentionSuggestions}from"../../../internal/default-strings/utility.generated.js";const MAX_VISIBLE_MENTION_ITEMS=50,MAX_MENTION_ITEMS=1e4;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"],caretMirrors=new WeakMap;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);let cached=caretMirrors.get(el);if(!cached||cached.mirror.ownerDocument!==owner){const mirror2=owner.createElement("div"),prefix2=owner.createTextNode(""),marker2=owner.createElement("span"),suffix2=owner.createTextNode("");marker2.append(suffix2),mirror2.append(prefix2,marker2),cached={mirror:mirror2,prefix:prefix2,marker:marker2,suffix:suffix2},caretMirrors.set(el,cached)}const{mirror,prefix,marker,suffix}=cached;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,before=el.value.slice(0,index),after=el.value.slice(index)||"";prefix.textContent!==before&&(prefix.textContent=before),suffix.textContent!==after&&(suffix.textContent=after),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{static{this.defaultStrings={...super.defaultStrings,mentionInputLimit:LYRA_DEFAULT_mentionInputLimit,mentionMoreResults:LYRA_DEFAULT_mentionMoreResults,mentionResultCount:LYRA_DEFAULT_mentionResultCount,mentionResultPosition:LYRA_DEFAULT_mentionResultPosition,mentionSuggestions:LYRA_DEFAULT_mentionSuggestions,noMatches:LYRA_DEFAULT_noMatches}}constructor(){super(),this._textareaFocusSessionGeneration=0,this.itemPositions=new WeakMap,this._items=Object.freeze([]),this.query="",this.open=!1,this.filter=null,this.activeIndex=0,this.listboxHidden=!0,this.listboxHideToken=0,this._listId=nextId("mention-popover-listbox"),this.virtualAnchor=null,this._isFirstUpdate=!0,this._silentClose=!1,this._ownsFocus=!1,this._focusTransferGeneration=0,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitMounted=!1,this.labelKeys=createHaystackMemo((item,locale)=>typeof item.label=="string"?item.label.toLocaleLowerCase(resolveIntlLocale(locale)):""),this.descriptionKeys=createHaystackMemo((item,locale)=>typeof item.description=="string"?item.description.toLocaleLowerCase(resolveIntlLocale(locale)):""),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.visibleItems[index];item&&this.commit(item)},this.onListboxKeyDown=e=>{e.defaultPrevented||!this._ownsFocus||this.handleKeyDown(e)&&this.open&&this.focusActiveOption()},this.inputLimited=!1,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open)}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),name===void 0&&(this.filteredMemo=void 0),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;if(next===this.itemsSource||next===previous)return;this.itemsSource=next;const source=Array.isArray(next)?next:[];this.inputLimited=source.length>MAX_MENTION_ITEMS;const rows=new Array(Math.min(source.length,MAX_MENTION_ITEMS));this.itemPositions=new WeakMap;for(let index=0;index<Math.min(source.length,MAX_MENTION_ITEMS);index++){const descriptor=getOwnDataDescriptor(source,String(index));if(typeof descriptor=="symbol")continue;const item=descriptor.value,copy={};if(item&&typeof item=="object"){let keys=[];try{keys=Object.keys(item)}catch{}for(const key of keys){const field=getOwnDataDescriptor(item,key);typeof field!="symbol"&&Object.defineProperty(copy,key,{value:field.value,enumerable:!0})}}const snapshot=Object.freeze(copy);rows[index]=snapshot,this.itemPositions.set(snapshot,index)}this._items=Object.freeze(rows),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback(),this.announceResultState()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,changed.has("open")&&this.open&&(this.listboxHidden=!1),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.visibleItems.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),this.limitMounted&&changed.has("inputLimited")&&this.inputLimited&&this.announcements.announcePolite(this.localize("mentionInputLimit")),this.limitMounted=!0,changed.has("open"))if(this.open)this.reposition();else{this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.settleListboxHidden();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]'),list=active?.parentElement;if(active&&list){const top=active.offsetTop,bottom=top+active.offsetHeight;top<list.scrollTop?list.scrollTop=top:bottom>list.scrollTop+list.clientHeight&&(list.scrollTop=bottom-list.clientHeight)}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._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.listboxHideToken++,this.listboxHidden=!0,this.open=!1}adoptedCallback(){super.adoptedCallback(),this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.announcements.adopted(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),this.open=!1}resetResultAnnouncements(){this.announcedResultCount=void 0,this.announcedResultPosition=void 0}announceResultState(){if(!this.open)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.announcements.announcePolite(resultState),this.announcedResultCount=resultState),position===void 0){this.announcedResultPosition=void 0;return}position!==this.announcedResultPosition&&(this.announcements.announcePolite(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,{items,query,filter}=this,memo=this.filteredMemo;if(memo&&memo[0]===items&&memo[1]===query&&memo[2]===filter&&memo[3]===locale)return memo[4];const q=(query??"").trim().toLocaleLowerCase(locale),labels=filter?void 0:this.labelKeys(items,locale),descriptions=filter?void 0:this.descriptionKeys(items,locale),rows=items.filter((item,index)=>typeof item.label!="string"||item.label.trim().length===0?!1:q?this.filter?this.filter(item,q):labels[index].includes(q)||descriptions[index].includes(q):!0);return this.filteredMemo=[items,query,filter,locale,rows],rows}get visibleItems(){const filtered=this.filteredItems;if(this.visibleMemo?.[0]===filtered)return this.visibleMemo[1];const visible=filtered.length>MAX_VISIBLE_MENTION_ITEMS?filtered.slice(0,MAX_VISIBLE_MENTION_ITEMS):filtered;return this.visibleMemo=[filtered,visible],visible}get activeDescendantId(){if(!this.open)return null;const idx=this.clampedIndex(this.visibleItems);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}),shadowFocusTarget(this)!==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)&&shadowFocusTarget(this)!==null}get listboxId(){return this._listId}handleKeyDown(e){if(!this.open||e.isComposing||e.keyCode===229)return!1;const rows=this.visibleItems;switch(e.key){case"ArrowDown":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),1),!0):!1;case"ArrowUp":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,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"Home":case"End":return!this._ownsFocus||!rows.length?!1:(e.preventDefault(),this.activeIndex=e.key==="Home"?this.stepEnabledIndex(rows,-1,1):this.stepEnabledIndex(rows,rows.length,-1),!0);case"Escape":return e.preventDefault(),this.open=!1,!0;default:return!1}}clampedIndex(rows){const count=rows.length;if(!count)return-1;const clamped=Math.min(Math.max(this.activeIndex,0),count-1);if(!rows[clamped]?.disabled)return clamped;for(let forward=clamped+1;forward<count;forward+=1)if(!rows[forward]?.disabled)return forward;for(let backward=clamped-1;backward>=0;backward-=1)if(!rows[backward]?.disabled)return backward;return-1}stepEnabledIndex(rows,from,direction){const count=rows.length;if(!count)return 0;let index=Math.min(Math.max(from+direction,0),count-1);for(let steps=0;steps<count;steps+=1){if(!rows[index]?.disabled)return index;if(index+=direction,index<0||index>=count)break}return from>=0&&from<count&&!rows[from]?.disabled?from:this.activeIndex}rowId(index){return`${this._listId}-opt-${index}`}commit(item){if(item.disabled)return;const index=this.itemPositions.get(item)??-1;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",strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});this.cleanup=placement,placement.ready.then(positioned=>{positioned||this.cleanup!==placement||!this.open||(this._silentClose=!0,this.open=!1)})}}async settleListboxHidden(){const token=++this.listboxHideToken;await this.updateComplete,!(token!==this.listboxHideToken||this.open)&&(await waitForTransitionSettle(this.renderRoot.querySelector('[part="listbox"]'),this,{reducedMotion:prefersReducedMotion(this)}).finished,!(token!==this.listboxHideToken||this.open)&&(this.listboxHidden=!0))}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==null?this.localize("noMatches"):this.emptyText}get effectiveLabel(){return hostAriaLabel(this)??(this.label==null?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}
|