@aceshooting/lyra-ui 32.1.0 → 33.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +247 -1576
- package/README.md +15 -2
- package/custom-elements.slim.json +1 -0
- package/dist/accent-roles.css +1 -0
- package/dist/cli/migrate-wa.mjs +50 -48
- package/dist/cli/migration-contract.json.gz +0 -0
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.d.ts +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +10 -0
- package/dist/components/conversation/code-block/code-block-base.class.d.ts +3 -1
- package/dist/components/conversation/code-block/code-block-base.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-core.class.d.ts +1 -1
- package/dist/components/conversation/code-block/code-block-core.class.js +1 -1
- package/dist/components/conversation/code-block/code-block.class.d.ts +3 -2
- package/dist/components/conversation/code-block/code-block.class.js +1 -1
- package/dist/components/conversation/code-block/code-grammar-registry.d.ts +35 -0
- package/dist/components/conversation/code-block/code-grammar-registry.js +1 -0
- package/dist/components/conversation/model-select/model-select.class.d.ts +8 -7
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +1 -1
- package/dist/components/conversation/usage-badge/usage-badge.class.d.ts +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +8 -7
- package/dist/components/data/table/table-support.d.ts +2 -3
- package/dist/components/data/table/table.class.d.ts +2 -1
- package/dist/components/data/timeline/timeline.class.d.ts +17 -6
- package/dist/components/data/timeline/timeline.class.js +2 -2
- package/dist/components/data/timeline/timeline.styles.js +1 -1
- package/dist/components/forms/catalog-picker-base.d.ts +14 -1
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +4 -5
- package/dist/components/forms/checkbox-group/checkbox-group.styles.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.d.ts +14 -5
- package/dist/components/forms/code-editor/code-editor.styles.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.d.ts +18 -7
- package/dist/components/forms/color-picker/color-picker.styles.js +1 -1
- package/dist/components/forms/combobox/combobox-option-html.js +1 -0
- package/dist/components/forms/combobox/combobox.class.d.ts +30 -9
- package/dist/components/forms/combobox/combobox.class.js +110 -21
- package/dist/components/forms/combobox/combobox.styles.js +1 -1
- package/dist/components/forms/country-picker/country-picker.class.d.ts +4 -5
- package/dist/components/forms/currency-picker/currency-picker.class.d.ts +4 -5
- package/dist/components/forms/date-picker/date-input.class.d.ts +14 -5
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.d.ts +10 -0
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +2 -1
- package/dist/components/forms/input/input-shared.d.ts +14 -5
- package/dist/components/forms/input/time-input.class.d.ts +15 -6
- package/dist/components/forms/input/time-input.styles.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +8 -7
- package/dist/components/forms/otp-input/otp-input.class.d.ts +4 -5
- package/dist/components/forms/otp-input/otp-input.styles.js +1 -1
- package/dist/components/forms/phone-input/phone-input.class.d.ts +14 -5
- package/dist/components/forms/phone-input/phone-input.styles.js +1 -1
- package/dist/components/forms/radio/radio-group.class.d.ts +4 -5
- package/dist/components/forms/radio/radio-group.styles.js +1 -1
- package/dist/components/forms/radio/radio.class.js +2 -2
- package/dist/components/forms/select/select.class.d.ts +5 -6
- package/dist/components/forms/signature-pad/signature-pad.class.d.ts +4 -5
- package/dist/components/forms/signature-pad/signature-pad.styles.js +1 -1
- package/dist/components/forms/slider/slider.class.d.ts +6 -5
- package/dist/components/forms/slider/slider.styles.js +1 -1
- package/dist/components/forms/textarea/textarea.class.d.ts +14 -5
- package/dist/components/forms/time-zone-picker/time-zone-picker.class.d.ts +4 -5
- package/dist/components/forms/token-input/token-input.class.d.ts +10 -10
- package/dist/components/forms/token-input/token-input.class.js +1 -1
- package/dist/components/forms/token-input/token-input.styles.js +1 -1
- package/dist/components/forms/unit-picker/unit-picker.class.d.ts +4 -5
- package/dist/components/layout/command-palette/command-palette.class.d.ts +1 -1
- package/dist/components/layout/menu/menu.class.d.ts +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.d.ts +1 -1
- package/dist/components/layout/segmented/segmented.class.d.ts +2 -2
- package/dist/components/layout/stepper/step.class.d.ts +14 -1
- package/dist/components/layout/stepper/step.class.js +2 -2
- package/dist/components/lr-map-anchor.d.ts +1 -1
- package/dist/components/media/file-input/file-input.class.d.ts +2 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/file-input/file-input.styles.js +1 -1
- package/dist/components/media/lightbox/lightbox-item.class.d.ts +10 -0
- package/dist/components/media/lightbox/lightbox-item.class.js +1 -1
- package/dist/components/media/lightbox/lightbox-source.js +1 -1
- package/dist/components/media/lightbox/lightbox-types.d.ts +4 -1
- package/dist/components/media/lightbox/lightbox.class.d.ts +42 -19
- package/dist/components/media/lightbox/lightbox.class.js +4 -3
- package/dist/components/media/lightbox/lightbox.styles.js +1 -1
- package/dist/components/media/map/map-anchor-avoid.js +1 -1
- package/dist/components/media/map/map-anchor-options.d.ts +9 -0
- package/dist/components/media/map/map.class.d.ts +19 -5
- package/dist/components/media/map/map.class.js +3 -3
- package/dist/components/overlays/context-menu/context-menu.class.d.ts +1 -1
- package/dist/components/overlays/dialog/dialog.class.d.ts +19 -3
- package/dist/components/overlays/dialog/dialog.class.js +1 -1
- package/dist/components/overlays/dialog/dialog.styles.js +1 -1
- package/dist/components/overlays/drawer/drawer.class.d.ts +8 -2
- package/dist/components/overlays/drawer/drawer.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.d.ts +1 -1
- package/dist/components/overlays/overlay/overlay.styles.js +1 -1
- package/dist/components/overlays/overlay/popover.class.d.ts +1 -1
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -0
- package/dist/components/overlays/overlay/tooltip.class.js +2 -2
- package/dist/components/overlays/toast/toast-item.class.d.ts +2 -2
- package/dist/components/overlays/toast/toast-item.styles.js +1 -1
- package/dist/components/retrieval/citation-badge/citation-badge.class.d.ts +1 -1
- package/dist/components/retrieval/entity-chip/entity-chip.class.d.ts +1 -1
- package/dist/components/utility/copy-button/copy-button.class.d.ts +2 -1
- package/dist/components/utility/copy-button/copy-button.class.js +1 -1
- package/dist/components/utility/export-button/export-button.class.d.ts +1 -1
- package/dist/components/utility/icon/icon-library-bootstrap.d.ts +50 -0
- package/dist/components/utility/icon/icon-library-bootstrap.js +1 -0
- package/dist/components/utility/icon/icon-library-font-awesome.d.ts +68 -0
- package/dist/components/utility/icon/icon-library-font-awesome.js +1 -0
- package/dist/components/utility/known-date/known-date.class.d.ts +10 -0
- package/dist/components/utility/mention-popover/mention-popover.class.d.ts +1 -1
- package/dist/components/utility/number-ticker/number-ticker.class.d.ts +10 -2
- package/dist/components/utility/number-ticker/number-ticker.class.js +1 -1
- package/dist/components/utility/tour/tour.class.d.ts +1 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/accessibility-visibility.js +1 -1
- package/dist/internal/autoloader-manifest.js +1 -1
- package/dist/internal/declarative-overlay-action.js +1 -0
- package/dist/internal/default-strings/forms.generated.js +1 -1
- package/dist/internal/document-token-css.generated.js +10 -0
- package/dist/internal/document-tokens.generated.js +2 -11
- package/dist/internal/document-tokens.js +2 -2
- package/dist/internal/dom-guards.js +1 -1
- package/dist/internal/external-label-association.js +1 -0
- package/dist/internal/focus-navigation.js +1 -1
- package/dist/internal/form-control/chrome.styles.js +1 -1
- package/dist/internal/form-control-labels.js +1 -1
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.d.ts +12 -3
- package/dist/internal/lyra-element.js +2 -2
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/theme-observation.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/lyra.js +1 -1
- package/dist/ssr.d.ts +1 -1
- package/dist/styles/tokens-root.css +1 -1
- package/dist/styles/utilities.css +1 -1
- package/dist/theme-core.css +1 -1
- package/dist/theme.css +1 -1
- package/llms/components/lr-button.md +4 -0
- package/llms/components/lr-card.md +2 -0
- package/llms/components/lr-checkbox-group.md +2 -2
- package/llms/components/lr-citation-badge.md +1 -1
- package/llms/components/lr-code-block-core.md +3 -1
- package/llms/components/lr-code-block.md +14 -0
- package/llms/components/lr-code-editor.md +2 -2
- package/llms/components/lr-color-picker.md +4 -4
- package/llms/components/lr-combobox.md +21 -5
- package/llms/components/lr-context-menu.md +1 -1
- package/llms/components/lr-copy-button.md +4 -3
- package/llms/components/lr-country-picker.md +2 -2
- package/llms/components/lr-currency-picker.md +2 -2
- package/llms/components/lr-date-input.md +1 -1
- package/llms/components/lr-date-picker.md +1 -1
- package/llms/components/lr-dialog.md +30 -2
- package/llms/components/lr-drawer.md +7 -1
- package/llms/components/lr-entity-chip.md +1 -1
- package/llms/components/lr-export-button.md +1 -1
- package/llms/components/lr-file-input.md +1 -1
- package/llms/components/lr-icon.md +96 -0
- package/llms/components/lr-input.md +2 -2
- package/llms/components/lr-lightbox.md +43 -17
- package/llms/components/lr-locale-picker.md +2 -2
- package/llms/components/lr-map.md +16 -1
- package/llms/components/lr-mention-popover.md +1 -1
- package/llms/components/lr-menu.md +1 -1
- package/llms/components/lr-model-select.md +4 -4
- package/llms/components/lr-native-time-input.md +2 -2
- package/llms/components/lr-number-input.md +2 -2
- package/llms/components/lr-number-ticker.md +7 -2
- package/llms/components/lr-otp-input.md +2 -2
- package/llms/components/lr-phone-input.md +2 -2
- package/llms/components/lr-popover.md +1 -1
- package/llms/components/lr-radio-group.md +2 -2
- package/llms/components/lr-segmented.md +1 -1
- package/llms/components/lr-select.md +3 -3
- package/llms/components/lr-selection-toolbar.md +1 -1
- package/llms/components/lr-signature-pad.md +2 -2
- package/llms/components/lr-slider.md +1 -1
- package/llms/components/lr-step.md +7 -1
- package/llms/components/lr-textarea.md +2 -2
- package/llms/components/lr-time-input.md +3 -3
- package/llms/components/lr-time-zone-picker.md +2 -2
- package/llms/components/lr-timeline.md +12 -5
- package/llms/components/lr-toast.md +1 -1
- package/llms/components/lr-token-input.md +10 -9
- package/llms/components/lr-tool-call-chip.md +1 -1
- package/llms/components/lr-tooltip.md +5 -0
- package/llms/components/lr-unit-picker.md +2 -2
- package/llms/components/lr-usage-badge.md +1 -1
- package/llms/components/lr-voice-picker.md +4 -3
- package/llms/index.md +128 -128
- package/llms/migration.md +87 -8
- package/llms/peers.md +2 -2
- package/llms/shared/events-and-types.md +1 -1
- package/llms/shared/forms-and-accessibility.md +4 -1
- package/llms/shared/frameworks-and-ssr.md +47 -1
- package/llms/shared/imports-and-registration.md +8 -1
- package/llms/shared/localization-and-rtl.md +5 -0
- package/llms/shared/native-styles-and-utilities.md +85 -8
- package/llms/shared/styles-and-tokens.md +58 -4
- package/llms/shared/testing-and-utilities.md +9 -0
- package/llms/shared.md +217 -16
- package/locales.json +1 -1
- package/package.json +15 -6
- package/registrations.json +1 -1
- package/skills/compose-lyra-interfaces/SKILL.md +1 -1
- package/skills/lyra-ui/SKILL.md +1 -1
- package/skills/lyra-ui/commands/migrate.md +1 -1
|
Binary file
|
|
@@ -76,7 +76,7 @@ import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from
|
|
|
76
76
|
* on the anchored detail tooltip.
|
|
77
77
|
* @cssprop [--lr-overlay-border=var(--lr-color-border-subtle)] - Shared floating-surface edge
|
|
78
78
|
* colour, on the anchored detail tooltip.
|
|
79
|
-
* @cssprop [--lr-overlay-radius=var(--lr-radius)] - Shared floating-surface corner radius, on the
|
|
79
|
+
* @cssprop [--lr-overlay-radius=var(--lr-radius-container)] - Shared floating-surface corner radius, on the
|
|
80
80
|
* anchored detail tooltip.
|
|
81
81
|
* @cssprop [--lr-overlay-shadow-anchored=var(--lr-shadow-m)] - Elevation of the anchored surface.
|
|
82
82
|
* @cssprop --lr-positioning-strategy - Cascading `absolute`/`fixed` override for the detail
|
|
@@ -134,6 +134,16 @@ export type ChatComposerToolbarAlign='start'|'end';export interface LyraChatComp
|
|
|
134
134
|
* entirely to a consumer-drawn wrapper -- chosen over a third `frame` value, since every other
|
|
135
135
|
* piece of this card's paint (background/border-color/radius above) is already a cssprop hook
|
|
136
136
|
* rather than a `frame` variant, and `none` already reads naturally as "I'll draw my own".
|
|
137
|
+
* @cssstate required - Matches while `required` is set. Style with `lr-chat-composer:state(required)`.
|
|
138
|
+
* @cssstate optional - Matches while `required` is not set — the complement of `required`.
|
|
139
|
+
* @cssstate valid - Matches while the control satisfies its constraints, including any
|
|
140
|
+
* `setCustomValidity()` error. Never matches while disabled or readonly.
|
|
141
|
+
* @cssstate invalid - Matches while it does not — from the very first render, before the user has
|
|
142
|
+
* touched anything. Never matches while disabled or readonly.
|
|
143
|
+
* @cssstate user-valid - `valid`, but only after the user has interacted: an edit, a blur,
|
|
144
|
+
* `reportValidity()`, or a submission attempt.
|
|
145
|
+
* @cssstate user-invalid - `invalid` after that same interaction. Style validation errors with this
|
|
146
|
+
* rather than `invalid`, so a pristine required field is not painted red before the user acts.
|
|
137
147
|
* @status stable
|
|
138
148
|
* @since 4.0.0
|
|
139
149
|
*/
|
|
@@ -30,7 +30,9 @@ get label():string;set label(value:string);
|
|
|
30
30
|
get withoutCopy():boolean;set withoutCopy(value:boolean);private readSlottedCode;private syncSlottedCode;protected hasHeaderActions:boolean;protected focusedLine:number;protected highlightedHtml:string|null;protected shikiReady:boolean;protected justCopied:boolean;protected copyFailed:boolean;protected isDarkTheme:boolean;
|
|
31
31
|
/** Set when the current language has no usable grammar, so the code renders as plain text.
|
|
32
32
|
* Each subclass sets it when a highlight attempt settles without output. */
|
|
33
|
-
protected grammarUnavailable:boolean;private readonly highlightInternals;private reportedGrammarError;protected restoreFocusedLineAfterUpdate:boolean;protected highlightToken:number;private plainTemplate?;private plainKey;private countedCode?;private countedLines;private paintedCode?;private plainDomChanged;private paintedLines;private previousHighlighted;private previousActive;protected get highlightLimited():boolean;protected readonly bodyId:string;protected resumedMove:boolean;private readonly teardown;private readonly announcements;protected readonly interactions:CodeBlockInteractionController;private readonly headerActions;constructor();connectedCallback():void;disconnectedCallback():void;
|
|
33
|
+
protected grammarUnavailable:boolean;private readonly highlightInternals;private reportedGrammarError;protected restoreFocusedLineAfterUpdate:boolean;protected highlightToken:number;private plainTemplate?;private plainKey;private countedCode?;private countedLines;private paintedCode?;private plainDomChanged;private paintedLines;private previousHighlighted;private previousActive;protected get highlightLimited():boolean;protected readonly bodyId:string;protected resumedMove:boolean;private readonly teardown;private readonly announcements;protected readonly interactions:CodeBlockInteractionController;private readonly headerActions;constructor();connectedCallback():void;disconnectedCallback():void;private stopGrammarSubscription?;private handleCodeGrammarChange;
|
|
34
|
+
/** Re-resolves the current language after the registry changed.*/
|
|
35
|
+
protected refreshRegisteredGrammar():void;protected releaseHighlight():void;adoptedCallback():void;private readonly toggleCollapsed;
|
|
34
36
|
/** Resolves a `line-range` anchor (or a `highlights` id string resolving to one) by scrolling
|
|
35
37
|
* its start line into view within `[part="body"]`. Resolves `false` when the anchor isn't a
|
|
36
38
|
* `line-range`, the id isn't found, or the start line is out of bounds. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{reportCopyOutcome}from"../../../internal/record-copy-feedback.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{nextId}from"../../../internal/a11y.js";import{dedent,stripLeadingNewline}from"../../../internal/dedent.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{SHIKI_SOURCE_MAX_CODE_UNITS}from"./shiki-types.js";import{normalizeShikiLanguage}from"../../../internal/shiki/core.js";import{CodeBlockHeaderActionsController,CodeBlockInteractionController,applyCodeBlockAriaBusy,clampCodeBlockFocusedLine,codeBlockActiveHighlightLineSet,codeBlockLineHasFocus,codeBlockLineCount,codeBlockLineHighlightSet,renderCodeBlockPlainCode,renderCodeBlockShell,restoreCodeBlockLineFocus,scrollCodeBlockToAnchor,tokenizeCodeBlock}from"./code-block-shared.js";import{LYRA_DEFAULT_codeBlockActiveLine,LYRA_DEFAULT_codeBlockHighlightLimit,LYRA_DEFAULT_codeBlockHighlightedLine,LYRA_DEFAULT_codeBlockLineLabel,LYRA_DEFAULT_codeBlockToggle,LYRA_DEFAULT_codeRegion,LYRA_DEFAULT_codeRegionWithLanguage,LYRA_DEFAULT_copiedToClipboard,LYRA_DEFAULT_copyCode}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";class LyraCodeBlockBase extends LyraElement{static{this.defaultStrings={...super.defaultStrings,codeBlockActiveLine:LYRA_DEFAULT_codeBlockActiveLine,codeBlockHighlightLimit:LYRA_DEFAULT_codeBlockHighlightLimit,codeBlockHighlightedLine:LYRA_DEFAULT_codeBlockHighlightedLine,codeBlockLineLabel:LYRA_DEFAULT_codeBlockLineLabel,codeBlockToggle:LYRA_DEFAULT_codeBlockToggle,codeRegion:LYRA_DEFAULT_codeRegion,codeRegionWithLanguage:LYRA_DEFAULT_codeRegionWithLanguage,copied:LYRA_DEFAULT_copied,copiedToClipboard:LYRA_DEFAULT_copiedToClipboard,copy:LYRA_DEFAULT_copy,copyCode:LYRA_DEFAULT_copyCode,copyFailed:LYRA_DEFAULT_copyFailed}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-text-select"])}get collapsed(){return this.collapsedValue}set collapsed(value){this.collapsedValue=value,markVetoGuardWrite(this.collapseWrites)}get withoutDedent(){return this.withoutDedentValue}set withoutDedent(value){const previous=this.withoutDedentValue;this.withoutDedentValue=value,this.requestUpdate("withoutDedent",previous),this.syncSlottedCode()}get label(){return this.labelValue}set label(value){const previous=this.labelValue;this.labelValue=value??"",this.requestUpdate("label",previous)}get withoutCopy(){return this.withoutCopyButton}set withoutCopy(value){this.withoutCopyButton=value}get sourceCode(){const code=this.code??"";return code===""?this.slottedCode:code}readSlottedCode(){let text="";for(const node of this.childNodes)if(node.nodeType===3)text+=node.nodeValue??"";else if(node.nodeType===1){const element=node;if(element.hasAttribute("slot"))continue;element.localName==="template"?text+=element.content.textContent??"":text+=element.textContent??""}return this.withoutDedentValue?stripLeadingNewline(text):dedent(text)}syncSlottedCode(){if(!this.isConnected)return;const next=this.readSlottedCode();next!==this.slottedCode&&(this.slottedCode=next)}get highlightLimited(){return this.sourceCode.length>SHIKI_SOURCE_MAX_CODE_UNITS}constructor(){super(),this.collapseWrites=new VetoWriteGuard,this.collapsedValue=!1,this.slottedCode="",this.withoutDedentValue=!1,this.labelValue="",this.wrap=!1,this.hasHeaderActions=!1,this.focusedLine=1,this.highlightedHtml=null,this.shikiReady=!1,this.justCopied=!1,this.copyFailed=!1,this.isDarkTheme=!1,this.grammarUnavailable=!1,this.highlightInternals=attachInternalsSafely(this),this.reportedGrammarError=!1,this.restoreFocusedLineAfterUpdate=!1,this.highlightToken=0,this.plainKey=[],this.countedLines=1,this.plainDomChanged=!1,this.paintedLines=new Map,this.previousHighlighted=new Set,this.previousActive=new Set,this.bodyId=nextId("code-block-body"),this.resumedMove=!1,this.teardown=new DeferredTeardown(()=>this.releaseHighlight()),this.announcements=new AnnouncementSinkController(this),this.interactions=new CodeBlockInteractionController({host:this,setFocusedLine:line=>{this.focusedLine=line},setJustCopied:value=>{this.justCopied=value},setCopyFailed:value=>{this.copyFailed=value},setDarkTheme:value=>{this.isDarkTheme=value},emitLineActivate:line=>this.emit("lr-line-activate",{line}),reportCopy:outcome=>reportCopyOutcome({emit:(name,detail)=>this.emit(name,detail??null),announce:ok=>this.announcements.announcePolite(ok?this.localize("copiedToClipboard"):this.localize("copyFailed"))},outcome,()=>this.isConnected&&this.sourceCode===outcome.text),emitTextSelect:selection=>this.emit("lr-text-select",selection)}),this.headerActions=new CodeBlockHeaderActionsController({host:this,setHasHeaderActions:value=>{this.hasHeaderActions=value}}),this.toggleCollapsed=()=>{if(!this.isConnected||!this.collapsible)return;const expanded=this.collapsed;requestThenCommit({guard:this.collapseWrites,requestDetail:{expanded},emitRequest:(detail,init)=>this.emit("lr-toggle-request",detail,init),commit:()=>{!this.isConnected||!this.collapsible||(this.collapsed=!expanded,this.emit("lr-toggle",{expanded}))}})},new ThemeWatcher(this,()=>this.refreshTheme())}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.refreshTheme(),this.headerActions.observe();const Observer=this.ownerDocument.defaultView?.MutationObserver;Observer&&!this.slottedObserver&&(this.slottedObserver=new Observer(()=>this.syncSlottedCode()),this.slottedObserver.observe(this,{childList:!0,characterData:!0,subtree:!0})),this.syncSlottedCode(),this.resumedMove=this.teardown.cancel()}disconnectedCallback(){super.disconnectedCallback(),this.teardown.schedule(),this.headerActions.disconnect(),this.interactions.disconnect(),this.slottedObserver?.disconnect(),this.slottedObserver=void 0}releaseHighlight(){this.highlightToken++,this.highlightedHtml=null}adoptedCallback(){this.teardown.flush(),super.adoptedCallback(),this.announcements.adopted(),this.interactions.disconnect()}async scrollToAnchor(target){return scrollCodeBlockToAnchor(this,target)}refreshTheme(){this.interactions.refreshTheme()}willUpdate(changed){super.willUpdate(changed),this.announcements.setExclusiveChannel(this.withoutCopyButton?void 0:"polite"),changed.has("withoutCopyButton")&&this.requestUpdate("withoutCopy",changed.get("withoutCopyButton")),this.seedFirstRenderState(()=>this.refreshTheme()),this.headerActions.sync(),this.restoreFocusedLineAfterUpdate=codeBlockLineHasFocus(this),(changed.has("code")||changed.has("slottedCode"))&&(this.plainTemplate=void 0,this.plainKey=[],this.focusedLine=clampCodeBlockFocusedLine(this.focusedLine,this.lineCount())),(changed.has("language")||changed.has("languages"))&&(this.grammarUnavailable=!1),this.beforeHighlightUpdate(changed),this.interactions.needsHighlightResync(changed,this.effectiveLocale,this.localize("codeBlockLineLabel"))&&(this.highlightLimited?(this.highlightToken++,this.highlightedHtml=null,this.grammarUnavailable=!1):this.shikiReady||this.hasPreSuppliedGrammar()?this.syncHighlight():this.highlightedHtml=null)}updated(changed){super.updated(changed),applyCodeBlockAriaBusy(this,!this.highlightLimited&&this.showsSkeleton()),this.syncHighlightStates(changed),this.patchLineState(),this.interactions.syncLineButtons(this.focusedLine,this.plainDomChanged),this.plainDomChanged=!1,this.restoreFocusedLineAfterUpdate&&(restoreCodeBlockLineFocus(this,this.focusedLine),this.restoreFocusedLineAfterUpdate=!1)}syncHighlightStates(changed){const highlighted=this.highlightedHtml!==null,wanted=normalizeShikiLanguage(this.language??"")!==""&&!this.highlightLimited,error=wanted&&!highlighted&&(this.grammarUnavailable||!this.grammarMayLoad());setCustomState(this.highlightInternals,"highlighted",highlighted),setCustomState(this.highlightInternals,"error",error),setCustomState(this.highlightInternals,"loading",wanted&&!highlighted&&!error),changed.has("highlightedHtml")&&highlighted&&this.emit("lr-load",{highlighted:!0}),error&&!this.reportedGrammarError&&this.emit("lr-load",{highlighted:!1}),this.reportedGrammarError=error}grammarMayLoad(){return!0}beforeHighlightUpdate(_changed){}hasPreSuppliedGrammar(){return!!this.preSuppliedGrammar()}lineHighlightSet(){return codeBlockLineHighlightSet(this.highlightLines??"",this.highlights,this.lineCount())}activeHighlightLineSet(){return codeBlockActiveHighlightLineSet(this.highlights,this.activeHighlightId,this.lineCount())}lineCount(){const code=this.sourceCode;return code!==this.countedCode&&(this.countedCode=code,this.countedLines=codeBlockLineCount(code)),this.countedLines}tokenize(hl,lang){return this.highlightLimited?null:tokenizeCodeBlock(hl,{code:this.sourceCode,lang,lineNumbers:this.lineNumbers,activatableLines:this.activatableLines,focusedLine:this.focusedLine,highlightedLines:this.lineHighlightSet(),activeLines:this.activeHighlightLineSet(),lineLabel:line=>this.localize("codeBlockLineLabel",void 0,{line:getNumberFormat(this.effectiveLocale).format(line)}),lineNumberText:line=>getNumberFormat(this.effectiveLocale).format(line)})}renderPlainCode(){return renderCodeBlockPlainCode({code:this.sourceCode,lineNumbers:this.lineNumbers,activatableLines:this.activatableLines,focusedLine:this.focusedLine,highlightedLines:this.lineHighlightSet(),activeLines:this.activeHighlightLineSet(),localize:this.localize.bind(this),lineLabel:line=>this.localize("codeBlockLineLabel",void 0,{line:getNumberFormat(this.effectiveLocale).format(line)}),lineNumberText:line=>getNumberFormat(this.effectiveLocale).format(line),onLineActivate:line=>this.interactions.onLineActivate(line),onLineKeyDown:(event,line)=>this.interactions.onLineKeyDown(event,line)})}patchLineState(){const code=this.renderRoot.querySelector("code");if(code!==this.paintedCode||this.plainDomChanged){this.paintedCode=code,this.paintedLines.clear();for(const line of code?.querySelectorAll(".line[data-line]")??[])line.removeAttribute("data-highlighted"),line.removeAttribute("data-active"),line.part?.remove("line-highlight"),this.paintedLines.set(Number(line.dataset.line),line)}const highlighted=this.lineHighlightSet(),active=this.activeHighlightLineSet(),changed=new Set([...this.previousHighlighted,...highlighted,...this.previousActive,...active]);for(const number of changed){const line=this.paintedLines.get(number);if(!line)continue;line.toggleAttribute("data-highlighted",highlighted.has(number)),line.toggleAttribute("data-active",active.has(number)),line.part?.toggle("line-highlight",highlighted.has(number));const gutter=line.querySelector("button.line-gutter");if(highlighted.has(number)){const description=active.has(number)?this.localize("codeBlockActiveLine"):this.localize("codeBlockHighlightedLine");line.setAttribute("role","mark"),line.setAttribute("aria-roledescription",description),gutter?.setAttribute("aria-description",description)}else line.removeAttribute("role"),line.removeAttribute("aria-roledescription"),gutter?.removeAttribute("aria-description")}this.previousHighlighted=highlighted,this.previousActive=active}cachedPlainCode(){const key=[this.sourceCode,this.lineNumbers,this.activatableLines,this.effectiveLocale,this.localize("codeBlockLineLabel")];return(!this.plainTemplate||key.some((value,index)=>value!==this.plainKey[index]))&&(this.plainDomChanged=!0,this.plainKey=key,this.plainTemplate=this.renderPlainCode()),this.plainTemplate}render(){return renderCodeBlockShell({filename:this.filename,language:this.language,copyable:!this.withoutCopyButton,copyAppearance:this.copyAppearance,hasHeaderActions:this.hasHeaderActions,collapsible:this.collapsible,collapsed:this.collapsed,justCopied:this.justCopied,copyFailed:this.copyFailed,bodyId:this.bodyId,accessibleLabel:this.accessibleLabel??(this.label||null),maxHeight:this.maxHeight,isDarkTheme:this.isDarkTheme,showSkeleton:!this.highlightLimited&&this.showsSkeleton(),highlightLimited:this.highlightLimited&&!!this.language,highlightedHtml:this.highlightedHtml,lineNumbers:this.lineNumbers,localize:this.localize.bind(this),renderPlainCode:()=>this.cachedPlainCode(),onToggle:this.toggleCollapsed,onCopy:()=>{this.interactions.copy()},bindSelectionBody:this.interactions.bindSelectionBody,onBodyClick:this.interactions.onBodyClick,onBodyKeyDown:this.interactions.onBodyKeyDown,onBodyFocusIn:this.interactions.onBodyFocusIn})}}__decorate([property({type:Boolean,reflect:!0})],LyraCodeBlockBase.prototype,"collapsed",null),__decorate([state()],LyraCodeBlockBase.prototype,"slottedCode",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCodeBlockBase.prototype,"wrap",void 0),__decorate([property({type:Boolean,attribute:"without-dedent",reflect:!0})],LyraCodeBlockBase.prototype,"withoutDedent",null),__decorate([property()],LyraCodeBlockBase.prototype,"label",null),__decorate([property({type:Boolean,attribute:"without-copy",reflect:!0})],LyraCodeBlockBase.prototype,"withoutCopy",null),__decorate([state()],LyraCodeBlockBase.prototype,"hasHeaderActions",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"highlightedHtml",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"shikiReady",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"justCopied",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"copyFailed",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"isDarkTheme",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"grammarUnavailable",void 0);export{LyraCodeBlockBase};
|
|
1
|
+
import{__decorate}from"tslib";import{reportCopyOutcome}from"../../../internal/record-copy-feedback.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{nextId}from"../../../internal/a11y.js";import{dedent,stripLeadingNewline}from"../../../internal/dedent.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{SHIKI_SOURCE_MAX_CODE_UNITS}from"./shiki-types.js";import{normalizeShikiLanguage}from"../../../internal/shiki/core.js";import{subscribeCodeGrammars}from"./code-grammar-registry.js";import{CodeBlockHeaderActionsController,CodeBlockInteractionController,applyCodeBlockAriaBusy,clampCodeBlockFocusedLine,codeBlockActiveHighlightLineSet,codeBlockLineHasFocus,codeBlockLineCount,codeBlockLineHighlightSet,renderCodeBlockPlainCode,renderCodeBlockShell,restoreCodeBlockLineFocus,scrollCodeBlockToAnchor,tokenizeCodeBlock}from"./code-block-shared.js";import{LYRA_DEFAULT_codeBlockActiveLine,LYRA_DEFAULT_codeBlockHighlightLimit,LYRA_DEFAULT_codeBlockHighlightedLine,LYRA_DEFAULT_codeBlockLineLabel,LYRA_DEFAULT_codeBlockToggle,LYRA_DEFAULT_codeRegion,LYRA_DEFAULT_codeRegionWithLanguage,LYRA_DEFAULT_copiedToClipboard,LYRA_DEFAULT_copyCode}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";class LyraCodeBlockBase extends LyraElement{static{this.defaultStrings={...super.defaultStrings,codeBlockActiveLine:LYRA_DEFAULT_codeBlockActiveLine,codeBlockHighlightLimit:LYRA_DEFAULT_codeBlockHighlightLimit,codeBlockHighlightedLine:LYRA_DEFAULT_codeBlockHighlightedLine,codeBlockLineLabel:LYRA_DEFAULT_codeBlockLineLabel,codeBlockToggle:LYRA_DEFAULT_codeBlockToggle,codeRegion:LYRA_DEFAULT_codeRegion,codeRegionWithLanguage:LYRA_DEFAULT_codeRegionWithLanguage,copied:LYRA_DEFAULT_copied,copiedToClipboard:LYRA_DEFAULT_copiedToClipboard,copy:LYRA_DEFAULT_copy,copyCode:LYRA_DEFAULT_copyCode,copyFailed:LYRA_DEFAULT_copyFailed}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-text-select"])}get collapsed(){return this.collapsedValue}set collapsed(value){this.collapsedValue=value,markVetoGuardWrite(this.collapseWrites)}get withoutDedent(){return this.withoutDedentValue}set withoutDedent(value){const previous=this.withoutDedentValue;this.withoutDedentValue=value,this.requestUpdate("withoutDedent",previous),this.syncSlottedCode()}get label(){return this.labelValue}set label(value){const previous=this.labelValue;this.labelValue=value??"",this.requestUpdate("label",previous)}get withoutCopy(){return this.withoutCopyButton}set withoutCopy(value){this.withoutCopyButton=value}get sourceCode(){const code=this.code??"";return code===""?this.slottedCode:code}readSlottedCode(){let text="";for(const node of this.childNodes)if(node.nodeType===3)text+=node.nodeValue??"";else if(node.nodeType===1){const element=node;if(element.hasAttribute("slot"))continue;element.localName==="template"?text+=element.content.textContent??"":text+=element.textContent??""}return this.withoutDedentValue?stripLeadingNewline(text):dedent(text)}syncSlottedCode(){if(!this.isConnected)return;const next=this.readSlottedCode();next!==this.slottedCode&&(this.slottedCode=next)}get highlightLimited(){return this.sourceCode.length>SHIKI_SOURCE_MAX_CODE_UNITS}constructor(){super(),this.collapseWrites=new VetoWriteGuard,this.collapsedValue=!1,this.slottedCode="",this.withoutDedentValue=!1,this.labelValue="",this.wrap=!1,this.hasHeaderActions=!1,this.focusedLine=1,this.highlightedHtml=null,this.shikiReady=!1,this.justCopied=!1,this.copyFailed=!1,this.isDarkTheme=!1,this.grammarUnavailable=!1,this.highlightInternals=attachInternalsSafely(this),this.reportedGrammarError=!1,this.restoreFocusedLineAfterUpdate=!1,this.highlightToken=0,this.plainKey=[],this.countedLines=1,this.plainDomChanged=!1,this.paintedLines=new Map,this.previousHighlighted=new Set,this.previousActive=new Set,this.bodyId=nextId("code-block-body"),this.resumedMove=!1,this.teardown=new DeferredTeardown(()=>this.releaseHighlight()),this.announcements=new AnnouncementSinkController(this),this.interactions=new CodeBlockInteractionController({host:this,setFocusedLine:line=>{this.focusedLine=line},setJustCopied:value=>{this.justCopied=value},setCopyFailed:value=>{this.copyFailed=value},setDarkTheme:value=>{this.isDarkTheme=value},emitLineActivate:line=>this.emit("lr-line-activate",{line}),reportCopy:outcome=>reportCopyOutcome({emit:(name,detail)=>this.emit(name,detail??null),announce:ok=>this.announcements.announcePolite(ok?this.localize("copiedToClipboard"):this.localize("copyFailed"))},outcome,()=>this.isConnected&&this.sourceCode===outcome.text),emitTextSelect:selection=>this.emit("lr-text-select",selection)}),this.headerActions=new CodeBlockHeaderActionsController({host:this,setHasHeaderActions:value=>{this.hasHeaderActions=value}}),this.toggleCollapsed=()=>{if(!this.isConnected||!this.collapsible)return;const expanded=this.collapsed;requestThenCommit({guard:this.collapseWrites,requestDetail:{expanded},emitRequest:(detail,init)=>this.emit("lr-toggle-request",detail,init),commit:()=>{!this.isConnected||!this.collapsible||(this.collapsed=!expanded,this.emit("lr-toggle",{expanded}))}})},new ThemeWatcher(this,()=>this.refreshTheme())}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.refreshTheme(),this.headerActions.observe();const Observer=this.ownerDocument.defaultView?.MutationObserver;Observer&&!this.slottedObserver&&(this.slottedObserver=new Observer(()=>this.syncSlottedCode()),this.slottedObserver.observe(this,{childList:!0,characterData:!0,subtree:!0})),this.syncSlottedCode(),this.resumedMove=this.teardown.cancel(),this.stopGrammarSubscription??=subscribeCodeGrammars(keys=>this.handleCodeGrammarChange(keys))}disconnectedCallback(){super.disconnectedCallback(),this.stopGrammarSubscription?.(),this.stopGrammarSubscription=void 0,this.teardown.schedule(),this.headerActions.disconnect(),this.interactions.disconnect(),this.slottedObserver?.disconnect(),this.slottedObserver=void 0}handleCodeGrammarChange(keys){!this.isConnected||!this.language||!keys.has(normalizeShikiLanguage(this.language))&&!keys.has(this.language)||(this.grammarUnavailable=!1,this.refreshRegisteredGrammar())}refreshRegisteredGrammar(){this.syncHighlight()}releaseHighlight(){this.highlightToken++,this.highlightedHtml=null}adoptedCallback(){this.teardown.flush(),super.adoptedCallback(),this.announcements.adopted(),this.interactions.disconnect()}async scrollToAnchor(target){return scrollCodeBlockToAnchor(this,target)}refreshTheme(){this.interactions.refreshTheme()}willUpdate(changed){super.willUpdate(changed),this.announcements.setExclusiveChannel(this.withoutCopyButton?void 0:"polite"),changed.has("withoutCopyButton")&&this.requestUpdate("withoutCopy",changed.get("withoutCopyButton")),this.seedFirstRenderState(()=>this.refreshTheme()),this.headerActions.sync(),this.restoreFocusedLineAfterUpdate=codeBlockLineHasFocus(this),(changed.has("code")||changed.has("slottedCode"))&&(this.plainTemplate=void 0,this.plainKey=[],this.focusedLine=clampCodeBlockFocusedLine(this.focusedLine,this.lineCount())),(changed.has("language")||changed.has("languages"))&&(this.grammarUnavailable=!1),this.beforeHighlightUpdate(changed),this.interactions.needsHighlightResync(changed,this.effectiveLocale,this.localize("codeBlockLineLabel"))&&(this.highlightLimited?(this.highlightToken++,this.highlightedHtml=null,this.grammarUnavailable=!1):this.shikiReady||this.hasPreSuppliedGrammar()?this.syncHighlight():this.highlightedHtml=null)}updated(changed){super.updated(changed),applyCodeBlockAriaBusy(this,!this.highlightLimited&&this.showsSkeleton()),this.syncHighlightStates(changed),this.patchLineState(),this.interactions.syncLineButtons(this.focusedLine,this.plainDomChanged),this.plainDomChanged=!1,this.restoreFocusedLineAfterUpdate&&(restoreCodeBlockLineFocus(this,this.focusedLine),this.restoreFocusedLineAfterUpdate=!1)}syncHighlightStates(changed){const highlighted=this.highlightedHtml!==null,wanted=normalizeShikiLanguage(this.language??"")!==""&&!this.highlightLimited,error=wanted&&!highlighted&&(this.grammarUnavailable||!this.grammarMayLoad());setCustomState(this.highlightInternals,"highlighted",highlighted),setCustomState(this.highlightInternals,"error",error),setCustomState(this.highlightInternals,"loading",wanted&&!highlighted&&!error),changed.has("highlightedHtml")&&highlighted&&this.emit("lr-load",{highlighted:!0}),error&&!this.reportedGrammarError&&this.emit("lr-load",{highlighted:!1}),this.reportedGrammarError=error}grammarMayLoad(){return!0}beforeHighlightUpdate(_changed){}hasPreSuppliedGrammar(){return!!this.preSuppliedGrammar()}lineHighlightSet(){return codeBlockLineHighlightSet(this.highlightLines??"",this.highlights,this.lineCount())}activeHighlightLineSet(){return codeBlockActiveHighlightLineSet(this.highlights,this.activeHighlightId,this.lineCount())}lineCount(){const code=this.sourceCode;return code!==this.countedCode&&(this.countedCode=code,this.countedLines=codeBlockLineCount(code)),this.countedLines}tokenize(hl,lang){return this.highlightLimited?null:tokenizeCodeBlock(hl,{code:this.sourceCode,lang,lineNumbers:this.lineNumbers,activatableLines:this.activatableLines,focusedLine:this.focusedLine,highlightedLines:this.lineHighlightSet(),activeLines:this.activeHighlightLineSet(),lineLabel:line=>this.localize("codeBlockLineLabel",void 0,{line:getNumberFormat(this.effectiveLocale).format(line)}),lineNumberText:line=>getNumberFormat(this.effectiveLocale).format(line)})}renderPlainCode(){return renderCodeBlockPlainCode({code:this.sourceCode,lineNumbers:this.lineNumbers,activatableLines:this.activatableLines,focusedLine:this.focusedLine,highlightedLines:this.lineHighlightSet(),activeLines:this.activeHighlightLineSet(),localize:this.localize.bind(this),lineLabel:line=>this.localize("codeBlockLineLabel",void 0,{line:getNumberFormat(this.effectiveLocale).format(line)}),lineNumberText:line=>getNumberFormat(this.effectiveLocale).format(line),onLineActivate:line=>this.interactions.onLineActivate(line),onLineKeyDown:(event,line)=>this.interactions.onLineKeyDown(event,line)})}patchLineState(){const code=this.renderRoot.querySelector("code");if(code!==this.paintedCode||this.plainDomChanged){this.paintedCode=code,this.paintedLines.clear();for(const line of code?.querySelectorAll(".line[data-line]")??[])line.removeAttribute("data-highlighted"),line.removeAttribute("data-active"),line.part?.remove("line-highlight"),this.paintedLines.set(Number(line.dataset.line),line)}const highlighted=this.lineHighlightSet(),active=this.activeHighlightLineSet(),changed=new Set([...this.previousHighlighted,...highlighted,...this.previousActive,...active]);for(const number of changed){const line=this.paintedLines.get(number);if(!line)continue;line.toggleAttribute("data-highlighted",highlighted.has(number)),line.toggleAttribute("data-active",active.has(number)),line.part?.toggle("line-highlight",highlighted.has(number));const gutter=line.querySelector("button.line-gutter");if(highlighted.has(number)){const description=active.has(number)?this.localize("codeBlockActiveLine"):this.localize("codeBlockHighlightedLine");line.setAttribute("role","mark"),line.setAttribute("aria-roledescription",description),gutter?.setAttribute("aria-description",description)}else line.removeAttribute("role"),line.removeAttribute("aria-roledescription"),gutter?.removeAttribute("aria-description")}this.previousHighlighted=highlighted,this.previousActive=active}cachedPlainCode(){const key=[this.sourceCode,this.lineNumbers,this.activatableLines,this.effectiveLocale,this.localize("codeBlockLineLabel")];return(!this.plainTemplate||key.some((value,index)=>value!==this.plainKey[index]))&&(this.plainDomChanged=!0,this.plainKey=key,this.plainTemplate=this.renderPlainCode()),this.plainTemplate}render(){return renderCodeBlockShell({filename:this.filename,language:this.language,copyable:!this.withoutCopyButton,copyAppearance:this.copyAppearance,hasHeaderActions:this.hasHeaderActions,collapsible:this.collapsible,collapsed:this.collapsed,justCopied:this.justCopied,copyFailed:this.copyFailed,bodyId:this.bodyId,accessibleLabel:this.accessibleLabel??(this.label||null),maxHeight:this.maxHeight,isDarkTheme:this.isDarkTheme,showSkeleton:!this.highlightLimited&&this.showsSkeleton(),highlightLimited:this.highlightLimited&&!!this.language,highlightedHtml:this.highlightedHtml,lineNumbers:this.lineNumbers,localize:this.localize.bind(this),renderPlainCode:()=>this.cachedPlainCode(),onToggle:this.toggleCollapsed,onCopy:()=>{this.interactions.copy()},bindSelectionBody:this.interactions.bindSelectionBody,onBodyClick:this.interactions.onBodyClick,onBodyKeyDown:this.interactions.onBodyKeyDown,onBodyFocusIn:this.interactions.onBodyFocusIn})}}__decorate([property({type:Boolean,reflect:!0})],LyraCodeBlockBase.prototype,"collapsed",null),__decorate([state()],LyraCodeBlockBase.prototype,"slottedCode",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCodeBlockBase.prototype,"wrap",void 0),__decorate([property({type:Boolean,attribute:"without-dedent",reflect:!0})],LyraCodeBlockBase.prototype,"withoutDedent",null),__decorate([property()],LyraCodeBlockBase.prototype,"label",null),__decorate([property({type:Boolean,attribute:"without-copy",reflect:!0})],LyraCodeBlockBase.prototype,"withoutCopy",null),__decorate([state()],LyraCodeBlockBase.prototype,"hasHeaderActions",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"highlightedHtml",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"shikiReady",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"justCopied",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"copyFailed",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"isDarkTheme",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"grammarUnavailable",void 0);export{LyraCodeBlockBase};
|
|
@@ -253,7 +253,7 @@ readonly anchorKinds:readonly LyraAnchor['kind'][];
|
|
|
253
253
|
* highlighted output. For a TypeScript annotation, use `import type { ShikiLanguageSource } from
|
|
254
254
|
* '@aceshooting/lyra-ui/components/lr-code-block-core.js'`; this granular
|
|
255
255
|
* type-only import emits no registration side effect. */
|
|
256
|
-
languages:Readonly<Record<string,ShikiLanguageSource>>;private highlighterGeneration;private activeLanguages?;connectedCallback():void;protected releaseHighlight():void;protected preSuppliedGrammar():ShikiLanguageSource|undefined;protected grammarMayLoad():boolean;protected beforeHighlightUpdate(changed:PropertyValues):void;
|
|
256
|
+
languages:Readonly<Record<string,ShikiLanguageSource>>;private highlighterGeneration;private activeLanguages?;private effectiveLanguages;connectedCallback():void;protected releaseHighlight():void;protected preSuppliedGrammar():ShikiLanguageSource|undefined;protected grammarMayLoad():boolean;protected beforeHighlightUpdate(changed:PropertyValues):void;
|
|
257
257
|
/** Whether this render shows the loading skeleton instead of the code. Unlike `<lr-code-block>`,
|
|
258
258
|
* the only highlighter this variant ever waits on is the fine-grained one seeded from
|
|
259
259
|
* `languages` -- so a `language` absent from that map has nothing pending and never shows the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{ensureShikiLanguageLoaded,loadShikiHighlighterCore,normalizeShikiLanguage,resolvedShikiLanguages}from"./shiki-types.js";import{styles}from"./code-block.styles.js";import{LyraCodeBlockBase}from"./code-block-base.class.js";import{codeBlockPreSuppliedGrammar,codeBlockShowsSkeleton}from"./code-block-shared.js";import"../../overlays/skeleton/skeleton.class.js";import{LYRA_DEFAULT_codeBlockHighlightLimit,LYRA_DEFAULT_codeBlockToggle,LYRA_DEFAULT_codeRegion,LYRA_DEFAULT_codeRegionWithLanguage,LYRA_DEFAULT_copiedToClipboard,LYRA_DEFAULT_copyCode}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";class LyraCodeBlockCore extends LyraCodeBlockBase{constructor(){super(...arguments),this.code="",this.language="",this.filename="",this.accessibleLabel=null,this.collapsible=!1,this.withoutCopyButton=!1,this.copyAppearance="text",this.maxHeight="",this.lineNumbers=!1,this.highlightLines="",this.activatableLines=!1,this._highlights=snapshotLyraHighlights([]),this.activeHighlightId=null,this.anchorKinds=["line-range"],this.languages={},this.highlighterGeneration=0}static{this.defaultStrings={...super.defaultStrings,codeBlockHighlightLimit:LYRA_DEFAULT_codeBlockHighlightLimit,codeBlockToggle:LYRA_DEFAULT_codeBlockToggle,codeRegion:LYRA_DEFAULT_codeRegion,codeRegionWithLanguage:LYRA_DEFAULT_codeRegionWithLanguage,copied:LYRA_DEFAULT_copied,copiedToClipboard:LYRA_DEFAULT_copiedToClipboard,copy:LYRA_DEFAULT_copy,copyCode:LYRA_DEFAULT_copyCode,copyFailed:LYRA_DEFAULT_copyFailed}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-text-select"])}static{this.ownedCollectionProperties=Object.freeze(["languages"])}static{this.styles=[LyraElement.styles,styles]}get highlights(){return this._highlights}set highlights(value){const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this.requestUpdate("highlights",previous)}connectedCallback(){if(super.connectedCallback(),this.resumedMove)return;const languages=this.
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{ensureShikiLanguageLoaded,loadShikiHighlighterCore,normalizeShikiLanguage,resolvedShikiLanguages}from"./shiki-types.js";import{withRegisteredCodeGrammars}from"./code-grammar-registry.js";import{styles}from"./code-block.styles.js";import{LyraCodeBlockBase}from"./code-block-base.class.js";import{codeBlockPreSuppliedGrammar,codeBlockShowsSkeleton}from"./code-block-shared.js";import"../../overlays/skeleton/skeleton.class.js";import{LYRA_DEFAULT_codeBlockHighlightLimit,LYRA_DEFAULT_codeBlockToggle,LYRA_DEFAULT_codeRegion,LYRA_DEFAULT_codeRegionWithLanguage,LYRA_DEFAULT_copiedToClipboard,LYRA_DEFAULT_copyCode}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";class LyraCodeBlockCore extends LyraCodeBlockBase{constructor(){super(...arguments),this.code="",this.language="",this.filename="",this.accessibleLabel=null,this.collapsible=!1,this.withoutCopyButton=!1,this.copyAppearance="text",this.maxHeight="",this.lineNumbers=!1,this.highlightLines="",this.activatableLines=!1,this._highlights=snapshotLyraHighlights([]),this.activeHighlightId=null,this.anchorKinds=["line-range"],this.languages={},this.highlighterGeneration=0}static{this.defaultStrings={...super.defaultStrings,codeBlockHighlightLimit:LYRA_DEFAULT_codeBlockHighlightLimit,codeBlockToggle:LYRA_DEFAULT_codeBlockToggle,codeRegion:LYRA_DEFAULT_codeRegion,codeRegionWithLanguage:LYRA_DEFAULT_codeRegionWithLanguage,copied:LYRA_DEFAULT_copied,copiedToClipboard:LYRA_DEFAULT_copiedToClipboard,copy:LYRA_DEFAULT_copy,copyCode:LYRA_DEFAULT_copyCode,copyFailed:LYRA_DEFAULT_copyFailed}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-text-select"])}static{this.ownedCollectionProperties=Object.freeze(["languages"])}static{this.styles=[LyraElement.styles,styles]}get highlights(){return this._highlights}set highlights(value){const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this.requestUpdate("highlights",previous)}effectiveLanguages(){return withRegisteredCodeGrammars(this.languages)}connectedCallback(){if(super.connectedCallback(),this.resumedMove)return;const languages=this.effectiveLanguages(),generation=this.activateLanguages(languages);!languages||Object.keys(languages).length===0||loadShikiHighlighterCore(resolvedShikiLanguages(languages)).then(()=>{!this.isConnected||generation!==this.highlighterGeneration||languages!==this.effectiveLanguages()||(this.shikiReady=!0,this.syncHighlight())})}releaseHighlight(){super.releaseHighlight(),this.activeLanguages=void 0,this.highlighterGeneration+=1,this.shikiReady=!1}preSuppliedGrammar(){return codeBlockPreSuppliedGrammar(this.effectiveLanguages(),this.language??"")}grammarMayLoad(){return this.preSuppliedGrammar()!==void 0}beforeHighlightUpdate(changed){changed.has("languages")&&this.activateLanguages(this.effectiveLanguages())}showsSkeleton(){return codeBlockShowsSkeleton(this.shikiReady,this.language,!!this.preSuppliedGrammar())}activateLanguages(languages){return this.activeLanguages===languages?this.highlighterGeneration:(this.activeLanguages=languages,this.highlighterGeneration+=1,this.highlightToken+=1,this.shikiReady=!1,this.highlightedHtml=null,this.highlighterGeneration)}syncHighlight(){const languages=this.effectiveLanguages(),generation=this.activateLanguages(languages),token=++this.highlightToken,lang=normalizeShikiLanguage(this.language??"");if(!lang||this.highlightLimited){this.highlightedHtml=null;return}const source=languages?.[lang]??languages?.[this.language];if(source===void 0){this.highlightedHtml=null,this.grammarUnavailable=!0;return}this.highlightedHtml=null,loadShikiHighlighterCore(resolvedShikiLanguages(languages)).then(async hl=>{if(token!==this.highlightToken||generation!==this.highlighterGeneration||languages!==this.effectiveLanguages())return;if(!hl){if(!this.isConnected)return;this.shikiReady=!0,this.highlightedHtml=null,this.grammarUnavailable=!0;return}const loaded=await ensureShikiLanguageLoaded(hl,lang,source);token===this.highlightToken&&(generation!==this.highlighterGeneration||languages!==this.effectiveLanguages()||this.isConnected&&(this.shikiReady=!0,this.highlightedHtml=loaded?this.tokenize(hl,lang):null,this.grammarUnavailable=this.highlightedHtml===null))})}}__decorate([property()],LyraCodeBlockCore.prototype,"code",void 0),__decorate([property()],LyraCodeBlockCore.prototype,"language",void 0),__decorate([property()],LyraCodeBlockCore.prototype,"filename",void 0),__decorate([property({attribute:"aria-label"})],LyraCodeBlockCore.prototype,"accessibleLabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCodeBlockCore.prototype,"collapsible",void 0),__decorate([property({type:Boolean,attribute:"without-copy-button",reflect:!0})],LyraCodeBlockCore.prototype,"withoutCopyButton",void 0),__decorate([property({attribute:"copy-appearance",reflect:!0})],LyraCodeBlockCore.prototype,"copyAppearance",void 0),__decorate([property({attribute:"max-height"})],LyraCodeBlockCore.prototype,"maxHeight",void 0),__decorate([property({type:Boolean,attribute:"line-numbers",reflect:!0})],LyraCodeBlockCore.prototype,"lineNumbers",void 0),__decorate([property({attribute:"highlight-lines"})],LyraCodeBlockCore.prototype,"highlightLines",void 0),__decorate([property({type:Boolean,attribute:"activatable-lines"})],LyraCodeBlockCore.prototype,"activatableLines",void 0),__decorate([property({attribute:!1})],LyraCodeBlockCore.prototype,"highlights",null),__decorate([property({attribute:"active-highlight-id"})],LyraCodeBlockCore.prototype,"activeHighlightId",void 0),__decorate([property({attribute:!1})],LyraCodeBlockCore.prototype,"languages",void 0);export{LyraCodeBlockCore};
|
|
@@ -274,6 +274,7 @@ readonly anchorKinds:readonly LyraAnchor['kind'][];
|
|
|
274
274
|
* this granular type-only import emits no registration side effect. */
|
|
275
275
|
languages?:Readonly<Record<string,ShikiLanguageInput>>;
|
|
276
276
|
/** Optional lazy grammar loaders, resolved only when their language is requested. Concrete
|
|
277
|
-
* `languages` entries take priority on duplicate keys.
|
|
277
|
+
* `languages` entries take priority on duplicate keys. Both maps win over grammars registered
|
|
278
|
+
* library-wide with `registerCodeGrammar()`. Unset preserves the default highlighter
|
|
278
279
|
* and concrete-grammar paths. Assign a new map object after changing entries. */
|
|
279
|
-
languageLoaders?:Readonly<Record<string,ShikiLanguageLoader>>;private highlighter?;private defaultHighlighterLoading;connectedCallback():void;protected beforeHighlightUpdate(changed:PropertyValues):void;private ensureDefaultHighlighter;protected preSuppliedGrammar():ShikiLanguageInput|undefined;protected hasPreSuppliedGrammar():boolean;protected showsSkeleton():boolean;protected syncHighlight():void;}declare global{interface HTMLElementTagNameMap{'lr-code-block':LyraCodeBlock;}}
|
|
280
|
+
languageLoaders?:Readonly<Record<string,ShikiLanguageLoader>>;private highlighter?;private defaultHighlighterLoading;connectedCallback():void;protected beforeHighlightUpdate(changed:PropertyValues):void;private ensureDefaultHighlighter;protected preSuppliedGrammar():ShikiLanguageInput|undefined;private effectiveLanguages;protected hasPreSuppliedGrammar():boolean;protected refreshRegisteredGrammar():void;protected showsSkeleton():boolean;protected syncHighlight():void;}declare global{interface HTMLElementTagNameMap{'lr-code-block':LyraCodeBlock;}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{combineShikiLanguageSources}from"../../../internal/shiki-language-sources.js";import{resolvedShikiLanguages,ensureShikiLanguageLoaded}from"./shiki-types.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{loadShikiHighlighter,loadShikiLanguage,loadShikiHighlighterCore,normalizeShikiLanguage,shikiHasLoadedLanguage}from"./code-loader.js";import{styles}from"./code-block.styles.js";import{LyraCodeBlockBase}from"./code-block-base.class.js";import{codeBlockPreSuppliedGrammar,codeBlockShowsSkeleton}from"./code-block-shared.js";import"../../overlays/skeleton/skeleton.class.js";import{LYRA_DEFAULT_codeBlockHighlightLimit,LYRA_DEFAULT_codeBlockToggle,LYRA_DEFAULT_codeRegion,LYRA_DEFAULT_codeRegionWithLanguage,LYRA_DEFAULT_copiedToClipboard,LYRA_DEFAULT_copyCode}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";class LyraCodeBlock extends LyraCodeBlockBase{constructor(){super(...arguments),this.code="",this.language="",this.filename="",this.accessibleLabel=null,this.collapsible=!1,this.withoutCopyButton=!1,this.copyAppearance="text",this.maxHeight="",this.lineNumbers=!1,this.highlightLines="",this.activatableLines=!1,this._highlights=snapshotLyraHighlights([]),this.activeHighlightId=null,this.anchorKinds=["line-range"],this.defaultHighlighterLoading=!1}static{this.defaultStrings={...super.defaultStrings,codeBlockHighlightLimit:LYRA_DEFAULT_codeBlockHighlightLimit,codeBlockToggle:LYRA_DEFAULT_codeBlockToggle,codeRegion:LYRA_DEFAULT_codeRegion,codeRegionWithLanguage:LYRA_DEFAULT_codeRegionWithLanguage,copied:LYRA_DEFAULT_copied,copiedToClipboard:LYRA_DEFAULT_copiedToClipboard,copy:LYRA_DEFAULT_copy,copyCode:LYRA_DEFAULT_copyCode,copyFailed:LYRA_DEFAULT_copyFailed}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-text-select"])}static{this.styles=[LyraElement.styles,styles]}get highlights(){return this._highlights}set highlights(value){const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),!this.resumedMove&&(this.ensureDefaultHighlighter(),(this.hasPreSuppliedGrammar()||this.highlighter)&&this.syncHighlight())}beforeHighlightUpdate(changed){(changed.has("code")||changed.has("slottedCode")||changed.has("language")||changed.has("languages")||changed.has("languageLoaders"))&&this.ensureDefaultHighlighter()}ensureDefaultHighlighter(){!this.isConnected||!this.language||this.highlightLimited||this.hasPreSuppliedGrammar()||this.highlighter||this.defaultHighlighterLoading||(this.defaultHighlighterLoading=!0,loadShikiHighlighter().then(hl=>{this.defaultHighlighterLoading=!1,this.isConnected&&(this.highlighter=hl,this.shikiReady=!0,this.syncHighlight())}))}preSuppliedGrammar(){return codeBlockPreSuppliedGrammar(this.languages,this.language??"")}
|
|
1
|
+
import{__decorate}from"tslib";import{combineShikiLanguageSources}from"../../../internal/shiki-language-sources.js";import{resolvedShikiLanguages,ensureShikiLanguageLoaded}from"./shiki-types.js";import{withRegisteredCodeGrammars}from"./code-grammar-registry.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{loadShikiHighlighter,loadShikiLanguage,loadShikiHighlighterCore,normalizeShikiLanguage,shikiHasLoadedLanguage}from"./code-loader.js";import{styles}from"./code-block.styles.js";import{LyraCodeBlockBase}from"./code-block-base.class.js";import{codeBlockPreSuppliedGrammar,codeBlockShowsSkeleton}from"./code-block-shared.js";import"../../overlays/skeleton/skeleton.class.js";import{LYRA_DEFAULT_codeBlockHighlightLimit,LYRA_DEFAULT_codeBlockToggle,LYRA_DEFAULT_codeRegion,LYRA_DEFAULT_codeRegionWithLanguage,LYRA_DEFAULT_copiedToClipboard,LYRA_DEFAULT_copyCode}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";class LyraCodeBlock extends LyraCodeBlockBase{constructor(){super(...arguments),this.code="",this.language="",this.filename="",this.accessibleLabel=null,this.collapsible=!1,this.withoutCopyButton=!1,this.copyAppearance="text",this.maxHeight="",this.lineNumbers=!1,this.highlightLines="",this.activatableLines=!1,this._highlights=snapshotLyraHighlights([]),this.activeHighlightId=null,this.anchorKinds=["line-range"],this.defaultHighlighterLoading=!1}static{this.defaultStrings={...super.defaultStrings,codeBlockHighlightLimit:LYRA_DEFAULT_codeBlockHighlightLimit,codeBlockToggle:LYRA_DEFAULT_codeBlockToggle,codeRegion:LYRA_DEFAULT_codeRegion,codeRegionWithLanguage:LYRA_DEFAULT_codeRegionWithLanguage,copied:LYRA_DEFAULT_copied,copiedToClipboard:LYRA_DEFAULT_copiedToClipboard,copy:LYRA_DEFAULT_copy,copyCode:LYRA_DEFAULT_copyCode,copyFailed:LYRA_DEFAULT_copyFailed}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-text-select"])}static{this.styles=[LyraElement.styles,styles]}get highlights(){return this._highlights}set highlights(value){const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),!this.resumedMove&&(this.ensureDefaultHighlighter(),(this.hasPreSuppliedGrammar()||this.highlighter)&&this.syncHighlight())}beforeHighlightUpdate(changed){(changed.has("code")||changed.has("slottedCode")||changed.has("language")||changed.has("languages")||changed.has("languageLoaders"))&&this.ensureDefaultHighlighter()}ensureDefaultHighlighter(){!this.isConnected||!this.language||this.highlightLimited||this.hasPreSuppliedGrammar()||this.highlighter||this.defaultHighlighterLoading||(this.defaultHighlighterLoading=!0,loadShikiHighlighter().then(hl=>{this.defaultHighlighterLoading=!1,this.isConnected&&(this.highlighter=hl,this.shikiReady=!0,this.syncHighlight())}))}preSuppliedGrammar(){return codeBlockPreSuppliedGrammar(this.languages,this.language??"")}effectiveLanguages(){return withRegisteredCodeGrammars(combineShikiLanguageSources(this.languages,this.languageLoaders))}hasPreSuppliedGrammar(){if(this.preSuppliedGrammar())return!0;const effective=this.effectiveLanguages();return effective!==this.languages&&!!codeBlockPreSuppliedGrammar(effective,this.language??"")}refreshRegisteredGrammar(){this.ensureDefaultHighlighter(),this.hasPreSuppliedGrammar()||this.highlighter?this.syncHighlight():(this.highlightToken++,this.highlightedHtml=null)}showsSkeleton(){return codeBlockShowsSkeleton(this.shikiReady,this.language,!this.hasPreSuppliedGrammar())}syncHighlight(){const token=++this.highlightToken,lang=normalizeShikiLanguage(this.language??"");if(!lang||this.highlightLimited){this.highlightedHtml=null;return}const languages=this.effectiveLanguages(),source=languages?.[lang]??languages?.[this.language];if(languages&&source){this.highlightedHtml=null,loadShikiHighlighterCore(resolvedShikiLanguages(languages)).then(async hl2=>{if(token!==this.highlightToken||!this.isConnected)return;const loaded=hl2&&await ensureShikiLanguageLoaded(hl2,lang,source);token!==this.highlightToken||!this.isConnected||(this.highlightedHtml=loaded&&hl2?this.tokenize(hl2,lang):null,this.grammarUnavailable=this.highlightedHtml===null)});return}const hl=this.highlighter;if(!hl){this.highlightedHtml=null,hl===null&&(this.grammarUnavailable=!0);return}if(shikiHasLoadedLanguage(hl,lang)){this.highlightedHtml=this.tokenize(hl,lang),this.grammarUnavailable=this.highlightedHtml===null;return}this.highlightedHtml=null,loadShikiLanguage(hl,lang).then(ok=>{token===this.highlightToken&&this.isConnected&&(this.highlightedHtml=ok?this.tokenize(hl,lang):null,this.grammarUnavailable=this.highlightedHtml===null)})}}__decorate([property()],LyraCodeBlock.prototype,"code",void 0),__decorate([property()],LyraCodeBlock.prototype,"language",void 0),__decorate([property()],LyraCodeBlock.prototype,"filename",void 0),__decorate([property({attribute:"aria-label"})],LyraCodeBlock.prototype,"accessibleLabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCodeBlock.prototype,"collapsible",void 0),__decorate([property({type:Boolean,attribute:"without-copy-button",reflect:!0})],LyraCodeBlock.prototype,"withoutCopyButton",void 0),__decorate([property({attribute:"copy-appearance",reflect:!0})],LyraCodeBlock.prototype,"copyAppearance",void 0),__decorate([property({attribute:"max-height"})],LyraCodeBlock.prototype,"maxHeight",void 0),__decorate([property({type:Boolean,attribute:"line-numbers",reflect:!0})],LyraCodeBlock.prototype,"lineNumbers",void 0),__decorate([property({attribute:"highlight-lines"})],LyraCodeBlock.prototype,"highlightLines",void 0),__decorate([property({type:Boolean,attribute:"activatable-lines"})],LyraCodeBlock.prototype,"activatableLines",void 0),__decorate([property({attribute:!1})],LyraCodeBlock.prototype,"highlights",null),__decorate([property({attribute:"active-highlight-id"})],LyraCodeBlock.prototype,"activeHighlightId",void 0),__decorate([property({attribute:!1})],LyraCodeBlock.prototype,"languages",void 0),__decorate([property({attribute:!1})],LyraCodeBlock.prototype,"languageLoaders",void 0);export{LyraCodeBlock};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Library-level registry of syntax grammars for `<lr-code-block>` and `<lr-code-block-core>`.
|
|
3
|
+
*
|
|
4
|
+
* A grammar registered here is available to every code block on the page, so an application can
|
|
5
|
+
* register a language once instead of passing a `languages` or `languageLoaders` map to each
|
|
6
|
+
* element. A per-element map always wins over this registry for the same language, and a block
|
|
7
|
+
* whose language is registered after it rendered re-highlights immediately.
|
|
8
|
+
*
|
|
9
|
+
* The module is side-effect-free and holds no element references: each connected code block
|
|
10
|
+
* subscribes while connected and unsubscribes when it disconnects.
|
|
11
|
+
*/
|
|
12
|
+
import type{ShikiLanguageSource}from'../../../internal/shiki/core.js';
|
|
13
|
+
/** Options for {@link registerCodeGrammar}.*/
|
|
14
|
+
export interface LyraCodeGrammarOptions{
|
|
15
|
+
/** Further language ids that resolve to the same grammar (for example `['gcl']`).*/
|
|
16
|
+
aliases?:readonly string[];}
|
|
17
|
+
/**
|
|
18
|
+
* Registers a grammar for every `<lr-code-block>` and `<lr-code-block-core>`, replacing one already
|
|
19
|
+
* registered under the same name. `grammarOrLoader` is a Shiki grammar object (or an array of them,
|
|
20
|
+
* as a grammar module's default export) or a lazy loader such as
|
|
21
|
+
* `() => import('@shikijs/langs/rust')`; a loader runs the first time a block needs that language.
|
|
22
|
+
* A language set on the element's own `languages` or `languageLoaders` map takes priority over the
|
|
23
|
+
* registry. Code blocks already showing that language re-highlight at once, so registration may
|
|
24
|
+
* happen after they rendered. A loader that fails leaves the block on its localized plain-text
|
|
25
|
+
* fallback. Names and aliases are case-insensitive; an alias that is already registered by another
|
|
26
|
+
* grammar moves to this one.
|
|
27
|
+
*
|
|
28
|
+
* @throws {TypeError} when the name, an alias or the grammar is invalid; nothing is registered then.
|
|
29
|
+
*/
|
|
30
|
+
export declare function registerCodeGrammar(name:string,grammarOrLoader:ShikiLanguageSource,options?:LyraCodeGrammarOptions):void;
|
|
31
|
+
/** Removes a grammar registered under `name` together with its aliases. Code blocks showing that
|
|
32
|
+
* language fall back to their default highlighting. Unknown names are ignored. */
|
|
33
|
+
export declare function unregisterCodeGrammar(name:string):void;
|
|
34
|
+
/** The grammar source registered for `name` (or one of its aliases), or `undefined`.*/
|
|
35
|
+
export declare function getCodeGrammar(name:string):ShikiLanguageSource|undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{normalizeShikiLanguage}from"../../../internal/shiki/core.js";const LISTENER_WARNING_KEY="lyra-code-grammar-listener-threw",LISTENER_WARNING="<lr-code-block> ignored a throwing code grammar listener.",MAX_GRAMMAR_NAME_LENGTH=64,MAX_GRAMMAR_ALIASES=32,GRAMMAR_NAME_PATTERN=/^[a-z0-9][a-z0-9._+#-]*$/,grammars=new Map,listeners=new Set;let version=0,snapshot;function validId(value,what){if(typeof value!="string")throw new TypeError(`${what} must be a string.`);const id=normalizeShikiLanguage(value);if(id.length===0||id.length>MAX_GRAMMAR_NAME_LENGTH||!GRAMMAR_NAME_PATTERN.test(id))throw new TypeError(`${what} must be 1-${MAX_GRAMMAR_NAME_LENGTH} characters of letters, digits and . _ + # -.`);return id}function notify(keys){if(version+=1,snapshot=void 0,keys.size!==0)for(const listener of[...listeners])try{listener(keys)}catch{devWarnOnce(LISTENER_WARNING_KEY,LISTENER_WARNING)}}function registerCodeGrammar(name,grammarOrLoader,options={}){const id=validId(name,"registerCodeGrammar() name");if(grammarOrLoader===null||typeof grammarOrLoader!="object"&&typeof grammarOrLoader!="function")throw new TypeError("registerCodeGrammar() needs a grammar object or a loader function.");const rawAliases=options?.aliases;if(rawAliases!==void 0&&!Array.isArray(rawAliases))throw new TypeError("registerCodeGrammar() aliases must be an array of strings.");if(rawAliases&&rawAliases.length>MAX_GRAMMAR_ALIASES)throw new TypeError(`registerCodeGrammar() accepts at most ${MAX_GRAMMAR_ALIASES} aliases.`);const ids=new Set([id]);for(const alias of rawAliases??[])ids.add(validId(alias,"registerCodeGrammar() alias"));const changed=new Set(ids);for(const[key,entry2]of grammars)entry2.owner===id&&(grammars.delete(key),changed.add(key));const entry={owner:id,source:grammarOrLoader};for(const key of ids)grammars.set(key,entry);notify(changed)}function unregisterCodeGrammar(name){if(typeof name!="string")return;const id=normalizeShikiLanguage(name),changed=new Set;for(const[key,entry]of grammars)entry.owner===id&&(grammars.delete(key),changed.add(key));notify(changed)}function getCodeGrammar(name){if(typeof name=="string")return grammars.get(normalizeShikiLanguage(name))?.source}function subscribeCodeGrammars(listener){return listeners.add(listener),()=>{listeners.delete(listener)}}const noElementMap={},mergedByElementMap=new WeakMap;function registeredSnapshot(){if(!snapshot){const next=Object.create(null);for(const[key,entry]of grammars)next[key]=entry.source;snapshot=Object.freeze(next)}return snapshot}function withRegisteredCodeGrammars(elementMap){if(grammars.size===0)return elementMap;const key=elementMap!==null&&typeof elementMap=="object"?elementMap:noElementMap,cached=mergedByElementMap.get(key);if(cached&&cached.version===version)return cached.merged;const merged=Object.create(null);if(Object.assign(merged,registeredSnapshot()),key!==noElementMap){let names=[];try{names=Object.getOwnPropertyNames(key)}catch{}for(const name of names){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(key,name)}catch{continue}if(!descriptor?.enumerable||!("value"in descriptor)||descriptor.value===void 0)continue;merged[name]=descriptor.value;const normalized=normalizeShikiLanguage(name);normalized!==name&&!Object.hasOwn(key,normalized)&&(merged[normalized]=descriptor.value)}}return Object.freeze(merged),mergedByElementMap.set(key,{version,merged}),merged}export{getCodeGrammar,registerCodeGrammar,subscribeCodeGrammars,unregisterCodeGrammar,withRegisteredCodeGrammars};
|
|
@@ -93,11 +93,10 @@ export type LyraModelSelectSelectionDirection=LyraSelectionDirection;export inte
|
|
|
93
93
|
* @cssprop [--lr-form-control-label-text-align=inherit] - Text alignment of the field label.
|
|
94
94
|
* @cssprop [--lr-form-control-label-text-transform=inherit] - Text transform of the field label.
|
|
95
95
|
* @cssprop [--lr-form-control-label-inline-size=30%] - Label column width while
|
|
96
|
-
* `label-placement="start"
|
|
97
|
-
* @cssprop [--lr-form-control-label-gap
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
* the field and the field, in top placement and once a `label-placement="start"` row collapses.
|
|
96
|
+
* `label-placement="start"`; `auto` sizes the column to the label text.
|
|
97
|
+
* @cssprop [--lr-form-control-label-gap] - Space between the label and the field: the label
|
|
98
|
+
* column gap while `label-placement="start"` (default `var(--lr-space-m)`), and the gap under a
|
|
99
|
+
* label above the field, in top placement or a collapsed start row (default `var(--lr-space-xs)`).
|
|
101
100
|
* @cssprop [--lr-form-control-label-collapse-inline-size=var(--lr-size-20rem)] - Control width
|
|
102
101
|
* below which `label-placement="start"` returns the label above the field.
|
|
103
102
|
* @csspart form-control-label - The `<label>` element containing the `label` property and slot.
|
|
@@ -161,8 +160,10 @@ export type LyraModelSelectSelectionDirection=LyraSelectionDirection;export inte
|
|
|
161
160
|
* @cssprop [--lr-overlay-border=var(--lr-color-border)] - Shared floating-surface edge colour, on
|
|
162
161
|
* the listbox. Unlike a floating panel's decorative edge, it defaults to
|
|
163
162
|
* the control tier: this popup belongs to the control it opens from.
|
|
164
|
-
* @cssprop
|
|
165
|
-
* the
|
|
163
|
+
* @cssprop --lr-overlay-radius - Shared floating-surface corner radius, read by the listbox only as
|
|
164
|
+
* the middle arm of `--lr-model-select-radius`, which still wins when set. Left unset, the listbox keeps
|
|
165
|
+
* this component's own radius default instead of the overlay family's `var(--lr-radius-container)`,
|
|
166
|
+
* so it keeps matching the trigger.
|
|
166
167
|
* @cssprop [--lr-overlay-shadow-anchored=var(--lr-shadow-m)] - Elevation of the anchored surface.
|
|
167
168
|
* @cssprop --lr-form-control-height - Default minimum trigger height.
|
|
168
169
|
* @cssprop --lr-form-control-padding-block - Default block padding of the trigger.
|
|
@@ -45,7 +45,7 @@ import type{LyraEventDetailSnapshot}from'../../../internal/lyra-element.js';impo
|
|
|
45
45
|
* on the toolbar.
|
|
46
46
|
* @cssprop [--lr-overlay-border=var(--lr-color-border-subtle)] - Shared floating-surface edge
|
|
47
47
|
* colour, on the toolbar.
|
|
48
|
-
* @cssprop [--lr-overlay-radius=var(--lr-radius)] - Shared floating-surface corner radius, on
|
|
48
|
+
* @cssprop [--lr-overlay-radius=var(--lr-radius-container)] - Shared floating-surface corner radius, on
|
|
49
49
|
* the toolbar.
|
|
50
50
|
* @cssprop [--lr-overlay-shadow-anchored=var(--lr-shadow-m)] - Elevation of the anchored surface.
|
|
51
51
|
* @status stable
|
|
@@ -48,7 +48,7 @@ import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from
|
|
|
48
48
|
* on the anchored breakdown tooltip.
|
|
49
49
|
* @cssprop [--lr-overlay-border=var(--lr-color-border-subtle)] - Shared floating-surface edge
|
|
50
50
|
* colour, on the anchored breakdown tooltip.
|
|
51
|
-
* @cssprop [--lr-overlay-radius=var(--lr-radius)] - Shared floating-surface corner radius, on the
|
|
51
|
+
* @cssprop [--lr-overlay-radius=var(--lr-radius-container)] - Shared floating-surface corner radius, on the
|
|
52
52
|
* anchored breakdown tooltip.
|
|
53
53
|
* @cssprop [--lr-overlay-shadow-anchored=var(--lr-shadow-m)] - Elevation of the anchored surface.
|
|
54
54
|
* @cssprop --lr-positioning-strategy - Cascading `absolute`/`fixed` override for the breakdown
|
|
@@ -113,11 +113,10 @@ export type LyraVoicePickerSelectionDirection=LyraSelectionDirection;export inte
|
|
|
113
113
|
* @cssprop [--lr-form-control-label-text-align=inherit] - Text alignment of the field label.
|
|
114
114
|
* @cssprop [--lr-form-control-label-text-transform=inherit] - Text transform of the field label.
|
|
115
115
|
* @cssprop [--lr-form-control-label-inline-size=30%] - Label column width while
|
|
116
|
-
* `label-placement="start"
|
|
117
|
-
* @cssprop [--lr-form-control-label-gap
|
|
118
|
-
*
|
|
119
|
-
*
|
|
120
|
-
* the field and the field, in top placement and once a `label-placement="start"` row collapses.
|
|
116
|
+
* `label-placement="start"`; `auto` sizes the column to the label text.
|
|
117
|
+
* @cssprop [--lr-form-control-label-gap] - Space between the label and the field: the label
|
|
118
|
+
* column gap while `label-placement="start"` (default `var(--lr-space-m)`), and the gap under a
|
|
119
|
+
* label above the field, in top placement or a collapsed start row (default `var(--lr-space-xs)`).
|
|
121
120
|
* @cssprop [--lr-form-control-label-collapse-inline-size=var(--lr-size-20rem)] - Control width
|
|
122
121
|
* below which `label-placement="start"` returns the label above the field.
|
|
123
122
|
* @csspart form-control-label - The `<label>` element containing the `label` property and slot.
|
|
@@ -198,8 +197,10 @@ export type LyraVoicePickerSelectionDirection=LyraSelectionDirection;export inte
|
|
|
198
197
|
* @cssprop [--lr-overlay-border=var(--lr-color-border)] - Shared floating-surface edge colour, on
|
|
199
198
|
* the listbox. Unlike a floating panel's decorative edge, it defaults to
|
|
200
199
|
* the control tier: this popup belongs to the control it opens from.
|
|
201
|
-
* @cssprop
|
|
202
|
-
* the
|
|
200
|
+
* @cssprop --lr-overlay-radius - Shared floating-surface corner radius, read by the listbox only as
|
|
201
|
+
* the middle arm of `--lr-voice-picker-radius`, which still wins when set. Left unset, the listbox keeps
|
|
202
|
+
* this component's own radius default instead of the overlay family's `var(--lr-radius-container)`,
|
|
203
|
+
* so it keeps matching the trigger.
|
|
203
204
|
* @cssprop [--lr-overlay-shadow-anchored=var(--lr-shadow-m)] - Elevation of the anchored surface.
|
|
204
205
|
* @cssprop --lr-voice-picker-expand-size - Maximum minimum hit-area size of the expand control; capped by the shared icon target size.
|
|
205
206
|
* @cssprop --lr-voice-picker-font-size - Trigger text size, defaulting to the selected component size.
|
|
@@ -334,6 +334,5 @@ export interface LyraTableEventMap<T=unknown,K extends string|number=string|numb
|
|
|
334
334
|
'lr-row-activate':CustomEvent<Readonly<{row:T;}>>;'lr-row-expand-request':CustomEvent<Readonly<{row:T;rowKey:K;expanded:boolean;}>>;'lr-row-expand-toggle':CustomEvent<Readonly<{row:T;rowKey:K;expanded:boolean;}>>;'lr-load-more':CustomEvent<null>;'lr-retry-request':CustomEvent<null>;'lr-selection-change':CustomEvent<Readonly<{selectedRowKeys:readonly K[];}>>;'lr-filter-change':CustomEvent<Readonly<{filterText:string;}>>;
|
|
335
335
|
/** One-based `page`; `offset` is `(page - 1) * pageSize`.*/
|
|
336
336
|
'lr-before-page-change':CustomEvent<Readonly<{page:number;pageSize:number;offset:number;}>>;
|
|
337
|
-
/**
|
|
338
|
-
|
|
339
|
-
'lr-page-change':CustomEvent<Readonly<{page:number;pageSize?:number;offset?:number;}>>;'lr-cell-edit':CustomEvent<Readonly<{row:T;columnKey:string;value:string|number;}>>;'lr-column-resize-request':CustomEvent<Readonly<{columnKey:string;width:number;}>>;'lr-column-resize':CustomEvent<Readonly<{columnKey:string;width:number;}>>;}export{};
|
|
337
|
+
/** Same shape as `lr-before-page-change`: one-based `page`; `offset` is `(page - 1) * pageSize`.*/
|
|
338
|
+
'lr-page-change':CustomEvent<Readonly<{page:number;pageSize:number;offset:number;}>>;'lr-cell-edit':CustomEvent<Readonly<{row:T;columnKey:string;value:string|number;}>>;'lr-column-resize-request':CustomEvent<Readonly<{columnKey:string;width:number;}>>;'lr-column-resize':CustomEvent<Readonly<{columnKey:string;width:number;}>>;}export{};
|
|
@@ -53,7 +53,8 @@ import type{LyraPaginationFormat}from'../pagination/pagination.class.js';import{
|
|
|
53
53
|
* the zero-based index of the page's first row. The nested pager's own event of this name stops
|
|
54
54
|
* inside the shadow root, so one page action reaches a document listener once, targeted at the
|
|
55
55
|
* table. Vetoing it keeps `page` and suppresses `lr-page-change`.
|
|
56
|
-
* @event lr-page-change - A pagination control requested a page. Frozen readonly `detail: { page, pageSize, offset }
|
|
56
|
+
* @event lr-page-change - A pagination control requested a page. Frozen readonly `detail: { page, pageSize, offset }`,
|
|
57
|
+
* all three always present (the same shape as `lr-before-page-change` and `<lr-pagination>`);
|
|
57
58
|
* `page` is one-based and `offset` is `(page - 1) * pageSize`.
|
|
58
59
|
* @event lr-cell-edit - An inline editor committed a value. `detail: { row, columnKey, value }`.
|
|
59
60
|
* @event lr-column-resize-request - Cancelable proposal before accepting a keyboard resize or
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraOrientation}from'../../../internal/shared-unions.js';import type{LyraTimelineItem}from'./timeline-item.class.js';
|
|
2
|
+
/** Layout axis of a timeline. `auto` runs it as a row while its measured inline size gives every
|
|
3
|
+
* item about 10em, and as a column otherwise. */
|
|
4
|
+
export type LyraTimelineOrientation=LyraOrientation|'auto';
|
|
2
5
|
/** Which side of its content an item's marker sits on; `alternate` swaps sides on every other item.*/
|
|
3
6
|
export type LyraTimelineMarkerPlacement='start'|'end'|'alternate';
|
|
4
7
|
/** Where a marker sits along its item's block extent.*/
|
|
@@ -49,8 +52,9 @@ readonly items:readonly LyraTimelineItem[];}export interface LyraTimelineEventMa
|
|
|
49
52
|
* landmark, so it doesn't need a two-layer `base`+`list` split). Flex container: `flex-direction:
|
|
50
53
|
* column` in `vertical` orientation (the default), `flex-direction: row` (with `overflow-x: auto`,
|
|
51
54
|
* `overflow-y: hidden`, and an edge-fade `mask-image` applied only while the strip actually
|
|
52
|
-
* overflows) in `horizontal` orientation
|
|
53
|
-
*
|
|
55
|
+
* overflows) in `horizontal` orientation and while an `auto` timeline runs as a row. Its
|
|
56
|
+
* `tabindex` rises from `-1` to `0` while (and only while) that horizontal strip genuinely
|
|
57
|
+
* overflows: timeline items are passive, so nothing
|
|
54
58
|
* inside is tabbable and the off-screen events would otherwise be pointer-only content. Style
|
|
55
59
|
* that state with `::part(base):focus-visible`.
|
|
56
60
|
* @cssprop [--lr-timeline-gap=var(--lr-space-l)] - Spacing between consecutive items along the
|
|
@@ -91,11 +95,18 @@ readonly items:readonly LyraTimelineItem[];}export interface LyraTimelineEventMa
|
|
|
91
95
|
export declare class LyraTimeline extends LyraElement<LyraTimelineEventMap>{protected static collectionSupport:import("../../../internal/lyra-element.js").LyraCollectionSupport;protected static readonly immutableEventDetails:readonly string[];protected static readonly identityEventDetailProperties:Readonly<{'lr-cluster-activate':readonly string[];}>;static styles:import("lit").CSSResultGroup[];private _orientation;
|
|
92
96
|
/** `'vertical'` (the default) lays items out in a column, the primary/most-common use case — an
|
|
93
97
|
* audit trail or agent history reads top-to-bottom. `'horizontal'` lays them out in a row.
|
|
94
|
-
*
|
|
95
|
-
* of
|
|
98
|
+
* `'auto'` picks between the two from the timeline's own measured inline size: a row while
|
|
99
|
+
* every item gets about 10em of it, a column otherwise, so a phone-width or narrow-pane timeline
|
|
100
|
+
* stacks with no breakpoint to author. An `auto` timeline renders as a column until it has
|
|
101
|
+
* been measured (including server-rendered markup). Read `effectiveOrientation` for the axis
|
|
102
|
+
* in effect. An unrecognized value keeps the `'vertical'` default.
|
|
96
103
|
* Deliberately differs from `<lr-stepper>`'s `'horizontal'` default — don't copy that default by
|
|
97
104
|
* habit. */
|
|
98
|
-
get orientation():
|
|
105
|
+
get orientation():LyraTimelineOrientation;set orientation(value:LyraTimelineOrientation);private _effectiveOrientation;
|
|
106
|
+
/** The layout axis in effect: `orientation` itself, or the measured choice of an
|
|
107
|
+
* `orientation="auto"` timeline (`'vertical'` until it has been measured). While `auto`, the
|
|
108
|
+
* host also carries a `data-effective-orientation` attribute with the same value. */
|
|
109
|
+
get effectiveOrientation():LyraOrientation;private measuredInlineSize;private readonly autoOrientationFrame;private readonly autoOrientationObserver;private _markerPlacement;
|
|
99
110
|
/** Which side of its content each item's marker sits on while the timeline runs as a column.
|
|
100
111
|
* `'start'` (the default) puts the marker before the content, `'end'` after it, and `'alternate'`
|
|
101
112
|
* switches sides on every other item so the rail runs down the middle, with an item's
|
|
@@ -167,7 +178,7 @@ rangeEnd?:Date|string|number;
|
|
|
167
178
|
* never inherits a host attribute automatically — same reasoning as `<lr-breadcrumb>`'s
|
|
168
179
|
* identical property. Unset falls back to the localized default; an explicitly empty
|
|
169
180
|
* `aria-label` stays empty. */
|
|
170
|
-
accessibleLabel:string|null;private slottedCount;private collisionClusters;private readonly managedClusterHiddenItems;private readonly managedClusterRepresentatives;private readonly clusterActivations;private readonly timestampObservedItems;private readonly numberedItems;private clusterMeasurementFrame?;private clusterMeasurementView?;private readonly timeExtentFrame;private focusRepairGeneration;private cachedTimelineItems?;private readonly timePositionedItems;private readonly overflowObservedItems;private overflowItemsPending;private timeGeometryObserver?;private timeGeometryBase?;private timeGeometryView?;private readonly geometryObservedItems;private readonly itemGeometry;private scrollOverflow;requestUpdate(...args:Parameters<LyraElement['requestUpdate']>):void;connectedCallback():void;disconnectedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private syncScrollTabStop;private countTimelineItems;firstUpdated(changed:PropertyValues):void;
|
|
181
|
+
accessibleLabel:string|null;private slottedCount;private collisionClusters;private readonly managedClusterHiddenItems;private readonly managedClusterRepresentatives;private readonly clusterActivations;private readonly timestampObservedItems;private readonly numberedItems;private clusterMeasurementFrame?;private clusterMeasurementView?;private readonly timeExtentFrame;private focusRepairGeneration;private cachedTimelineItems?;private readonly timePositionedItems;private readonly overflowObservedItems;private overflowItemsPending;private timeGeometryObserver?;private timeGeometryBase?;private timeGeometryView?;private readonly geometryObservedItems;private readonly itemGeometry;private scrollOverflow;requestUpdate(...args:Parameters<LyraElement['requestUpdate']>):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private armAutoOrientation;private resetAutoOrientation;private syncEffectiveOrientation;private autoRunsAsRow;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private syncScrollTabStop;private countTimelineItems;firstUpdated(changed:PropertyValues):void;
|
|
171
182
|
/** Read-only, live-updated count of default-slot `<lr-timeline-item>` assignments, including
|
|
172
183
|
* flattened forwarding slots — handy for building a `"{count} events"` header without
|
|
173
184
|
* hand-counting DOM children. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{OwnedFrame}from"../../../internal/owned-timer.js";import{layoutScale,toLayoutRect}from"../../../internal/layout-scale.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html}from"lit";import{property,state}from"lit/decorators.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter,blankNumberConverter}from"../../../internal/converters.js";import{tag}from"../../../internal/prefix.js";import{observeScrollOverflow,SCROLL_OVERFLOW_ATTRIBUTE}from"../../../internal/scroll-overflow.js";import{isUsableActiveElement,safeDeepActiveElement}from"../../../internal/active-element.js";import{OBSERVE_TIMELINE_ITEM_TIMESTAMP,SET_TIMELINE_CLUSTER_PRESENTATION,SET_TIMELINE_ITEM_ORDINAL,TIMELINE_ITEM_ORDINAL_OF,isTimelineClusterItemContract,isTimelineOrdinalItem,timeValueChanged}from"./timeline-cluster.js";import{finiteInteger}from"../../../internal/numbers.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{styles}from"./timeline.styles.js";import{LYRA_DEFAULT_timeline,LYRA_DEFAULT_timelineClusterCount}from"../../../internal/default-strings/data.generated.js";const TIMELINE_ORIENTATION=literalSetConverter(["vertical","horizontal"],"vertical"),TIMELINE_MARKER_PLACEMENT=literalSetConverter(["start","end","alternate"],"start"),TIMELINE_MARKER_ALIGNMENT=literalSetConverter(["start","center"],"start");function safelyContainsActive(container,candidate){if(!isUsableActiveElement(candidate))return!1;try{return container.contains(candidate)}catch{return!1}}const TIMELINE_SCALE=literalSetConverter(["flow","time"],"flow"),TIMELINE_COLLISION=literalSetConverter(["overlap","stack","cluster"],"overlap"),EMPTY_TIMELINE_CLUSTERS=/* @__PURE__ */(()=>Object.freeze([]))(),CLUSTER_HIDDEN_ATTRIBUTE="data-lr-timeline-cluster-hidden",TIMELINE_COLLISION_THRESHOLD=.015;function timelineEpochMs(raw){if(raw==null)return null;const ms=(raw instanceof Date?raw:typeof raw=="number"?new Date(raw):new Date(String(raw))).getTime();return Number.isFinite(ms)?ms:null}function itemEpochMs(element){return timelineEpochMs(element.timestamp)}class LyraTimeline extends LyraElement{constructor(){super(...arguments),this._orientation="vertical",this._markerPlacement="start",this._markerAlignment="start",this.label="",this._scale="flow",this._collision="overlap",this.ordered=!1,this.start=1,this.accessibleLabel=null,this.slottedCount=0,this.collisionClusters=EMPTY_TIMELINE_CLUSTERS,this.managedClusterHiddenItems=new Set,this.managedClusterRepresentatives=new Set,this.clusterActivations=new Map,this.timestampObservedItems=new Set,this.numberedItems=new Set,this.timeExtentFrame=new OwnedFrame(this),this.focusRepairGeneration=0,this.timePositionedItems=new Set,this.overflowObservedItems=new Set,this.overflowItemsPending=!0,this.geometryObservedItems=new Set,this.itemGeometry=new Map,this.scrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part~="base"]'),()=>{this.scheduleTimeExtentMeasurement(),this.scale==="time"&&this.collision==="cluster"&&this.scheduleClusterMeasurement(),this.syncScrollTabStop()}),this.onSlotChange=()=>{this.cachedTimelineItems=void 0,this.overflowItemsPending=!0,this.invalidateTimeGeometry();const current=new Set(this.timelineItems());for(const item of this.overflowObservedItems)current.has(item)||this.overflowObservedItems.delete(item);this.updateBrowserDerivedState(()=>{this.slottedCount=current.size,this.applyTimeScale(),this.syncItemObservations()}),this.syncOrdinals()},this.onTimelineItemTimestampChange=()=>{this.isConnected&&this.scheduleAfterUpdate(()=>this.applyTimeScale(),"timeline-item-timestamps")}}static{this.defaultStrings={...super.defaultStrings,timeline:LYRA_DEFAULT_timeline,timelineClusterCount:LYRA_DEFAULT_timelineClusterCount}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-cluster-activate"])}static{this.identityEventDetailProperties=Object.freeze({"lr-cluster-activate":Object.freeze(["items"])})}static{this.styles=[LyraElement.styles,scrollOverflowFadeStyles,styles]}get orientation(){return this._orientation}set orientation(value){const normalized=TIMELINE_ORIENTATION.normalizeReflected(this,"orientation",value),previous=this._orientation;previous!==normalized&&(this._orientation=normalized,this.requestUpdate("orientation",previous))}get markerPlacement(){return this._markerPlacement}set markerPlacement(value){const normalized=TIMELINE_MARKER_PLACEMENT.normalizeReflected(this,"marker-placement",value),previous=this._markerPlacement;previous!==normalized&&(this._markerPlacement=normalized,this.requestUpdate("markerPlacement",previous))}get markerAlignment(){return this._markerAlignment}set markerAlignment(value){const normalized=TIMELINE_MARKER_ALIGNMENT.normalizeReflected(this,"marker-alignment",value),previous=this._markerAlignment;previous!==normalized&&(this._markerAlignment=normalized,this.requestUpdate("markerAlignment",previous))}get scale(){return this._scale}set scale(value){const normalized=TIMELINE_SCALE.normalizeReflected(this,"scale",value),previous=this._scale;previous!==normalized&&(this._scale=normalized,this.requestUpdate("scale",previous))}get collision(){return this._collision}set collision(value){const normalized=TIMELINE_COLLISION.normalizeReflected(this,"collision",value),previous=this._collision;previous!==normalized&&(this._collision=normalized,this.requestUpdate("collision",previous))}requestUpdate(...args){args[0]===void 0&&this.itemGeometry?.clear(),super.requestUpdate(...args)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.scheduleAfterUpdate(()=>{this.applyTimeScale(),this.syncItemObservations(),this.syncOrdinals()},"timeline-clusters")}disconnectedCallback(){this.cancelClusterMeasurement(),this.timeExtentFrame.cancel(),this.focusRepairGeneration+=1,this.restoreClusterPresentation(),this.restoreClusterVisibility(),this.syncTimestampObservers([]),this.cachedTimelineItems=void 0,this.syncOrdinals(),this.overflowObservedItems.clear(),this.overflowItemsPending=!0,this.stopTimeGeometryObserver(),this.collisionClusters.length>0&&(this.collisionClusters=EMPTY_TIMELINE_CLUSTERS),super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.slottedCount=Array.from(this.children).filter(element=>!element.getAttribute("slot")&&element.localName===tag("timeline-item")).length),this.hasUpdated?(changed.has("scale")||changed.has("collision")||changed.has("rangeStart")||changed.has("rangeEnd"))&&this.applyTimeScale():this.seedFirstRenderState(()=>this.applyTimeScale())}updated(changed){super.updated(changed),(changed.size===0||[...changed.keys()].some(key=>key!=="accessibleLabel"))&&this.invalidateTimeGeometry(),(this.overflowItemsPending||changed.has("scale")||changed.has("orientation"))&&this.syncItemObservations(),(changed.has("ordered")||changed.has("start"))&&this.syncOrdinals(),this.syncScrollTabStop(),this.scheduleTimeExtentMeasurement(),(changed.has("collisionClusters")||changed.has("orientation"))&&this.collisionClusters.length>0&&this.scheduleAfterUpdate(()=>this.applyTimeScale(),"timeline-cluster-measurement"),this.collisionClusters.length>0&&this.syncClusterPresentations(this.collisionClusters)}syncScrollTabStop(){const base=this.renderRoot.querySelector('[part~="base"]');if(!base)return;const reachableOnlyByScrolling=this.orientation==="horizontal"&&base.hasAttribute(SCROLL_OVERFLOW_ATTRIBUTE);base.setAttribute("tabindex",reachableOnlyByScrolling?"0":"-1")}countTimelineItems(slot){return slot.assignedElements({flatten:!0}).filter(element=>element.localName===tag("timeline-item")).length}firstUpdated(changed){super.firstUpdated(changed),this.scheduleAfterUpdate(()=>this.updateBrowserDerivedState(()=>{const slot=this.shadowRoot.querySelector("slot");this.cachedTimelineItems=void 0,this.overflowItemsPending=!0,this.slottedCount=this.countTimelineItems(slot),this.applyTimeScale(),this.syncItemObservations(),this.syncOrdinals()}),"timeline-first-slot-reconciliation")}get itemCount(){return this.slottedCount}get firstOrdinal(){return finiteInteger(this.start,1)}syncOrdinals(){const items=this.isConnected?this.timelineItems():[],current=new Set(items);for(const item of this.numberedItems)current.has(item)||(isTimelineOrdinalItem(item)&&item[SET_TIMELINE_ITEM_ORDINAL](void 0),this.numberedItems.delete(item));const first=this.firstOrdinal;items.forEach((item,index)=>{isTimelineOrdinalItem(item)&&(item[SET_TIMELINE_ITEM_ORDINAL](this.ordered?first+index:void 0),this.ordered?this.numberedItems.add(item):this.numberedItems.delete(item))})}[TIMELINE_ITEM_ORDINAL_OF](item){if(this.scale==="time"&&this.onTimelineItemTimestampChange(),!this.ordered)return;const index=this.timelineItems().indexOf(item);if(!(index<0))return this.numberedItems.add(item),this.firstOrdinal+index}syncTimestampObservers(items){const current=new Set(items);for(const item of this.timestampObservedItems)current.has(item)||(isTimelineClusterItemContract(item)&&item[OBSERVE_TIMELINE_ITEM_TIMESTAMP](this.onTimelineItemTimestampChange,!1),this.timestampObservedItems.delete(item));for(const item of current)this.timestampObservedItems.has(item)||isTimelineClusterItemContract(item)&&(item[OBSERVE_TIMELINE_ITEM_TIMESTAMP](this.onTimelineItemTimestampChange,!0),this.timestampObservedItems.add(item))}timelineItems(){return this.cachedTimelineItems??=this.collectTimelineItems()}collectTimelineItems(){const slot=this.shadowRoot?.querySelector("slot");return(slot?slot.assignedElements({flatten:!0}):Array.from(this.children).filter(element=>!element.getAttribute("slot"))).filter(element=>element.localName===tag("timeline-item"))}timeRange(stamps){const pinnedStart=timelineEpochMs(this.rangeStart),pinnedEnd=timelineEpochMs(this.rangeEnd);if(pinnedStart!==null&&pinnedEnd!==null&&pinnedEnd>pinnedStart)return[pinnedStart,pinnedEnd];let lo=1/0,hi=-1/0;for(const stamp of stamps)stamp!==null&&(stamp<lo&&(lo=stamp),stamp>hi&&(hi=stamp));return hi>lo?[lo,hi]:null}applyTimeScale(){if(this.scheduleTimeExtentMeasurement(),this.scale!=="time"){this.overflowItemsPending=!0,this.timestampObservedItems.size&&this.syncTimestampObservers([]);for(const item of this.timePositionedItems)item.style.removeProperty("--_lr-timeline-item-offset"),item.style.removeProperty("--_lr-timeline-item-lane");this.timePositionedItems.clear(),this.applyCollisionClusters([]);return}this.invalidateTimeGeometry();const items=this.timelineItems(),currentItems=new Set(items);this.syncTimestampObservers(items);const clusterThreshold=this.collision==="cluster"?this.clusterCollisionThreshold():TIMELINE_COLLISION_THRESHOLD;for(const previous of this.timePositionedItems)currentItems.has(previous)||(previous.style.removeProperty("--_lr-timeline-item-offset"),previous.style.removeProperty("--_lr-timeline-item-lane"));this.timePositionedItems.clear();for(const item of items)this.timePositionedItems.add(item);const stamps=items.map(item=>itemEpochMs(item)),range=this.timeRange(stamps),lastIndex=Math.max(1,items.length-1),offsets=new Array(items.length).fill(0);items.forEach((item,index)=>{const stamp=stamps[index]??null,ratio=range&&stamp!==null?(stamp-range[0])/(range[1]-range[0]):this.collision==="cluster"&&stamp!==null?0:index/lastIndex,clamped=Math.min(1,Math.max(0,ratio));offsets[index]=clamped,item.style.setProperty("--_lr-timeline-item-offset",`${clamped*100}%`)}),this.applyCollisionLanes(items,offsets),this.applyCollisionClusters(this.collision==="cluster"?this.buildCollisionClusters(items,offsets,clusterThreshold):[])}applyCollisionLanes(items,offsets){if(this.collision!=="stack"){for(const item of items)item.style.removeProperty("--_lr-timeline-item-lane");return}const order=items.map((_,index)=>index).sort((a,b)=>(offsets[a]??0)-(offsets[b]??0)),laneTails=[],lanes=new Array(items.length).fill(0);for(const index of order){const offset=offsets[index]??0;let lane=laneTails.findIndex(tail=>offset-tail>=TIMELINE_COLLISION_THRESHOLD);lane===-1&&(lane=laneTails.length),laneTails[lane]=offset,lanes[index]=lane}items.forEach((item,index)=>{item.style.setProperty("--_lr-timeline-item-lane",String(lanes[index]??0))})}buildCollisionClusters(items,offsets,threshold){const order=items.map((_,index)=>index).sort((a,b)=>(offsets[a]??0)-(offsets[b]??0)||a-b),clusters=[];let window=[],windowStart=0;const flush=()=>{if(window.length<2){window=[];return}const memberIndexes=[...window].sort((a,b)=>a-b);clusters.push({offset:windowStart,items:memberIndexes.map(index=>items[index])}),window=[]};for(const index of order){const offset=offsets[index]??0;window.length>0&&offset-windowStart>=threshold&&flush(),window.length===0&&(windowStart=offset),window.push(index)}return flush(),clusters}clusterCollisionThreshold(){const base=this.renderRoot.querySelector('[part~="base"]');if(!base)return TIMELINE_COLLISION_THRESHOLD;const axisExtent=this.orientation==="horizontal"?base.clientWidth:base.clientHeight;if(!Number.isFinite(axisExtent)||axisExtent<=0)return TIMELINE_COLLISION_THRESHOLD;let markerExtent=0;for(const item of this.managedClusterRepresentatives){const marker=item.shadowRoot?.querySelector('[part="cluster"]');if(!marker)continue;const rect=toLayoutRect(marker,marker.getBoundingClientRect());markerExtent=Math.max(markerExtent,this.orientation==="horizontal"?rect.width:rect.height)}return!Number.isFinite(markerExtent)||markerExtent<=0?TIMELINE_COLLISION_THRESHOLD:Math.max(TIMELINE_COLLISION_THRESHOLD,markerExtent/axisExtent)}scheduleTimeExtentMeasurement(){this.timeExtentFrame.pending||this.timeExtentFrame.schedule(()=>{const base=this.renderRoot.querySelector('[part~="base"]');if(!base)return;let overhang=0;if(this.scale==="time"&&this.orientation!=="horizontal"){const bottom=base.getBoundingClientRect().bottom,scaleY=layoutScale(base).y;for(const item of this.timelineItems()){const geometry=this.timeItemGeometry(item,bottom,scaleY);overhang=Math.max(overhang,geometry.bottom)}}const trailing=`${Math.ceil(overhang)}px`;if(base.style.getPropertyValue("--_lr-timeline-trailing-extent")!==trailing&&base.style.setProperty("--_lr-timeline-trailing-extent",trailing),this.scale!=="time"||this.orientation!=="horizontal"||this.collision==="cluster"){base.style.removeProperty("--_lr-timeline-content-height");return}let extent=0;for(const item of this.timelineItems())extent=Math.max(extent,this.timeItemGeometry(item,0).extent);const height=`${extent+Math.max(0,base.offsetHeight-base.clientHeight)}px`;base.style.getPropertyValue("--_lr-timeline-content-height")!==height&&base.style.setProperty("--_lr-timeline-content-height",height)})}syncItemObservations(){if(this.syncTimeGeometryObserver(),this.overflowItemsPending){const added=this.timelineItems().filter(item=>!this.overflowObservedItems.has(item));if(added.length&&this.scale!=="time"){this.scrollOverflow.observeExtra(added);for(const item of added)this.overflowObservedItems.add(item)}this.overflowItemsPending=!1}}invalidateTimeGeometry(item){item?this.itemGeometry.delete(item):this.itemGeometry.clear()}timeItemGeometry(item,baseBottom,scaleY=1){let geometry=this.itemGeometry.get(item);return geometry||(geometry=item.getClientRects().length?{bottom:this.orientation==="horizontal"?0:(item.getBoundingClientRect().bottom-baseBottom)/scaleY,extent:this.orientation==="horizontal"?item.offsetTop+item.offsetHeight+1:0}:{bottom:0,extent:0},this.itemGeometry.set(item,geometry)),geometry}stopTimeGeometryObserver(){this.timeGeometryObserver?.disconnect(),this.timeGeometryObserver=void 0,this.timeGeometryBase=void 0,this.timeGeometryView=void 0,this.geometryObservedItems.clear(),this.itemGeometry.clear()}syncTimeGeometryObserver(){const view=this.ownerDocument?.defaultView,base=this.renderRoot.querySelector('[part~="base"]');if(this.scale!=="time"||!this.isConnected||!view||!base){this.stopTimeGeometryObserver();return}if(view!==this.timeGeometryView||base!==this.timeGeometryBase){this.stopTimeGeometryObserver();const Observer=view.ResizeObserver;if(!Observer)return;const observer=new Observer(entries=>{if(!(this.timeGeometryObserver!==observer||this.ownerDocument.defaultView!==view)){for(const entry of entries)this.invalidateTimeGeometry(entry.target===base?void 0:entry.target);this.scrollOverflow.measure(),this.syncScrollTabStop(),this.scheduleTimeExtentMeasurement(),this.collision==="cluster"&&this.scheduleClusterMeasurement()}});this.timeGeometryObserver=observer,this.timeGeometryBase=base,this.timeGeometryView=view,observer.observe(base)}const items=new Set(this.timelineItems());for(const previous of this.geometryObservedItems)items.has(previous)||(this.timeGeometryObserver?.unobserve(previous),this.geometryObservedItems.delete(previous),this.itemGeometry.delete(previous));for(const item of items)this.geometryObservedItems.has(item)||(this.timeGeometryObserver?.observe(item),this.geometryObservedItems.add(item))}scheduleClusterMeasurement(){const view=this.ownerDocument.defaultView;view&&(this.clusterMeasurementFrame!==void 0&&this.clusterMeasurementView===view||(this.cancelClusterMeasurement(),this.clusterMeasurementView=view,this.clusterMeasurementFrame=view.requestAnimationFrame(()=>{this.clusterMeasurementFrame=void 0,this.clusterMeasurementView=void 0,this.isConnected&&this.ownerDocument.defaultView===view&&this.scale==="time"&&this.collision==="cluster"&&this.applyTimeScale()})))}cancelClusterMeasurement(){this.clusterMeasurementFrame!==void 0&&this.clusterMeasurementView&&this.clusterMeasurementView.cancelAnimationFrame(this.clusterMeasurementFrame),this.clusterMeasurementFrame=void 0,this.clusterMeasurementView=void 0}sameClusters(left,right){return left.length===right.length&&left.every((cluster,index)=>cluster.offset===right[index]?.offset&&cluster.items.length===right[index]?.items.length&&cluster.items.every((item,itemIndex)=>item===right[index]?.items[itemIndex]))}captureClusterFocusRepair(clusters){const active=safeDeepActiveElement(this.ownerDocument);if(!active)return;const focusedItem=this.timelineItems().find(item=>item===active||safelyContainsActive(item,active)||safeDeepActiveElement(item.shadowRoot)===active);if(!focusedItem)return;const wasRepresentative=this.managedClusterRepresentatives.has(focusedItem),nextCluster=clusters.find(cluster=>cluster.items.includes(focusedItem)),nextRepresentative=nextCluster?.items[0],mode=nextCluster?"cluster":"item";if(mode==="cluster"&&wasRepresentative&&nextRepresentative===focusedItem||mode==="item"&&!wasRepresentative)return;const base=this.renderRoot.querySelector('[part~="base"]');let snapshot;try{snapshot=captureComposedFocusRepair(focusedItem,base)}catch{return}if(snapshot)return{item:mode==="cluster"?nextRepresentative:focusedItem,mode,snapshot}}scheduleClusterFocusRepair(repair){const generation=++this.focusRepairGeneration;repair&&repair.item.updateComplete.then(()=>{if(generation!==this.focusRepairGeneration||!this.isConnected)return;const base=this.renderRoot.querySelector('[part~="base"]'),target=repair.mode==="cluster"?repair.item.shadowRoot?.querySelector('[part="cluster"]')??null:collectComposedFocusTargets(repair.item).elements[0]??base;try{applyComposedFocusRepair(repair.snapshot,target)}catch{}})}applyCollisionClusters(clusters){const frozen=Object.freeze(clusters.map(cluster=>Object.freeze({offset:cluster.offset,items:Object.freeze([...cluster.items])}))),changed=!this.sameClusters(this.collisionClusters,frozen),focusRepair=changed?this.captureClusterFocusRepair(frozen):void 0,representatives=new Set(frozen.map(cluster=>cluster.items[0])),hiddenItems=new Set(frozen.flatMap(cluster=>cluster.items.filter(item=>!representatives.has(item))));for(const item of this.managedClusterHiddenItems){if(hiddenItems.has(item)){item.hasAttribute(CLUSTER_HIDDEN_ATTRIBUTE)||item.setAttribute(CLUSTER_HIDDEN_ATTRIBUTE,"");continue}item.getAttribute(CLUSTER_HIDDEN_ATTRIBUTE)===""&&item.removeAttribute(CLUSTER_HIDDEN_ATTRIBUTE),this.managedClusterHiddenItems.delete(item)}for(const item of hiddenItems)this.managedClusterHiddenItems.has(item)||item.hasAttribute(CLUSTER_HIDDEN_ATTRIBUTE)||(item.setAttribute(CLUSTER_HIDDEN_ATTRIBUTE,""),this.managedClusterHiddenItems.add(item));if(changed){this.restoreClusterPresentation();for(const cluster of frozen){const representative=cluster.items[0];this.clusterActivations.set(representative,()=>this.activateCluster(cluster.items)),this.managedClusterRepresentatives.add(representative)}this.collisionClusters=frozen,this.syncClusterPresentations(frozen),this.scheduleClusterFocusRepair(focusRepair)}for(const cluster of frozen)cluster.items[0].style.setProperty("--_lr-timeline-item-offset",`${cluster.offset*100}%`)}syncClusterPresentations(clusters){for(const cluster of clusters){const representative=cluster.items[0],activate=this.clusterActivations.get(representative);if(!activate)continue;const countText=getNumberFormat(this.effectiveLocale).format(cluster.items.length);isTimelineClusterItemContract(representative)&&representative[SET_TIMELINE_CLUSTER_PRESENTATION]({accessibleLabel:this.localize("timelineClusterCount",void 0,{count:countText}),countText,activate})}}restoreClusterPresentation(){for(const item of this.managedClusterRepresentatives)isTimelineClusterItemContract(item)&&item[SET_TIMELINE_CLUSTER_PRESENTATION](void 0);this.managedClusterRepresentatives.clear(),this.clusterActivations.clear()}restoreClusterVisibility(){for(const item of this.managedClusterHiddenItems)item.getAttribute(CLUSTER_HIDDEN_ATTRIBUTE)===""&&item.removeAttribute(CLUSTER_HIDDEN_ATTRIBUTE);this.managedClusterHiddenItems.clear()}activateCluster(items){const snapshot=this.ownerDocument.defaultView?.Array.from(items)??[...items];this.emit("lr-cluster-activate",Object.freeze({items:Object.freeze(snapshot)}))}render(){const label=this.accessibleLabel!=null?this.accessibleLabel:this.label?this.label:this.localize("timeline");return this.ordered?html`
|
|
1
|
+
import{__decorate}from"tslib";import{OwnedFrame}from"../../../internal/owned-timer.js";import{OwnedResizeObserver,readInlineSize}from"../../../internal/owned-observer.js";import{layoutScale,toLayoutRect}from"../../../internal/layout-scale.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html}from"lit";import{property,state}from"lit/decorators.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter,blankNumberConverter}from"../../../internal/converters.js";import{tag}from"../../../internal/prefix.js";import{observeScrollOverflow,SCROLL_OVERFLOW_ATTRIBUTE}from"../../../internal/scroll-overflow.js";import{isUsableActiveElement,safeDeepActiveElement}from"../../../internal/active-element.js";import{OBSERVE_TIMELINE_ITEM_TIMESTAMP,SET_TIMELINE_CLUSTER_PRESENTATION,SET_TIMELINE_ITEM_ORDINAL,TIMELINE_ITEM_ORDINAL_OF,isTimelineClusterItemContract,isTimelineOrdinalItem,timeValueChanged}from"./timeline-cluster.js";import{finiteInteger}from"../../../internal/numbers.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{styles}from"./timeline.styles.js";import{LYRA_DEFAULT_timeline,LYRA_DEFAULT_timelineClusterCount}from"../../../internal/default-strings/data.generated.js";const TIMELINE_ORIENTATION=literalSetConverter(["vertical","horizontal","auto"],"vertical"),AUTO_ROW_ITEM_EMS=10,TIMELINE_MARKER_PLACEMENT=literalSetConverter(["start","end","alternate"],"start"),TIMELINE_MARKER_ALIGNMENT=literalSetConverter(["start","center"],"start");function safelyContainsActive(container,candidate){if(!isUsableActiveElement(candidate))return!1;try{return container.contains(candidate)}catch{return!1}}const TIMELINE_SCALE=literalSetConverter(["flow","time"],"flow"),TIMELINE_COLLISION=literalSetConverter(["overlap","stack","cluster"],"overlap"),EMPTY_TIMELINE_CLUSTERS=/* @__PURE__ */(()=>Object.freeze([]))(),CLUSTER_HIDDEN_ATTRIBUTE="data-lr-timeline-cluster-hidden",TIMELINE_COLLISION_THRESHOLD=.015;function timelineEpochMs(raw){if(raw==null)return null;const ms=(raw instanceof Date?raw:typeof raw=="number"?new Date(raw):new Date(String(raw))).getTime();return Number.isFinite(ms)?ms:null}function itemEpochMs(element){return timelineEpochMs(element.timestamp)}class LyraTimeline extends LyraElement{constructor(){super(...arguments),this._orientation="vertical",this._effectiveOrientation="vertical",this.measuredInlineSize=Number.NaN,this.autoOrientationFrame=new OwnedFrame(this),this.autoOrientationObserver=new OwnedResizeObserver(this,entries=>{const width=readInlineSize(entries[entries.length-1]);width!==void 0&&this.autoOrientationFrame.schedule(()=>{this.measuredInlineSize=width,this.syncEffectiveOrientation()})}),this._markerPlacement="start",this._markerAlignment="start",this.label="",this._scale="flow",this._collision="overlap",this.ordered=!1,this.start=1,this.accessibleLabel=null,this.slottedCount=0,this.collisionClusters=EMPTY_TIMELINE_CLUSTERS,this.managedClusterHiddenItems=new Set,this.managedClusterRepresentatives=new Set,this.clusterActivations=new Map,this.timestampObservedItems=new Set,this.numberedItems=new Set,this.timeExtentFrame=new OwnedFrame(this),this.focusRepairGeneration=0,this.timePositionedItems=new Set,this.overflowObservedItems=new Set,this.overflowItemsPending=!0,this.geometryObservedItems=new Set,this.itemGeometry=new Map,this.scrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part~="base"]'),()=>{this.scheduleTimeExtentMeasurement(),this.scale==="time"&&this.collision==="cluster"&&this.scheduleClusterMeasurement(),this.syncScrollTabStop()}),this.onSlotChange=()=>{this.cachedTimelineItems=void 0,this.overflowItemsPending=!0,this.invalidateTimeGeometry();const current=new Set(this.timelineItems());for(const item of this.overflowObservedItems)current.has(item)||this.overflowObservedItems.delete(item);this.updateBrowserDerivedState(()=>{this.slottedCount=current.size,this.applyTimeScale(),this.syncItemObservations()}),this.syncOrdinals()},this.onTimelineItemTimestampChange=()=>{this.isConnected&&this.scheduleAfterUpdate(()=>this.applyTimeScale(),"timeline-item-timestamps")}}static{this.defaultStrings={...super.defaultStrings,timeline:LYRA_DEFAULT_timeline,timelineClusterCount:LYRA_DEFAULT_timelineClusterCount}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-cluster-activate"])}static{this.identityEventDetailProperties=Object.freeze({"lr-cluster-activate":Object.freeze(["items"])})}static{this.styles=[LyraElement.styles,scrollOverflowFadeStyles,styles]}get orientation(){return this._orientation}set orientation(value){const normalized=TIMELINE_ORIENTATION.normalizeReflected(this,"orientation",value),previous=this._orientation;previous!==normalized&&(this._orientation=normalized,this.requestUpdate("orientation",previous))}get effectiveOrientation(){return this._effectiveOrientation}get markerPlacement(){return this._markerPlacement}set markerPlacement(value){const normalized=TIMELINE_MARKER_PLACEMENT.normalizeReflected(this,"marker-placement",value),previous=this._markerPlacement;previous!==normalized&&(this._markerPlacement=normalized,this.requestUpdate("markerPlacement",previous))}get markerAlignment(){return this._markerAlignment}set markerAlignment(value){const normalized=TIMELINE_MARKER_ALIGNMENT.normalizeReflected(this,"marker-alignment",value),previous=this._markerAlignment;previous!==normalized&&(this._markerAlignment=normalized,this.requestUpdate("markerAlignment",previous))}get scale(){return this._scale}set scale(value){const normalized=TIMELINE_SCALE.normalizeReflected(this,"scale",value),previous=this._scale;previous!==normalized&&(this._scale=normalized,this.requestUpdate("scale",previous))}get collision(){return this._collision}set collision(value){const normalized=TIMELINE_COLLISION.normalizeReflected(this,"collision",value),previous=this._collision;previous!==normalized&&(this._collision=normalized,this.requestUpdate("collision",previous))}requestUpdate(...args){args[0]===void 0&&this.itemGeometry?.clear(),super.requestUpdate(...args)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.orientation==="auto"&&this.armAutoOrientation(),this.hasUpdated&&this.scheduleAfterUpdate(()=>{this.applyTimeScale(),this.syncItemObservations(),this.syncOrdinals()},"timeline-clusters")}disconnectedCallback(){this.cancelClusterMeasurement(),this.timeExtentFrame.cancel(),this.focusRepairGeneration+=1,this.restoreClusterPresentation(),this.restoreClusterVisibility(),this.syncTimestampObservers([]),this.cachedTimelineItems=void 0,this.syncOrdinals(),this.overflowObservedItems.clear(),this.overflowItemsPending=!0,this.stopTimeGeometryObserver(),this.collisionClusters.length>0&&(this.collisionClusters=EMPTY_TIMELINE_CLUSTERS),this.resetAutoOrientation(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetAutoOrientation()}armAutoOrientation(){this.autoOrientationObserver.active||(this.autoOrientationObserver.clear(),this.autoOrientationObserver.observe(this))}resetAutoOrientation(){this.autoOrientationFrame.cancel(),this.autoOrientationObserver.clear()}syncEffectiveOrientation(){const auto=this.orientation==="auto",next=auto?this.autoRunsAsRow()?"horizontal":"vertical":this.orientation;auto?this.getAttribute("data-effective-orientation")!==next&&this.setAttribute("data-effective-orientation",next):this.hasAttribute("data-effective-orientation")&&this.removeAttribute("data-effective-orientation"),this._effectiveOrientation!==next&&(this._effectiveOrientation=next)}autoRunsAsRow(){const width=this.measuredInlineSize;if(!Number.isFinite(width)||width<=0)return!1;const fontSize=Number.parseFloat(getComputedStyle(this).fontSize);return!Number.isFinite(fontSize)||fontSize<=0?!1:width>=Math.max(1,this.slottedCount)*fontSize*AUTO_ROW_ITEM_EMS}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.slottedCount=Array.from(this.children).filter(element=>!element.getAttribute("slot")&&element.localName===tag("timeline-item")).length),(!this.hasUpdated||changed.has("orientation")||changed.has("slottedCount"))&&this.syncEffectiveOrientation(),this.isConnected&&this.orientation==="auto"&&this.seedFirstRenderState(()=>{const width=this.getBoundingClientRect().width;width>0&&(this.measuredInlineSize=width),this.syncEffectiveOrientation()}),this.hasUpdated?(changed.has("scale")||changed.has("collision")||changed.has("rangeStart")||changed.has("rangeEnd"))&&this.applyTimeScale():this.seedFirstRenderState(()=>this.applyTimeScale())}updated(changed){super.updated(changed),(changed.size===0||[...changed.keys()].some(key=>key!=="accessibleLabel"))&&this.invalidateTimeGeometry(),(this.overflowItemsPending||changed.has("scale")||changed.has("_effectiveOrientation"))&&this.syncItemObservations(),(changed.has("ordered")||changed.has("start"))&&this.syncOrdinals(),this.syncScrollTabStop(),this.scheduleTimeExtentMeasurement(),(changed.has("collisionClusters")||changed.has("_effectiveOrientation"))&&this.collisionClusters.length>0&&this.scheduleAfterUpdate(()=>this.applyTimeScale(),"timeline-cluster-measurement"),this.collisionClusters.length>0&&this.syncClusterPresentations(this.collisionClusters),this.orientation==="auto"?this.armAutoOrientation():this.resetAutoOrientation()}syncScrollTabStop(){const base=this.renderRoot.querySelector('[part~="base"]');if(!base)return;const reachableOnlyByScrolling=this._effectiveOrientation==="horizontal"&&base.hasAttribute(SCROLL_OVERFLOW_ATTRIBUTE);base.setAttribute("tabindex",reachableOnlyByScrolling?"0":"-1")}countTimelineItems(slot){return slot.assignedElements({flatten:!0}).filter(element=>element.localName===tag("timeline-item")).length}firstUpdated(changed){super.firstUpdated(changed),this.scheduleAfterUpdate(()=>this.updateBrowserDerivedState(()=>{const slot=this.shadowRoot.querySelector("slot");this.cachedTimelineItems=void 0,this.overflowItemsPending=!0,this.slottedCount=this.countTimelineItems(slot),this.applyTimeScale(),this.syncItemObservations(),this.syncOrdinals()}),"timeline-first-slot-reconciliation")}get itemCount(){return this.slottedCount}get firstOrdinal(){return finiteInteger(this.start,1)}syncOrdinals(){const items=this.isConnected?this.timelineItems():[],current=new Set(items);for(const item of this.numberedItems)current.has(item)||(isTimelineOrdinalItem(item)&&item[SET_TIMELINE_ITEM_ORDINAL](void 0),this.numberedItems.delete(item));const first=this.firstOrdinal;items.forEach((item,index)=>{isTimelineOrdinalItem(item)&&(item[SET_TIMELINE_ITEM_ORDINAL](this.ordered?first+index:void 0),this.ordered?this.numberedItems.add(item):this.numberedItems.delete(item))})}[TIMELINE_ITEM_ORDINAL_OF](item){if(this.scale==="time"&&this.onTimelineItemTimestampChange(),!this.ordered)return;const index=this.timelineItems().indexOf(item);if(!(index<0))return this.numberedItems.add(item),this.firstOrdinal+index}syncTimestampObservers(items){const current=new Set(items);for(const item of this.timestampObservedItems)current.has(item)||(isTimelineClusterItemContract(item)&&item[OBSERVE_TIMELINE_ITEM_TIMESTAMP](this.onTimelineItemTimestampChange,!1),this.timestampObservedItems.delete(item));for(const item of current)this.timestampObservedItems.has(item)||isTimelineClusterItemContract(item)&&(item[OBSERVE_TIMELINE_ITEM_TIMESTAMP](this.onTimelineItemTimestampChange,!0),this.timestampObservedItems.add(item))}timelineItems(){return this.cachedTimelineItems??=this.collectTimelineItems()}collectTimelineItems(){const slot=this.shadowRoot?.querySelector("slot");return(slot?slot.assignedElements({flatten:!0}):Array.from(this.children).filter(element=>!element.getAttribute("slot"))).filter(element=>element.localName===tag("timeline-item"))}timeRange(stamps){const pinnedStart=timelineEpochMs(this.rangeStart),pinnedEnd=timelineEpochMs(this.rangeEnd);if(pinnedStart!==null&&pinnedEnd!==null&&pinnedEnd>pinnedStart)return[pinnedStart,pinnedEnd];let lo=1/0,hi=-1/0;for(const stamp of stamps)stamp!==null&&(stamp<lo&&(lo=stamp),stamp>hi&&(hi=stamp));return hi>lo?[lo,hi]:null}applyTimeScale(){if(this.scheduleTimeExtentMeasurement(),this.scale!=="time"){this.overflowItemsPending=!0,this.timestampObservedItems.size&&this.syncTimestampObservers([]);for(const item of this.timePositionedItems)item.style.removeProperty("--_lr-timeline-item-offset"),item.style.removeProperty("--_lr-timeline-item-lane");this.timePositionedItems.clear(),this.applyCollisionClusters([]);return}this.invalidateTimeGeometry();const items=this.timelineItems(),currentItems=new Set(items);this.syncTimestampObservers(items);const clusterThreshold=this.collision==="cluster"?this.clusterCollisionThreshold():TIMELINE_COLLISION_THRESHOLD;for(const previous of this.timePositionedItems)currentItems.has(previous)||(previous.style.removeProperty("--_lr-timeline-item-offset"),previous.style.removeProperty("--_lr-timeline-item-lane"));this.timePositionedItems.clear();for(const item of items)this.timePositionedItems.add(item);const stamps=items.map(item=>itemEpochMs(item)),range=this.timeRange(stamps),lastIndex=Math.max(1,items.length-1),offsets=new Array(items.length).fill(0);items.forEach((item,index)=>{const stamp=stamps[index]??null,ratio=range&&stamp!==null?(stamp-range[0])/(range[1]-range[0]):this.collision==="cluster"&&stamp!==null?0:index/lastIndex,clamped=Math.min(1,Math.max(0,ratio));offsets[index]=clamped,item.style.setProperty("--_lr-timeline-item-offset",`${clamped*100}%`)}),this.applyCollisionLanes(items,offsets),this.applyCollisionClusters(this.collision==="cluster"?this.buildCollisionClusters(items,offsets,clusterThreshold):[])}applyCollisionLanes(items,offsets){if(this.collision!=="stack"){for(const item of items)item.style.removeProperty("--_lr-timeline-item-lane");return}const order=items.map((_,index)=>index).sort((a,b)=>(offsets[a]??0)-(offsets[b]??0)),laneTails=[],lanes=new Array(items.length).fill(0);for(const index of order){const offset=offsets[index]??0;let lane=laneTails.findIndex(tail=>offset-tail>=TIMELINE_COLLISION_THRESHOLD);lane===-1&&(lane=laneTails.length),laneTails[lane]=offset,lanes[index]=lane}items.forEach((item,index)=>{item.style.setProperty("--_lr-timeline-item-lane",String(lanes[index]??0))})}buildCollisionClusters(items,offsets,threshold){const order=items.map((_,index)=>index).sort((a,b)=>(offsets[a]??0)-(offsets[b]??0)||a-b),clusters=[];let window=[],windowStart=0;const flush=()=>{if(window.length<2){window=[];return}const memberIndexes=[...window].sort((a,b)=>a-b);clusters.push({offset:windowStart,items:memberIndexes.map(index=>items[index])}),window=[]};for(const index of order){const offset=offsets[index]??0;window.length>0&&offset-windowStart>=threshold&&flush(),window.length===0&&(windowStart=offset),window.push(index)}return flush(),clusters}clusterCollisionThreshold(){const base=this.renderRoot.querySelector('[part~="base"]');if(!base)return TIMELINE_COLLISION_THRESHOLD;const axisExtent=this._effectiveOrientation==="horizontal"?base.clientWidth:base.clientHeight;if(!Number.isFinite(axisExtent)||axisExtent<=0)return TIMELINE_COLLISION_THRESHOLD;let markerExtent=0;for(const item of this.managedClusterRepresentatives){const marker=item.shadowRoot?.querySelector('[part="cluster"]');if(!marker)continue;const rect=toLayoutRect(marker,marker.getBoundingClientRect());markerExtent=Math.max(markerExtent,this._effectiveOrientation==="horizontal"?rect.width:rect.height)}return!Number.isFinite(markerExtent)||markerExtent<=0?TIMELINE_COLLISION_THRESHOLD:Math.max(TIMELINE_COLLISION_THRESHOLD,markerExtent/axisExtent)}scheduleTimeExtentMeasurement(){this.timeExtentFrame.pending||this.timeExtentFrame.schedule(()=>{const base=this.renderRoot.querySelector('[part~="base"]');if(!base)return;let overhang=0;if(this.scale==="time"&&this._effectiveOrientation!=="horizontal"){const bottom=base.getBoundingClientRect().bottom,scaleY=layoutScale(base).y;for(const item of this.timelineItems()){const geometry=this.timeItemGeometry(item,bottom,scaleY);overhang=Math.max(overhang,geometry.bottom)}}const trailing=`${Math.ceil(overhang)}px`;if(base.style.getPropertyValue("--_lr-timeline-trailing-extent")!==trailing&&base.style.setProperty("--_lr-timeline-trailing-extent",trailing),this.scale!=="time"||this._effectiveOrientation!=="horizontal"||this.collision==="cluster"){base.style.removeProperty("--_lr-timeline-content-height");return}let extent=0;for(const item of this.timelineItems())extent=Math.max(extent,this.timeItemGeometry(item,0).extent);const height=`${extent+Math.max(0,base.offsetHeight-base.clientHeight)}px`;base.style.getPropertyValue("--_lr-timeline-content-height")!==height&&base.style.setProperty("--_lr-timeline-content-height",height)})}syncItemObservations(){if(this.syncTimeGeometryObserver(),this.overflowItemsPending){const added=this.timelineItems().filter(item=>!this.overflowObservedItems.has(item));if(added.length&&this.scale!=="time"){this.scrollOverflow.observeExtra(added);for(const item of added)this.overflowObservedItems.add(item)}this.overflowItemsPending=!1}}invalidateTimeGeometry(item){item?this.itemGeometry.delete(item):this.itemGeometry.clear()}timeItemGeometry(item,baseBottom,scaleY=1){let geometry=this.itemGeometry.get(item);return geometry||(geometry=item.getClientRects().length?{bottom:this._effectiveOrientation==="horizontal"?0:(item.getBoundingClientRect().bottom-baseBottom)/scaleY,extent:this._effectiveOrientation==="horizontal"?item.offsetTop+item.offsetHeight+1:0}:{bottom:0,extent:0},this.itemGeometry.set(item,geometry)),geometry}stopTimeGeometryObserver(){this.timeGeometryObserver?.disconnect(),this.timeGeometryObserver=void 0,this.timeGeometryBase=void 0,this.timeGeometryView=void 0,this.geometryObservedItems.clear(),this.itemGeometry.clear()}syncTimeGeometryObserver(){const view=this.ownerDocument?.defaultView,base=this.renderRoot.querySelector('[part~="base"]');if(this.scale!=="time"||!this.isConnected||!view||!base){this.stopTimeGeometryObserver();return}if(view!==this.timeGeometryView||base!==this.timeGeometryBase){this.stopTimeGeometryObserver();const Observer=view.ResizeObserver;if(!Observer)return;const observer=new Observer(entries=>{if(!(this.timeGeometryObserver!==observer||this.ownerDocument.defaultView!==view)){for(const entry of entries)this.invalidateTimeGeometry(entry.target===base?void 0:entry.target);this.scrollOverflow.measure(),this.syncScrollTabStop(),this.scheduleTimeExtentMeasurement(),this.collision==="cluster"&&this.scheduleClusterMeasurement()}});this.timeGeometryObserver=observer,this.timeGeometryBase=base,this.timeGeometryView=view,observer.observe(base)}const items=new Set(this.timelineItems());for(const previous of this.geometryObservedItems)items.has(previous)||(this.timeGeometryObserver?.unobserve(previous),this.geometryObservedItems.delete(previous),this.itemGeometry.delete(previous));for(const item of items)this.geometryObservedItems.has(item)||(this.timeGeometryObserver?.observe(item),this.geometryObservedItems.add(item))}scheduleClusterMeasurement(){const view=this.ownerDocument.defaultView;view&&(this.clusterMeasurementFrame!==void 0&&this.clusterMeasurementView===view||(this.cancelClusterMeasurement(),this.clusterMeasurementView=view,this.clusterMeasurementFrame=view.requestAnimationFrame(()=>{this.clusterMeasurementFrame=void 0,this.clusterMeasurementView=void 0,this.isConnected&&this.ownerDocument.defaultView===view&&this.scale==="time"&&this.collision==="cluster"&&this.applyTimeScale()})))}cancelClusterMeasurement(){this.clusterMeasurementFrame!==void 0&&this.clusterMeasurementView&&this.clusterMeasurementView.cancelAnimationFrame(this.clusterMeasurementFrame),this.clusterMeasurementFrame=void 0,this.clusterMeasurementView=void 0}sameClusters(left,right){return left.length===right.length&&left.every((cluster,index)=>cluster.offset===right[index]?.offset&&cluster.items.length===right[index]?.items.length&&cluster.items.every((item,itemIndex)=>item===right[index]?.items[itemIndex]))}captureClusterFocusRepair(clusters){const active=safeDeepActiveElement(this.ownerDocument);if(!active)return;const focusedItem=this.timelineItems().find(item=>item===active||safelyContainsActive(item,active)||safeDeepActiveElement(item.shadowRoot)===active);if(!focusedItem)return;const wasRepresentative=this.managedClusterRepresentatives.has(focusedItem),nextCluster=clusters.find(cluster=>cluster.items.includes(focusedItem)),nextRepresentative=nextCluster?.items[0],mode=nextCluster?"cluster":"item";if(mode==="cluster"&&wasRepresentative&&nextRepresentative===focusedItem||mode==="item"&&!wasRepresentative)return;const base=this.renderRoot.querySelector('[part~="base"]');let snapshot;try{snapshot=captureComposedFocusRepair(focusedItem,base)}catch{return}if(snapshot)return{item:mode==="cluster"?nextRepresentative:focusedItem,mode,snapshot}}scheduleClusterFocusRepair(repair){const generation=++this.focusRepairGeneration;repair&&repair.item.updateComplete.then(()=>{if(generation!==this.focusRepairGeneration||!this.isConnected)return;const base=this.renderRoot.querySelector('[part~="base"]'),target=repair.mode==="cluster"?repair.item.shadowRoot?.querySelector('[part="cluster"]')??null:collectComposedFocusTargets(repair.item).elements[0]??base;try{applyComposedFocusRepair(repair.snapshot,target)}catch{}})}applyCollisionClusters(clusters){const frozen=Object.freeze(clusters.map(cluster=>Object.freeze({offset:cluster.offset,items:Object.freeze([...cluster.items])}))),changed=!this.sameClusters(this.collisionClusters,frozen),focusRepair=changed?this.captureClusterFocusRepair(frozen):void 0,representatives=new Set(frozen.map(cluster=>cluster.items[0])),hiddenItems=new Set(frozen.flatMap(cluster=>cluster.items.filter(item=>!representatives.has(item))));for(const item of this.managedClusterHiddenItems){if(hiddenItems.has(item)){item.hasAttribute(CLUSTER_HIDDEN_ATTRIBUTE)||item.setAttribute(CLUSTER_HIDDEN_ATTRIBUTE,"");continue}item.getAttribute(CLUSTER_HIDDEN_ATTRIBUTE)===""&&item.removeAttribute(CLUSTER_HIDDEN_ATTRIBUTE),this.managedClusterHiddenItems.delete(item)}for(const item of hiddenItems)this.managedClusterHiddenItems.has(item)||item.hasAttribute(CLUSTER_HIDDEN_ATTRIBUTE)||(item.setAttribute(CLUSTER_HIDDEN_ATTRIBUTE,""),this.managedClusterHiddenItems.add(item));if(changed){this.restoreClusterPresentation();for(const cluster of frozen){const representative=cluster.items[0];this.clusterActivations.set(representative,()=>this.activateCluster(cluster.items)),this.managedClusterRepresentatives.add(representative)}this.collisionClusters=frozen,this.syncClusterPresentations(frozen),this.scheduleClusterFocusRepair(focusRepair)}for(const cluster of frozen)cluster.items[0].style.setProperty("--_lr-timeline-item-offset",`${cluster.offset*100}%`)}syncClusterPresentations(clusters){for(const cluster of clusters){const representative=cluster.items[0],activate=this.clusterActivations.get(representative);if(!activate)continue;const countText=getNumberFormat(this.effectiveLocale).format(cluster.items.length);isTimelineClusterItemContract(representative)&&representative[SET_TIMELINE_CLUSTER_PRESENTATION]({accessibleLabel:this.localize("timelineClusterCount",void 0,{count:countText}),countText,activate})}}restoreClusterPresentation(){for(const item of this.managedClusterRepresentatives)isTimelineClusterItemContract(item)&&item[SET_TIMELINE_CLUSTER_PRESENTATION](void 0);this.managedClusterRepresentatives.clear(),this.clusterActivations.clear()}restoreClusterVisibility(){for(const item of this.managedClusterHiddenItems)item.getAttribute(CLUSTER_HIDDEN_ATTRIBUTE)===""&&item.removeAttribute(CLUSTER_HIDDEN_ATTRIBUTE);this.managedClusterHiddenItems.clear()}activateCluster(items){const snapshot=this.ownerDocument.defaultView?.Array.from(items)??[...items];this.emit("lr-cluster-activate",Object.freeze({items:Object.freeze(snapshot)}))}render(){const label=this.accessibleLabel!=null?this.accessibleLabel:this.label?this.label:this.localize("timeline");return this.ordered?html`
|
|
2
2
|
<div class="frame">
|
|
3
3
|
<ol part="base timeline" role="list" tabindex="-1" aria-label=${label}>
|
|
4
4
|
<slot @slotchange=${this.onSlotChange}></slot>
|
|
@@ -10,4 +10,4 @@ import{__decorate}from"tslib";import{OwnedFrame}from"../../../internal/owned-tim
|
|
|
10
10
|
<slot @slotchange=${this.onSlotChange}></slot>
|
|
11
11
|
</div>
|
|
12
12
|
</div>
|
|
13
|
-
`}}__decorate([property({reflect:!0,converter:TIMELINE_ORIENTATION})],LyraTimeline.prototype,"orientation",null),__decorate([property({attribute:"marker-placement",reflect:!0,converter:TIMELINE_MARKER_PLACEMENT})],LyraTimeline.prototype,"markerPlacement",null),__decorate([property({attribute:"marker-alignment",reflect:!0,converter:TIMELINE_MARKER_ALIGNMENT})],LyraTimeline.prototype,"markerAlignment",null),__decorate([property()],LyraTimeline.prototype,"label",void 0),__decorate([property({reflect:!0,converter:TIMELINE_SCALE})],LyraTimeline.prototype,"scale",null),__decorate([property({reflect:!0,converter:TIMELINE_COLLISION})],LyraTimeline.prototype,"collision",null),__decorate([property({type:Boolean,reflect:!0})],LyraTimeline.prototype,"ordered",void 0),__decorate([property({converter:blankNumberConverter(1)})],LyraTimeline.prototype,"start",void 0),__decorate([property({attribute:!1,hasChanged:timeValueChanged})],LyraTimeline.prototype,"rangeStart",void 0),__decorate([property({attribute:!1,hasChanged:timeValueChanged})],LyraTimeline.prototype,"rangeEnd",void 0),__decorate([property({attribute:"aria-label"})],LyraTimeline.prototype,"accessibleLabel",void 0),__decorate([state()],LyraTimeline.prototype,"slottedCount",void 0),__decorate([state()],LyraTimeline.prototype,"collisionClusters",void 0);export{LyraTimeline};
|
|
13
|
+
`}}__decorate([property({reflect:!0,converter:TIMELINE_ORIENTATION})],LyraTimeline.prototype,"orientation",null),__decorate([state()],LyraTimeline.prototype,"_effectiveOrientation",void 0),__decorate([property({attribute:"marker-placement",reflect:!0,converter:TIMELINE_MARKER_PLACEMENT})],LyraTimeline.prototype,"markerPlacement",null),__decorate([property({attribute:"marker-alignment",reflect:!0,converter:TIMELINE_MARKER_ALIGNMENT})],LyraTimeline.prototype,"markerAlignment",null),__decorate([property()],LyraTimeline.prototype,"label",void 0),__decorate([property({reflect:!0,converter:TIMELINE_SCALE})],LyraTimeline.prototype,"scale",null),__decorate([property({reflect:!0,converter:TIMELINE_COLLISION})],LyraTimeline.prototype,"collision",null),__decorate([property({type:Boolean,reflect:!0})],LyraTimeline.prototype,"ordered",void 0),__decorate([property({converter:blankNumberConverter(1)})],LyraTimeline.prototype,"start",void 0),__decorate([property({attribute:!1,hasChanged:timeValueChanged})],LyraTimeline.prototype,"rangeStart",void 0),__decorate([property({attribute:!1,hasChanged:timeValueChanged})],LyraTimeline.prototype,"rangeEnd",void 0),__decorate([property({attribute:"aria-label"})],LyraTimeline.prototype,"accessibleLabel",void 0),__decorate([state()],LyraTimeline.prototype,"slottedCount",void 0),__decorate([state()],LyraTimeline.prototype,"collisionClusters",void 0);export{LyraTimeline};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host{display:block;min-inline-size:0;--_lr-timeline-item-direction:row;--_lr-timeline-item-track-direction:column;--_lr-timeline-item-gap-block-end:var(--lr-timeline-gap, var(--lr-space-l));--_lr-timeline-item-gap-inline-end:0}:host([orientation=horizontal]){--_lr-timeline-item-direction:column;--_lr-timeline-item-track-direction:row;--_lr-timeline-item-gap-block-end:0;--_lr-timeline-item-gap-inline-end:var(--lr-timeline-gap, var(--lr-space-l));--_lr-timeline-item-opposite-basis:auto;--_lr-timeline-item-opposite-align:start;--_lr-timeline-item-rail-gap-block:0;--_lr-timeline-item-rail-gap-inline:var(--lr-timeline-connector-gap, 0)}.frame{display:block;min-inline-size:0}:host([marker-placement=alternate]) .frame{container-type:inline-size;contain-intrinsic-inline-size:var(--lr-size-20rem)}:host([marker-placement=end]:not([orientation=horizontal])) [part~=base]{--_lr-timeline-item-direction:row-reverse;--_lr-timeline-item-content-align:end;--_lr-timeline-item-opposite-align:start}:host([marker-alignment=center]:not([orientation=horizontal])) [part~=base]{--_lr-timeline-item-track-justify:center;--_lr-timeline-item-rail-position:absolute;--_lr-timeline-item-rail-inline:100%;--_lr-timeline-item-rail-block:auto;--_lr-timeline-item-rail-gap-block:0;--_lr-timeline-item-rail-bg:transparent;--_lr-timeline-item-rail-halves:'';--_lr-timeline-item-rail-visibility-center:visible;--_lr-timeline-item-track-pad:var(--_lr-timeline-item-gap-block-end)}@container (min-width:30em){:host([marker-placement=alternate]:not([orientation=horizontal])) [part~=base]{--_lr-timeline-item-base-display:grid;--_lr-timeline-item-track-col:2;--_lr-timeline-alt-content-col:3;--_lr-timeline-alt-opposite-col:1;--_lr-timeline-alt-flip-content-col:1;--_lr-timeline-alt-flip-opposite-col:3;--_lr-timeline-alt-flip-content-align:end;--_lr-timeline-alt-flip-opposite-align:start}}[part~=base]{display:flex;flex-direction:column;min-inline-size:0;margin:0;padding:0}:host([scale=time]) [part~=base]{position:relative;display:block;block-size:var(--lr-timeline-time-extent,var(--lr-size-20rem));margin-block-end:var(--_lr-timeline-trailing-extent,0)}:host([scale=time][orientation=horizontal]) [part~=base]{block-size:var(--_lr-timeline-content-height,auto);inline-size:var(--lr-timeline-time-extent,var(--lr-size-20rem))}:host([scale=time]) ::slotted(*){position:absolute;box-sizing:border-box;inset-block-start:var(--_lr-timeline-item-offset,0%);inset-inline-start:0;inline-size:100%}:host([scale=time][collision=stack]) ::slotted(*){--_lr-timeline-lane-indent:calc( var(--_lr-timeline-item-lane, 0) * var(--lr-timeline-collision-offset, var(--lr-space-l)) );inset-inline-start:var(--_lr-timeline-lane-indent);inline-size:calc(100% - var(--_lr-timeline-lane-indent))}:host([scale=time][collision=stack][orientation=horizontal]) ::slotted(*){inset-inline-start:var(--_lr-timeline-item-offset,0%);inset-block-start:var(--_lr-timeline-lane-indent);inline-size:auto}:host([scale=time][orientation=horizontal]) ::slotted(*){inset-block-start:0;inset-inline-start:var(--_lr-timeline-item-offset,0%);inline-size:auto}:host([scale=time][collision=cluster]) ::slotted([data-lr-timeline-cluster-hidden]){display:none!important}:host([scale=time][collision=cluster][orientation=horizontal]) [part~=base]{min-block-size:max(var(--lr-icon-button-size),var(--lr-timeline-cluster-size,var(--lr-size-2rem)))}:host([orientation=horizontal]) [part~=base]{flex-direction:row;overflow-x:auto;overflow-y:hidden;padding:calc(var(--lr-space-2xs) + var(--lr-border-width-medium))}[part~=base]:focus-visible{${focusRing}}:host(:not([orientation=horizontal])) [part~=base]{-webkit-mask-image:none;mask-image:none}::slotted([role=listitem]:last-child){--_lr-timeline-item-rail-visibility:hidden}`;export{styles};
|
|
1
|
+
import{focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host{display:block;min-inline-size:0;--_lr-timeline-item-direction:row;--_lr-timeline-item-track-direction:column;--_lr-timeline-item-gap-block-end:var(--lr-timeline-gap, var(--lr-space-l));--_lr-timeline-item-gap-inline-end:0}:host(:is([orientation=horizontal],[data-effective-orientation=horizontal])){--_lr-timeline-item-direction:column;--_lr-timeline-item-track-direction:row;--_lr-timeline-item-gap-block-end:0;--_lr-timeline-item-gap-inline-end:var(--lr-timeline-gap, var(--lr-space-l));--_lr-timeline-item-opposite-basis:auto;--_lr-timeline-item-opposite-align:start;--_lr-timeline-item-rail-gap-block:0;--_lr-timeline-item-rail-gap-inline:var(--lr-timeline-connector-gap, 0)}.frame{display:block;min-inline-size:0}:host([marker-placement=alternate]) .frame{container-type:inline-size;contain-intrinsic-inline-size:var(--lr-size-20rem)}:host([marker-placement=end]:not([orientation=horizontal],[data-effective-orientation=horizontal])) [part~=base]{--_lr-timeline-item-direction:row-reverse;--_lr-timeline-item-content-align:end;--_lr-timeline-item-opposite-align:start}:host([marker-alignment=center]:not([orientation=horizontal],[data-effective-orientation=horizontal])) [part~=base]{--_lr-timeline-item-track-justify:center;--_lr-timeline-item-rail-position:absolute;--_lr-timeline-item-rail-inline:100%;--_lr-timeline-item-rail-block:auto;--_lr-timeline-item-rail-gap-block:0;--_lr-timeline-item-rail-bg:transparent;--_lr-timeline-item-rail-halves:'';--_lr-timeline-item-rail-visibility-center:visible;--_lr-timeline-item-track-pad:var(--_lr-timeline-item-gap-block-end)}@container (min-width:30em){:host([marker-placement=alternate]:not([orientation=horizontal],[data-effective-orientation=horizontal])) [part~=base]{--_lr-timeline-item-base-display:grid;--_lr-timeline-item-track-col:2;--_lr-timeline-alt-content-col:3;--_lr-timeline-alt-opposite-col:1;--_lr-timeline-alt-flip-content-col:1;--_lr-timeline-alt-flip-opposite-col:3;--_lr-timeline-alt-flip-content-align:end;--_lr-timeline-alt-flip-opposite-align:start}}[part~=base]{display:flex;flex-direction:column;min-inline-size:0;margin:0;padding:0}:host([scale=time]) [part~=base]{position:relative;display:block;block-size:var(--lr-timeline-time-extent,var(--lr-size-20rem));margin-block-end:var(--_lr-timeline-trailing-extent,0)}:host([scale=time]:is([orientation=horizontal],[data-effective-orientation=horizontal])) [part~=base]{block-size:var(--_lr-timeline-content-height,auto);inline-size:var(--lr-timeline-time-extent,var(--lr-size-20rem))}:host([scale=time]) ::slotted(*){position:absolute;box-sizing:border-box;inset-block-start:var(--_lr-timeline-item-offset,0%);inset-inline-start:0;inline-size:100%}:host([scale=time][collision=stack]) ::slotted(*){--_lr-timeline-lane-indent:calc( var(--_lr-timeline-item-lane, 0) * var(--lr-timeline-collision-offset, var(--lr-space-l)) );inset-inline-start:var(--_lr-timeline-lane-indent);inline-size:calc(100% - var(--_lr-timeline-lane-indent))}:host([scale=time][collision=stack]:is([orientation=horizontal],[data-effective-orientation=horizontal])) ::slotted(*){inset-inline-start:var(--_lr-timeline-item-offset,0%);inset-block-start:var(--_lr-timeline-lane-indent);inline-size:auto}:host([scale=time]:is([orientation=horizontal],[data-effective-orientation=horizontal])) ::slotted(*){inset-block-start:0;inset-inline-start:var(--_lr-timeline-item-offset,0%);inline-size:auto}:host([scale=time][collision=cluster]) ::slotted([data-lr-timeline-cluster-hidden]){display:none!important}:host([scale=time][collision=cluster]:is([orientation=horizontal],[data-effective-orientation=horizontal])) [part~=base]{min-block-size:max(var(--lr-icon-button-size),var(--lr-timeline-cluster-size,var(--lr-size-2rem)))}:host(:is([orientation=horizontal],[data-effective-orientation=horizontal])) [part~=base]{flex-direction:row;overflow-x:auto;overflow-y:hidden;padding:calc(var(--lr-space-2xs) + var(--lr-border-width-medium))}[part~=base]:focus-visible{${focusRing}}:host(:not([orientation=horizontal],[data-effective-orientation=horizontal])) [part~=base]{-webkit-mask-image:none;mask-image:none}::slotted([role=listitem]:last-child){--_lr-timeline-item-rail-visibility:hidden}`;export{styles};
|