@carbon/ai-chat-components 1.11.0 → 1.12.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/custom-elements.json +2358 -1973
- package/es/components/card/src/card-footer.scss.js +1 -1
- package/es/components/card/src/card-steps.scss.js +1 -1
- package/es/components/card/src/card.scss.js +1 -1
- package/es/components/chat-button/src/chat-button.scss.js +1 -1
- package/es/components/chat-history/src/history-panel-item-input.js +0 -1
- package/es/components/chat-history/src/history-panel-item-input.js.map +1 -1
- package/es/components/code-snippet/src/codemirror/language-controller.js +1 -1
- package/es/components/code-snippet/src/codemirror/language-controller.js.map +1 -1
- package/es/components/file-uploads/src/file-upload-item.d.ts +14 -1
- package/es/components/file-uploads/src/file-upload-item.js +78 -2
- package/es/components/file-uploads/src/file-upload-item.js.map +1 -1
- package/es/components/file-uploads/src/file-uploads.d.ts +29 -4
- package/es/components/file-uploads/src/file-uploads.js +69 -16
- package/es/components/file-uploads/src/file-uploads.js.map +1 -1
- package/es/components/launcher/src/launcher.scss.js +1 -1
- package/es/components/prompt-line/autocomplete/index.d.ts +1 -1
- package/es/components/prompt-line/autocomplete/src/autocomplete.d.ts +6 -0
- package/es/components/prompt-line/autocomplete/src/autocomplete.js +37 -11
- package/es/components/prompt-line/autocomplete/src/autocomplete.js.map +1 -1
- package/es/components/prompt-line/index.d.ts +3 -2
- package/es/components/prompt-line/index.js +2 -1
- package/es/components/prompt-line/index.js.map +1 -1
- package/es/components/prompt-line/src/__tests__/wait-for-rich.d.ts +20 -0
- package/es/components/prompt-line/src/autocomplete-controller-element.d.ts +84 -0
- package/es/components/prompt-line/src/autocomplete-controller-element.js +262 -0
- package/es/components/prompt-line/src/autocomplete-controller-element.js.map +1 -0
- package/es/components/prompt-line/src/autocomplete-controller.d.ts +10 -69
- package/es/components/prompt-line/src/autocomplete-controller.js +57 -251
- package/es/components/prompt-line/src/autocomplete-controller.js.map +1 -1
- package/es/components/prompt-line/src/prompt-line-rich-runtime.js +3 -0
- package/es/components/prompt-line/src/prompt-line-rich-runtime.js.map +1 -1
- package/es/components/prompt-line/src/prompt-line-shell.scss.js +1 -1
- package/es/components/prompt-line/src/prompt-line-textarea-runtime.js +0 -5
- package/es/components/prompt-line/src/prompt-line-textarea-runtime.js.map +1 -1
- package/es/components/prompt-line/src/prompt-line.js +1 -1
- package/es/components/prompt-line/src/prompt-line.js.map +1 -1
- package/es/components/prompt-line/src/send-control.d.ts +7 -0
- package/es/components/prompt-line/src/send-control.js +53 -5
- package/es/components/prompt-line/src/send-control.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/build-extensions.js +1 -1
- package/es/components/prompt-line/src/tiptap/build-extensions.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/carbon-autocomplete.d.ts +5 -6
- package/es/components/prompt-line/src/tiptap/carbon-autocomplete.js +24 -48
- package/es/components/prompt-line/src/tiptap/carbon-autocomplete.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/carbon-mention.js +14 -48
- package/es/components/prompt-line/src/tiptap/carbon-mention.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/carbon-starter-trigger.js +3 -4
- package/es/components/prompt-line/src/tiptap/carbon-starter-trigger.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/keymap.d.ts +1 -1
- package/es/components/prompt-line/src/tiptap/keymap.js +3 -4
- package/es/components/prompt-line/src/tiptap/keymap.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/render-token-chip.js +0 -1
- package/es/components/prompt-line/src/tiptap/render-token-chip.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/resolve-config-items.d.ts +18 -0
- package/es/components/prompt-line/src/tiptap/resolve-config-items.js +32 -0
- package/es/components/prompt-line/src/tiptap/resolve-config-items.js.map +1 -0
- package/es/components/prompt-line/src/tiptap/strip-presentation-fields.d.ts +18 -0
- package/es/components/prompt-line/src/tiptap/strip-presentation-fields.js +22 -0
- package/es/components/prompt-line/src/tiptap/strip-presentation-fields.js.map +1 -0
- package/es/components/prompt-line/src/tiptap/trigger-utils.d.ts +12 -8
- package/es/components/prompt-line/src/tiptap/trigger-utils.js +16 -1
- package/es/components/prompt-line/src/tiptap/trigger-utils.js.map +1 -1
- package/es/components/prompt-line/src/tiptap/types.d.ts +11 -3
- package/es/components/toolbar/src/toolbar.d.ts +8 -0
- package/es/components/toolbar/src/toolbar.js +65 -19
- package/es/components/toolbar/src/toolbar.js.map +1 -1
- package/es/components/video-player/src/providers/vimeo-provider.js +1 -1
- package/es/components/video-player/src/providers/vimeo-provider.js.map +1 -1
- package/es/globals/decorators/carbon-element.js +2 -3
- package/es/globals/decorators/carbon-element.js.map +1 -1
- package/es/globals/utils/aria-announcer-manager.d.ts +56 -0
- package/es/globals/utils/aria-announcer-manager.js +46 -1
- package/es/globals/utils/aria-announcer-manager.js.map +1 -1
- package/es/globals/utils/focus-utils.js +1 -3
- package/es/globals/utils/focus-utils.js.map +1 -1
- package/es/globals/utils/iconTransform.d.ts +16 -2
- package/es/globals/utils/iconTransform.js +22 -1
- package/es/globals/utils/iconTransform.js.map +1 -1
- package/es/react/hooks/useChatAutocomplete.d.ts +5 -0
- package/es/react/hooks/useChatAutocomplete.js +26 -1
- package/es/react/hooks/useChatAutocomplete.js.map +1 -1
- package/es/react/markdown.js +0 -1
- package/es/react/markdown.js.map +1 -1
- package/es/typings/overflow-menu.d.ts +4 -0
- package/es-custom/components/card/src/card-footer.scss.js +1 -1
- package/es-custom/components/card/src/card-steps.scss.js +1 -1
- package/es-custom/components/card/src/card.scss.js +1 -1
- package/es-custom/components/chat-button/src/chat-button.scss.js +1 -1
- package/es-custom/components/chat-history/src/history-panel-item-input.js +0 -1
- package/es-custom/components/chat-history/src/history-panel-item-input.js.map +1 -1
- package/es-custom/components/code-snippet/src/codemirror/language-controller.js +1 -1
- package/es-custom/components/code-snippet/src/codemirror/language-controller.js.map +1 -1
- package/es-custom/components/file-uploads/src/file-upload-item.d.ts +14 -1
- package/es-custom/components/file-uploads/src/file-upload-item.js +78 -2
- package/es-custom/components/file-uploads/src/file-upload-item.js.map +1 -1
- package/es-custom/components/file-uploads/src/file-uploads.d.ts +29 -4
- package/es-custom/components/file-uploads/src/file-uploads.js +69 -16
- package/es-custom/components/file-uploads/src/file-uploads.js.map +1 -1
- package/es-custom/components/launcher/src/launcher.scss.js +1 -1
- package/es-custom/components/prompt-line/autocomplete/index.d.ts +1 -1
- package/es-custom/components/prompt-line/autocomplete/src/autocomplete.d.ts +6 -0
- package/es-custom/components/prompt-line/autocomplete/src/autocomplete.js +37 -11
- package/es-custom/components/prompt-line/autocomplete/src/autocomplete.js.map +1 -1
- package/es-custom/components/prompt-line/index.d.ts +3 -2
- package/es-custom/components/prompt-line/index.js +2 -1
- package/es-custom/components/prompt-line/index.js.map +1 -1
- package/es-custom/components/prompt-line/src/__tests__/wait-for-rich.d.ts +20 -0
- package/es-custom/components/prompt-line/src/autocomplete-controller-element.d.ts +84 -0
- package/es-custom/components/prompt-line/src/autocomplete-controller-element.js +262 -0
- package/es-custom/components/prompt-line/src/autocomplete-controller-element.js.map +1 -0
- package/es-custom/components/prompt-line/src/autocomplete-controller.d.ts +10 -69
- package/es-custom/components/prompt-line/src/autocomplete-controller.js +57 -251
- package/es-custom/components/prompt-line/src/autocomplete-controller.js.map +1 -1
- package/es-custom/components/prompt-line/src/prompt-line-rich-runtime.js +3 -0
- package/es-custom/components/prompt-line/src/prompt-line-rich-runtime.js.map +1 -1
- package/es-custom/components/prompt-line/src/prompt-line-shell.scss.js +1 -1
- package/es-custom/components/prompt-line/src/prompt-line-textarea-runtime.js +0 -5
- package/es-custom/components/prompt-line/src/prompt-line-textarea-runtime.js.map +1 -1
- package/es-custom/components/prompt-line/src/prompt-line.js +1 -1
- package/es-custom/components/prompt-line/src/prompt-line.js.map +1 -1
- package/es-custom/components/prompt-line/src/send-control.d.ts +7 -0
- package/es-custom/components/prompt-line/src/send-control.js +53 -5
- package/es-custom/components/prompt-line/src/send-control.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/build-extensions.js +1 -1
- package/es-custom/components/prompt-line/src/tiptap/build-extensions.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/carbon-autocomplete.d.ts +5 -6
- package/es-custom/components/prompt-line/src/tiptap/carbon-autocomplete.js +24 -48
- package/es-custom/components/prompt-line/src/tiptap/carbon-autocomplete.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/carbon-mention.js +14 -48
- package/es-custom/components/prompt-line/src/tiptap/carbon-mention.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/carbon-starter-trigger.js +3 -4
- package/es-custom/components/prompt-line/src/tiptap/carbon-starter-trigger.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/keymap.d.ts +1 -1
- package/es-custom/components/prompt-line/src/tiptap/keymap.js +3 -4
- package/es-custom/components/prompt-line/src/tiptap/keymap.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/render-token-chip.js +0 -1
- package/es-custom/components/prompt-line/src/tiptap/render-token-chip.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/resolve-config-items.d.ts +18 -0
- package/es-custom/components/prompt-line/src/tiptap/resolve-config-items.js +32 -0
- package/es-custom/components/prompt-line/src/tiptap/resolve-config-items.js.map +1 -0
- package/es-custom/components/prompt-line/src/tiptap/strip-presentation-fields.d.ts +18 -0
- package/es-custom/components/prompt-line/src/tiptap/strip-presentation-fields.js +22 -0
- package/es-custom/components/prompt-line/src/tiptap/strip-presentation-fields.js.map +1 -0
- package/es-custom/components/prompt-line/src/tiptap/trigger-utils.d.ts +12 -8
- package/es-custom/components/prompt-line/src/tiptap/trigger-utils.js +16 -1
- package/es-custom/components/prompt-line/src/tiptap/trigger-utils.js.map +1 -1
- package/es-custom/components/prompt-line/src/tiptap/types.d.ts +11 -3
- package/es-custom/components/toolbar/src/toolbar.d.ts +8 -0
- package/es-custom/components/toolbar/src/toolbar.js +65 -19
- package/es-custom/components/toolbar/src/toolbar.js.map +1 -1
- package/es-custom/components/video-player/src/providers/vimeo-provider.js +1 -1
- package/es-custom/components/video-player/src/providers/vimeo-provider.js.map +1 -1
- package/es-custom/globals/decorators/carbon-element.js +2 -3
- package/es-custom/globals/decorators/carbon-element.js.map +1 -1
- package/es-custom/globals/utils/aria-announcer-manager.d.ts +56 -0
- package/es-custom/globals/utils/aria-announcer-manager.js +46 -1
- package/es-custom/globals/utils/aria-announcer-manager.js.map +1 -1
- package/es-custom/globals/utils/focus-utils.js +1 -3
- package/es-custom/globals/utils/focus-utils.js.map +1 -1
- package/es-custom/globals/utils/iconTransform.d.ts +16 -2
- package/es-custom/globals/utils/iconTransform.js +22 -1
- package/es-custom/globals/utils/iconTransform.js.map +1 -1
- package/es-custom/react/hooks/useChatAutocomplete.d.ts +5 -0
- package/es-custom/react/hooks/useChatAutocomplete.js +26 -1
- package/es-custom/react/hooks/useChatAutocomplete.js.map +1 -1
- package/es-custom/react/markdown.js +0 -1
- package/es-custom/react/markdown.js.map +1 -1
- package/es-custom/typings/overflow-menu.d.ts +4 -0
- package/package.json +6 -6
- package/scss/_custom-properties.scss +0 -17
- package/scss/_tokens-component.scss +1 -2
|
@@ -86,19 +86,23 @@ let CDSAIChatToolbar = CDSAIChatToolbar_1 = class CDSAIChatToolbar extends LitEl
|
|
|
86
86
|
*/
|
|
87
87
|
this.renderIconButton = (action) => {
|
|
88
88
|
const tooltipAlign = this.isRTL ? 'bottom-start' : 'bottom-end';
|
|
89
|
+
const { isSelected } = action;
|
|
89
90
|
return html `
|
|
90
91
|
<cds-custom-icon-button
|
|
92
|
+
align=${tooltipAlign}
|
|
93
|
+
@click=${action.onClick}
|
|
91
94
|
?data-fixed=${action.fixed}
|
|
95
|
+
data-pressed=${isSelected !== undefined ? String(isSelected) : nothing}
|
|
96
|
+
?data-selected=${isSelected === true}
|
|
92
97
|
data-testid=${action.testId || nothing}
|
|
93
|
-
|
|
98
|
+
?disabled=${action.disabled}
|
|
99
|
+
enter-delay-ms="0"
|
|
94
100
|
href=${action.href || nothing}
|
|
95
|
-
|
|
96
|
-
size=${action.size || BUTTON_SIZE.MEDIUM}
|
|
97
|
-
align=${tooltipAlign}
|
|
101
|
+
?isSelected=${isSelected === true}
|
|
98
102
|
kind="ghost"
|
|
99
|
-
enter-delay-ms="0"
|
|
100
103
|
leave-delay-ms="0"
|
|
101
|
-
|
|
104
|
+
size=${action.size || BUTTON_SIZE.MEDIUM}
|
|
105
|
+
target=${action.href ? action.target || '_self' : nothing}>
|
|
102
106
|
${iconLoader(action.icon, {
|
|
103
107
|
slot: 'icon',
|
|
104
108
|
})}
|
|
@@ -122,6 +126,39 @@ let CDSAIChatToolbar = CDSAIChatToolbar_1 = class CDSAIChatToolbar extends LitEl
|
|
|
122
126
|
this.setupResizeObserver();
|
|
123
127
|
}
|
|
124
128
|
}
|
|
129
|
+
updated() {
|
|
130
|
+
// Carbon's delegatesFocus moves focus to the inner shadow <button>, so
|
|
131
|
+
// ARIA attributes on the host are invisible to assistive tech. Mirror
|
|
132
|
+
// them onto the inner button after each element's update cycle completes.
|
|
133
|
+
void this._patchShadowButtonAttrs('cds-custom-icon-button[data-pressed]', {
|
|
134
|
+
'aria-pressed': 'data-pressed',
|
|
135
|
+
});
|
|
136
|
+
void this._patchShadowButtonAttrs('cds-custom-overflow-menu-item[role="menuitemcheckbox"]', { role: 'role', 'aria-checked': 'aria-checked' });
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Copies attributes from each host element matching `selector` onto its
|
|
140
|
+
* inner shadow `<button>`, after the element's own update cycle completes.
|
|
141
|
+
*
|
|
142
|
+
* @param selector - CSS selector scoped to this shadow root.
|
|
143
|
+
* @param attrMap - `{ targetAttr: sourceAttr }` pairs to copy.
|
|
144
|
+
* @internal
|
|
145
|
+
*/
|
|
146
|
+
async _patchShadowButtonAttrs(selector, attrMap) {
|
|
147
|
+
await Promise.all(Array.from(this.shadowRoot?.querySelectorAll(selector) ??
|
|
148
|
+
[]).map(async (el) => {
|
|
149
|
+
await el.updateComplete;
|
|
150
|
+
const btn = el.shadowRoot?.querySelector('button');
|
|
151
|
+
if (!btn) {
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
for (const [target, source] of Object.entries(attrMap)) {
|
|
155
|
+
const value = el.getAttribute(source);
|
|
156
|
+
if (value !== null) {
|
|
157
|
+
btn.setAttribute(target, value);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}));
|
|
161
|
+
}
|
|
125
162
|
sortActions() {
|
|
126
163
|
return [...this.actions].sort((a, b) => {
|
|
127
164
|
if (a.fixed && !b.fixed) {
|
|
@@ -273,19 +310,28 @@ let CDSAIChatToolbar = CDSAIChatToolbar_1 = class CDSAIChatToolbar extends LitEl
|
|
|
273
310
|
>${CDSAIChatToolbar_1.OVERFLOW_MENU_LABEL}</span
|
|
274
311
|
>
|
|
275
312
|
<cds-custom-overflow-menu-body ?flipped=${!this.isRTL}>
|
|
276
|
-
${repeat(hiddenActions, (item) => item.text, (item) =>
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
313
|
+
${repeat(hiddenActions, (item) => item.text, (item) => {
|
|
314
|
+
return html `
|
|
315
|
+
<cds-custom-overflow-menu-item
|
|
316
|
+
@click=${item.onClick}
|
|
317
|
+
href=${item.href || nothing}
|
|
318
|
+
target=${item.href ? item.target || '_self' : nothing}
|
|
319
|
+
?disabled=${item.disabled}
|
|
320
|
+
?danger=${item.danger}
|
|
321
|
+
danger-description=${item.dangerDescription || nothing}
|
|
322
|
+
?divider=${item.divider}
|
|
323
|
+
?data-selected=${item.isSelected === true}
|
|
324
|
+
role=${item.isSelected !== undefined
|
|
325
|
+
? 'menuitemcheckbox'
|
|
326
|
+
: nothing}
|
|
327
|
+
aria-checked=${item.isSelected !== undefined
|
|
328
|
+
? String(item.isSelected)
|
|
329
|
+
: nothing}
|
|
330
|
+
data-testid=${item.testId || nothing}>
|
|
331
|
+
${item.text}
|
|
332
|
+
</cds-custom-overflow-menu-item>
|
|
333
|
+
`;
|
|
334
|
+
})}
|
|
289
335
|
</cds-custom-overflow-menu-body>
|
|
290
336
|
</cds-custom-overflow-menu>
|
|
291
337
|
`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toolbar.js","sources":["../../../../src/components/toolbar/src/toolbar.ts"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\nimport { LitElement, html, nothing } from 'lit';\nimport { property, state, query } from 'lit/decorators.js';\nimport { repeat } from 'lit/directives/repeat.js';\nimport '@carbon/web-components/es-custom/components/button/index.js';\nimport '@carbon/web-components/es-custom/components/overflow-menu/index.js';\nimport { OVERFLOW_MENU_SIZE } from '@carbon/web-components/es-custom/components/overflow-menu/defs.js';\nimport OverflowMenuVertical16 from '@carbon/icons/es/overflow-menu--vertical/16.js';\nimport { iconLoader } from '@carbon/web-components/es-custom/globals/internal/icon-loader.js';\nimport prefix from '../../../globals/settings.js';\nimport commonStyles from '../../../globals/scss/common.scss?lit';\nimport styles from './toolbar.scss?lit';\nimport { CarbonIcon } from '@carbon/web-components/es-custom/globals/internal/icon-loader-utils.js';\nimport { carbonElement } from '../../../globals/decorators/index.js';\nimport '../../truncated-text/index.js';\nimport { BaseOverflowMenuItem } from '../../../typings/overflow-menu.js';\nimport { PageObjectId } from '../../../testing/PageObjectId.js';\n\nconst blockClass = `${prefix}-toolbar`;\nimport { BUTTON_SIZE } from '@carbon/web-components/es-custom/components/button/defs.js';\n\n/**\n * Actions that display in the toolbar.\n * Extends BaseOverflowMenuItem to support all overflow menu item properties\n * including danger variants, dividers, and links (href/target).\n *\n * Actions can be either:\n * - Interactive buttons with onClick handlers\n * - Links with href/target attributes\n */\nexport interface Action extends BaseOverflowMenuItem {\n /**\n * `@carbon/icons` icon for the action.\n */\n icon: CarbonIcon;\n\n /**\n * Size of button. Defaults to BUTTON_SIZE.MEDIUM.\n */\n size?: BUTTON_SIZE;\n\n /**\n * When overflow handling is enabled, setting fixed to true will force this action out of the overflow menu.\n */\n fixed?: boolean;\n}\n\n/**\n * Toolbar.\n *\n * @element cds-custom-aichat-toolbar\n * @slot navigation - Defines the navigation area of the toolbar.\n * @slot title - Defines the title section of the toolbar.\n * @slot fixed-actions - Defines the area for displaying actions that are always visible (not overflowed) in the toolbar.\n * @slot toolbar-ai-label - Defines the area for displaying the AI label in the toolbar.\n *\n */\n@carbonElement(blockClass)\nclass CDSAIChatToolbar extends LitElement {\n /** Whether the component is in RTL mode.\n * @internal\n */\n @state() private isRTL = false;\n\n /** The list of actions. */\n @property({ type: Array, attribute: false, reflect: false })\n actions: Action[] = [];\n\n /** Should actions be overflowing. */\n @property({ type: Boolean, attribute: 'overflow', reflect: true })\n overflow = false;\n\n @property({ type: String })\n titleText?: string;\n\n @property({ type: String })\n nameText?: string;\n\n /** Container holding all action buttons and the overflow menu.\n * @internal\n */\n @query(`.${blockClass}__end`) private container!: HTMLElement;\n @query(`.${blockClass}__actions-container`)\n private actionsContainer!: HTMLElement;\n\n @query(`.${blockClass}__decorator-container`)\n private decoratorContainer!: HTMLElement;\n\n @query(`.${blockClass}__fixed-actions`)\n private fixedActions!: HTMLElement;\n\n @state()\n private containerWidth = 0;\n\n private resizeObserver?: ResizeObserver;\n\n private static readonly OVERFLOW_MENU_LABEL = 'Options';\n\n connectedCallback(): void {\n super.connectedCallback();\n this.addEventListener('keydown', this._handleToolbarKeydown);\n }\n\n disconnectedCallback() {\n this.resizeObserver?.disconnect();\n this.resizeObserver = undefined;\n this.removeEventListener('keydown', this._handleToolbarKeydown);\n super.disconnectedCallback();\n }\n\n firstUpdated() {\n if (this.overflow) {\n this.setupResizeObserver();\n }\n }\n\n private sortActions() {\n return [...this.actions].sort((a, b) => {\n if (a.fixed && !b.fixed) {\n return -1;\n }\n if (!a.fixed && b.fixed) {\n return 1;\n }\n return 0;\n });\n }\n\n private setupResizeObserver() {\n this.resizeObserver?.disconnect();\n this.resizeObserver = new ResizeObserver((entries) => {\n const width = entries[0].contentRect.width;\n if (width !== this.containerWidth) {\n this.containerWidth = width;\n }\n });\n this.resizeObserver.observe(this.container);\n }\n\n private getActions() {\n if (!this.container || this.container.getBoundingClientRect().width === 0) {\n return {\n visibleActions: [],\n hiddenActions: [],\n };\n }\n\n const actionsContainerWidth =\n this.actionsContainer.getBoundingClientRect().width;\n const overflowMenuIconWidth = 40;\n const fixedActionsWidth =\n this.fixedActions.getBoundingClientRect().width || 0;\n const decoratorContainerWidth =\n this.decoratorContainer.getBoundingClientRect().width || 0;\n /**\n * to properly gauge the container width we need to account for some additional variables\n * 1. the size of the overflow menu icon, which should always be a constant\n * 2. the size of any optional fixed width items\n * 3. the size of any optional decorator items\n */\n const containerWidth =\n actionsContainerWidth -\n (overflowMenuIconWidth + fixedActionsWidth + decoratorContainerWidth);\n const children = this.actionsContainer.children;\n let currentWidth = 0;\n const visibleChildren: Element[] = [];\n const hiddenChildren: Element[] = [];\n for (const el of children) {\n const elWidth = el.getBoundingClientRect().width;\n const newWidth = currentWidth + elWidth;\n const widthCheck = newWidth < containerWidth;\n if (widthCheck) {\n currentWidth = newWidth;\n visibleChildren.push(el);\n } else {\n hiddenChildren.push(el);\n }\n }\n const idx = visibleChildren.length;\n const sortedActions = this.sortActions();\n const visibleActions = sortedActions.slice(0, idx);\n const hiddenActions = sortedActions.slice(idx);\n\n return {\n visibleActions,\n hiddenActions,\n };\n }\n\n /**\n * Returns the focused overflow menu item (if exists) by traversing shadow DOM\n */\n private findFocusedOverflowMenuItem(activeElem: Element): Element | null {\n if (activeElem.tagName.toLowerCase() === 'cds-custom-overflow-menu-item') {\n return activeElem;\n }\n\n if (activeElem?.shadowRoot?.activeElement) {\n return this.findFocusedOverflowMenuItem(\n activeElem.shadowRoot.activeElement\n );\n }\n\n return null;\n }\n\n private _handleToolbarKeydown = (event: KeyboardEvent) => {\n if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') {\n return;\n }\n\n let focusedMenuItem: Element | null = null;\n\n if (document.activeElement) {\n focusedMenuItem = this.findFocusedOverflowMenuItem(\n document.activeElement\n );\n }\n\n if (focusedMenuItem) {\n event.preventDefault();\n const menuBody = focusedMenuItem.closest('cds-custom-overflow-menu-body');\n\n if (!menuBody) {\n return;\n }\n\n const items = Array.from(\n menuBody.querySelectorAll('cds-custom-overflow-menu-item:not([disabled])')\n ) as HTMLElement[];\n\n const currentIndex = items.indexOf(focusedMenuItem as HTMLElement);\n if (currentIndex === -1) {\n return;\n }\n\n const direction = event.key === 'ArrowDown' ? 1 : -1;\n const nextIndex =\n (currentIndex + direction + items.length) % items.length;\n items[nextIndex]?.focus();\n }\n };\n\n /**\n * Renders an action as an icon button.\n * Note: Some Action properties only apply when rendered in overflow menu:\n * - danger/dangerDescription: cds-custom-icon-button doesn't support danger variant\n * - divider: Only applicable in menu context\n */\n private renderIconButton = (action: Action) => {\n const tooltipAlign = this.isRTL ? 'bottom-start' : 'bottom-end';\n\n return html`\n <cds-custom-icon-button\n ?data-fixed=${action.fixed}\n data-testid=${action.testId || nothing}\n @click=${action.onClick}\n href=${action.href || nothing}\n target=${action.href ? action.target || '_self' : nothing}\n size=${action.size || BUTTON_SIZE.MEDIUM}\n align=${tooltipAlign}\n kind=\"ghost\"\n enter-delay-ms=\"0\"\n leave-delay-ms=\"0\"\n ?disabled=${action.disabled}>\n ${iconLoader(action.icon, {\n slot: 'icon',\n })}\n <span slot=\"tooltip-content\">${action.text}</span>\n </cds-custom-icon-button>\n `;\n };\n\n private getOverflowMenuSize(): OVERFLOW_MENU_SIZE {\n return (this.actions?.[0]?.size ||\n OVERFLOW_MENU_SIZE.MEDIUM) as OVERFLOW_MENU_SIZE;\n }\n\n render() {\n const {\n hiddenActions: rawHiddenActions,\n visibleActions: rawVisibleActions,\n } = this.getActions();\n const showOverflowMenu = rawHiddenActions.length > 1;\n const visibleActions = showOverflowMenu\n ? rawVisibleActions\n : [...rawVisibleActions, ...rawHiddenActions];\n const hiddenActions = showOverflowMenu ? rawHiddenActions : [];\n const showInitialActions =\n rawVisibleActions.length === 0 && rawHiddenActions.length === 0;\n\n return html`\n <div data-rounded=\"top\" class=${blockClass}>\n <div data-fixed class=\"${blockClass}__start\">\n <div data-fixed class=\"${blockClass}__navigation\">\n <slot name=\"navigation\"></slot>\n </div>\n\n <div data-fixed class=\"${blockClass}__title\">\n <slot name=\"title\">\n ${\n this.titleText || this.nameText\n ? html`\n <cds-custom-aichat-truncated-text\n lines=\"1\"\n type=\"tooltip\"\n align=${this.isRTL ? 'bottom-end' : 'bottom-start'}\n value=\"${[this.titleText, this.nameText]\n .filter(Boolean)\n .join(' ')}\">\n ${\n this.titleText\n ? html`<span\n data-testid=${PageObjectId.HEADER_TITLE}\n >${this.titleText}</span\n >`\n : nothing\n }\n ${this.titleText && this.nameText ? html`` : nothing}\n ${\n this.nameText\n ? html`<span\n class=\"${blockClass}__name\"\n data-testid=${PageObjectId.HEADER_NAME}\n >${this.nameText}</span\n >`\n : nothing\n }\n </cds-custom-aichat-truncated-text>\n `\n : nothing\n }\n </slot>\n </div>\n </div>\n <div\n class=\"${blockClass}__end\"\n data-rounded=\"top-right\"\n data-floating-menu-container>\n <div class=\"${blockClass}__actions-container\">\n <div class=\"${blockClass}__decorator-container\">\n <slot name=\"decorator\"></slot>\n </div>\n ${repeat(\n showInitialActions ? this.actions : visibleActions,\n (action) => action.text,\n this.renderIconButton\n )}\n ${\n showOverflowMenu\n ? html`\n <cds-custom-overflow-menu\n size=${this.getOverflowMenuSize()}\n align=${this.isRTL ? 'bottom-start' : 'bottom-end'}\n data-offset\n ?data-hidden=${hiddenActions.length === 0}\n kind=\"ghost\"\n close-on-activation\n enter-delay-ms=\"0\"\n leave-delay-ms=\"0\">\n ${iconLoader(OverflowMenuVertical16, {\n class: `${blockClass}-overflow-icon`,\n slot: 'icon',\n })}\n <span slot=\"tooltip-content\"\n >${CDSAIChatToolbar.OVERFLOW_MENU_LABEL}</span\n >\n <cds-custom-overflow-menu-body ?flipped=${!this.isRTL}>\n ${repeat(\n hiddenActions,\n (item) => item.text,\n (item) => html`\n <cds-custom-overflow-menu-item\n @click=${item.onClick}\n href=${item.href || nothing}\n target=${\n item.href ? item.target || '_self' : nothing\n }\n ?disabled=${item.disabled}\n ?danger=${item.danger}\n danger-description=${\n item.dangerDescription || nothing\n }\n ?divider=${item.divider}\n data-testid=${item.testId || nothing}>\n ${item.text}\n </cds-custom-overflow-menu-item>\n `\n )}\n </cds-custom-overflow-menu-body>\n </cds-custom-overflow-menu>\n `\n : nothing\n }\n <div data-fixed class=\"${blockClass}__fixed-actions\">\n <slot name=\"fixed-actions\"></slot>\n </div>\n </div>\n </div>\n </div>\n `;\n }\n\n static styles = [commonStyles, styles];\n}\n\nexport { CDSAIChatToolbar };\nexport default CDSAIChatToolbar;\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;AAOG;;AAmBH,MAAM,UAAU,GAAG,CAAA,EAAG,MAAM,UAAU;AA6BtC;;;;;;;;;AASG;AAEH,IAAM,gBAAgB,GAAA,kBAAA,GAAtB,MAAM,gBAAiB,SAAQ,UAAU,CAAA;AAAzC,IAAA,WAAA,GAAA;;AACE;;AAEG;QACc,IAAA,CAAA,KAAK,GAAG,KAAK;;QAI9B,IAAA,CAAA,OAAO,GAAa,EAAE;;QAItB,IAAA,CAAA,QAAQ,GAAG,KAAK;QAsBR,IAAA,CAAA,cAAc,GAAG,CAAC;AAkHlB,QAAA,IAAA,CAAA,qBAAqB,GAAG,CAAC,KAAoB,KAAI;AACvD,YAAA,IAAI,KAAK,CAAC,GAAG,KAAK,SAAS,IAAI,KAAK,CAAC,GAAG,KAAK,WAAW,EAAE;gBACxD;YACF;YAEA,IAAI,eAAe,GAAmB,IAAI;AAE1C,YAAA,IAAI,QAAQ,CAAC,aAAa,EA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Ae,gBAAgB;;"}
|
|
1
|
+
{"version":3,"file":"toolbar.js","sources":["../../../../src/components/toolbar/src/toolbar.ts"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\nimport { LitElement, html, nothing } from 'lit';\nimport { property, state, query } from 'lit/decorators.js';\nimport { repeat } from 'lit/directives/repeat.js';\nimport '@carbon/web-components/es-custom/components/button/index.js';\nimport '@carbon/web-components/es-custom/components/overflow-menu/index.js';\nimport { OVERFLOW_MENU_SIZE } from '@carbon/web-components/es-custom/components/overflow-menu/defs.js';\nimport OverflowMenuVertical16 from '@carbon/icons/es/overflow-menu--vertical/16.js';\nimport { iconLoader } from '@carbon/web-components/es-custom/globals/internal/icon-loader.js';\nimport prefix from '../../../globals/settings.js';\nimport commonStyles from '../../../globals/scss/common.scss?lit';\nimport styles from './toolbar.scss?lit';\nimport { CarbonIcon } from '@carbon/web-components/es-custom/globals/internal/icon-loader-utils.js';\nimport { carbonElement } from '../../../globals/decorators/index.js';\nimport '../../truncated-text/index.js';\nimport { BaseOverflowMenuItem } from '../../../typings/overflow-menu.js';\nimport { PageObjectId } from '../../../testing/PageObjectId.js';\n\nconst blockClass = `${prefix}-toolbar`;\nimport { BUTTON_SIZE } from '@carbon/web-components/es-custom/components/button/defs.js';\n\n/**\n * Actions that display in the toolbar.\n * Extends BaseOverflowMenuItem to support all overflow menu item properties\n * including danger variants, dividers, and links (href/target).\n *\n * Actions can be either:\n * - Interactive buttons with onClick handlers\n * - Links with href/target attributes\n */\nexport interface Action extends BaseOverflowMenuItem {\n /**\n * `@carbon/icons` icon for the action.\n */\n icon: CarbonIcon;\n\n /**\n * Size of button. Defaults to BUTTON_SIZE.MEDIUM.\n */\n size?: BUTTON_SIZE;\n\n /**\n * When overflow handling is enabled, setting fixed to true will force this action out of the overflow menu.\n */\n fixed?: boolean;\n\n /**\n * Renders this action as a two-state toggle and sets its current state.\n * When `true` or `false`, the button exposes `aria-pressed` and a visible\n * pressed treatment. Omit the field for a plain button with no toggle\n * semantics — `undefined` is intentionally distinct from `false`.\n */\n isSelected?: boolean;\n}\n\n/**\n * Toolbar.\n *\n * @element cds-custom-aichat-toolbar\n * @slot navigation - Defines the navigation area of the toolbar.\n * @slot title - Defines the title section of the toolbar.\n * @slot fixed-actions - Defines the area for displaying actions that are always visible (not overflowed) in the toolbar.\n * @slot toolbar-ai-label - Defines the area for displaying the AI label in the toolbar.\n *\n */\n@carbonElement(blockClass)\nclass CDSAIChatToolbar extends LitElement {\n /** Whether the component is in RTL mode.\n * @internal\n */\n @state() private isRTL = false;\n\n /** The list of actions. */\n @property({ type: Array, attribute: false, reflect: false })\n actions: Action[] = [];\n\n /** Should actions be overflowing. */\n @property({ type: Boolean, attribute: 'overflow', reflect: true })\n overflow = false;\n\n @property({ type: String })\n titleText?: string;\n\n @property({ type: String })\n nameText?: string;\n\n /** Container holding all action buttons and the overflow menu.\n * @internal\n */\n @query(`.${blockClass}__end`) private container!: HTMLElement;\n @query(`.${blockClass}__actions-container`)\n private actionsContainer!: HTMLElement;\n\n @query(`.${blockClass}__decorator-container`)\n private decoratorContainer!: HTMLElement;\n\n @query(`.${blockClass}__fixed-actions`)\n private fixedActions!: HTMLElement;\n\n @state()\n private containerWidth = 0;\n\n private resizeObserver?: ResizeObserver;\n\n private static readonly OVERFLOW_MENU_LABEL = 'Options';\n\n connectedCallback(): void {\n super.connectedCallback();\n this.addEventListener('keydown', this._handleToolbarKeydown);\n }\n\n disconnectedCallback() {\n this.resizeObserver?.disconnect();\n this.resizeObserver = undefined;\n this.removeEventListener('keydown', this._handleToolbarKeydown);\n super.disconnectedCallback();\n }\n\n firstUpdated() {\n if (this.overflow) {\n this.setupResizeObserver();\n }\n }\n\n updated() {\n // Carbon's delegatesFocus moves focus to the inner shadow <button>, so\n // ARIA attributes on the host are invisible to assistive tech. Mirror\n // them onto the inner button after each element's update cycle completes.\n void this._patchShadowButtonAttrs('cds-custom-icon-button[data-pressed]', {\n 'aria-pressed': 'data-pressed',\n });\n void this._patchShadowButtonAttrs(\n 'cds-custom-overflow-menu-item[role=\"menuitemcheckbox\"]',\n { role: 'role', 'aria-checked': 'aria-checked' }\n );\n }\n\n /**\n * Copies attributes from each host element matching `selector` onto its\n * inner shadow `<button>`, after the element's own update cycle completes.\n *\n * @param selector - CSS selector scoped to this shadow root.\n * @param attrMap - `{ targetAttr: sourceAttr }` pairs to copy.\n * @internal\n */\n private async _patchShadowButtonAttrs(\n selector: string,\n attrMap: Record<string, string>\n ): Promise<void> {\n await Promise.all(\n Array.from(\n this.shadowRoot?.querySelectorAll<LitElement & HTMLElement>(selector) ??\n []\n ).map(async (el) => {\n await el.updateComplete;\n const btn = el.shadowRoot?.querySelector('button');\n if (!btn) {\n return;\n }\n for (const [target, source] of Object.entries(attrMap)) {\n const value = el.getAttribute(source);\n if (value !== null) {\n btn.setAttribute(target, value);\n }\n }\n })\n );\n }\n\n private sortActions() {\n return [...this.actions].sort((a, b) => {\n if (a.fixed && !b.fixed) {\n return -1;\n }\n if (!a.fixed && b.fixed) {\n return 1;\n }\n return 0;\n });\n }\n\n private setupResizeObserver() {\n this.resizeObserver?.disconnect();\n this.resizeObserver = new ResizeObserver((entries) => {\n const width = entries[0].contentRect.width;\n if (width !== this.containerWidth) {\n this.containerWidth = width;\n }\n });\n this.resizeObserver.observe(this.container);\n }\n\n private getActions() {\n if (!this.container || this.container.getBoundingClientRect().width === 0) {\n return {\n visibleActions: [],\n hiddenActions: [],\n };\n }\n\n const actionsContainerWidth =\n this.actionsContainer.getBoundingClientRect().width;\n const overflowMenuIconWidth = 40;\n const fixedActionsWidth =\n this.fixedActions.getBoundingClientRect().width || 0;\n const decoratorContainerWidth =\n this.decoratorContainer.getBoundingClientRect().width || 0;\n /**\n * to properly gauge the container width we need to account for some additional variables\n * 1. the size of the overflow menu icon, which should always be a constant\n * 2. the size of any optional fixed width items\n * 3. the size of any optional decorator items\n */\n const containerWidth =\n actionsContainerWidth -\n (overflowMenuIconWidth + fixedActionsWidth + decoratorContainerWidth);\n const children = this.actionsContainer.children;\n let currentWidth = 0;\n const visibleChildren: Element[] = [];\n const hiddenChildren: Element[] = [];\n for (const el of children) {\n const elWidth = el.getBoundingClientRect().width;\n const newWidth = currentWidth + elWidth;\n const widthCheck = newWidth < containerWidth;\n if (widthCheck) {\n currentWidth = newWidth;\n visibleChildren.push(el);\n } else {\n hiddenChildren.push(el);\n }\n }\n const idx = visibleChildren.length;\n const sortedActions = this.sortActions();\n const visibleActions = sortedActions.slice(0, idx);\n const hiddenActions = sortedActions.slice(idx);\n\n return {\n visibleActions,\n hiddenActions,\n };\n }\n\n /**\n * Returns the focused overflow menu item (if exists) by traversing shadow DOM\n */\n private findFocusedOverflowMenuItem(activeElem: Element): Element | null {\n if (activeElem.tagName.toLowerCase() === 'cds-custom-overflow-menu-item') {\n return activeElem;\n }\n\n if (activeElem?.shadowRoot?.activeElement) {\n return this.findFocusedOverflowMenuItem(\n activeElem.shadowRoot.activeElement\n );\n }\n\n return null;\n }\n\n private _handleToolbarKeydown = (event: KeyboardEvent) => {\n if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') {\n return;\n }\n\n let focusedMenuItem: Element | null = null;\n\n if (document.activeElement) {\n focusedMenuItem = this.findFocusedOverflowMenuItem(\n document.activeElement\n );\n }\n\n if (focusedMenuItem) {\n event.preventDefault();\n const menuBody = focusedMenuItem.closest('cds-custom-overflow-menu-body');\n\n if (!menuBody) {\n return;\n }\n\n const items = Array.from(\n menuBody.querySelectorAll('cds-custom-overflow-menu-item:not([disabled])')\n ) as HTMLElement[];\n\n const currentIndex = items.indexOf(focusedMenuItem as HTMLElement);\n if (currentIndex === -1) {\n return;\n }\n\n const direction = event.key === 'ArrowDown' ? 1 : -1;\n const nextIndex =\n (currentIndex + direction + items.length) % items.length;\n items[nextIndex]?.focus();\n }\n };\n\n /**\n * Renders an action as an icon button.\n * Note: Some Action properties only apply when rendered in overflow menu:\n * - danger/dangerDescription: cds-custom-icon-button doesn't support danger variant\n * - divider: Only applicable in menu context\n */\n private renderIconButton = (action: Action) => {\n const tooltipAlign = this.isRTL ? 'bottom-start' : 'bottom-end';\n const { isSelected } = action;\n\n return html`\n <cds-custom-icon-button\n align=${tooltipAlign}\n @click=${action.onClick}\n ?data-fixed=${action.fixed}\n data-pressed=${isSelected !== undefined ? String(isSelected) : nothing}\n ?data-selected=${isSelected === true}\n data-testid=${action.testId || nothing}\n ?disabled=${action.disabled}\n enter-delay-ms=\"0\"\n href=${action.href || nothing}\n ?isSelected=${isSelected === true}\n kind=\"ghost\"\n leave-delay-ms=\"0\"\n size=${action.size || BUTTON_SIZE.MEDIUM}\n target=${action.href ? action.target || '_self' : nothing}>\n ${iconLoader(action.icon, {\n slot: 'icon',\n })}\n <span slot=\"tooltip-content\">${action.text}</span>\n </cds-custom-icon-button>\n `;\n };\n\n private getOverflowMenuSize(): OVERFLOW_MENU_SIZE {\n return (this.actions?.[0]?.size ||\n OVERFLOW_MENU_SIZE.MEDIUM) as OVERFLOW_MENU_SIZE;\n }\n\n render() {\n const {\n hiddenActions: rawHiddenActions,\n visibleActions: rawVisibleActions,\n } = this.getActions();\n const showOverflowMenu = rawHiddenActions.length > 1;\n const visibleActions = showOverflowMenu\n ? rawVisibleActions\n : [...rawVisibleActions, ...rawHiddenActions];\n const hiddenActions = showOverflowMenu ? rawHiddenActions : [];\n const showInitialActions =\n rawVisibleActions.length === 0 && rawHiddenActions.length === 0;\n\n return html`\n <div data-rounded=\"top\" class=${blockClass}>\n <div data-fixed class=\"${blockClass}__start\">\n <div data-fixed class=\"${blockClass}__navigation\">\n <slot name=\"navigation\"></slot>\n </div>\n\n <div data-fixed class=\"${blockClass}__title\">\n <slot name=\"title\">\n ${\n this.titleText || this.nameText\n ? html`\n <cds-custom-aichat-truncated-text\n lines=\"1\"\n type=\"tooltip\"\n align=${this.isRTL ? 'bottom-end' : 'bottom-start'}\n value=\"${[this.titleText, this.nameText]\n .filter(Boolean)\n .join(' ')}\">\n ${\n this.titleText\n ? html`<span\n data-testid=${PageObjectId.HEADER_TITLE}\n >${this.titleText}</span\n >`\n : nothing\n }\n ${this.titleText && this.nameText ? html`` : nothing}\n ${\n this.nameText\n ? html`<span\n class=\"${blockClass}__name\"\n data-testid=${PageObjectId.HEADER_NAME}\n >${this.nameText}</span\n >`\n : nothing\n }\n </cds-custom-aichat-truncated-text>\n `\n : nothing\n }\n </slot>\n </div>\n </div>\n <div\n class=\"${blockClass}__end\"\n data-rounded=\"top-right\"\n data-floating-menu-container>\n <div class=\"${blockClass}__actions-container\">\n <div class=\"${blockClass}__decorator-container\">\n <slot name=\"decorator\"></slot>\n </div>\n ${repeat(\n showInitialActions ? this.actions : visibleActions,\n (action) => action.text,\n this.renderIconButton\n )}\n ${\n showOverflowMenu\n ? html`\n <cds-custom-overflow-menu\n size=${this.getOverflowMenuSize()}\n align=${this.isRTL ? 'bottom-start' : 'bottom-end'}\n data-offset\n ?data-hidden=${hiddenActions.length === 0}\n kind=\"ghost\"\n close-on-activation\n enter-delay-ms=\"0\"\n leave-delay-ms=\"0\">\n ${iconLoader(OverflowMenuVertical16, {\n class: `${blockClass}-overflow-icon`,\n slot: 'icon',\n })}\n <span slot=\"tooltip-content\"\n >${CDSAIChatToolbar.OVERFLOW_MENU_LABEL}</span\n >\n <cds-custom-overflow-menu-body ?flipped=${!this.isRTL}>\n ${repeat(\n hiddenActions,\n (item) => item.text,\n (item) => {\n return html`\n <cds-custom-overflow-menu-item\n @click=${item.onClick}\n href=${item.href || nothing}\n target=${\n item.href ? item.target || '_self' : nothing\n }\n ?disabled=${item.disabled}\n ?danger=${item.danger}\n danger-description=${\n item.dangerDescription || nothing\n }\n ?divider=${item.divider}\n ?data-selected=${item.isSelected === true}\n role=${\n item.isSelected !== undefined\n ? 'menuitemcheckbox'\n : nothing\n }\n aria-checked=${\n item.isSelected !== undefined\n ? String(item.isSelected)\n : nothing\n }\n data-testid=${item.testId || nothing}>\n ${item.text}\n </cds-custom-overflow-menu-item>\n `;\n }\n )}\n </cds-custom-overflow-menu-body>\n </cds-custom-overflow-menu>\n `\n : nothing\n }\n <div data-fixed class=\"${blockClass}__fixed-actions\">\n <slot name=\"fixed-actions\"></slot>\n </div>\n </div>\n </div>\n </div>\n `;\n }\n\n static styles = [commonStyles, styles];\n}\n\nexport { CDSAIChatToolbar };\nexport default CDSAIChatToolbar;\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;AAOG;;AAmBH,MAAM,UAAU,GAAG,CAAA,EAAG,MAAM,UAAU;AAqCtC;;;;;;;;;AASG;AAEH,IAAM,gBAAgB,GAAA,kBAAA,GAAtB,MAAM,gBAAiB,SAAQ,UAAU,CAAA;AAAzC,IAAA,WAAA,GAAA;;AACE;;AAEG;QACc,IAAA,CAAA,KAAK,GAAG,KAAK;;QAI9B,IAAA,CAAA,OAAO,GAAa,EAAE;;QAItB,IAAA,CAAA,QAAQ,GAAG,KAAK;QAsBR,IAAA,CAAA,cAAc,GAAG,CAAC;AA+JlB,QAAA,IAAA,CAAA,qBAAqB,GAAG,CAAC,KAAoB,KAAI;AACvD,YAAA,IAAI,KAAK,CAAC,GAAG,KAAK,SAAS,IAAI,KAAK,CAAC,GAAG,KAAK,WAAW,EAAE;gBACxD;YACF;YAEA,IAAI,eAAe,GAAmB,IAAI;AAE1C,YAAA,IAAI,QAAQ,CAAC,aAAa,EAAE;gBAC1B,eAAe,GAAG,IAAI,CAAC,2BAA2B,CAChD,QAAQ,CAAC,aAAa,CACvB;YACH;YAEA,IAAI,eAAe,EAAE;gBACnB,KAAK,CAAC,cAAc,EAAE;gBACtB,MAAM,QAAQ,GAAG,eAAe,CAAC,OAAO,CAAC,wBAAwB,CAAC;gBAElE,IAAI,CAAC,QAAQ,EAAE;oBACb;gBACF;AAEA,gBAAA,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CACtB,QAAQ,CAAC,gBAAgB,CAAC,wCA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AM,EAAE;AACP,CAAA,EAAA,gBAAA,CAAA,SAAA,EAAA,WAAA,EAAA,MAAA,CAAA;AAGnB,UAAA,CAAA;AADC,IAAA,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE;AACR,CAAA,EAAA,gBAAA,CAAA,SAAA,EAAA,UAAA,EAAA,MAAA,CAAA;AAKoB,UAAA,CAAA;AAArC,IAAA,KAAK,CAAC,CAAA,CAAA,EAAI,UAAU,CAAA,KAAA,CAAO;AAAkC,CAAA,EAAA,gBAAA,CAAA,SAAA,EAAA,WAAA,EAAA,MAAA,CAAA;AAEtD,UAAA,CAAA;AADP,IAAA,KAAK,CAAC,CAAA,CAAA,EAAI,UAAU,CAAA,mBAAA,CAAqB;AACH,CAAA,EAAA,gBAAA,CAAA,SAAA,EAAA,kBAAA,EAAA,MAAA,CAAA;AAG/B,UAAA,CAAA;AADP,IAAA,KAAK,CAAC,CAAA,CAAA,EAAI,UAAU,CAAA,qBAAA,CAAuB;AACH,CAAA,EAAA,gBAAA,CAAA,SAAA,EAAA,oBAAA,EAAA,MAAA,CAAA;AAGjC,UAAA,CAAA;AADP,IAAA,KAAK,CAAC,CAAA,CAAA,EAAI,UAAU,CAAA,eAAA,CAAiB;AACH,CAAA,EAAA,gBAAA,CAAA,SAAA,EAAA,cAAA,EAAA,MAAA,CAAA;AAG3B,UAAA,CAAA;AADP,IAAA,KAAK;AACqB,CAAA,EAAA,gBAAA,CAAA,SAAA,EAAA,gBAAA,EAAA,MAAA,CAAA;AAlCvB,gBAAgB,GAAA,kBAAA,GAAA,UAAA,CAAA;IADrB,aAAa,CAAC,UAAU;AACnB,CAAA,EAAA,gBAAgB,CAwZrB;AAGD,yBAAe,gBAAgB;;"}
|
|
@@ -146,7 +146,7 @@ class VimeoProvider extends BaseProvider {
|
|
|
146
146
|
this.triggerError(new Error(this.config.errorMessage || 'Failed to load video'));
|
|
147
147
|
});
|
|
148
148
|
}
|
|
149
|
-
catch (
|
|
149
|
+
catch (_error) {
|
|
150
150
|
if (this.iframe) {
|
|
151
151
|
this.updateAriaAttributes(this.iframe, 'error');
|
|
152
152
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vimeo-provider.js","sources":["../../../../../src/components/video-player/src/providers/vimeo-provider.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * Portions of this code are derived from react-player\n * Copyright (c) 2017 Pete Cook\n * Licensed under the MIT License\n * https://github.com/cookpete/react-player/blob/v2.15.1/LICENSE\n *\n * Vimeo player implementation adapted from:\n * https://github.com/cookpete/react-player/blob/v2.15.1/src/players/Vimeo.js\n */\n\nimport { BaseProvider, ProviderConfig } from './base-provider.js';\nimport { ScriptLoader } from '../../../shared/media-utils/script-loader.js';\n\nconst SDK_URL = 'https://player.vimeo.com/api/player.js';\n\n// Declare Vimeo Player API types\ndeclare global {\n interface Window {\n Vimeo: any;\n }\n}\n\n/**\n * Clean Vimeo URL by removing management paths\n */\nfunction cleanUrl(url: string): string {\n return url.replace('/manage/videos', '');\n}\n\n/**\n * Provider for Vimeo videos using the Vimeo Player API\n */\nexport class VimeoProvider extends BaseProvider {\n private player: any = null;\n private playerContainer: HTMLDivElement | null = null;\n private iframe: HTMLIFrameElement | null = null;\n private isReady = false;\n\n /**\n * Update aria attributes based on state\n */\n protected updateAriaAttributes(\n element: HTMLElement,\n state: 'loading' | 'ready' | 'error'\n ): void {\n element.setAttribute('aria-label', this.getStateLabel(state));\n element.setAttribute('aria-busy', state === 'loading' ? 'true' : 'false');\n }\n\n /**\n * Initialize the provider and load Vimeo Player API\n */\n async init(container: HTMLElement, config: ProviderConfig): Promise<void> {\n await super.init(container, config);\n\n if (!this.container) {\n throw new Error('Container element is required');\n }\n\n // Create container for Vimeo player. Sizing/positioning of the wrapper\n // and the iframe Vimeo inserts inside it are handled by the\n // .cds-custom-aichat--video-player__provider SCSS rules in video-player.scss.\n this.playerContainer = document.createElement('div');\n this.container.appendChild(this.playerContainer);\n\n // Load Vimeo Player API\n await this.loadVimeoAPI();\n }\n\n /**\n * Load the Vimeo Player API script\n */\n private async loadVimeoAPI(): Promise<void> {\n if (window.Vimeo && window.Vimeo.Player) {\n return Promise.resolve();\n }\n\n await ScriptLoader.load(SDK_URL);\n\n // Wait for Vimeo to be available\n return new Promise((resolve, reject) => {\n const checkVimeo = () => {\n if (window.Vimeo && window.Vimeo.Player) {\n resolve();\n } else {\n setTimeout(checkVimeo, 100);\n }\n };\n checkVimeo();\n\n // Timeout after 5 seconds\n setTimeout(() => {\n if (!window.Vimeo || !window.Vimeo.Player) {\n reject(new Error('Vimeo Player API failed to load'));\n }\n }, 5000);\n });\n }\n\n /**\n * Load a Vimeo video URL\n */\n async load(url: string): Promise<void> {\n if (!this.playerContainer) {\n throw new Error('Player container not initialized');\n }\n\n // Wait for API to be ready\n if (!window.Vimeo || !window.Vimeo.Player) {\n await this.loadVimeoAPI();\n }\n\n const cleanedUrl = cleanUrl(url);\n\n try {\n // Create new player\n this.player = new window.Vimeo.Player(this.playerContainer, {\n url: cleanedUrl,\n autoplay: this.config.playing || false,\n controls: true,\n playsinline: true,\n });\n\n // Wait for player to be ready\n await this.player.ready();\n\n // Track the SDK-created iframe for ARIA updates. Its sizing is handled\n // by the .cds-custom-aichat--video-player__provider iframe SCSS rule.\n this.iframe = this.playerContainer.querySelector(\n 'iframe'\n ) as HTMLIFrameElement;\n if (this.iframe) {\n this.updateAriaAttributes(this.iframe, 'loading');\n }\n\n // Set up event listeners\n this.player.on('loaded', () => {\n if (this.iframe) {\n this.updateAriaAttributes(this.iframe, 'ready');\n }\n this.isReady = true;\n this.triggerReady();\n });\n\n this.player.on('play', () => {\n this.triggerPlay();\n });\n\n this.player.on('pause', () => {\n this.triggerPause();\n });\n\n this.player.on('ended', () => {\n this.triggerPause();\n });\n\n this.player.on('error', (_error: any) => {\n if (this.iframe) {\n this.updateAriaAttributes(this.iframe, 'error');\n }\n // Use the generic error message from config\n this.triggerError(\n new Error(this.config.errorMessage || 'Failed to load video')\n );\n });\n } catch (error) {\n if (this.iframe) {\n this.updateAriaAttributes(this.iframe, 'error');\n }\n // Use the generic error message from config\n this.triggerError(\n new Error(this.config.errorMessage || 'Failed to load video')\n );\n }\n }\n\n /**\n * Start or resume playback\n */\n play(): void {\n if (this.player && this.isReady) {\n this.player.play().catch((error: any) => {\n console.warn('Vimeo play was prevented:', error);\n });\n }\n }\n\n /**\n * Pause playback\n */\n pause(): void {\n if (this.player && this.isReady) {\n this.player.pause().catch((error: any) => {\n console.warn('Vimeo pause failed:', error);\n });\n }\n }\n\n /**\n * Clean up the provider\n */\n destroy(): void {\n if (this.player) {\n this.player.destroy().catch((error: any) => {\n console.warn('Vimeo destroy failed:', error);\n });\n this.player = null;\n }\n this.playerContainer = null;\n this.isReady = false;\n super.destroy();\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;;;AAQG;AAKH,MAAM,OAAO,GAAG,wCAAwC;AASxD;;AAEG;AACH,SAAS,QAAQ,CAAC,GAAW,EAAA;IAC3B,OAAO,GAAG,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;AAC1C;AAEA;;AAEG;AACG,MAAO,aAAc,SAAQ,YAAY,CAAA;AAA/C,IAAA,WAAA,GAAA;;QACU,IAAA,CAAA,MAAM,GAAQ,IAAI;QAClB,IAAA,CAAA,eAAe,GAA0B,IAAI;QAC7C,IAAA,CAAA,MAAM,GAA6B,IAAI;QACvC,IAAA,CAAA,OAAO,GAAG,KAAK;IAgLzB;AA9KE;;AAEG;IACO,oBAAoB,CAC5B,OAAoB,EACpB,KAAoC,EAAA;AAEpC,QAAA,OAAO,CAAC,YAAY,CAAC,YAAY,EAAE,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;AAC7D,QAAA,OAAO,CAAC,YAAY,CAAC,WAAW,EAAE,KAAK,KAA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,IAAI,CAAC,OAAO,EAAE;YAC/B,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC,KAAU,KAAI;AACvC,gBAAA,OAAO,CAAC,IAAI,CAAC,qBAAqB,EAAE,KAAK,CAAC;AAC5C,YAAA,CAAC,CAAC;QACJ;IACF;AAEA;;AAEG;IACH,OAAO,GAAA;AACL,QAAA,IAAI,IAAI,CAAC,MAAM,EAAE;YACf,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,KAAU,KAAI;AACzC,gBAAA,OAAO,CAAC,IAAI,CAAC,uBAAuB,EAAE,KAAK,CAAC;AAC9C,YAAA,CAAC,CAAC;AACF,YAAA,IAAI,CAAC,MAAM,GAAG,IAAI;QACpB;AACA,QAAA,IAAI,CAAC,eAAe,GAAG,IAAI;AAC3B,QAAA,IAAI,CAAC,OAAO,GAAG,KAAK;QACpB,KAAK,CAAC,OAAO,EAAE;IACjB;AACD;;"}
|
|
1
|
+
{"version":3,"file":"vimeo-provider.js","sources":["../../../../../src/components/video-player/src/providers/vimeo-provider.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * Portions of this code are derived from react-player\n * Copyright (c) 2017 Pete Cook\n * Licensed under the MIT License\n * https://github.com/cookpete/react-player/blob/v2.15.1/LICENSE\n *\n * Vimeo player implementation adapted from:\n * https://github.com/cookpete/react-player/blob/v2.15.1/src/players/Vimeo.js\n */\n\nimport { BaseProvider, ProviderConfig } from './base-provider.js';\nimport { ScriptLoader } from '../../../shared/media-utils/script-loader.js';\n\nconst SDK_URL = 'https://player.vimeo.com/api/player.js';\n\n// Declare Vimeo Player API types\ndeclare global {\n interface Window {\n Vimeo: any;\n }\n}\n\n/**\n * Clean Vimeo URL by removing management paths\n */\nfunction cleanUrl(url: string): string {\n return url.replace('/manage/videos', '');\n}\n\n/**\n * Provider for Vimeo videos using the Vimeo Player API\n */\nexport class VimeoProvider extends BaseProvider {\n private player: any = null;\n private playerContainer: HTMLDivElement | null = null;\n private iframe: HTMLIFrameElement | null = null;\n private isReady = false;\n\n /**\n * Update aria attributes based on state\n */\n protected updateAriaAttributes(\n element: HTMLElement,\n state: 'loading' | 'ready' | 'error'\n ): void {\n element.setAttribute('aria-label', this.getStateLabel(state));\n element.setAttribute('aria-busy', state === 'loading' ? 'true' : 'false');\n }\n\n /**\n * Initialize the provider and load Vimeo Player API\n */\n async init(container: HTMLElement, config: ProviderConfig): Promise<void> {\n await super.init(container, config);\n\n if (!this.container) {\n throw new Error('Container element is required');\n }\n\n // Create container for Vimeo player. Sizing/positioning of the wrapper\n // and the iframe Vimeo inserts inside it are handled by the\n // .cds-custom-aichat--video-player__provider SCSS rules in video-player.scss.\n this.playerContainer = document.createElement('div');\n this.container.appendChild(this.playerContainer);\n\n // Load Vimeo Player API\n await this.loadVimeoAPI();\n }\n\n /**\n * Load the Vimeo Player API script\n */\n private async loadVimeoAPI(): Promise<void> {\n if (window.Vimeo && window.Vimeo.Player) {\n return Promise.resolve();\n }\n\n await ScriptLoader.load(SDK_URL);\n\n // Wait for Vimeo to be available\n return new Promise((resolve, reject) => {\n const checkVimeo = () => {\n if (window.Vimeo && window.Vimeo.Player) {\n resolve();\n } else {\n setTimeout(checkVimeo, 100);\n }\n };\n checkVimeo();\n\n // Timeout after 5 seconds\n setTimeout(() => {\n if (!window.Vimeo || !window.Vimeo.Player) {\n reject(new Error('Vimeo Player API failed to load'));\n }\n }, 5000);\n });\n }\n\n /**\n * Load a Vimeo video URL\n */\n async load(url: string): Promise<void> {\n if (!this.playerContainer) {\n throw new Error('Player container not initialized');\n }\n\n // Wait for API to be ready\n if (!window.Vimeo || !window.Vimeo.Player) {\n await this.loadVimeoAPI();\n }\n\n const cleanedUrl = cleanUrl(url);\n\n try {\n // Create new player\n this.player = new window.Vimeo.Player(this.playerContainer, {\n url: cleanedUrl,\n autoplay: this.config.playing || false,\n controls: true,\n playsinline: true,\n });\n\n // Wait for player to be ready\n await this.player.ready();\n\n // Track the SDK-created iframe for ARIA updates. Its sizing is handled\n // by the .cds-custom-aichat--video-player__provider iframe SCSS rule.\n this.iframe = this.playerContainer.querySelector(\n 'iframe'\n ) as HTMLIFrameElement;\n if (this.iframe) {\n this.updateAriaAttributes(this.iframe, 'loading');\n }\n\n // Set up event listeners\n this.player.on('loaded', () => {\n if (this.iframe) {\n this.updateAriaAttributes(this.iframe, 'ready');\n }\n this.isReady = true;\n this.triggerReady();\n });\n\n this.player.on('play', () => {\n this.triggerPlay();\n });\n\n this.player.on('pause', () => {\n this.triggerPause();\n });\n\n this.player.on('ended', () => {\n this.triggerPause();\n });\n\n this.player.on('error', (_error: any) => {\n if (this.iframe) {\n this.updateAriaAttributes(this.iframe, 'error');\n }\n // Use the generic error message from config\n this.triggerError(\n new Error(this.config.errorMessage || 'Failed to load video')\n );\n });\n } catch (_error) {\n if (this.iframe) {\n this.updateAriaAttributes(this.iframe, 'error');\n }\n // Use the generic error message from config\n this.triggerError(\n new Error(this.config.errorMessage || 'Failed to load video')\n );\n }\n }\n\n /**\n * Start or resume playback\n */\n play(): void {\n if (this.player && this.isReady) {\n this.player.play().catch((error: any) => {\n console.warn('Vimeo play was prevented:', error);\n });\n }\n }\n\n /**\n * Pause playback\n */\n pause(): void {\n if (this.player && this.isReady) {\n this.player.pause().catch((error: any) => {\n console.warn('Vimeo pause failed:', error);\n });\n }\n }\n\n /**\n * Clean up the provider\n */\n destroy(): void {\n if (this.player) {\n this.player.destroy().catch((error: any) => {\n console.warn('Vimeo destroy failed:', error);\n });\n this.player = null;\n }\n this.playerContainer = null;\n this.isReady = false;\n super.destroy();\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;;;AAQG;AAKH,MAAM,OAAO,GAAG,wCAAwC;AASxD;;AAEG;AACH,SAAS,QAAQ,CAAC,GAAW,EA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z);
|
|
19
19
|
}
|
|
20
|
-
catch (
|
|
20
|
+
catch (_error) {
|
|
21
21
|
// console.warn(`Attempting to re-define ${tagName}`);
|
|
22
22
|
}
|
|
23
23
|
// Cast as any because TS doesn't recognize the return type as being a
|
|
@@ -25,7 +25,6 @@ const legacyCustomElement = (tagName, clazz) => {
|
|
|
25
25
|
// `Constructor<HTMLElement>` for some reason.
|
|
26
26
|
// `Constructor<HTMLElement>` is helpful to make sure the decorator is
|
|
27
27
|
// applied to elements however.
|
|
28
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
29
28
|
return clazz;
|
|
30
29
|
};
|
|
31
30
|
const standardCustomElement = (tagName, descriptor) => {
|
|
@@ -38,7 +37,7 @@ const standardCustomElement = (tagName, descriptor) => {
|
|
|
38
37
|
try {
|
|
39
38
|
customElements.define(tagName, clazz);
|
|
40
39
|
}
|
|
41
|
-
catch (
|
|
40
|
+
catch (_error) {
|
|
42
41
|
// console.warn(`Attempting to re-define ${tagName}`);
|
|
43
42
|
}
|
|
44
43
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"carbon-element.js","sources":["../../../src/globals/decorators/carbon-element.ts"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\n/*\n * IMPORTANT: For compatibility with tsickle and the Closure JS compiler, all\n * property decorators (but not class decorators) in this file that have\n * an @ExportDecoratedItems annotation must be defined as a regular function,\n * not an arrow function.\n */\ndeclare type Constructor<T> = {\n new (...args: any[]): T;\n};\ninterface ClassDescriptor {\n kind: 'class';\n elements: ClassElement[];\n finisher?: <T>(clazz: Constructor<T>) => void | Constructor<T>;\n}\ninterface ClassElement {\n kind: 'field' | 'method';\n key: PropertyKey;\n placement: 'static' | 'prototype' | 'own';\n // eslint-disable-next-line @typescript-eslint/
|
|
1
|
+
{"version":3,"file":"carbon-element.js","sources":["../../../src/globals/decorators/carbon-element.ts"],"sourcesContent":["/*\n * Copyright IBM Corp. 2025, 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\n/*\n * IMPORTANT: For compatibility with tsickle and the Closure JS compiler, all\n * property decorators (but not class decorators) in this file that have\n * an @ExportDecoratedItems annotation must be defined as a regular function,\n * not an arrow function.\n */\ndeclare type Constructor<T> = {\n new (...args: any[]): T;\n};\ninterface ClassDescriptor {\n kind: 'class';\n elements: ClassElement[];\n finisher?: <T>(clazz: Constructor<T>) => void | Constructor<T>;\n}\ninterface ClassElement {\n kind: 'field' | 'method';\n key: PropertyKey;\n placement: 'static' | 'prototype' | 'own';\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n initializer?: Function;\n extras?: ClassElement[];\n finisher?: <T>(clazz: Constructor<T>) => void | Constructor<T>;\n descriptor?: PropertyDescriptor;\n}\n\n/**\n * Allow for custom element classes with private constructors\n */\ntype CustomElementClass = Omit<typeof HTMLElement, 'new'>;\n\nconst legacyCustomElement = (tagName: string, clazz: CustomElementClass) => {\n try {\n customElements.define(tagName, clazz as CustomElementConstructor);\n } catch (_error) {\n // console.warn(`Attempting to re-define ${tagName}`);\n }\n // Cast as any because TS doesn't recognize the return type as being a\n // subtype of the decorated class when clazz is typed as\n // `Constructor<HTMLElement>` for some reason.\n // `Constructor<HTMLElement>` is helpful to make sure the decorator is\n // applied to elements however.\n\n return clazz as any;\n};\n\nconst standardCustomElement = (\n tagName: string,\n descriptor: ClassDescriptor\n) => {\n const { kind, elements } = descriptor;\n return {\n kind,\n elements,\n // This callback is called once the class is otherwise fully defined\n finisher(clazz: Constructor<HTMLElement>) {\n try {\n customElements.define(tagName, clazz);\n } catch (_error) {\n // console.warn(`Attempting to re-define ${tagName}`);\n }\n },\n };\n};\n\n/**\n * Class decorator factory that defines the decorated class as a custom element.\n *\n * ```js\n * @carbonElement('my-element')\n * class MyElement extends LitElement {\n * render() {\n * return html``;\n * }\n * }\n * ```\n *\n * @param tagName The tag name of the custom element to define.\n */\nexport function carbonElement(tagName: string) {\n return (classOrDescriptor: CustomElementClass | ClassDescriptor) =>\n typeof classOrDescriptor === 'function'\n ? legacyCustomElement(tagName, classOrDescriptor)\n : standardCustomElement(tagName, classOrDescriptor as ClassDescriptor);\n}\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AAgCH,MAAM,mBAAmB,GAAG,CAAC,OAAe,EAAE,KAAyB,KAAI;AACzE,IAAA,IAAI;AACF,QAAA,cAAc,CAAC,MAAM,CAAC,OAAO,EAAE,KAAiC,CAAC;IACnE;IAAE,OAAO,MAAM,EAAE;;IAEjB;;;;;;AAOA,IAAA,OAAO,KAAY;AACrB,CAAC;AAED,MAAM,qBAAqB,GAAG,CAC5B,OAAe,EACf,UAA2B,KACzB;AACF,IAAA,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,UAAU;IACrC,OAAO;QACL,IAAI;QACJ,QAAQ;;AAER,QAAA,QAAQ,CAAC,KAA+B,EAAA;AACtC,YAAA,IAAI;AACF,gBAAA,cAAc,CAAC,MAAM,CAAC,OAAO,EAAE,KAAK,CAAC;YACvC;YAAE,OAAO,MAAM,EAAE;;YAEjB;QACF,CAAC;KACF;AACH,CAAC;AAED;;;;;;;;;;;;;AAaG;AACG,SAAU,aAAa,CAAC,OAAe,EAAA;IAC3C,OAAO,CAAC,iBAAuD,KAC7D,OAAO,iBAAiB,KAAK;AAC3B,UAAE,mBAAmB,CAAC,OAAO,EAAE,iBAAiB;AAChD,UAAE,qBAAqB,CAAC,OAAO,EAAE,iBAAoC,CAAC;AAC5E;;"}
|
|
@@ -15,6 +15,51 @@
|
|
|
15
15
|
* screen reader is currently reading. Use sparingly.
|
|
16
16
|
*/
|
|
17
17
|
type AnnouncerPoliteness = 'polite' | 'assertive';
|
|
18
|
+
/**
|
|
19
|
+
* Options for {@link mountAriaAnnouncer}.
|
|
20
|
+
*/
|
|
21
|
+
export interface AriaAnnouncerOptions {
|
|
22
|
+
/**
|
|
23
|
+
* Number of polite `aria-live="polite"` regions to create and rotate through.
|
|
24
|
+
* Default `1`. The React `AriaAnnouncerProvider` passes `3` explicitly: in
|
|
25
|
+
* earlier testing FF + JAWS occasionally re-read entire region contents on
|
|
26
|
+
* append; a third region ensures there is always a fresh region for the next
|
|
27
|
+
* announcement.
|
|
28
|
+
*/
|
|
29
|
+
politeCount?: number;
|
|
30
|
+
/**
|
|
31
|
+
* Number of `aria-live="assertive"` regions to create.
|
|
32
|
+
* Default 0 (polite-only).
|
|
33
|
+
*/
|
|
34
|
+
assertiveCount?: number;
|
|
35
|
+
/**
|
|
36
|
+
* Sets `aria-atomic` on every created region. Default `false`.
|
|
37
|
+
*
|
|
38
|
+
* Note: `aria-atomic` is intentionally left off by default. With it, FF +
|
|
39
|
+
* JAWS read some messages cleanly but Chrome stops announcing buttons inside
|
|
40
|
+
* the region. Without it, FF + JAWS sometimes double-read parts but Chrome
|
|
41
|
+
* handles buttons. The default (off) is the lesser evil.
|
|
42
|
+
*/
|
|
43
|
+
ariaAtomic?: boolean;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Handle returned by {@link mountAriaAnnouncer}. Call `disconnect` when the
|
|
47
|
+
* host element is removed from the DOM to cancel pending timers and clean up
|
|
48
|
+
* the created regions.
|
|
49
|
+
*/
|
|
50
|
+
export interface AriaAnnouncerHandle {
|
|
51
|
+
/**
|
|
52
|
+
* Queue a message for announcement on the next tick. Multiple same-tick calls
|
|
53
|
+
* for the same politeness are coalesced into a single write. Defaults to
|
|
54
|
+
* `"polite"`; falls back to polite if assertive regions were not created.
|
|
55
|
+
*/
|
|
56
|
+
announce(message: string, politeness?: AnnouncerPoliteness): void;
|
|
57
|
+
/**
|
|
58
|
+
* Cancel pending announcements, disconnect the manager, and remove the
|
|
59
|
+
* created live regions from `container`.
|
|
60
|
+
*/
|
|
61
|
+
disconnect(): void;
|
|
62
|
+
}
|
|
18
63
|
/**
|
|
19
64
|
* Manages ARIA live region announcements for screen readers.
|
|
20
65
|
*
|
|
@@ -59,4 +104,15 @@ export declare class AriaAnnouncerManager {
|
|
|
59
104
|
private clearChannel;
|
|
60
105
|
private doAnnouncements;
|
|
61
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* Create visually-hidden `aria-live` regions inside `container`, wire them to
|
|
109
|
+
* a new {@link AriaAnnouncerManager}, and return a handle. The caller is
|
|
110
|
+
* responsible for hiding the container (e.g. with a visually-hidden wrapper or
|
|
111
|
+
* CSS class); this function only creates the live regions themselves.
|
|
112
|
+
*
|
|
113
|
+
* @param container - The element to append the live regions into.
|
|
114
|
+
* @param options - Region counts and aria-atomic setting. All fields have
|
|
115
|
+
* sensible defaults; pass `{}` for a single polite region.
|
|
116
|
+
*/
|
|
117
|
+
export declare function mountAriaAnnouncer(container: HTMLElement, options?: AriaAnnouncerOptions): AriaAnnouncerHandle;
|
|
62
118
|
export {};
|
|
@@ -120,6 +120,51 @@ class AriaAnnouncerManager {
|
|
|
120
120
|
channel.currentIndex = (channel.currentIndex + 1) % channel.regions.length;
|
|
121
121
|
}
|
|
122
122
|
}
|
|
123
|
+
/**
|
|
124
|
+
* Create visually-hidden `aria-live` regions inside `container`, wire them to
|
|
125
|
+
* a new {@link AriaAnnouncerManager}, and return a handle. The caller is
|
|
126
|
+
* responsible for hiding the container (e.g. with a visually-hidden wrapper or
|
|
127
|
+
* CSS class); this function only creates the live regions themselves.
|
|
128
|
+
*
|
|
129
|
+
* @param container - The element to append the live regions into.
|
|
130
|
+
* @param options - Region counts and aria-atomic setting. All fields have
|
|
131
|
+
* sensible defaults; pass `{}` for a single polite region.
|
|
132
|
+
*/
|
|
133
|
+
function mountAriaAnnouncer(container, options = {}) {
|
|
134
|
+
const { politeCount = 1, assertiveCount = 0, ariaAtomic = false } = options;
|
|
135
|
+
function createRegion(politeness) {
|
|
136
|
+
const el = document.createElement('div');
|
|
137
|
+
el.setAttribute('aria-live', politeness);
|
|
138
|
+
if (ariaAtomic) {
|
|
139
|
+
el.setAttribute('aria-atomic', 'true');
|
|
140
|
+
}
|
|
141
|
+
container.appendChild(el);
|
|
142
|
+
return el;
|
|
143
|
+
}
|
|
144
|
+
const politeRegions = [];
|
|
145
|
+
for (let i = 0; i < politeCount; i++) {
|
|
146
|
+
politeRegions.push(createRegion('polite'));
|
|
147
|
+
}
|
|
148
|
+
const assertiveRegions = [];
|
|
149
|
+
for (let i = 0; i < assertiveCount; i++) {
|
|
150
|
+
assertiveRegions.push(createRegion('assertive'));
|
|
151
|
+
}
|
|
152
|
+
const manager = new AriaAnnouncerManager();
|
|
153
|
+
manager.connect(politeRegions, assertiveRegions);
|
|
154
|
+
return {
|
|
155
|
+
announce(message, politeness = 'polite') {
|
|
156
|
+
manager.announce(message, politeness);
|
|
157
|
+
},
|
|
158
|
+
disconnect() {
|
|
159
|
+
manager.disconnect();
|
|
160
|
+
[...politeRegions, ...assertiveRegions].forEach((el) => {
|
|
161
|
+
if (el.parentNode) {
|
|
162
|
+
el.parentNode.removeChild(el);
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
}
|
|
123
168
|
|
|
124
|
-
export { AriaAnnouncerManager };
|
|
169
|
+
export { AriaAnnouncerManager, mountAriaAnnouncer };
|
|
125
170
|
//# sourceMappingURL=aria-announcer-manager.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aria-announcer-manager.js","sources":["../../../src/globals/utils/aria-announcer-manager.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2025, 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * Politeness of a live-region announcement.\n *\n * - `polite` — status/content updates the user benefits from but shouldn't have\n * interrupted. The default.\n * - `assertive` — errors that block the user's progress; interrupts whatever the\n * screen reader is currently reading. Use sparingly.\n */\ntype AnnouncerPoliteness = 'polite' | 'assertive';\n\n/**\n * One live-region channel: the regions it rotates through plus the pending-queue\n * and timer state used to coalesce same-tick announcements.\n */\ninterface AnnouncerChannel {\n regions: HTMLDivElement[];\n currentIndex: number;\n pendingAnnouncements: string[];\n announcementTimeoutId: number | null;\n}\n\nfunction createChannel(): AnnouncerChannel {\n return {\n regions: [],\n currentIndex: 0,\n pendingAnnouncements: [],\n announcementTimeoutId: null,\n };\n}\n\n/**\n * Manages ARIA live region announcements for screen readers.\n *\n * Rotates writes across N visually-hidden live regions. Rotation forces\n * assistive tech to re-announce identical messages and lets us clear\n * previous content without racing the announcement.\n *\n * Two independent channels are maintained — `polite` and `assertive` — each with\n * its own regions, rotation, and coalescing queue, so an assertive (blocking)\n * message never coalesces with a polite one. Assertive is opt-in: pass assertive\n * regions to {@link connect} and a politeness to {@link announce}. The politeness\n * of the rendered region (its `aria-live` value) is owned by the consumer's\n * markup; the channel only routes text to the right set of regions.\n *\n * `chat-shell` connects two polite regions; the React announcer in\n * `@carbon/ai-chat` connects three polite regions (the extra region helps NVDA +\n * JAWS reliably pick up back-to-back identical messages) plus assertive regions.\n *\n * Both consumers share this implementation so a fix to the screen-reader\n * workarounds (250 ms NVDA delay, dual-clear pattern) propagates to both.\n */\nexport class AriaAnnouncerManager {\n private polite = createChannel();\n private assertive = createChannel();\n\n /**\n * Initialize the manager with the live-region elements it should rotate\n * through. `politeRegions` must contain at least one element; two or three is\n * typical. `assertiveRegions` is optional — omit it for polite-only consumers.\n */\n connect(\n politeRegions: HTMLDivElement[],\n assertiveRegions: HTMLDivElement[] = []\n ): void {\n this.polite.regions = politeRegions.slice();\n this.polite.currentIndex = 0;\n this.assertive.regions = assertiveRegions.slice();\n this.assertive.currentIndex = 0;\n }\n\n /**\n * Cancel any pending announcements and detach from the regions.\n */\n disconnect(): void {\n this.clearChannel(this.polite);\n this.clearChannel(this.assertive);\n this.polite.regions = [];\n this.assertive.regions = [];\n }\n\n /**\n * Queue a message to be announced on the next tick. Multiple calls in the\n * same tick (and politeness) are coalesced into a single announcement.\n * Defaults to polite; falls back to polite if assertive is requested but no\n * assertive regions are connected.\n */\n announce(message: string, politeness: AnnouncerPoliteness = 'polite'): void {\n if (!message || typeof window === 'undefined') {\n return;\n }\n\n const channel =\n politeness === 'assertive' && this.assertive.regions.length > 0\n ? this.assertive\n : this.polite;\n\n channel.pendingAnnouncements.push(message);\n\n if (channel.announcementTimeoutId === null) {\n // 250 ms delay works around an NVDA bug: a focus change at the same\n // time as a live-region update can drop the announcement entirely.\n // Smaller numbers were less reliable in testing.\n channel.announcementTimeoutId = window.setTimeout(() => {\n this.doAnnouncements(channel);\n }, 250);\n }\n }\n\n private clearChannel(channel: AnnouncerChannel): void {\n if (\n channel.announcementTimeoutId !== null &&\n typeof window !== 'undefined'\n ) {\n window.clearTimeout(channel.announcementTimeoutId);\n channel.announcementTimeoutId = null;\n }\n channel.pendingAnnouncements = [];\n }\n\n private doAnnouncements(channel: AnnouncerChannel): void {\n channel.announcementTimeoutId = null;\n\n if (\n channel.pendingAnnouncements.length === 0 ||\n channel.regions.length === 0\n ) {\n channel.pendingAnnouncements = [];\n return;\n }\n\n const message = channel.pendingAnnouncements.join(' ');\n channel.pendingAnnouncements = [];\n\n const writeRegion = channel.regions[channel.currentIndex];\n if (writeRegion) {\n writeRegion.textContent = message;\n }\n\n // Clear every other region so the active one stands out as the change.\n channel.regions.forEach((region, index) => {\n if (index !== channel.currentIndex && region) {\n region.textContent = '';\n }\n });\n\n channel.currentIndex = (channel.currentIndex + 1) % channel.regions.length;\n }\n}\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AAuBH,SAAS,aAAa,GAAA;IACpB,OAAO;AACL,QAAA,OAAO,EAAE,EAAE;AACX,QAAA,YAAY,EAAE,CAAC;AACf,QAAA,oBAAoB,EAAE,EAAE;AACxB,QAAA,qBAAqB,EAAE,IAAI;KAC5B;AACH;AAEA;;;;;;;;;;;;;;;;;;;;AAoBG;MACU,oBAAoB,CAAA;AAAjC,IAAA,WAAA,GAA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":["../../../src/globals/utils/aria-announcer-manager.ts"],"sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2025, 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/**\n * Politeness of a live-region announcement.\n *\n * - `polite` — status/content updates the user benefits from but shouldn't have\n * interrupted. The default.\n * - `assertive` — errors that block the user's progress; interrupts whatever the\n * screen reader is currently reading. Use sparingly.\n */\ntype AnnouncerPoliteness = 'polite' | 'assertive';\n\n/**\n * Options for {@link mountAriaAnnouncer}.\n */\nexport interface AriaAnnouncerOptions {\n /**\n * Number of polite `aria-live=\"polite\"` regions to create and rotate through.\n * Default `1`. The React `AriaAnnouncerProvider` passes `3` explicitly: in\n * earlier testing FF + JAWS occasionally re-read entire region contents on\n * append; a third region ensures there is always a fresh region for the next\n * announcement.\n */\n politeCount?: number;\n /**\n * Number of `aria-live=\"assertive\"` regions to create.\n * Default 0 (polite-only).\n */\n assertiveCount?: number;\n /**\n * Sets `aria-atomic` on every created region. Default `false`.\n *\n * Note: `aria-atomic` is intentionally left off by default. With it, FF +\n * JAWS read some messages cleanly but Chrome stops announcing buttons inside\n * the region. Without it, FF + JAWS sometimes double-read parts but Chrome\n * handles buttons. The default (off) is the lesser evil.\n */\n ariaAtomic?: boolean;\n}\n\n/**\n * Handle returned by {@link mountAriaAnnouncer}. Call `disconnect` when the\n * host element is removed from the DOM to cancel pending timers and clean up\n * the created regions.\n */\nexport interface AriaAnnouncerHandle {\n /**\n * Queue a message for announcement on the next tick. Multiple same-tick calls\n * for the same politeness are coalesced into a single write. Defaults to\n * `\"polite\"`; falls back to polite if assertive regions were not created.\n */\n announce(message: string, politeness?: AnnouncerPoliteness): void;\n /**\n * Cancel pending announcements, disconnect the manager, and remove the\n * created live regions from `container`.\n */\n disconnect(): void;\n}\n\n/**\n * One live-region channel: the regions it rotates through plus the pending-queue\n * and timer state used to coalesce same-tick announcements.\n */\ninterface AnnouncerChannel {\n regions: HTMLDivElement[];\n currentIndex: number;\n pendingAnnouncements: string[];\n announcementTimeoutId: number | null;\n}\n\nfunction createChannel(): AnnouncerChannel {\n return {\n regions: [],\n currentIndex: 0,\n pendingAnnouncements: [],\n announcementTimeoutId: null,\n };\n}\n\n/**\n * Manages ARIA live region announcements for screen readers.\n *\n * Rotates writes across N visually-hidden live regions. Rotation forces\n * assistive tech to re-announce identical messages and lets us clear\n * previous content without racing the announcement.\n *\n * Two independent channels are maintained — `polite` and `assertive` — each with\n * its own regions, rotation, and coalescing queue, so an assertive (blocking)\n * message never coalesces with a polite one. Assertive is opt-in: pass assertive\n * regions to {@link connect} and a politeness to {@link announce}. The politeness\n * of the rendered region (its `aria-live` value) is owned by the consumer's\n * markup; the channel only routes text to the right set of regions.\n *\n * `chat-shell` connects two polite regions; the React announcer in\n * `@carbon/ai-chat` connects three polite regions (the extra region helps NVDA +\n * JAWS reliably pick up back-to-back identical messages) plus assertive regions.\n *\n * Both consumers share this implementation so a fix to the screen-reader\n * workarounds (250 ms NVDA delay, dual-clear pattern) propagates to both.\n */\nexport class AriaAnnouncerManager {\n private polite = createChannel();\n private assertive = createChannel();\n\n /**\n * Initialize the manager with the live-region elements it should rotate\n * through. `politeRegions` must contain at least one element; two or three is\n * typical. `assertiveRegions` is optional — omit it for polite-only consumers.\n */\n connect(\n politeRegions: HTMLDivElement[],\n assertiveRegions: HTMLDivElement[] = []\n ): void {\n this.polite.regions = politeRegions.slice();\n this.polite.currentIndex = 0;\n this.assertive.regions = assertiveRegions.slice();\n this.assertive.currentIndex = 0;\n }\n\n /**\n * Cancel any pending announcements and detach from the regions.\n */\n disconnect(): void {\n this.clearChannel(this.polite);\n this.clearChannel(this.assertive);\n this.polite.regions = [];\n this.assertive.regions = [];\n }\n\n /**\n * Queue a message to be announced on the next tick. Multiple calls in the\n * same tick (and politeness) are coalesced into a single announcement.\n * Defaults to polite; falls back to polite if assertive is requested but no\n * assertive regions are connected.\n */\n announce(message: string, politeness: AnnouncerPoliteness = 'polite'): void {\n if (!message || typeof window === 'undefined') {\n return;\n }\n\n const channel =\n politeness === 'assertive' && this.assertive.regions.length > 0\n ? this.assertive\n : this.polite;\n\n channel.pendingAnnouncements.push(message);\n\n if (channel.announcementTimeoutId === null) {\n // 250 ms delay works around an NVDA bug: a focus change at the same\n // time as a live-region update can drop the announcement entirely.\n // Smaller numbers were less reliable in testing.\n channel.announcementTimeoutId = window.setTimeout(() => {\n this.doAnnouncements(channel);\n }, 250);\n }\n }\n\n private clearChannel(channel: AnnouncerChannel): void {\n if (\n channel.announcementTimeoutId !== null &&\n typeof window !== 'undefined'\n ) {\n window.clearTimeout(channel.announcementTimeoutId);\n channel.announcementTimeoutId = null;\n }\n channel.pendingAnnouncements = [];\n }\n\n private doAnnouncements(channel: AnnouncerChannel): void {\n channel.announcementTimeoutId = null;\n\n if (\n channel.pendingAnnouncements.length === 0 ||\n channel.regions.length === 0\n ) {\n channel.pendingAnnouncements = [];\n return;\n }\n\n const message = channel.pendingAnnouncements.join(' ');\n channel.pendingAnnouncements = [];\n\n const writeRegion = channel.regions[channel.currentIndex];\n if (writeRegion) {\n writeRegion.textContent = message;\n }\n\n // Clear every other region so the active one stands out as the change.\n channel.regions.forEach((region, index) => {\n if (index !== channel.currentIndex && region) {\n region.textContent = '';\n }\n });\n\n channel.currentIndex = (channel.currentIndex + 1) % channel.regions.length;\n }\n}\n\n/**\n * Create visually-hidden `aria-live` regions inside `container`, wire them to\n * a new {@link AriaAnnouncerManager}, and return a handle. The caller is\n * responsible for hiding the container (e.g. with a visually-hidden wrapper or\n * CSS class); this function only creates the live regions themselves.\n *\n * @param container - The element to append the live regions into.\n * @param options - Region counts and aria-atomic setting. All fields have\n * sensible defaults; pass `{}` for a single polite region.\n */\nexport function mountAriaAnnouncer(\n container: HTMLElement,\n options: AriaAnnouncerOptions = {}\n): AriaAnnouncerHandle {\n const { politeCount = 1, assertiveCount = 0, ariaAtomic = false } = options;\n\n function createRegion(politeness: AnnouncerPoliteness): HTMLDivElement {\n const el = document.createElement('div');\n el.setAttribute('aria-live', politeness);\n if (ariaAtomic) {\n el.setAttribute('aria-atomic', 'true');\n }\n container.appendChild(el);\n return el;\n }\n\n const politeRegions: HTMLDivElement[] = [];\n for (let i = 0; i < politeCount; i++) {\n politeRegions.push(createRegion('polite'));\n }\n\n const assertiveRegions: HTMLDivElement[] = [];\n for (let i = 0; i < assertiveCount; i++) {\n assertiveRegions.push(createRegion('assertive'));\n }\n\n const manager = new AriaAnnouncerManager();\n manager.connect(politeRegions, assertiveRegions);\n\n return {\n announce(message: string, politeness: AnnouncerPoliteness = 'polite') {\n manager.announce(message, politeness);\n },\n disconnect() {\n manager.disconnect();\n [...politeRegions, ...assertiveRegions].forEach((el) => {\n if (el.parentNode) {\n el.parentNode.removeChild(el);\n }\n });\n },\n };\n}\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AAsEH,SAAS,aAAa,GAAA;IACpB,OAAO;AACL,QAAA,OAAO,EAAE,EAAE;AACX,QAAA,YAAY,EAAE,CAAC;AACf,QAAA,oBAAoB,EAAE,EAAE;AACxB,QAAA,qBAAqB,EAAE,IAAI;KAC5B;AACH;AAEA;;;;;;;;;;;;;;;;;;;;AAoBG;MACU,oBAAoB,CAAA;AAAjC,IAAA,WAAA,GAAA;QACU,IAAA,CAAA,MAAM,GAAG,aAAa,EAAE;QACxB,IAAA,CAAA,SAAS,GAAG,aAAa,EAAE;IA8FrC;AA5FE;;;;AAIG;AACH,IAAA,OAAO,CACL,aAA+B,EAC/B,gBAAA,GAAqC,EAAE,EAAA;QAEvC,IAAI,CAAC,MAAM,CAAC,OAAO,GAAG,aAAa,CAAC,KAAK,EAAE;AAC3C,QAAA,IAAI,CAAC,MAAM,CAAC,YAAY,GAAG,CAAC;QAC5B,IAAI,CAAC,SAAS,CAAC,OAAO,GAAG,gBAAgB,CAAC,KAAK,EAAE;AACjD,QAAA,IAAI,CAAC,SAAS,CAAC,YAAY,GAAG,CAAC;IACjC;AAEA;;AAEG;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A,OAAO,EAAE;IACX;IAEA,MAAM,aAAa,GAAqB,EAAE;AAC1C,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,EAAE,CAAC,EAAE,EAAE;QACpC,aAAa,CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;IAC5C;IAEA,MAAM,gBAAgB,GAAqB,EAAE;AAC7C,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,EAAE,EAAE;QACvC,gBAAgB,CAAC,IAAI,CAAC,YAAY,CAAC,WAAW,CAAC,CAAC;IAClD;AAEA,IAAA,MAAM,OAAO,GAAG,IAAI,oBAAoB,EAAE;AAC1C,IAAA,OAAO,CAAC,OAAO,CAAC,aAAa,EAAE,gBAAgB,CAAC;IAEhD,OAAO;AACL,QAAA,QAAQ,CAAC,OAAe,EAAE,UAAA,GAAkC,QAAQ,EAAA;AAClE,YAAA,OAAO,CAAC,QAAQ,CAAC,OAAO,EAAE,UAAU,CAAC;QACvC,CAAC;QACD,UAAU,GAAA;YACR,OAAO,CAAC,UAAU,EAAE;AACpB,YAAA,CAAC,GAAG,aAAa,EAAE,GAAG,gBAAgB,CAAC,CAAC,OAAO,CAAC,CAAC,EAAE,KAAI;AACrD,gBAAA,IAAI,EAAE,CAAC,UAAU,EAAE;AACjB,oBAAA,EAAE,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;gBAC/B;AACF,YAAA,CAAC,CAAC;QACJ,CAAC;KACF;AACH;;"}
|
|
@@ -147,9 +147,7 @@ function* walkComposedTree(node, whatToShow = 0, filter = () => true, skipNode =
|
|
|
147
147
|
if (filter(node)) {
|
|
148
148
|
yield node;
|
|
149
149
|
}
|
|
150
|
-
const children =
|
|
151
|
-
// eslint-disable-next-line no-nested-ternary
|
|
152
|
-
node instanceof HTMLElement && node.shadowRoot
|
|
150
|
+
const children = node instanceof HTMLElement && node.shadowRoot
|
|
153
151
|
? node.shadowRoot.children
|
|
154
152
|
: node instanceof HTMLSlotElement
|
|
155
153
|
? node.assignedNodes({ flatten: true })
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"focus-utils.js","sources":["../../../src/globals/utils/focus-utils.ts"],"sourcesContent":["/*\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\n/**\n * Gets the deepest active element, traversing through all shadow DOM boundaries.\n * This handles nested shadow roots, slotted elements, and will return the actual\n * focused element regardless of how many shadow DOM levels exist.\n *\n * @returns The deepest active element, or null if no element has focus\n */\nfunction getDeepActiveElement(): Element | null {\n let activeElement = document.activeElement;\n\n // Traverse through all shadow DOM levels and handle slotted elements\n while (activeElement) {\n // If the active element is a slot, get the actual assigned element that has focus\n if (activeElement instanceof HTMLSlotElement) {\n const assignedElements = activeElement.assignedElements({\n flatten: true,\n });\n // Find which assigned element actually has focus\n const focusedAssigned = assignedElements.find((el) => {\n if ((el as any).shadowRoot?.activeElement) {\n return true;\n }\n return (\n el === document.activeElement || el.contains(document.activeElement)\n );\n });\n if (focusedAssigned) {\n activeElement = focusedAssigned;\n continue;\n }\n }\n\n // Check if there's a shadow root with an active element\n const shadowRoot = (activeElement as any).shadowRoot;\n if (shadowRoot?.activeElement) {\n activeElement = shadowRoot.activeElement;\n continue;\n }\n\n // No deeper level found\n break;\n }\n\n return activeElement;\n}\n\n/**\n * Checks if an element should be ignored due to visibility or accessibility attributes.\n *\n * @param element - The DOM element to check\n * @param exceptions - Array of selectors to ignore when checking the element (e.g., 'dialog', '[popover]')\n * @returns True if the element should be ignored by focus management, false otherwise\n */\nfunction isElementInvisible(\n element: Element,\n exceptions: string[] = ['dialog', '[popover]']\n): boolean {\n if (!element || !(element instanceof HTMLElement)) {\n return false;\n }\n\n if (exceptions.length > 0 && element.matches(exceptions.join(','))) {\n return false;\n }\n\n const computedStyle = window.getComputedStyle(element);\n const isStyleHidden =\n computedStyle.display === 'none' || computedStyle.visibility === 'hidden';\n const isAttributeHidden = element.matches(\n '[disabled], [hidden], [inert], [aria-hidden=\"true\"]'\n );\n\n return isStyleHidden || isAttributeHidden;\n}\n\n/**\n * Checks if an element is focusable. An element is considered focusable if it matches\n * standard focusable elements criteria (such as buttons, inputs, etc., that are not disabled\n * and do not have a negative tabindex) or is a custom element with a shadow root that delegates focus.\n * Based on https://gist.github.com/oscarmarina/9ce95f491a4c53ed01d989de4a87c0c9\n *\n * @param element - The DOM element to check for focusability\n * @returns True if the element is focusable, false otherwise\n */\nfunction isFocusable(element: Element): boolean {\n if (!(element instanceof HTMLElement)) {\n return false;\n }\n\n // https://stackoverflow.com/a/30753870/76472\n const knownFocusableElements =\n 'a[href],area[href],button:not([disabled]),details,iframe,object,input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[contentEditable=\"true\"],[tabindex]:not([tabindex^=\"-\"])';\n\n if (element.matches(knownFocusableElements)) {\n return true;\n }\n\n const isDisabledCustomElement =\n element.localName.includes('-') &&\n element.matches('[disabled], [aria-disabled=\"true\"]');\n\n if (isDisabledCustomElement) {\n return false;\n }\n\n return element.shadowRoot?.delegatesFocus ?? false;\n}\n\n/**\n * Attempts to focus an element if it's focusable, visible, and not disabled.\n * This is an enhanced version that checks visibility, accessibility attributes,\n * and proper focusability before attempting to set focus. It is shadow DOM aware\n * and handles slotted elements correctly.\n *\n * @param element - The element to attempt to focus\n * @param exceptions - Array of selectors to ignore when checking visibility (e.g., 'dialog', '[popover]')\n * @returns True if focus was successfully set, false otherwise\n */\nfunction tryFocus(\n element: Element | null | undefined,\n exceptions?: string[]\n): boolean {\n if (!element || !(element instanceof HTMLElement)) {\n return false;\n }\n\n // Check if element is invisible or should be ignored\n if (isElementInvisible(element, exceptions)) {\n return false;\n }\n\n // Check if element is focusable\n if (!isFocusable(element)) {\n return false;\n }\n\n // Get the current deep active element (shadow DOM aware)\n const previousActiveElement = getDeepActiveElement();\n\n // Only call focus if the element doesn't already have focus\n if (previousActiveElement !== element) {\n element.focus();\n }\n\n // Verify focus was actually set by checking the deep active element\n // This works across shadow DOM boundaries, with slotted elements, and delegatesFocus configurations\n const currentActiveElement = getDeepActiveElement();\n return (\n currentActiveElement === element || element.contains(currentActiveElement)\n );\n}\n\n/**\n * Traverse the composed tree from the root, selecting elements that meet the provided filter criteria.\n * This function properly handles Shadow DOM boundaries.\n * Based on https://github.com/JanMiksovsky/elix/blob/main/src/core/dom.js#L320\n *\n * @param node - The root node for traversal\n * @param whatToShow - NodeFilter code for node types to include (use 0 to retrieve all nodes)\n * @param filter - Filters nodes. Child nodes are considered even if parent does not satisfy the filter\n * @param skipNode - Determines whether to skip a node and its children\n * @returns An iterator yielding nodes meeting the filter criteria\n */\nfunction* walkComposedTree(\n node: Node,\n whatToShow = 0,\n filter: (node: Node) => boolean = () => true,\n skipNode: (node: Node) => boolean = () => false\n): IterableIterator<Node> {\n if ((whatToShow && node.nodeType !== whatToShow) || skipNode(node)) {\n return;\n }\n\n if (filter(node)) {\n yield node;\n }\n\n const children =\n // eslint-disable-next-line no-nested-ternary\n node instanceof HTMLElement && node.shadowRoot\n ? node.shadowRoot.children\n : node instanceof HTMLSlotElement\n ? node.assignedNodes({ flatten: true })\n : node.childNodes;\n\n for (const child of children) {\n yield* walkComposedTree(child, whatToShow, filter, skipNode);\n }\n}\n\n/**\n * Retrieves the first and last focusable children of a node using a TreeWalker.\n *\n * @param walker - The TreeWalker object used to traverse the node's children\n * @returns A tuple containing the first and last focusable children. If no focusable children are found, `null` is returned for both\n */\nfunction getFirstAndLastFocusableChildren(\n walker: IterableIterator<HTMLElement>\n): [first: HTMLElement | null, last: HTMLElement | null] {\n let firstFocusableChild: HTMLElement | null = null;\n let lastFocusableChild: HTMLElement | null = null;\n\n for (const currentNode of walker) {\n if (!firstFocusableChild) {\n firstFocusableChild = currentNode;\n }\n lastFocusableChild = currentNode;\n }\n\n return [firstFocusableChild, lastFocusableChild];\n}\n\n/**\n * Finds a descendant of `searchRoot` via `selector` and focuses it after the next\n * two animation frames. Use when DOM updates (Lit, React, reorder) replace or move\n * nodes so the previous focused element is detached (e.g. list pin/unpin).\n *\n * Tries {@link tryFocus} first for visibility/focusability checks; if that does\n * not take focus (e.g. some custom element hosts), falls back to {@link HTMLElement.focus}.\n *\n * @param searchRoot - Root to query (`Element`, `ShadowRoot`, `Document`, or `DocumentFragment`, e.g. Lit `renderRoot`)\n * @param selector - CSS selector that resolves to the node to focus.\n */\nfunction focusElementAfterRepaint(\n searchRoot: Document | Element | ShadowRoot | DocumentFragment,\n selector: string\n): void {\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n const el = searchRoot.querySelector(selector);\n if (!(el instanceof HTMLElement)) {\n return;\n }\n if (!tryFocus(el)) {\n el.focus();\n }\n });\n });\n}\n\nexport {\n getDeepActiveElement,\n isElementInvisible,\n isFocusable,\n tryFocus,\n walkComposedTree,\n getFirstAndLastFocusableChildren,\n focusElementAfterRepaint,\n};\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;AAMG;AACH,SAAS,oBAAoB,GAAA;AAC3B,IAAA,IAAI,aAAa,GAAG,QAAQ,CAAC,aAAa;;IAG1C,OAAO,aAAa,EAAE;;AAEpB,QAAA,IAAI,aAAa,YAAY,eAAe,EAAE;AAC5C,YAAA,MAAM,gBAAgB,GAAG,aAAa,CAAC,gBAAgB,CAAC;AACtD,gBAAA,OAAO,EAAE,IAAI;AACd,aAAA,CAAC;;YAEF,MAAM,eAAe,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC,EAAE,KAAI;AACnD,gBAAA,IAAK,EAAU,CAAC,UAAU,EAAE,aAAa,EAAE;AACzC,oBAAA,OAAO,IAAI;gBACb;AACA,gBAAA,QACE,EAAE,KAAK,QAAQ,CAAC,aAAa,IAAI,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,aAAa,CAAC;AAExE,YAAA,CAAC,CAAC;YACF,IAAI,eAAe,EAAE;gB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CAAC,EAAE,OAAO,EAAE,IAAI,EAAE;AACtC,cAAE,IAAI,CAAC,UAAU;AAEvB,IAAA,KAAK,MAAM,KAAK,IAAI,QAAQ,EAAE;AAC5B,QAAA,OAAO,gBAAgB,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC;IAC9D;AACF;AAEA;;;;;AAKG;AACH,SAAS,gCAAgC,CACvC,MAAqC,EAAA;IAErC,IAAI,mBAAmB,GAAuB,IAAI;IAClD,IAAI,kBAAkB,GAAuB,IAAI;AAEjD,IAAA,KAAK,MAAM,WAAW,IAAI,MAAM,EAAE;QAChC,IAAI,CAAC,mBAAmB,EAAE;YACxB,mBAAmB,GAAG,WAAW;QACnC;QACA,kBAAkB,GAAG,WAAW;IAClC;AAEA,IAAA,OAAO,CAAC,mBAAmB,EAAE,kBAAkB,CAAC;AAClD;AAEA;;;;;;;;;;AAUG;AACH,SAAS,wBAAwB,CAC/B,UAA8D,EAC9D,QAAgB,EAAA;IAEhB,qBAAqB,CAAC,MAAK;QACzB,qBAAqB,CAAC,MAAK;YACzB,MAAM,EAAE,GAAG,UAAU,CAAC,aAAa,CAAC,QAAQ,CAAC;AAC7C,YAAA,IAAI,EAAE,EAAE,YAAY,WAAW,CAAC,EAAE;gBAChC;YACF;AACA,YAAA,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE;gBACjB,EAAE,CAAC,KAAK,EAAE;YACZ;AACF,QAAA,CAAC,CAAC;AACJ,IAAA,CAAC,CAAC;AACJ;;"}
|
|
1
|
+
{"version":3,"file":"focus-utils.js","sources":["../../../src/globals/utils/focus-utils.ts"],"sourcesContent":["/*\n * Copyright IBM Corp. 2026\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @license\n */\n\n/**\n * Gets the deepest active element, traversing through all shadow DOM boundaries.\n * This handles nested shadow roots, slotted elements, and will return the actual\n * focused element regardless of how many shadow DOM levels exist.\n *\n * @returns The deepest active element, or null if no element has focus\n */\nfunction getDeepActiveElement(): Element | null {\n let activeElement = document.activeElement;\n\n // Traverse through all shadow DOM levels and handle slotted elements\n while (activeElement) {\n // If the active element is a slot, get the actual assigned element that has focus\n if (activeElement instanceof HTMLSlotElement) {\n const assignedElements = activeElement.assignedElements({\n flatten: true,\n });\n // Find which assigned element actually has focus\n const focusedAssigned = assignedElements.find((el) => {\n if ((el as any).shadowRoot?.activeElement) {\n return true;\n }\n return (\n el === document.activeElement || el.contains(document.activeElement)\n );\n });\n if (focusedAssigned) {\n activeElement = focusedAssigned;\n continue;\n }\n }\n\n // Check if there's a shadow root with an active element\n const shadowRoot = (activeElement as any).shadowRoot;\n if (shadowRoot?.activeElement) {\n activeElement = shadowRoot.activeElement;\n continue;\n }\n\n // No deeper level found\n break;\n }\n\n return activeElement;\n}\n\n/**\n * Checks if an element should be ignored due to visibility or accessibility attributes.\n *\n * @param element - The DOM element to check\n * @param exceptions - Array of selectors to ignore when checking the element (e.g., 'dialog', '[popover]')\n * @returns True if the element should be ignored by focus management, false otherwise\n */\nfunction isElementInvisible(\n element: Element,\n exceptions: string[] = ['dialog', '[popover]']\n): boolean {\n if (!element || !(element instanceof HTMLElement)) {\n return false;\n }\n\n if (exceptions.length > 0 && element.matches(exceptions.join(','))) {\n return false;\n }\n\n const computedStyle = window.getComputedStyle(element);\n const isStyleHidden =\n computedStyle.display === 'none' || computedStyle.visibility === 'hidden';\n const isAttributeHidden = element.matches(\n '[disabled], [hidden], [inert], [aria-hidden=\"true\"]'\n );\n\n return isStyleHidden || isAttributeHidden;\n}\n\n/**\n * Checks if an element is focusable. An element is considered focusable if it matches\n * standard focusable elements criteria (such as buttons, inputs, etc., that are not disabled\n * and do not have a negative tabindex) or is a custom element with a shadow root that delegates focus.\n * Based on https://gist.github.com/oscarmarina/9ce95f491a4c53ed01d989de4a87c0c9\n *\n * @param element - The DOM element to check for focusability\n * @returns True if the element is focusable, false otherwise\n */\nfunction isFocusable(element: Element): boolean {\n if (!(element instanceof HTMLElement)) {\n return false;\n }\n\n // https://stackoverflow.com/a/30753870/76472\n const knownFocusableElements =\n 'a[href],area[href],button:not([disabled]),details,iframe,object,input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[contentEditable=\"true\"],[tabindex]:not([tabindex^=\"-\"])';\n\n if (element.matches(knownFocusableElements)) {\n return true;\n }\n\n const isDisabledCustomElement =\n element.localName.includes('-') &&\n element.matches('[disabled], [aria-disabled=\"true\"]');\n\n if (isDisabledCustomElement) {\n return false;\n }\n\n return element.shadowRoot?.delegatesFocus ?? false;\n}\n\n/**\n * Attempts to focus an element if it's focusable, visible, and not disabled.\n * This is an enhanced version that checks visibility, accessibility attributes,\n * and proper focusability before attempting to set focus. It is shadow DOM aware\n * and handles slotted elements correctly.\n *\n * @param element - The element to attempt to focus\n * @param exceptions - Array of selectors to ignore when checking visibility (e.g., 'dialog', '[popover]')\n * @returns True if focus was successfully set, false otherwise\n */\nfunction tryFocus(\n element: Element | null | undefined,\n exceptions?: string[]\n): boolean {\n if (!element || !(element instanceof HTMLElement)) {\n return false;\n }\n\n // Check if element is invisible or should be ignored\n if (isElementInvisible(element, exceptions)) {\n return false;\n }\n\n // Check if element is focusable\n if (!isFocusable(element)) {\n return false;\n }\n\n // Get the current deep active element (shadow DOM aware)\n const previousActiveElement = getDeepActiveElement();\n\n // Only call focus if the element doesn't already have focus\n if (previousActiveElement !== element) {\n element.focus();\n }\n\n // Verify focus was actually set by checking the deep active element\n // This works across shadow DOM boundaries, with slotted elements, and delegatesFocus configurations\n const currentActiveElement = getDeepActiveElement();\n return (\n currentActiveElement === element || element.contains(currentActiveElement)\n );\n}\n\n/**\n * Traverse the composed tree from the root, selecting elements that meet the provided filter criteria.\n * This function properly handles Shadow DOM boundaries.\n * Based on https://github.com/JanMiksovsky/elix/blob/main/src/core/dom.js#L320\n *\n * @param node - The root node for traversal\n * @param whatToShow - NodeFilter code for node types to include (use 0 to retrieve all nodes)\n * @param filter - Filters nodes. Child nodes are considered even if parent does not satisfy the filter\n * @param skipNode - Determines whether to skip a node and its children\n * @returns An iterator yielding nodes meeting the filter criteria\n */\nfunction* walkComposedTree(\n node: Node,\n whatToShow = 0,\n filter: (node: Node) => boolean = () => true,\n skipNode: (node: Node) => boolean = () => false\n): IterableIterator<Node> {\n if ((whatToShow && node.nodeType !== whatToShow) || skipNode(node)) {\n return;\n }\n\n if (filter(node)) {\n yield node;\n }\n\n const children =\n node instanceof HTMLElement && node.shadowRoot\n ? node.shadowRoot.children\n : node instanceof HTMLSlotElement\n ? node.assignedNodes({ flatten: true })\n : node.childNodes;\n\n for (const child of children) {\n yield* walkComposedTree(child, whatToShow, filter, skipNode);\n }\n}\n\n/**\n * Retrieves the first and last focusable children of a node using a TreeWalker.\n *\n * @param walker - The TreeWalker object used to traverse the node's children\n * @returns A tuple containing the first and last focusable children. If no focusable children are found, `null` is returned for both\n */\nfunction getFirstAndLastFocusableChildren(\n walker: IterableIterator<HTMLElement>\n): [first: HTMLElement | null, last: HTMLElement | null] {\n let firstFocusableChild: HTMLElement | null = null;\n let lastFocusableChild: HTMLElement | null = null;\n\n for (const currentNode of walker) {\n if (!firstFocusableChild) {\n firstFocusableChild = currentNode;\n }\n lastFocusableChild = currentNode;\n }\n\n return [firstFocusableChild, lastFocusableChild];\n}\n\n/**\n * Finds a descendant of `searchRoot` via `selector` and focuses it after the next\n * two animation frames. Use when DOM updates (Lit, React, reorder) replace or move\n * nodes so the previous focused element is detached (e.g. list pin/unpin).\n *\n * Tries {@link tryFocus} first for visibility/focusability checks; if that does\n * not take focus (e.g. some custom element hosts), falls back to {@link HTMLElement.focus}.\n *\n * @param searchRoot - Root to query (`Element`, `ShadowRoot`, `Document`, or `DocumentFragment`, e.g. Lit `renderRoot`)\n * @param selector - CSS selector that resolves to the node to focus.\n */\nfunction focusElementAfterRepaint(\n searchRoot: Document | Element | ShadowRoot | DocumentFragment,\n selector: string\n): void {\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n const el = searchRoot.querySelector(selector);\n if (!(el instanceof HTMLElement)) {\n return;\n }\n if (!tryFocus(el)) {\n el.focus();\n }\n });\n });\n}\n\nexport {\n getDeepActiveElement,\n isElementInvisible,\n isFocusable,\n tryFocus,\n walkComposedTree,\n getFirstAndLastFocusableChildren,\n focusElementAfterRepaint,\n};\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;AAOG;AAEH;;;;;;AAMG;AACH,SAAS,oBAAoB,GAAA;AAC3B,IAAA,IAAI,aAAa,GAAG,QAAQ,CAAC,aAAa;;IAG1C,OAAO,aAAa,EAAE;;AAEpB,QAAA,IAAI,aAAa,YAAY,eAAe,EAAE;AAC5C,YAAA,MAAM,gBAAgB,GAAG,aAAa,CAAC,gBAAgB,CAAC;AACtD,gBAAA,OAAO,EAAE,IAAI;AACd,aAAA,CAAC;;YAEF,MAAM,eAAe,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC,EAAE,KAAI;AACnD,gBAAA,IAAK,EAAU,CAAC,UAAU,EAAE,aAAa,EAAE;AACzC,oBAAA,OAAO,IAAI;gBACb;AACA,gBAAA,QACE,EAAE,KAAK,QAAQ,CAAC,aAAa,IAAI,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,aAAa,CAAC;AAExE,YAAA,CAAC,CAAC;YACF,IAAI,eAAe,EAAE;gBACnB,aAAa,GAAG,eAAe;gBAC/B;YACF;QACF;;AAGA,QAAA,MAAM,UAAU,GAAI,aAAqB,CAAC,UAAU;AACpD,QAAA,IAAI,UAAU,EAAE,aAAa,EAAE;AAC7B,YAAA,aAAa,GAAG,UAAU,CAAC,aAAa;YACxC;QACF;;QAGA;IACF;AAEA,IAAA,OAAO,aAAa;AACtB;AAEA;;;;;;AAMG;AACH,SAAS,kBAAkB,CACzB,OAAgB,EAChB,aAAuB,CAAC,QAAQ,EAAE,WAAW,CAAC,EAAA;IAE9C,IAAI,CAAC,OAAO,IAAI,EAAE,OAAO,YAAY,WAAW,CAAC,EAAE;AACjD,QAAA,OAA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