@aceshooting/lyra-ui 28.0.0 → 28.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/dist/components/agent-tools/commit-card/commit-card.class.d.ts +2 -2
  3. package/dist/components/agent-tools/commit-card/commit-card.class.js +7 -8
  4. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  5. package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +1 -1
  6. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +4 -4
  7. package/dist/components/charts/chart/box-plot.class.d.ts +5 -3
  8. package/dist/components/charts/chart/box-plot.class.js +18 -17
  9. package/dist/components/charts/chart/chart.class.d.ts +6 -4
  10. package/dist/components/charts/chart/chart.class.js +19 -18
  11. package/dist/components/charts/chart/lite-chart.class.d.ts +1 -1
  12. package/dist/components/charts/chart/lite-chart.class.js +8 -8
  13. package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
  14. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  15. package/dist/components/data/data-grid/data-grid-processing.js +1 -1
  16. package/dist/components/data/gauge/gauge.class.js +1 -1
  17. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -1
  18. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +2 -2
  19. package/dist/components/data/heatmap/heatmap-label-cache.js +1 -0
  20. package/dist/components/data/heatmap/heatmap.class.d.ts +3 -2
  21. package/dist/components/data/heatmap/heatmap.class.js +2 -2
  22. package/dist/components/data/heatmap/heatmap.styles.js +1 -1
  23. package/dist/components/data/stat/stat.class.d.ts +11 -9
  24. package/dist/components/data/stat/stat.class.js +4 -2
  25. package/dist/components/data/tree/tree.class.js +1 -1
  26. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  27. package/dist/components/forms/color-picker/color-picker.class.js +3 -3
  28. package/dist/components/forms/combobox/combobox.class.d.ts +2 -4
  29. package/dist/components/forms/combobox/combobox.class.js +1 -1
  30. package/dist/components/forms/emoji-picker/emoji-picker.class.js +5 -5
  31. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  32. package/dist/components/forms/select/select.class.js +4 -3
  33. package/dist/components/forms/toggle-group/toggle-group.class.js +1 -1
  34. package/dist/components/layout/command-palette/command-palette.styles.js +1 -1
  35. package/dist/components/layout/filter-bar/filter-bar.class.js +3 -3
  36. package/dist/components/layout/menu/menu.class.js +1 -1
  37. package/dist/components/layout/menubar/menubar.class.js +1 -1
  38. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.d.ts +1 -1
  39. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
  40. package/dist/components/layout/page/page.class.js +1 -1
  41. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  42. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +1 -1
  43. package/dist/components/media/file-input/file-input.class.js +1 -1
  44. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  45. package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.d.ts +1 -1
  46. package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +2 -2
  47. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  48. package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
  49. package/dist/components/retrieval/graph/graph-canvas.js +1 -1
  50. package/dist/components/retrieval/graph-legend/graph-legend.class.js +2 -2
  51. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
  52. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
  53. package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +1 -1
  54. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +4 -4
  55. package/dist/components/retrieval/source-picker/source-picker.class.d.ts +1 -1
  56. package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
  57. package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
  58. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
  59. package/dist/framework-types.d.ts +1 -1
  60. package/dist/internal/default-strings/charts.generated.js +1 -1
  61. package/dist/internal/localization-types.d.ts +1 -1
  62. package/dist/internal/localization.js +1 -1
  63. package/dist/internal/native-modal-carrier.js +2 -2
  64. package/dist/internal/nonmodal-overlay-manager.js +1 -1
  65. package/dist/internal/open-overlay-ancestors.js +1 -0
  66. package/dist/internal/open-overlay-raise.styles.js +1 -1
  67. package/dist/internal/overlay-manager.d.ts +2 -0
  68. package/dist/internal/overlay-manager.js +1 -1
  69. package/dist/internal/package-metadata.js +1 -1
  70. package/dist/testing/happy-dom-shims.d.ts +3 -1
  71. package/dist/testing/happy-dom-shims.js +1 -1
  72. package/llms/components/lr-box-plot.md +5 -0
  73. package/llms/components/lr-chart.md +6 -0
  74. package/llms/components/lr-color-picker.md +2 -0
  75. package/llms/components/lr-commit-card.md +3 -2
  76. package/llms/components/lr-heatmap.md +10 -2
  77. package/llms/components/lr-select.md +2 -0
  78. package/llms/components/lr-stat.md +4 -0
  79. package/llms/peers.md +1 -1
  80. package/llms/shared/ai-and-peers.md +44 -0
  81. package/llms/shared/testing-and-utilities.md +14 -1
  82. package/llms/shared.md +58 -1
  83. package/locales.json +138 -138
  84. package/package.json +7 -6
  85. package/registrations.json +1 -1
@@ -1 +1 @@
1
- import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{overlaySurface}from"../../../internal/overlay-surface.styles.js";const styles=css` :host { display: contents; --_lr-command-palette-z-index: var( --lr-overlay-stack-index, var(--lr-layer-modal) ); --_lr-command-palette-max-inline-size: var(--lr-size-48rem); --_lr-command-palette-max-block-size: 70vh; --_lr-command-palette-list-max-block-size: 50vh; --_lr-command-palette-offset-block-start: 12vh; --_lr-command-palette-row-height: var(--lr-size-3rem); --_lr-command-palette-group-height: var(--lr-size-2rem); } [part="backdrop"] { position: fixed; inset: 0; z-index: var( --lr-command-palette-z-index, var(--_lr-command-palette-z-index) ); display: grid; place-items: start center; padding-block-start: var( --lr-command-palette-offset-block-start, var(--_lr-command-palette-offset-block-start) ); background: var(--lr-color-overlay); } [part="dialog"] { inline-size: min( var( --lr-command-palette-max-inline-size, var(--_lr-command-palette-max-inline-size) ), calc(100vw - 2 * var(--lr-space-l)) ); min-inline-size: 0; max-block-size: var( --lr-command-palette-max-block-size, var(--_lr-command-palette-max-block-size) ); overflow: hidden; --_lr-overlay-surface: var(--lr-color-surface-container-highest); ${overlaySurface} box-shadow: var(--lr-overlay-shadow-modal, var(--lr-shadow-xl)); color: var(--lr-color-text); } [part="search"] { display: flex; align-items: center; min-inline-size: 0; gap: var(--lr-command-palette-search-gap, var(--lr-space-s)); padding: var(--lr-command-palette-search-padding, var(--lr-space-m)); border-block-end: var(--lr-border-width-thin) solid var(--lr-color-border); } [part="input"] { flex: 1; min-inline-size: 0; min-block-size: var(--lr-command-palette-search-min-height, auto); border: 0; outline: 0; background: transparent; color: inherit; font: inherit; font-size: var(--lr-command-palette-search-font-size, inherit); } [part="input"]:focus-visible { ${focusRing} border-radius: var(--lr-radius-xs); } [part="input"]::placeholder { color: var(--lr-color-text-quiet); opacity: 1; } [part="input"]::-webkit-search-cancel-button, [part="input"]::-webkit-search-decoration { -webkit-appearance: none; appearance: none; display: none; } [part="clear-button"] { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; ${iconHitTarget} border: 0; border-radius: var(--lr-radius-xs); background: transparent; cursor: pointer; color: var(--lr-color-text-quiet); padding: var(--lr-space-xs); font: inherit; transition: background-color var(--lr-transition-fast), color var(--lr-transition-fast); } [part="clear-button"]:hover { color: var(--lr-color-text); } [part="clear-button"]:active { color: var(--lr-color-text); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="clear-button"]:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: calc(-1 * var(--lr-focus-ring-width)); } [part="list"] { position: relative; max-block-size: var( --lr-command-palette-list-max-block-size, var(--_lr-command-palette-list-max-block-size) ); overflow-x: hidden; overflow-y: auto; padding: var(--lr-space-xs); } [part="list-spacer"] { position: relative; min-inline-size: 0; } [part="command-group"] { display: contents; } [part="group"] { position: absolute; inset-inline: 0; block-size: var( --lr-command-palette-group-height, var(--_lr-command-palette-group-height) ); box-sizing: border-box; overflow: hidden; padding: var(--lr-space-xs) var(--lr-space-s); color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-sm); font-weight: var(--lr-font-weight-semibold); text-overflow: ellipsis; white-space: nowrap; } [part="command"] { position: absolute; inset-inline: 0; display: flex; align-items: center; min-inline-size: 0; block-size: var( --lr-command-palette-row-height, var(--_lr-command-palette-row-height) ); box-sizing: border-box; gap: var(--lr-space-s); inline-size: 100%; overflow: hidden; padding: var(--lr-space-s); border: 0; border-radius: var(--lr-radius); background: transparent; color: inherit; font: inherit; text-align: start; cursor: pointer; transition: background-color var(--lr-transition-fast); } :where([part="command"]):hover:where(:not(:disabled)) { background: var( --lr-command-palette-active-bg, var(--lr-color-brand-quiet) ); } :where([part="command"]):active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-command-palette-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="command"][data-active="true"] { background: var( --lr-command-palette-active-bg, var(--lr-color-brand-quiet) ); } [part="command"][data-active="true"]:active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-command-palette-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="command"]:disabled { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part="icon"] { display: inline-flex; align-items: center; flex: none; block-size: var(--lr-size-1em); max-inline-size: var(--lr-size-1-25rem); } [part="label"], [part="description"], [part="shortcut"] { min-inline-size: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part="label"] { flex: 0 1000 auto; } [part="description"] { flex: 1 1000 auto; color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-sm); } [part="shortcut"] { flex: 0 1 auto; max-inline-size: 40%; color: var(--lr-color-text-quiet); font-family: var(--lr-font-mono); font-size: var(--lr-font-size-sm); } [part="empty"] { padding: var(--lr-space-l); color: var(--lr-color-text-quiet); text-align: center; } @media (forced-colors: active) { [part="command"][data-active="true"] { outline: var(--lr-border-width-medium) solid currentColor; outline-offset: calc(-1 * var(--lr-border-width-medium)); font-weight: var(--lr-font-weight-semibold); } } `;export{styles};
1
+ import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{overlaySurface}from"../../../internal/overlay-surface.styles.js";const styles=css` :host { display: contents; --_lr-command-palette-z-index: var( --lr-overlay-stack-index, var(--lr-layer-modal) ); --_lr-command-palette-max-inline-size: var(--lr-size-48rem); --_lr-command-palette-max-block-size: 70vh; --_lr-command-palette-list-max-block-size: 50vh; --_lr-command-palette-offset-block-start: 12vh; --_lr-command-palette-row-height: var(--lr-size-3rem); --_lr-command-palette-group-height: var(--lr-size-2rem); } [part="backdrop"] { position: fixed; inset: 0; z-index: var( --lr-command-palette-z-index, var(--_lr-command-palette-z-index) ); display: grid; place-items: start center; padding-block-start: var( --lr-command-palette-offset-block-start, var(--_lr-command-palette-offset-block-start) ); background: var(--lr-color-overlay); } [part="dialog"] { inline-size: min( var( --lr-command-palette-max-inline-size, var(--_lr-command-palette-max-inline-size) ), calc(100vw - 2 * var(--lr-space-l)) ); min-inline-size: 0; max-block-size: var( --lr-command-palette-max-block-size, var(--_lr-command-palette-max-block-size) ); overflow: hidden; --_lr-overlay-surface: var(--lr-color-surface-container-highest); ${overlaySurface} box-shadow: var(--lr-overlay-shadow-modal, var(--lr-shadow-xl)); color: var(--lr-color-text); } [part="search"] { display: flex; align-items: center; min-inline-size: 0; gap: var(--lr-command-palette-search-gap, var(--lr-space-s)); padding: var(--lr-command-palette-search-padding, var(--lr-space-m)); border-block-end: var(--lr-border-width-thin) solid var(--lr-color-border); } [part="input"] { flex: 1; min-inline-size: 0; min-block-size: var(--lr-command-palette-search-min-height, auto); border: 0; outline: 0; background: transparent; color: inherit; font: inherit; font-size: var(--lr-command-palette-search-font-size, inherit); } [part="input"]:focus-visible { ${focusRing} border-radius: var(--lr-radius-xs); } [part="input"]::placeholder { color: var(--lr-color-text-quiet); opacity: 1; } [part="input"]::-webkit-search-cancel-button, [part="input"]::-webkit-search-decoration { -webkit-appearance: none; appearance: none; display: none; } [part="clear-button"] { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; ${iconHitTarget} border: 0; border-radius: var(--lr-radius-xs); background: transparent; cursor: pointer; color: var(--lr-color-text-quiet); padding: var(--lr-space-xs); font: inherit; transition: background-color var(--lr-transition-fast), color var(--lr-transition-fast); } [part="clear-button"]:hover { color: var(--lr-color-text); } [part="clear-button"]:active { color: var(--lr-color-text); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="clear-button"]:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: calc(-1 * var(--lr-focus-ring-width)); } [part="list"] { position: relative; max-block-size: var( --lr-command-palette-list-max-block-size, var(--_lr-command-palette-list-max-block-size) ); overflow-x: hidden; overflow-y: auto; padding: var(--lr-space-xs); } [part="list-spacer"] { position: relative; min-inline-size: 0; } [part="command-group"] { display: contents; } [part="group"] { position: absolute; inset-inline: 0; block-size: var( --lr-command-palette-group-height, var(--_lr-command-palette-group-height) ); box-sizing: border-box; overflow: hidden; padding: var(--lr-space-xs) var(--lr-space-s); color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-sm); font-weight: var(--lr-font-weight-semibold); text-overflow: ellipsis; white-space: nowrap; } [part="command"] { position: absolute; inset-inline: 0; display: flex; align-items: center; min-inline-size: 0; block-size: var( --lr-command-palette-row-height, var(--_lr-command-palette-row-height) ); box-sizing: border-box; gap: var(--lr-space-s); inline-size: 100%; overflow: hidden; padding: var(--lr-space-s); border: 0; border-radius: var(--lr-radius); background: transparent; color: inherit; font: inherit; text-align: start; cursor: pointer; transition: background-color var(--lr-transition-fast); } :where([part="command"]):hover:where(:not(:disabled)) { background: var( --lr-command-palette-active-bg, var(--lr-color-brand-quiet) ); } :where([part="command"]):active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-command-palette-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="command"][data-active="true"] { background: var( --lr-command-palette-active-bg, var(--lr-color-brand-quiet) ); } [part="command"][data-active="true"]:active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-command-palette-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="command"]:disabled { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part="icon"] { display: inline-flex; align-items: center; flex: none; block-size: var(--lr-size-1em); max-inline-size: var(--lr-size-1-25rem); } [part="label"], [part="description"], [part="shortcut"] { min-inline-size: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part="label"] { flex: 0 1000 auto; } [part="description"] { flex: 1 1000 auto; color: inherit; font-size: var(--lr-font-size-sm); } [part="shortcut"] { flex: 0 1 auto; max-inline-size: 40%; color: inherit; font-family: var(--lr-font-mono); font-size: var(--lr-font-size-sm); } [part="empty"] { padding: var(--lr-space-l); color: var(--lr-color-text-quiet); text-align: center; } @media (forced-colors: active) { [part="command"][data-active="true"] { outline: var(--lr-border-width-medium) solid currentColor; outline-offset: calc(-1 * var(--lr-border-width-medium)); font-weight: var(--lr-font-weight-semibold); } } `;export{styles};
@@ -1,9 +1,9 @@
1
- import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{getDateTimeFormat,getListFormat}from"../../../internal/intl-cache.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{srOnly}from"../../../internal/a11y.js";import{styles}from"./filter-bar.styles.js";import{LYRA_DEFAULT_filterBarActiveFilters,LYRA_DEFAULT_filterBarReset}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";const MAX_FILTER_COLLECTION_ENTRIES=1e4,MAX_FILTER_COLLECTION_NODES=5e4,MAX_FILTER_COLLECTION_DEPTH=16,OMIT_FILTER_VALUE=Symbol("omit-filter-value"),EMPTY_FILTERS=Object.freeze([]),EMPTY_VALUE=Object.freeze({}),EMPTY_DATE_PRESETS=Object.freeze([]);function isPlainFilterRecord(value){try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function snapshotFilterEntry(value,budget,depth){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(depth>MAX_FILTER_COLLECTION_DEPTH||budget.remaining<=0)return OMIT_FILTER_VALUE;const existing=budget.seen.get(value);if(existing!==void 0)return existing;let isArray=!1;try{isArray=Array.isArray(value)}catch{return OMIT_FILTER_VALUE}if(isArray){const output2=[];budget.seen.set(value,output2);let length=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(length=Math.min(descriptor.value,MAX_FILTER_COLLECTION_ENTRIES))}catch{return Object.freeze(output2)}for(let index=0;index<length&&budget.remaining>0;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;budget.remaining-=1;const entry=snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&output2.push(entry)}return Object.freeze(output2)}if(!isPlainFilterRecord(value))return value;const output={};budget.seen.set(value,output);let descriptors;try{descriptors=Object.getOwnPropertyDescriptors(value)}catch{return OMIT_FILTER_VALUE}let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES||budget.remaining<=0)break;const descriptor=descriptors[key];if(!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1,budget.remaining-=1;const entry=key==="icon"?descriptor.value:snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function snapshotFilterDefinitions(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return EMPTY_FILTERS}return isArray?snapshotFilterEntry(value,{remaining:MAX_FILTER_COLLECTION_NODES,seen:new WeakMap},0):EMPTY_FILTERS}function snapshotFilterFieldValue(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return}if(!isArray)return typeof value=="string"||typeof value=="boolean"||value===void 0?value:void 0;const output=[];let sourceLength=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(sourceLength=descriptor.value)}catch{return Object.freeze(output)}const length=Math.min(sourceLength,MAX_FILTER_COLLECTION_ENTRIES);for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}descriptor&&"value"in descriptor&&typeof descriptor.value=="string"&&output.push(descriptor.value)}return Object.freeze(output)}const SELECT_EXPORT_PARTS=["form-control-label: filter-control-label","trigger: filter-control-field","display-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),COMBOBOX_EXPORT_PARTS=["form-control-label: filter-control-label","combobox: filter-control-field","combobox-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","tags: filter-control-tags","tag: filter-control-tag","tag-overflow: filter-control-tag-overflow","tag-label: filter-control-tag-label","tag__remove-button: filter-control-tag-remove-button","tag__remove-button__base: filter-control-tag-remove-button-base","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","error: filter-control-error","hint: filter-control-hint"].join(", "),CHECKBOX_MENU_EXPORT_PARTS=["base: filter-control-listbox"].join(", "),CHECKBOX_MENU_TRIGGER_EXPORT_PARTS=["base: filter-control-field","start: filter-control-start","label: filter-control-label-group","caret: filter-control-expand-icon"].join(", "),DATE_INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","expand-button: filter-control-expand-button","expand-icon: filter-control-expand-icon","popup: filter-control-popup","error: filter-control-error","hint: filter-control-hint"].join(", "),SAFE_FILTER_ID_PART=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function fieldPartNames(filterId){return SAFE_FILTER_ID_PART.test(filterId)?`field field-${filterId}`:"field"}function isChoiceDefinition(definition){return definition.type==="select"||definition.type==="combobox"||definition.type==="checkbox-menu"}function isBuiltInSet(value){return value==null?!1:typeof value=="boolean"?value:Array.isArray(value)?value.length>0:value!==""}function filterValueEqualsDefault(value,defaultValue){const valueIsArray=Array.isArray(value),defaultIsArray=Array.isArray(defaultValue);return valueIsArray||defaultIsArray?!valueIsArray||!defaultIsArray?!1:value.length===defaultValue.length&&value.every((entry,index)=>entry===defaultValue[index]):Object.is(value,defaultValue)}function defineFilterValueEntry(record,key,value){Object.defineProperty(record,key,{value,enumerable:!0,configurable:!0,writable:!0})}function cloneFilterValueRecord(value){const clone={},descriptors=Object.getOwnPropertyDescriptors(value);let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES)break;const descriptor=descriptors[key];if(typeof key!="string"||!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1;const fieldValue=snapshotFilterFieldValue(descriptor.value);fieldValue!==void 0&&defineFilterValueEntry(clone,key,fieldValue)}return clone}function cloneFilterValue(value){return Object.freeze(cloneFilterValueRecord(value))}class LyraFilterBar extends LyraElement{constructor(){super(...arguments),this.label="",this.disabled=!1,this.loading=!1,this.activeFiltersDisplay="all",this.touchedFilters=new Set,this.slotPresence=new SlotPresenceController(this),this._filters=EMPTY_FILTERS,this._value=EMPTY_VALUE,this.rawValue=EMPTY_VALUE,this.debounceControllers=new Map,this.chipFocusGeneration=0,this.schemaGeneration=0,this.onControlChange=(def,e)=>{const control=e.target;if(def.type==="combobox"&&this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,control.value,def.debounce);return}this.setFilterValue(def.filterId,control.value,control.appliedPreset)},this.stopControlAlias=event=>{event.stopPropagation()},this.onCustomControlChange=(def,generation,e)=>{e.stopPropagation();const next=def.custom.adapter.valueFromEvent(e);if(this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,next,def.debounce,pending=>this.setCustomContextValue(def,generation,pending));return}this.setCustomContextValue(def,generation,next)},this.stopMenuItemChangeAlias=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,filterBarActiveFilters:LYRA_DEFAULT_filterBarActiveFilters,filterBarReset:LYRA_DEFAULT_filterBarReset}}static{this.styles=[LyraElement.styles,srOnly,styles]}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-validity-change"])}static{this.properties={filters:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0}}}get filters(){return this._filters}set filters(next){if(next===this.filtersInput)return;this.filtersInput=next;const old=this._filters,widened=next;this.cancelDebounce(),this.renewSchemaContext();const seen=new Set;this._filters=Object.freeze(snapshotFilterDefinitions(widened).filter(definition=>{try{return!definition||typeof definition.filterId!="string"||definition.filterId.length===0||definition.filterId!==definition.filterId.trim()||typeof definition.label!="string"||definition.label.trim().length===0||seen.has(definition.filterId)||isChoiceDefinition(definition)&&!Array.isArray(definition.options)||definition.type==="custom"&&(!definition.custom?.adapter||typeof definition.custom.render!="function")?!1:(seen.add(definition.filterId),!0)}catch{return!1}}).map(definition=>{const choices=definition.options;if(choices===void 0)return definition;const options=(Array.isArray(choices)?choices:[]).filter(option=>{try{return option!==null&&typeof option=="object"&&typeof Object.getOwnPropertyDescriptor(option,"value")?.value=="string"&&typeof Object.getOwnPropertyDescriptor(option,"label")?.value=="string"}catch{return!1}});return Object.freeze({...definition,options:Object.freeze(options)})}));const ids=new Set(this._filters.map(definition=>definition.filterId));this.touchedFilters=new Set([...this.touchedFilters].filter(id=>ids.has(id)));const oldValue=this._value;this._value=this.normalizeValue(this.rawValue),this.requestUpdate("filters",old),this._value!==oldValue&&this.requestUpdate("value",oldValue)}get value(){return cloneFilterValue(this._value)}set value(next){if(next===this.valueInput)return;this.valueInput=next;const old=this._value,widened=next;try{this.rawValue=cloneFilterValue(widened??EMPTY_VALUE)}catch{this.rawValue=EMPTY_VALUE}this._value=this.normalizeValue(widened),this.requestUpdate("value",old)}renewSchemaContext(){this.schemaAbortController?.abort();const AbortControllerCtor=this.ownerDocument.defaultView?.AbortController??AbortController;this.schemaAbortController=new AbortControllerCtor,this.schemaGeneration+=1}get schemaSignal(){return this.schemaAbortController||this.renewSchemaContext(),this.schemaAbortController.signal}isEmpty(def,value){if(def.type==="chip")return typeof def.isEmpty=="function"?def.isEmpty(value):!isBuiltInSet(value);if(def.type!=="custom")return!isBuiltInSet(value);const{adapter}=def.custom;if(adapter.isEmpty)return adapter.isEmpty(value);const clear=adapter.clearValue;return Array.isArray(value)&&Array.isArray(clear)?value.length===clear.length&&value.every((entry,index)=>entry===clear[index]):Object.is(value,clear)}valueFor(def){return Object.prototype.hasOwnProperty.call(this._value,def.filterId)?this._value[def.filterId]:def.type==="custom"?def.custom.adapter.clearValue:def.type==="chip"?def.clearValue:void 0}normalizeValue(value){const normalized={};for(const def of this._filters){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value??{},def.filterId)}catch{continue}if(!descriptor||!("value"in descriptor))continue;const fieldValue=snapshotFilterFieldValue(descriptor.value);this.isEmpty(def,fieldValue)||defineFilterValueEntry(normalized,def.filterId,fieldValue)}return Object.freeze(normalized)}get hasActiveFilters(){return this._filters.some(def=>!this.isEmpty(def,this.valueFor(def)))}filterIsChanged(def){const value=this.valueFor(def),defaultValue=def.defaultValue;return defaultValue!==void 0&&!this.isEmpty(def,defaultValue)?!filterValueEqualsDefault(value,defaultValue):!this.isEmpty(def,value)}get hasChangedFilters(){return this._filters.some(def=>this.filterIsChanged(def))}get hasResettableFilters(){return this.activeFiltersDisplay==="changed"?this.hasChangedFilters:this.hasActiveFilters}get invalidFilterIds(){return Object.freeze(this._filters.filter(def=>def.required&&this.isEmpty(def,this.valueFor(def))).map(def=>def.filterId))}checkValidity(){return this.invalidFilterIds.length===0}reportValidity(){const invalid=this.invalidFilterIds;return invalid.length&&(this.touchedFilters=new Set([...this.touchedFilters,...invalid])),invalid.length===0}reset(){if(this.disabled)return;this.cancelDebounce(),this.touchedFilters=new Set;const self=this;self.value=self.resetValue,self.emit("lr-input",Object.freeze({value:self.value,filterId:void 0,appliedPreset:void 0})),self.emit("lr-reset",Object.freeze({value:self.value}))}get resetValue(){const out={};for(const def of this._filters)if(def.defaultValue!==void 0&&!this.isEmpty(def,def.defaultValue)){const value=Array.isArray(def.defaultValue)?Object.freeze([...def.defaultValue]):def.defaultValue;defineFilterValueEntry(out,def.filterId,value)}return Object.freeze(out)}setFilterValue(id,value,appliedPreset){const definition=this._filters.find(candidate=>candidate.filterId===id);if(this.disabled||!definition)return;const next={...this._value};this.isEmpty(definition,value)?delete next[id]:defineFilterValueEntry(next,id,value);const self=this;self.value=next,self.emit("lr-input",Object.freeze({value:self.value,filterId:id,appliedPreset}))}setCustomContextValue(definition,generation,value){generation!==this.schemaGeneration||this.schemaSignal.aborted||!this.isConnected||!this._filters.includes(definition)||this.setFilterValue(definition.filterId,value)}markTouched(id){this.disabled||this.touchedFilters.has(id)||(this.touchedFilters=new Set(this.touchedFilters).add(id))}isDebounced(delay){return typeof delay=="number"&&Number.isFinite(delay)&&delay>0}scheduleDebounce(id,value,delay,commit=pending=>this.setFilterValue(id,pending)){let controller=this.debounceControllers.get(id);if(!controller){const created=new DebounceController(delay,pending=>{this.debounceControllers.get(id)===created&&this.debounceControllers.delete(id),pending!==void 0&&commit(pending)});controller=created,this.debounceControllers.set(id,created)}controller.delayMs=delay,controller.push(value)}hasPendingDebounce(id){return this.debounceControllers.get(id)?.pending??!1}onTextInput(def,e){if(this.disabled)return;const next=e.target.value??"";if(!this.isDebounced(def.debounce)){this.cancelDebounce(def.filterId),this.setFilterValue(def.filterId,next);return}this.scheduleDebounce(def.filterId,next,def.debounce)}flushDebounce(id){this.debounceControllers.get(id)?.flush()}cancelDebounce(id){for(const[key,controller]of this.debounceControllers)id!==void 0&&key!==id||(controller.dispose(),this.debounceControllers.delete(key))}onFieldFocusout(id){this.flushDebounce(id),this.markTouched(id)}repairFocusAfterChipRemoval(index,filterId,shouldRepairFocus){const generation=++this.chipFocusGeneration;shouldRepairFocus&&this.updateComplete.then(()=>{if(!this.isConnected||this.disabled||generation!==this.chipFocusGeneration||deepActiveElement(this.ownerDocument)!==this.ownerDocument.body)return;const chips=this.renderRoot.querySelectorAll('[part="chip"]'),chip=chips[Math.min(index,chips.length-1)],target=chip?collectFocusableElements(chip)[0]:void 0;if(target){target.focus();return}for(const control of this.renderRoot.querySelectorAll("[data-filter-id]"))if(control.dataset.filterId===filterId){collectFocusableElements(control)[0]?.focus();return}})}clearFilter(id,shouldRepairFocus=!1){if(this.disabled)return;this.cancelDebounce(id);const index=this.activeEntries.findIndex(entry=>entry.def.filterId===id),def=this._filters.find(f=>f.filterId===id);if(!def)return;const clearValue=def.type==="custom"?def.custom.adapter.clearValue:def.type==="chip"?def.clearValue??"":def.type==="checkbox-menu"||def.type==="combobox"&&def.multiple?[]:"";this.setFilterValue(id,clearValue),this.repairFocusAfterChipRemoval(Math.max(0,index),id,shouldRepairFocus)}displayValueFor(def,value){if(def.type==="custom"){const formatted=def.custom?.adapter.formatValue?.(value,this.effectiveLocale);return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(def.type==="chip"){const formatted=typeof def.formatValue=="function"?def.formatValue(value,this.effectiveLocale):void 0;return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(isChoiceDefinition(def)){const labels=(Array.isArray(value)?value.filter(entry=>typeof entry=="string"):typeof value=="string"?[value]:[]).map(v=>def.options?.find(o=>o.value===v)?.label??v);return labels.length>1?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(labels):labels[0]??""}if(def.type==="text")return typeof value=="string"?value:"";if(typeof value!="string")return"";const formatter=getDateTimeFormat(this.effectiveLocale,{year:"numeric",month:"short",day:"numeric",timeZone:"UTC"}),parseIso=input=>{const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(input);if(!match)return;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=new Date(0);return date.setUTCHours(0,0,0,0),date.setUTCFullYear(year,month-1,day),date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date:void 0},segments=value.split("/");if(def.type==="date"&&segments.length!==1||def.type==="date-range"&&segments.length!==2)return value;const[startText,endText]=segments,start=parseIso(startText??""),end=endText===void 0?void 0:parseIso(endText);return!start||endText!==void 0&&(!end||end.getTime()<start.getTime())?value:end?formatter.formatRange(start,end):formatter.format(start)}get activeEntries(){return this.activeFiltersDisplay==="hidden"?[]:this._filters.filter(def=>!this.isEmpty(def,this.valueFor(def))).filter(def=>this.activeFiltersDisplay!=="changed"||!filterValueEqualsDefault(this.valueFor(def),def.defaultValue)).map(def=>({def,display:this.displayValueFor(def,this.valueFor(def))}))}disconnectedCallback(){super.disconnectedCallback(),this.cancelDebounce(),this.closeCheckboxMenus(),this.schemaAbortController?.abort(),this.schemaAbortController=void 0,this.schemaGeneration+=1}closeCheckboxMenus(){for(const menu of this.renderRoot?.querySelectorAll(`${tag("dropdown")}[data-filter-id]`)??[])menu.open&&(menu.open=!1)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.closeCheckboxMenus(),(!this.schemaAbortController||this.schemaAbortController.signal.aborted)&&(this.renewSchemaContext(),this.hasUpdated&&this.requestUpdate()),this.hasUpdated&&queueMicrotask(()=>{this.isConnected&&this.syncTextControls()})}syncTextControls(){if(!this._filters.some(def=>def.type==="text"))return;const fields=new Map;for(const node of this.renderRoot.querySelectorAll(`${tag("input")}[data-filter-id]`)){const element=node,id=element.dataset.filterId;id!==void 0&&fields.set(id,element)}for(const def of this._filters){if(def.type!=="text"||this.hasPendingDebounce(def.filterId))continue;const field=fields.get(def.filterId);if(!field)continue;const raw=this._value[def.filterId],next=typeof raw=="string"?raw:"";field.value!==next&&(field.value=next)}}willUpdate(changed){super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.cancelDebounce()}updated(changed){if(super.updated(changed),this.syncTextControls(),changed.has("value")||changed.has("filters")){const invalidFilterIds=this.invalidFilterIds,valid=invalidFilterIds.length===0,key=JSON.stringify({valid,invalidFilterIds});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,invalidFilterIds:Object.freeze([...invalidFilterIds])})))}}renderStartAdornment(icon,slotName="start"){return icon==null?nothing:html`<span slot=${slotName} aria-hidden="true" inert>${icon}</span>`}renderOption(option){return html`<lr-option
1
+ import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{getDateTimeFormat,getListFormat}from"../../../internal/intl-cache.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{srOnly}from"../../../internal/a11y.js";import{styles}from"./filter-bar.styles.js";import{LYRA_DEFAULT_filterBarActiveFilters,LYRA_DEFAULT_filterBarReset}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";const MAX_FILTER_COLLECTION_ENTRIES=1e4,MAX_FILTER_COLLECTION_NODES=5e4,MAX_FILTER_COLLECTION_DEPTH=16,OMIT_FILTER_VALUE=Symbol("omit-filter-value"),EMPTY_FILTERS=Object.freeze([]),EMPTY_VALUE=Object.freeze({}),EMPTY_DATE_PRESETS=Object.freeze([]);function isPlainFilterRecord(value){try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function snapshotFilterEntry(value,budget,depth){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(depth>MAX_FILTER_COLLECTION_DEPTH||budget.remaining<=0)return OMIT_FILTER_VALUE;const existing=budget.seen.get(value);if(existing!==void 0)return existing;let isArray=!1;try{isArray=Array.isArray(value)}catch{return OMIT_FILTER_VALUE}if(isArray){const output2=[];budget.seen.set(value,output2);let length=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(length=Math.min(descriptor.value,MAX_FILTER_COLLECTION_ENTRIES))}catch{return Object.freeze(output2)}for(let index=0;index<length&&budget.remaining>0;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;budget.remaining-=1;const entry=snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&output2.push(entry)}return Object.freeze(output2)}if(!isPlainFilterRecord(value))return value;const output={};budget.seen.set(value,output);let descriptors;try{descriptors=Object.getOwnPropertyDescriptors(value)}catch{return OMIT_FILTER_VALUE}let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES||budget.remaining<=0)break;const descriptor=descriptors[key];if(!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1,budget.remaining-=1;const entry=key==="icon"?descriptor.value:snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function snapshotFilterDefinitions(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return EMPTY_FILTERS}return isArray?snapshotFilterEntry(value,{remaining:MAX_FILTER_COLLECTION_NODES,seen:new WeakMap},0):EMPTY_FILTERS}function snapshotFilterFieldValue(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return}if(!isArray)return typeof value=="string"||typeof value=="boolean"||value===void 0?value:void 0;const output=[];let sourceLength=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(sourceLength=descriptor.value)}catch{return Object.freeze(output)}const length=Math.min(sourceLength,MAX_FILTER_COLLECTION_ENTRIES);for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}descriptor&&"value"in descriptor&&typeof descriptor.value=="string"&&output.push(descriptor.value)}return Object.freeze(output)}const SELECT_EXPORT_PARTS=["form-control-label: filter-control-label","trigger: filter-control-field","display-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),COMBOBOX_EXPORT_PARTS=["form-control-label: filter-control-label","combobox: filter-control-field","combobox-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","tags: filter-control-tags","tag: filter-control-tag","tag-overflow: filter-control-tag-overflow","tag-label: filter-control-tag-label","tag__remove-button: filter-control-tag-remove-button","tag__remove-button__base: filter-control-tag-remove-button-base","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","error: filter-control-error","hint: filter-control-hint"].join(", "),CHECKBOX_MENU_EXPORT_PARTS=["base: filter-control-listbox"].join(", "),CHECKBOX_MENU_TRIGGER_EXPORT_PARTS=["base: filter-control-field","start: filter-control-start","label: filter-control-label-group","caret: filter-control-expand-icon"].join(", "),DATE_INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","expand-button: filter-control-expand-button","expand-icon: filter-control-expand-icon","popup: filter-control-popup","error: filter-control-error","hint: filter-control-hint"].join(", "),SAFE_FILTER_ID_PART=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function fieldPartNames(filterId){return SAFE_FILTER_ID_PART.test(filterId)?`field field-${filterId}`:"field"}function isChoiceDefinition(definition){return definition.type==="select"||definition.type==="combobox"||definition.type==="checkbox-menu"}function isBuiltInSet(value){return value==null?!1:typeof value=="boolean"?value:Array.isArray(value)?value.length>0:value!==""}function filterValueEqualsDefault(value,defaultValue){const valueIsArray=Array.isArray(value),defaultIsArray=Array.isArray(defaultValue);return valueIsArray||defaultIsArray?!valueIsArray||!defaultIsArray?!1:value.length===defaultValue.length&&value.every((entry,index)=>entry===defaultValue[index]):Object.is(value,defaultValue)}function defineFilterValueEntry(record,key,value){Object.defineProperty(record,key,{value,enumerable:!0,configurable:!0,writable:!0})}function cloneFilterValueRecord(value){const clone={},descriptors=Object.getOwnPropertyDescriptors(value);let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES)break;const descriptor=descriptors[key];if(typeof key!="string"||!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1;const fieldValue=snapshotFilterFieldValue(descriptor.value);fieldValue!==void 0&&defineFilterValueEntry(clone,key,fieldValue)}return clone}function cloneFilterValue(value){return Object.freeze(cloneFilterValueRecord(value))}class LyraFilterBar extends LyraElement{constructor(){super(...arguments),this.label="",this.disabled=!1,this.loading=!1,this.activeFiltersDisplay="all",this.touchedFilters=new Set,this.slotPresence=new SlotPresenceController(this),this._filters=EMPTY_FILTERS,this._value=EMPTY_VALUE,this.rawValue=EMPTY_VALUE,this.debounceControllers=new Map,this.chipFocusGeneration=0,this.schemaGeneration=0,this.onControlChange=(def,e)=>{const control=e.target;if(def.type==="combobox"&&this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,control.value,def.debounce);return}this.setFilterValue(def.filterId,control.value,control.appliedPreset)},this.stopControlAlias=event=>{event.stopPropagation()},this.onCustomControlChange=(def,generation,e)=>{e.stopPropagation();const next=def.custom.adapter.valueFromEvent(e);if(this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,next,def.debounce,pending=>this.setCustomContextValue(def,generation,pending));return}this.setCustomContextValue(def,generation,next)},this.stopMenuItemChangeAlias=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,filterBarActiveFilters:LYRA_DEFAULT_filterBarActiveFilters,filterBarReset:LYRA_DEFAULT_filterBarReset}}static{this.styles=[LyraElement.styles,srOnly,styles]}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-validity-change"])}static{this.properties={filters:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0}}}get filters(){return this._filters}set filters(next){if(next===this.filtersInput)return;this.filtersInput=next;const old=this._filters,widened=next;this.cancelDebounce(),this.renewSchemaContext();const seen=new Set;this._filters=Object.freeze(snapshotFilterDefinitions(widened).filter(definition=>{try{return!definition||typeof definition.filterId!="string"||definition.filterId.length===0||definition.filterId!==definition.filterId.trim()||typeof definition.label!="string"||definition.label.trim().length===0||seen.has(definition.filterId)||isChoiceDefinition(definition)&&!Array.isArray(definition.options)||definition.type==="custom"&&(!definition.custom?.adapter||typeof definition.custom.render!="function")?!1:(seen.add(definition.filterId),!0)}catch{return!1}}).map(definition=>{const choices=definition.options;if(choices===void 0)return definition;const options=(Array.isArray(choices)?choices:[]).filter(option=>{try{return option!==null&&typeof option=="object"&&typeof Object.getOwnPropertyDescriptor(option,"value")?.value=="string"&&typeof Object.getOwnPropertyDescriptor(option,"label")?.value=="string"}catch{return!1}});return Object.freeze({...definition,options:Object.freeze(options)})}));const ids=new Set(this._filters.map(definition=>definition.filterId));this.touchedFilters=new Set([...this.touchedFilters].filter(id=>ids.has(id)));const oldValue=this._value;this._value=this.normalizeValue(this.rawValue),this.requestUpdate("filters",old),this._value!==oldValue&&this.requestUpdate("value",oldValue)}get value(){return cloneFilterValue(this._value)}set value(next){if(next===this.valueInput)return;this.valueInput=next;const old=this._value,widened=next;try{this.rawValue=cloneFilterValue(widened??EMPTY_VALUE)}catch{this.rawValue=EMPTY_VALUE}this._value=this.normalizeValue(widened),this.requestUpdate("value",old)}renewSchemaContext(){this.schemaAbortController?.abort();const AbortControllerCtor=this.ownerDocument.defaultView?.AbortController??AbortController;this.schemaAbortController=new AbortControllerCtor,this.schemaGeneration+=1}get schemaSignal(){return this.schemaAbortController||this.renewSchemaContext(),this.schemaAbortController.signal}isEmpty(def,value){if(def.type==="chip")return typeof def.isEmpty=="function"?def.isEmpty(value):!isBuiltInSet(value);if(def.type!=="custom")return!isBuiltInSet(value);const{adapter}=def.custom;if(adapter.isEmpty)return adapter.isEmpty(value);const clear=adapter.clearValue;return Array.isArray(value)&&Array.isArray(clear)?value.length===clear.length&&value.every((entry,index)=>entry===clear[index]):Object.is(value,clear)}valueFor(def){return Object.prototype.hasOwnProperty.call(this._value,def.filterId)?this._value[def.filterId]:def.type==="custom"?def.custom.adapter.clearValue:def.type==="chip"?def.clearValue:void 0}normalizeValue(value){const normalized={};for(const def of this._filters){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value??{},def.filterId)}catch{continue}if(!descriptor||!("value"in descriptor))continue;const fieldValue=snapshotFilterFieldValue(descriptor.value);this.isEmpty(def,fieldValue)||defineFilterValueEntry(normalized,def.filterId,fieldValue)}return Object.freeze(normalized)}get hasActiveFilters(){return this._filters.some(def=>!this.isEmpty(def,this.valueFor(def)))}filterIsChanged(def){const value=this.valueFor(def),defaultValue=def.defaultValue;return defaultValue!==void 0&&!this.isEmpty(def,defaultValue)?!filterValueEqualsDefault(value,defaultValue):!this.isEmpty(def,value)}get hasChangedFilters(){return this._filters.some(def=>this.filterIsChanged(def))}get hasResettableFilters(){return this.activeFiltersDisplay==="changed"?this.hasChangedFilters:this.hasActiveFilters}get invalidFilterIds(){return Object.freeze(this._filters.filter(def=>def.required&&this.isEmpty(def,this.valueFor(def))).map(def=>def.filterId))}checkValidity(){return this.invalidFilterIds.length===0}reportValidity(){const invalid=this.invalidFilterIds;return invalid.length&&(this.touchedFilters=new Set([...this.touchedFilters,...invalid])),invalid.length===0}reset(){if(this.disabled)return;this.cancelDebounce(),this.touchedFilters=new Set;const self=this;self.value=self.resetValue,self.emit("lr-input",Object.freeze({value:self.value,filterId:void 0,appliedPreset:void 0})),self.emit("lr-reset",Object.freeze({value:self.value}))}get resetValue(){const out={};for(const def of this._filters)if(def.defaultValue!==void 0&&!this.isEmpty(def,def.defaultValue)){const value=Array.isArray(def.defaultValue)?Object.freeze([...def.defaultValue]):def.defaultValue;defineFilterValueEntry(out,def.filterId,value)}return Object.freeze(out)}setFilterValue(id,value,appliedPreset){const definition=this._filters.find(candidate=>candidate.filterId===id);if(this.disabled||!definition)return;const next={...this._value};this.isEmpty(definition,value)?delete next[id]:defineFilterValueEntry(next,id,value);const self=this;self.value=next,self.emit("lr-input",Object.freeze({value:self.value,filterId:id,appliedPreset}))}setCustomContextValue(definition,generation,value){generation!==this.schemaGeneration||this.schemaSignal.aborted||!this.isConnected||!this._filters.includes(definition)||this.setFilterValue(definition.filterId,value)}markTouched(id){this.disabled||this.touchedFilters.has(id)||(this.touchedFilters=new Set(this.touchedFilters).add(id))}isDebounced(delay){return typeof delay=="number"&&Number.isFinite(delay)&&delay>0}scheduleDebounce(id,value,delay,commit=pending=>this.setFilterValue(id,pending)){let controller=this.debounceControllers.get(id);if(!controller){const created=new DebounceController(delay,pending=>{this.debounceControllers.get(id)===created&&this.debounceControllers.delete(id),pending!==void 0&&commit(pending)});controller=created,this.debounceControllers.set(id,created)}controller.delayMs=delay,controller.push(value)}hasPendingDebounce(id){return this.debounceControllers.get(id)?.pending??!1}onTextInput(def,e){if(this.disabled)return;const next=e.target.value??"";if(!this.isDebounced(def.debounce)){this.cancelDebounce(def.filterId),this.setFilterValue(def.filterId,next);return}this.scheduleDebounce(def.filterId,next,def.debounce)}flushDebounce(id){this.debounceControllers.get(id)?.flush()}cancelDebounce(id){for(const[key,controller]of this.debounceControllers)id!==void 0&&key!==id||(controller.dispose(),this.debounceControllers.delete(key))}onFieldFocusout(id){this.flushDebounce(id),this.markTouched(id)}repairFocusAfterChipRemoval(index,filterId,shouldRepairFocus){const generation=++this.chipFocusGeneration;shouldRepairFocus&&this.updateComplete.then(()=>{if(!this.isConnected||this.disabled||generation!==this.chipFocusGeneration||deepActiveElement(this.ownerDocument)!==this.ownerDocument.body)return;const chips=this.renderRoot.querySelectorAll('[part="chip"]'),chip=chips[Math.min(index,chips.length-1)],target=chip?collectFocusableElements(chip)[0]:void 0;if(target){target.focus();return}for(const control of this.renderRoot.querySelectorAll("[data-filter-id]"))if(control.dataset.filterId===filterId){collectFocusableElements(control)[0]?.focus();return}})}clearFilter(id,shouldRepairFocus=!1){if(this.disabled)return;this.cancelDebounce(id);const index=this.activeEntries.findIndex(entry=>entry.def.filterId===id),def=this._filters.find(f=>f.filterId===id);if(!def)return;const clearValue=def.type==="custom"?def.custom.adapter.clearValue:def.type==="chip"?def.clearValue??"":def.type==="checkbox-menu"||def.type==="combobox"&&def.multiple?[]:"";this.setFilterValue(id,clearValue),this.repairFocusAfterChipRemoval(Math.max(0,index),id,shouldRepairFocus)}displayValueFor(def,value){if(def.type==="custom"){const formatted=def.custom?.adapter.formatValue?.(value,this.effectiveLocale);return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(def.type==="chip"){const formatted=typeof def.formatValue=="function"?def.formatValue(value,this.effectiveLocale):void 0;return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(isChoiceDefinition(def)){const values=Array.isArray(value)?value.filter(entry=>typeof entry=="string"):typeof value=="string"?[value]:[],optionLabels=values.length>1?new Map:void 0;if(optionLabels)for(const option of def.options??[]){const optionValue=option.value;optionLabels.has(optionValue)||optionLabels.set(optionValue,option.label)}const labels=values.map(v=>optionLabels?optionLabels.get(v)??v:def.options?.find(o=>o.value===v)?.label??v);return labels.length>1?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(labels):labels[0]??""}if(def.type==="text")return typeof value=="string"?value:"";if(typeof value!="string")return"";const formatter=getDateTimeFormat(this.effectiveLocale,{year:"numeric",month:"short",day:"numeric",timeZone:"UTC"}),parseIso=input=>{const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(input);if(!match)return;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=new Date(0);return date.setUTCHours(0,0,0,0),date.setUTCFullYear(year,month-1,day),date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date:void 0},segments=value.split("/");if(def.type==="date"&&segments.length!==1||def.type==="date-range"&&segments.length!==2)return value;const[startText,endText]=segments,start=parseIso(startText??""),end=endText===void 0?void 0:parseIso(endText);return!start||endText!==void 0&&(!end||end.getTime()<start.getTime())?value:end?formatter.formatRange(start,end):formatter.format(start)}get activeEntries(){return this.activeFiltersDisplay==="hidden"?[]:this._filters.filter(def=>!this.isEmpty(def,this.valueFor(def))).filter(def=>this.activeFiltersDisplay!=="changed"||!filterValueEqualsDefault(this.valueFor(def),def.defaultValue)).map(def=>({def,display:this.displayValueFor(def,this.valueFor(def))}))}disconnectedCallback(){super.disconnectedCallback(),this.cancelDebounce(),this.closeCheckboxMenus(),this.schemaAbortController?.abort(),this.schemaAbortController=void 0,this.schemaGeneration+=1}closeCheckboxMenus(){for(const menu of this.renderRoot?.querySelectorAll(`${tag("dropdown")}[data-filter-id]`)??[])menu.open&&(menu.open=!1)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.closeCheckboxMenus(),(!this.schemaAbortController||this.schemaAbortController.signal.aborted)&&(this.renewSchemaContext(),this.hasUpdated&&this.requestUpdate()),this.hasUpdated&&queueMicrotask(()=>{this.isConnected&&this.syncTextControls()})}syncTextControls(){if(!this._filters.some(def=>def.type==="text"))return;const fields=new Map;for(const node of this.renderRoot.querySelectorAll(`${tag("input")}[data-filter-id]`)){const element=node,id=element.dataset.filterId;id!==void 0&&fields.set(id,element)}for(const def of this._filters){if(def.type!=="text"||this.hasPendingDebounce(def.filterId))continue;const field=fields.get(def.filterId);if(!field)continue;const raw=this._value[def.filterId],next=typeof raw=="string"?raw:"";field.value!==next&&(field.value=next)}}willUpdate(changed){super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.cancelDebounce()}updated(changed){if(super.updated(changed),this.syncTextControls(),changed.has("value")||changed.has("filters")){const invalidFilterIds=this.invalidFilterIds,valid=invalidFilterIds.length===0,key=JSON.stringify({valid,invalidFilterIds});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,invalidFilterIds:Object.freeze([...invalidFilterIds])})))}}renderStartAdornment(icon,slotName="start"){return icon==null?nothing:html`<span slot=${slotName} aria-hidden="true" inert>${icon}</span>`}renderOption(option){return html`<lr-option
2
2
  value=${option.value}
3
3
  search-text=${option.searchText??nothing}
4
4
  ?disabled=${option.disabled===!0}
5
5
  >${this.renderStartAdornment(option.icon)}${option.label}</lr-option
6
- >`}labelRouting(def){const hidden=def.labelVisibility==="hidden";return{label:hidden?"":def.label,placeholder:def.placeholder||(hidden?def.label:""),accessibleLabel:hidden?def.label:nothing}}labelAutoAttribute(def){return def.labelVisibility==="auto"}onCheckboxMenuToggle(def,event){if(event.stopPropagation(),event.preventDefault(),this.disabled)return;const detail=event.detail,current=this.valueFor(def),selected=Array.isArray(current)?current.filter(entry=>typeof entry=="string"):[],next=detail.checked?selected.includes(detail.value)?selected:[...selected,detail.value]:selected.filter(entry=>entry!==detail.value);this.setFilterValue(def.filterId,Object.freeze(next))}renderCheckboxMenu(def,value,errorText){const selected=Array.isArray(value)?value.filter(entry=>typeof entry=="string"):[],size=def.size??"m",routing=this.labelRouting(def),summary=selected.length>0?this.displayValueFor(def,value):routing.placeholder,showLabel=def.labelVisibility!=="hidden"||summary!==def.label;return html`<div
6
+ >`}labelRouting(def){const hidden=def.labelVisibility==="hidden";return{label:hidden?"":def.label,placeholder:def.placeholder||(hidden?def.label:""),accessibleLabel:hidden?def.label:nothing}}labelAutoAttribute(def){return def.labelVisibility==="auto"}onCheckboxMenuToggle(def,event){if(event.stopPropagation(),event.preventDefault(),this.disabled)return;const detail=event.detail,current=this.valueFor(def),selected=Array.isArray(current)?current.filter(entry=>typeof entry=="string"):[],next=detail.checked?selected.includes(detail.value)?selected:[...selected,detail.value]:selected.filter(entry=>entry!==detail.value);this.setFilterValue(def.filterId,Object.freeze(next))}renderCheckboxMenu(def,value,errorText){const selected=Array.isArray(value)?value.filter(entry=>typeof entry=="string"):[],selectedValues=new Set(selected),size=def.size??"m",routing=this.labelRouting(def),summary=selected.length>0?this.displayValueFor(def,value):routing.placeholder,showLabel=def.labelVisibility!=="hidden"||summary!==def.label;return html`<div
7
7
  part="filter-control"
8
8
  class="checkbox-menu"
9
9
  ?data-label-auto=${this.labelAutoAttribute(def)}
@@ -35,7 +35,7 @@ import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../intern
35
35
  part="filter-control-option"
36
36
  type="checkbox"
37
37
  value=${option.value}
38
- ?checked=${selected.includes(option.value)}
38
+ ?checked=${selectedValues.has(option.value)}
39
39
  ?disabled=${option.disabled===!0}
40
40
  @lr-menu-item-change-request=${event=>this.onCheckboxMenuToggle(def,event)}
41
41
  @lr-menu-item-change=${this.stopMenuItemChangeAlias}
@@ -1,4 +1,4 @@
1
- var _a;import{__decorate}from"tslib";import{maxCssTime}from"../../../internal/css-motion-time.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{isRovingTargetAvailable,resolveListMove}from"../../../internal/list-navigation.js";import{PopupController}from"../../../internal/popup-controller.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{collectFocusableElements,composedContains}from"../../../internal/overlay-manager.js";import{styles}from"./menu.styles.js";import{menuItemOwner,submenuPanelController}from"./menu-shared.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{activeElementIn,isUsableActiveElement,safeDeepActiveElement}from"../../../internal/active-element.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import"./menu-item.class.js";import{LYRA_DEFAULT_menuLabel}from"../../../internal/default-strings/shared.generated.js";const SUBMENU_PLACEMENT="right-start",SUBMENU_FALLBACK_PLACEMENTS=["right-end","left-start","left-end","bottom-start","top-start"],MENUBAR_PLACEMENT="bottom-start",SUBMENU_OPEN_DELAY=150,SUBMENU_CLOSE_DELAY=300;function isLyraMenuItemElement(value){return isHtmlElement(value)?value.localName===tag("menu-item")||value.localName===tag("dropdown-item"):!1}function isLyraMenuElement(value){return isHtmlElement(value)&&value.localName===tag("menu")}let menuWidthScaleRegistered=!1;function registerMenuWidthScale(){if(!menuWidthScaleRegistered&&(menuWidthScaleRegistered=!0,!(typeof CSS>"u"||typeof CSS.registerProperty!="function")))try{CSS.registerProperty({name:"--_lr-menu-max-inline-size",syntax:"<length-percentage>",inherits:!1,initialValue:"100%"})}catch{}}class LyraMenu extends LyraElement{constructor(){super(...arguments),this.presentationOpen=!1,this.presentationHidden=!0,this.submenuAnchor=null,this.submenuStateChange=null,this.dropdownContained=!1,this.dropdownOwner=null,this._dropdownOpen=!1,this.dropdownRendersMenuRole=!1,this.dropdownStayOpenOnSelect=!1,this.items=[],this.activeIndex=-1,this.presentationPositioned=!1,this.popupController=new PopupController({host:this,onPointer:event=>this.onDocPointer(event)}),this.menubarAnchored=!1,this.pendingFocus="first",this.listId=nextId("menu-list"),this.owningMenu={activate:item=>this.onOwnedItemSelect(item),uncheckRadioGroup:(item,group)=>this.uncheckRadioGroupSiblings(item,group)},this.typeBuffer=new TypeAheadBuffer(this),this[_a]=this.createSubmenuController(),this.onRegionSlotChange=()=>{this.syncRegionState()},this.onDocPointer=e=>{const path=e.composedPath();path.includes(this)||this.submenuAnchor&&path.includes(this.submenuAnchor)||this.closePresentation()},this.onItemsSlotChange=e=>{this.syncItemsFromSlot(e.target)},this.itemStateChangeReconciliationPending=!1,this.onItemStateChangeEvent=event=>{event.stopPropagation(),!this.itemStateChangeReconciliationPending&&(this.itemStateChangeReconciliationPending=!0,queueMicrotask(()=>{this.itemStateChangeReconciliationPending=!1,this.onItemStateChange()}))},this.onItemStateChange=()=>{const navigable=this.items.filter(item=>this.isNavigable(item));if(this.activeIndex>=0&&!this.isNavigable(this.items[this.activeIndex])){const current=this.activeIndex,displaced=this.items[current],focused=safeDeepActiveElement(this.ownerDocument),displacedHadFocus=focused===null||focused===this.ownerDocument.body||focused===displaced||composedContains(displaced,focused),next=navigable.find(item=>this.items.indexOf(item)>current)??navigable.find(item=>this.items.indexOf(item)<current);next?this.setActiveItem(next,displacedHadFocus):(this.activeIndex=-1,this.applyRovingTabIndex(),displacedHadFocus&&this.rehomeZeroSurvivorFocus());return}this.applyRovingTabIndex()},this.onListFocusIn=e=>{const target=e.target;if(!isLyraMenuItemElement(target))return;const index=this.items.indexOf(target);index===-1||index===this.activeIndex||!this.isNavigable(target)||(this.activeIndex=index,this.applyRovingTabIndex(),this.closeSubmenus(target))},this.onListKeyDown=e=>{if(this.isForeignEvent(e)||e.altKey||e.ctrlKey||e.metaKey||e.isComposing||e.keyCode===229)return;const isItemTarget=isLyraMenuItemElement(e.target);if(e.key==="Escape"&&isItemTarget&&!this.hasStandalonePresentation){e.preventDefault(),this.closePresentation({focusTrigger:!0});return}if(!isItemTarget)return;const navigable=this.items.filter(i=>this.isNavigable(i)),current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentNavIndex=current?navigable.indexOf(current):-1,intoSubmenuKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight";switch(e.key){case"ArrowRight":case"ArrowLeft":e.key===intoSubmenuKey?current?.hasSubmenu&&this.isNavigable(current)&&(e.preventDefault(),this.closeSubmenus(current),current.openSubmenu("first")):this.submenuAnchor&&!this.menubarAnchored&&(e.preventDefault(),this.closePresentation({focusTrigger:!0}));break;case"ArrowDown":case"ArrowUp":case"Home":case"End":{e.preventDefault();const nextIndex=resolveListMove(e,{count:navigable.length,current:currentNavIndex,orientation:"vertical"});nextIndex!==null&&this.setActiveItem(navigable[nextIndex]);break}case"Enter":case" ":e.preventDefault(),current?.hasSubmenu?(this.closeSubmenus(current),current.openSubmenu("first")):current?.isLinkItem?current.click():current?.select();break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);return}},this.onPopupPointerOver=e=>{if(!this.interactionOpen)return;const hovered=this.ownItemFromEvent(e);this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&opened===hovered?(this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuCloseTimer=void 0):opened&&this.scheduleSubmenuClose(opened),!(!hovered||hovered===opened||!hovered.hasSubmenu||!this.isNavigable(hovered))&&(this.submenuOpenTimer=this.scheduleOwnedTimeout(()=>{this.submenuOpenTimer=void 0,!(!this.interactionOpen||!this.items.includes(hovered))&&(this.closeSubmenus(hovered),hovered.openSubmenu("none"))},SUBMENU_OPEN_DELAY))},this.onPopupPointerLeave=()=>{this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&this.scheduleSubmenuClose(opened)},this.onNestedSelect=e=>{if(e.target===this)return;const event=e;this.dropdownStayOpenOnSelect&&event.preventDefault(),queueMicrotask(()=>{event.defaultPrevented||this.dismissAfterSelection(!0)})},this.onPopupKeyDown=e=>{const listEl=this.popupPart("list");if(e.key==="Escape"){if(listEl&&e.composedPath().includes(listEl)||this.hasStandalonePresentation)return;e.preventDefault(),this.closePresentation({focusTrigger:!0});return}e.key==="Tab"&&this.tabWouldLeavePopup(e)&&this.closePresentation()}}static{_a=submenuPanelController}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-select"])}static{this.identityEventDetailProperties=Object.freeze({"lr-select":Object.freeze(["item"])})}static{this.styles=[LyraElement.styles,styles]}get dropdownOpen(){return this._dropdownOpen}set dropdownOpen(next){const normalized=!!next;if(normalized===this._dropdownOpen)return;const old=this._dropdownOpen;this._dropdownOpen=normalized,this.presentationOpen=normalized,this.requestUpdate("dropdownOpen",old)}createSubmenuController(){const menu=this;return{get open(){return menu.submenuAnchor!==null&&menu.presentationOpen},attach(anchor,onStateChange,options){menu.submenuAnchor&&menu.submenuAnchor!==anchor&&menu.closePresentation(),menu.menubarAnchored=options?.menubar===!0,menu.submenuAnchor=anchor,menu.submenuStateChange=onStateChange,menu.syncPresentationState(),menu.requestUpdate()},detach(anchor){menu.submenuAnchor===anchor&&(menu.closePresentation(),menu.submenuAnchor=null,menu.menubarAnchored=!1,menu.submenuStateChange=null,menu.cleanup?.(),menu.cleanup=void 0,menu.syncPresentationState(),menu.requestUpdate())},async show(focus="first"){menu.submenuAnchor&&(menu.openPresentation(focus),await menu.updateComplete,await menu.focusAfterPlacement(focus))},async hide(options){menu.closePresentation(options),await menu.updateComplete}}}connectedCallback(){if(super.connectedCallback(),registerMenuWidthScale(),this.hasUpdated){const slot=this.renderRoot.querySelector("slot:not([name])");slot&&this.syncItemsFromSlot(slot)}}firstUpdated(changed){super.firstUpdated(changed),this.syncRegionState(),this.syncPresentationState();const slot=this.itemsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.syncItemsFromSlot(s))})}get hasStandalonePresentation(){return!this.dropdownContained&&!this.submenuAnchor}get interactionOpen(){return this.hasStandalonePresentation||this.presentationOpen}syncPresentationState(){const standalone=this.hasStandalonePresentation;if(this.toggleAttribute("data-inline",standalone),this.toggleAttribute("data-submenu",this.submenuAnchor!==null),this.toggleAttribute("data-contained",this.dropdownContained),standalone){const active=this.activeIndex>=0?this.items[this.activeIndex]:void 0;if(!active||!this.isNavigable(active)){const first=this.items.find(item=>this.isNavigable(item));this.activeIndex=first?this.items.indexOf(first):-1}}else this.presentationOpen||(this.activeIndex=-1);this.applyRovingTabIndex()}syncRegionState(){const assigned=selector=>this.renderRoot.querySelector(selector)?.assignedElements({flatten:!0}).length??0;this.toggleAttribute("data-has-header",assigned('slot[name="header"]')>0),this.toggleAttribute("data-has-footer",assigned('slot[name="footer"]')>0),this.toggleAttribute("data-list-empty",assigned("slot:not([name])")===0)}willUpdate(changed){super.willUpdate(changed),this.presentationOpen&&this.submenuAnchor&&(this.cancelPresentationHideWatch(),this.presentationHidden=!1)}updated(changed){super.updated(changed);const list=this.renderRoot.querySelector('[part~="list"]')??void 0;syncAriaDescribedByElements(this,list,this.getAttribute("aria-describedby")),(changed.has("presentationOpen")||changed.has("dropdownOpen")||changed.has("dropdownContained"))&&(this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.presentationOpen?this.submenuAnchor?(this.popupController.bindPointer(),this.reposition()):(this.popupController.unbindPointer(),this.presentationPositioned=!0,this.focusRoving(this.pendingFocus)):(this.popupController.unbindPointer(),this.resetTypeAhead(),this.activeIndex=-1,this.applyRovingTabIndex(),this.clearSubmenuTimers(),this.closeSubmenus(),this.submenuAnchor&&this.schedulePresentationHide())),changed.has("dropdownContained")&&this.syncPresentationState(),changed.has("dropdownSize")&&this.applyDropdownSize()}reposition(){this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1;const popup=this.renderRoot.querySelector(".submenu-surface");if(this.submenuAnchor&&popup){const placement=this.menubarAnchored?MENUBAR_PLACEMENT:rtlAwarePlacement(SUBMENU_PLACEMENT,this),topLayer=this.submenuAnchor.closest(tag("menubar"))?.topLayer===!0;this.placedTopLayer=syncTopLayerRelease(popup,this.placedTopLayer,topLayer),this.cleanup=place(this.submenuAnchor,popup,{placement,flipFallbackPlacements:this.menubarAnchored?void 0:SUBMENU_FALLBACK_PLACEMENTS.map(candidate=>rtlAwarePlacement(candidate,this)),...topLayerPlacement(topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))})}}cancelPresentationHideWatch(){this.presentationHideWatcher?.(),this.presentationHideWatcher=void 0}schedulePresentationHide(){this.cancelPresentationHideWatch();const surface=this.renderRoot.querySelector(".submenu-surface"),view=this.ownerDocument.defaultView,transitionMs=surface&&view?maxCssTime(view.getComputedStyle(surface).transitionDuration)+maxCssTime(view.getComputedStyle(surface).transitionDelay):0,waitForEvent=!!(surface&&view&&transitionMs>0&&!prefersReducedMotion(this));let settled=!1,timeout;const finish=()=>{settled||(settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd),this.presentationHideWatcher===cancel&&(this.presentationHideWatcher=void 0),this.presentationHidden=!0)},onEnd=event=>{event.target===surface&&finish()},cancel=()=>{settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd)};this.presentationHideWatcher=cancel,waitForEvent&&surface&&view?(surface.addEventListener("transitionend",onEnd),timeout=view.setTimeout(finish,transitionMs+50)):queueMicrotask(finish)}async focusAfterPlacement(focus){if(!this.presentationOpen||!this.submenuAnchor)return;const positioned=this.cleanup!==void 0&&(this.presentationPositioned||await waitForDeferredPlacement(()=>this.cleanup));if(!(!this.presentationOpen||!this.submenuAnchor)){if(!positioned){this.closePresentation(),await this.updateComplete;return}this.presentationPositioned=!0,this.focusRoving(focus)}}disconnectedCallback(){super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.resetTypeAhead(),this.clearSubmenuTimers(),this.itemStateObserver?.disconnect(),this.itemStateObserver=void 0,this.popupController.unbindPointer();for(const item of this.items)this.releaseItemOwner(item);this._dropdownOpen=!1,this.presentationOpen=!1,this.cancelPresentationHideWatch(),this.presentationHidden=!0,this.submenuStateChange?.(!1)}scheduleOwnedTimeout(callback,delay){const owner=this.ownerDocument.defaultView;if(owner)return{owner,handle:owner.setTimeout(callback,delay)}}clearOwnedTimeout(timer){timer&&timer.owner.clearTimeout(timer.handle)}focusContained(focus="first"){if(this.dropdownContained&&this.dropdownOwner)if(this.dropdownOwner.open)this.pendingFocus=focus,this.focusRoving(focus);else{const transition=this.dropdownOwner.show();this.dropdownOwner.open&&(this.pendingFocus=focus)}}openPresentation(focus="first"){if(this.dropdownContained&&this.dropdownOwner){this.focusContained(focus);return}this.pendingFocus=focus,this.presentationOpen?(!this.submenuAnchor||this.presentationPositioned)&&this.focusRoving(focus):(this.presentationOpen=!0,this.submenuStateChange?.(!0))}closePresentation(options){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide(options);return}this.presentationOpen&&(this.presentationOpen=!1,this.submenuStateChange?.(!1),options?.focusTrigger&&this.submenuAnchor&&resolveAccessibleTrigger(this.submenuAnchor).focus())}syncItemsFromSlot(slot){const assigned=slot.assignedElements({flatten:!0}).filter(isLyraMenuItemElement);if(assigned.length===this.items.length&&assigned.every((item,index)=>item===this.items[index]))return;this.itemStateObserver?.disconnect();const previousItems=this.items,previouslyActive=this.activeIndex>=0?this.items[this.activeIndex]:void 0,focusedBefore=safeDeepActiveElement(this.ownerDocument),activeItemLostFocus=!!previouslyActive&&(focusedBefore===null||focusedBefore===this.ownerDocument.body||focusedBefore===previouslyActive||composedContains(previouslyActive,focusedBefore));this.items=assigned;for(const item of previousItems)this.items.includes(item)||this.releaseItemOwner(item);for(const item of this.items)this.acquireItemOwner(item);this.applyDropdownSize();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){const owner=this.ownerDocument;let observer;observer=new MutationObserverCtor(()=>{this.itemStateObserver!==observer||this.ownerDocument!==owner||this.onItemStateChange()}),this.itemStateObserver=observer;for(const item of this.items)this.itemStateObserver.observe(item,{attributes:!0,attributeFilter:["disabled","hidden","aria-hidden","inert"]})}if(this.activeIndex=previouslyActive?this.items.indexOf(previouslyActive):-1,this.syncPresentationState(),this.syncRegionState(),this.interactionOpen)if(this.activeIndex===-1){const successor=this.items.find(item=>this.isNavigable(item));previouslyActive&&successor?this.setActiveItem(successor,activeItemLostFocus):this.focusRoving(this.pendingFocus),activeItemLostFocus&&!this.items.some(item=>this.isNavigable(item))&&this.rehomeZeroSurvivorFocus()}else{const active=activeElementIn(this.ownerDocument);!(isUsableActiveElement(active)&&this.contains(active))&&activeItemLostFocus&&this.items[this.activeIndex].focus()}}acquireItemOwner(item){item[menuItemOwner]?.(this.owningMenu)}releaseItemOwner(item){item[menuItemOwner]?.(null,this.owningMenu)}uncheckRadioGroupSiblings(item,group){for(const sibling of this.items)sibling!==item&&sibling.type==="radio"&&sibling.group===group&&sibling.checked&&(sibling.checked=!1)}isNavigable(item){return!item.interactionDisabled&&isRovingTargetAvailable(item)}applyDropdownSize(){if(this.dropdownSize)for(const item of this.items)item.size=this.dropdownSize}rehomeZeroSurvivorFocus(){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide({focusTrigger:!0});return}if(this.submenuAnchor){this.closePresentation({focusTrigger:!0});return}const list=this.renderRoot.querySelector('[part~="list"]');list&&(list.tabIndex=-1,list.focus({preventScroll:!0}))}onOwnedItemSelect(item){if(!isLyraMenuItemElement(item)||!this.items.includes(item))return;!this.emit("lr-select",{item},{cancelable:!0}).defaultPrevented&&!this.dropdownStayOpenOnSelect&&this.dismissAfterSelection(!0)}dismissAfterSelection(focusTrigger){this.closeSubmenus(),this.dropdownContained?this.dropdownOwner&&this.dropdownOwner.hide({focusTrigger}):this.submenuAnchor&&this.closePresentation({focusTrigger})}applyRovingTabIndex(){this.items.forEach((item,i)=>{item.tabIndex=i===this.activeIndex?0:-1})}focusRoving(which){if(which==="none")return;const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const item=which==="first"?navigable[0]:navigable[navigable.length-1];item&&this.setActiveItem(item)}setActiveItem(item,moveFocus=!0){this.activeIndex=this.items.indexOf(item),this.applyRovingTabIndex(),this.closeSubmenus(item),moveFocus&&item.focus()}closeSubmenus(keep){for(const item of this.items)item!==keep&&item.submenuOpen&&item.closeSubmenu()}openSubmenuItem(){return this.items.find(item=>item.submenuOpen)}clearSubmenuTimers(){this.clearOwnedTimeout(this.submenuOpenTimer),this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuOpenTimer=void 0,this.submenuCloseTimer=void 0}ownItemFromEvent(e){let owner;for(const node of e.composedPath()){if(node===this)break;isLyraMenuItemElement(node)&&(owner=node)}return owner}isForeignEvent(e){for(const node of e.composedPath()){if(node===this)return!1;if(isLyraMenuElement(node))return!0}return!1}scheduleSubmenuClose(item){this.submenuCloseTimer||(this.submenuCloseTimer=this.scheduleOwnedTimeout(()=>{this.submenuCloseTimer=void 0,item.submenuOpen&&(composedContains(item,safeDeepActiveElement(this.ownerDocument))||item.closeSubmenu())},SUBMENU_CLOSE_DELAY))}popupPart(name){return this.renderRoot.querySelector(`[part="${name}"]`)}tabWouldLeavePopup(e){const header=this.popupPart("header"),footer=this.popupPart("footer"),listEl=this.popupPart("list"),backwards=e.shiftKey,active=safeDeepActiveElement(this.ownerDocument),headerStops=header?collectFocusableElements(header):[],footerStops=footer?collectFocusableElements(footer):[],listStops=listEl?collectFocusableElements(listEl):[],hasNeighbor=stops=>{const index=active?stops.indexOf(active):-1;return index===-1?!1:backwards?index>0:index<stops.length-1},path=e.composedPath();return footer&&path.includes(footer)?hasNeighbor(footerStops)?!1:backwards?listStops.length===0&&headerStops.length===0:!0:header&&path.includes(header)?hasNeighbor(headerStops)?!1:backwards?!0:listStops.length===0&&footerStops.length===0:!isLyraMenuItemElement(e.target)&&hasNeighbor(listStops)?!1:backwards?headerStops.length===0:footerStops.length===0}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentIndex=current?navigable.indexOf(current):-1,match=this.typeBuffer.match(navigable,currentIndex,item=>item.getTextLabel(),this.effectiveLocale);match!==null&&this.setActiveItem(navigable[match])}resetTypeAhead(){this.typeBuffer.clear()}get effectiveLabel(){const hostLabel=this.getAttribute("aria-label");return hostLabel!==null?hostLabel:this.label!==void 0?this.label:this.dropdownLabel!==void 0?this.dropdownLabel:this.localize("menuLabel")}renderContents(bindPointerOver=!0){return html`
1
+ var _a;import{__decorate}from"tslib";import{maxCssTime}from"../../../internal/css-motion-time.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{isRovingTargetAvailable,resolveListMove}from"../../../internal/list-navigation.js";import{PopupController}from"../../../internal/popup-controller.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{collectFocusableElements,composedContains}from"../../../internal/overlay-manager.js";import{styles}from"./menu.styles.js";import{menuItemOwner,submenuPanelController}from"./menu-shared.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{activeElementIn,isUsableActiveElement,safeDeepActiveElement}from"../../../internal/active-element.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import"./menu-item.class.js";import{LYRA_DEFAULT_menuLabel}from"../../../internal/default-strings/shared.generated.js";const SUBMENU_PLACEMENT="right-start",SUBMENU_FALLBACK_PLACEMENTS=["right-end","left-start","left-end","bottom-start","top-start"],MENUBAR_PLACEMENT="bottom-start",SUBMENU_OPEN_DELAY=150,SUBMENU_CLOSE_DELAY=300;function isLyraMenuItemElement(value){return isHtmlElement(value)?value.localName===tag("menu-item")||value.localName===tag("dropdown-item"):!1}function isLyraMenuElement(value){return isHtmlElement(value)&&value.localName===tag("menu")}let menuWidthScaleRegistered=!1;function registerMenuWidthScale(){if(!menuWidthScaleRegistered&&(menuWidthScaleRegistered=!0,!(typeof CSS>"u"||typeof CSS.registerProperty!="function")))try{CSS.registerProperty({name:"--_lr-menu-max-inline-size",syntax:"<length-percentage>",inherits:!1,initialValue:"100%"})}catch{}}class LyraMenu extends LyraElement{constructor(){super(...arguments),this.presentationOpen=!1,this.presentationHidden=!0,this.submenuAnchor=null,this.submenuStateChange=null,this.dropdownContained=!1,this.dropdownOwner=null,this._dropdownOpen=!1,this.dropdownRendersMenuRole=!1,this.dropdownStayOpenOnSelect=!1,this.items=[],this.activeIndex=-1,this.presentationPositioned=!1,this.popupController=new PopupController({host:this,onPointer:event=>this.onDocPointer(event)}),this.menubarAnchored=!1,this.pendingFocus="first",this.listId=nextId("menu-list"),this.owningMenu={activate:item=>this.onOwnedItemSelect(item),uncheckRadioGroup:(item,group)=>this.uncheckRadioGroupSiblings(item,group)},this.typeBuffer=new TypeAheadBuffer(this),this[_a]=this.createSubmenuController(),this.onRegionSlotChange=()=>{this.syncRegionState()},this.onDocPointer=e=>{const path=e.composedPath();path.includes(this)||this.submenuAnchor&&path.includes(this.submenuAnchor)||this.closePresentation()},this.onItemsSlotChange=e=>{this.syncItemsFromSlot(e.target)},this.itemStateChangeReconciliationPending=!1,this.onItemStateChangeEvent=event=>{event.stopPropagation(),!this.itemStateChangeReconciliationPending&&(this.itemStateChangeReconciliationPending=!0,queueMicrotask(()=>{this.itemStateChangeReconciliationPending=!1,this.onItemStateChange()}))},this.onItemStateChange=()=>{const navigable=[];if(this.items.forEach((item,index)=>{this.isNavigable(item)&&navigable.push({item,index})}),this.activeIndex>=0&&!this.isNavigable(this.items[this.activeIndex])){const current=this.activeIndex,displaced=this.items[current],focused=safeDeepActiveElement(this.ownerDocument),displacedHadFocus=focused===null||focused===this.ownerDocument.body||focused===displaced||composedContains(displaced,focused),next=navigable.find(({index})=>index>current)?.item??navigable.find(({index})=>index<current)?.item;next?this.setActiveItem(next,displacedHadFocus):(this.activeIndex=-1,this.applyRovingTabIndex(),displacedHadFocus&&this.rehomeZeroSurvivorFocus());return}this.applyRovingTabIndex()},this.onListFocusIn=e=>{const target=e.target;if(!isLyraMenuItemElement(target))return;const index=this.items.indexOf(target);index===-1||index===this.activeIndex||!this.isNavigable(target)||(this.activeIndex=index,this.applyRovingTabIndex(),this.closeSubmenus(target))},this.onListKeyDown=e=>{if(this.isForeignEvent(e)||e.altKey||e.ctrlKey||e.metaKey||e.isComposing||e.keyCode===229)return;const isItemTarget=isLyraMenuItemElement(e.target);if(e.key==="Escape"&&isItemTarget&&!this.hasStandalonePresentation){e.preventDefault(),this.closePresentation({focusTrigger:!0});return}if(!isItemTarget)return;const navigable=this.items.filter(i=>this.isNavigable(i)),current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentNavIndex=current?navigable.indexOf(current):-1,intoSubmenuKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight";switch(e.key){case"ArrowRight":case"ArrowLeft":e.key===intoSubmenuKey?current?.hasSubmenu&&this.isNavigable(current)&&(e.preventDefault(),this.closeSubmenus(current),current.openSubmenu("first")):this.submenuAnchor&&!this.menubarAnchored&&(e.preventDefault(),this.closePresentation({focusTrigger:!0}));break;case"ArrowDown":case"ArrowUp":case"Home":case"End":{e.preventDefault();const nextIndex=resolveListMove(e,{count:navigable.length,current:currentNavIndex,orientation:"vertical"});nextIndex!==null&&this.setActiveItem(navigable[nextIndex]);break}case"Enter":case" ":e.preventDefault(),current?.hasSubmenu?(this.closeSubmenus(current),current.openSubmenu("first")):current?.isLinkItem?current.click():current?.select();break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);return}},this.onPopupPointerOver=e=>{if(!this.interactionOpen)return;const hovered=this.ownItemFromEvent(e);this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&opened===hovered?(this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuCloseTimer=void 0):opened&&this.scheduleSubmenuClose(opened),!(!hovered||hovered===opened||!hovered.hasSubmenu||!this.isNavigable(hovered))&&(this.submenuOpenTimer=this.scheduleOwnedTimeout(()=>{this.submenuOpenTimer=void 0,!(!this.interactionOpen||!this.items.includes(hovered))&&(this.closeSubmenus(hovered),hovered.openSubmenu("none"))},SUBMENU_OPEN_DELAY))},this.onPopupPointerLeave=()=>{this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&this.scheduleSubmenuClose(opened)},this.onNestedSelect=e=>{if(e.target===this)return;const event=e;this.dropdownStayOpenOnSelect&&event.preventDefault(),queueMicrotask(()=>{event.defaultPrevented||this.dismissAfterSelection(!0)})},this.onPopupKeyDown=e=>{const listEl=this.popupPart("list");if(e.key==="Escape"){if(listEl&&e.composedPath().includes(listEl)||this.hasStandalonePresentation)return;e.preventDefault(),this.closePresentation({focusTrigger:!0});return}e.key==="Tab"&&this.tabWouldLeavePopup(e)&&this.closePresentation()}}static{_a=submenuPanelController}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-select"])}static{this.identityEventDetailProperties=Object.freeze({"lr-select":Object.freeze(["item"])})}static{this.styles=[LyraElement.styles,styles]}get dropdownOpen(){return this._dropdownOpen}set dropdownOpen(next){const normalized=!!next;if(normalized===this._dropdownOpen)return;const old=this._dropdownOpen;this._dropdownOpen=normalized,this.presentationOpen=normalized,this.requestUpdate("dropdownOpen",old)}createSubmenuController(){const menu=this;return{get open(){return menu.submenuAnchor!==null&&menu.presentationOpen},attach(anchor,onStateChange,options){menu.submenuAnchor&&menu.submenuAnchor!==anchor&&menu.closePresentation(),menu.menubarAnchored=options?.menubar===!0,menu.submenuAnchor=anchor,menu.submenuStateChange=onStateChange,menu.syncPresentationState(),menu.requestUpdate()},detach(anchor){menu.submenuAnchor===anchor&&(menu.closePresentation(),menu.submenuAnchor=null,menu.menubarAnchored=!1,menu.submenuStateChange=null,menu.cleanup?.(),menu.cleanup=void 0,menu.syncPresentationState(),menu.requestUpdate())},async show(focus="first"){menu.submenuAnchor&&(menu.openPresentation(focus),await menu.updateComplete,await menu.focusAfterPlacement(focus))},async hide(options){menu.closePresentation(options),await menu.updateComplete}}}connectedCallback(){if(super.connectedCallback(),registerMenuWidthScale(),this.hasUpdated){const slot=this.renderRoot.querySelector("slot:not([name])");slot&&this.syncItemsFromSlot(slot)}}firstUpdated(changed){super.firstUpdated(changed),this.syncRegionState(),this.syncPresentationState();const slot=this.itemsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.syncItemsFromSlot(s))})}get hasStandalonePresentation(){return!this.dropdownContained&&!this.submenuAnchor}get interactionOpen(){return this.hasStandalonePresentation||this.presentationOpen}syncPresentationState(){const standalone=this.hasStandalonePresentation;if(this.toggleAttribute("data-inline",standalone),this.toggleAttribute("data-submenu",this.submenuAnchor!==null),this.toggleAttribute("data-contained",this.dropdownContained),standalone){const active=this.activeIndex>=0?this.items[this.activeIndex]:void 0;if(!active||!this.isNavigable(active)){const first=this.items.find(item=>this.isNavigable(item));this.activeIndex=first?this.items.indexOf(first):-1}}else this.presentationOpen||(this.activeIndex=-1);this.applyRovingTabIndex()}syncRegionState(){const assigned=selector=>this.renderRoot.querySelector(selector)?.assignedElements({flatten:!0}).length??0;this.toggleAttribute("data-has-header",assigned('slot[name="header"]')>0),this.toggleAttribute("data-has-footer",assigned('slot[name="footer"]')>0),this.toggleAttribute("data-list-empty",assigned("slot:not([name])")===0)}willUpdate(changed){super.willUpdate(changed),this.presentationOpen&&this.submenuAnchor&&(this.cancelPresentationHideWatch(),this.presentationHidden=!1)}updated(changed){super.updated(changed);const list=this.renderRoot.querySelector('[part~="list"]')??void 0;syncAriaDescribedByElements(this,list,this.getAttribute("aria-describedby")),(changed.has("presentationOpen")||changed.has("dropdownOpen")||changed.has("dropdownContained"))&&(this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.presentationOpen?this.submenuAnchor?(this.popupController.bindPointer(),this.reposition()):(this.popupController.unbindPointer(),this.presentationPositioned=!0,this.focusRoving(this.pendingFocus)):(this.popupController.unbindPointer(),this.resetTypeAhead(),this.activeIndex=-1,this.applyRovingTabIndex(),this.clearSubmenuTimers(),this.closeSubmenus(),this.submenuAnchor&&this.schedulePresentationHide())),changed.has("dropdownContained")&&this.syncPresentationState(),changed.has("dropdownSize")&&this.applyDropdownSize()}reposition(){this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1;const popup=this.renderRoot.querySelector(".submenu-surface");if(this.submenuAnchor&&popup){const placement=this.menubarAnchored?MENUBAR_PLACEMENT:rtlAwarePlacement(SUBMENU_PLACEMENT,this),topLayer=this.submenuAnchor.closest(tag("menubar"))?.topLayer===!0;this.placedTopLayer=syncTopLayerRelease(popup,this.placedTopLayer,topLayer),this.cleanup=place(this.submenuAnchor,popup,{placement,flipFallbackPlacements:this.menubarAnchored?void 0:SUBMENU_FALLBACK_PLACEMENTS.map(candidate=>rtlAwarePlacement(candidate,this)),...topLayerPlacement(topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))})}}cancelPresentationHideWatch(){this.presentationHideWatcher?.(),this.presentationHideWatcher=void 0}schedulePresentationHide(){this.cancelPresentationHideWatch();const surface=this.renderRoot.querySelector(".submenu-surface"),view=this.ownerDocument.defaultView,transitionMs=surface&&view?maxCssTime(view.getComputedStyle(surface).transitionDuration)+maxCssTime(view.getComputedStyle(surface).transitionDelay):0,waitForEvent=!!(surface&&view&&transitionMs>0&&!prefersReducedMotion(this));let settled=!1,timeout;const finish=()=>{settled||(settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd),this.presentationHideWatcher===cancel&&(this.presentationHideWatcher=void 0),this.presentationHidden=!0)},onEnd=event=>{event.target===surface&&finish()},cancel=()=>{settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd)};this.presentationHideWatcher=cancel,waitForEvent&&surface&&view?(surface.addEventListener("transitionend",onEnd),timeout=view.setTimeout(finish,transitionMs+50)):queueMicrotask(finish)}async focusAfterPlacement(focus){if(!this.presentationOpen||!this.submenuAnchor)return;const positioned=this.cleanup!==void 0&&(this.presentationPositioned||await waitForDeferredPlacement(()=>this.cleanup));if(!(!this.presentationOpen||!this.submenuAnchor)){if(!positioned){this.closePresentation(),await this.updateComplete;return}this.presentationPositioned=!0,this.focusRoving(focus)}}disconnectedCallback(){super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.resetTypeAhead(),this.clearSubmenuTimers(),this.itemStateObserver?.disconnect(),this.itemStateObserver=void 0,this.popupController.unbindPointer();for(const item of this.items)this.releaseItemOwner(item);this._dropdownOpen=!1,this.presentationOpen=!1,this.cancelPresentationHideWatch(),this.presentationHidden=!0,this.submenuStateChange?.(!1)}scheduleOwnedTimeout(callback,delay){const owner=this.ownerDocument.defaultView;if(owner)return{owner,handle:owner.setTimeout(callback,delay)}}clearOwnedTimeout(timer){timer&&timer.owner.clearTimeout(timer.handle)}focusContained(focus="first"){if(this.dropdownContained&&this.dropdownOwner)if(this.dropdownOwner.open)this.pendingFocus=focus,this.focusRoving(focus);else{const transition=this.dropdownOwner.show();this.dropdownOwner.open&&(this.pendingFocus=focus)}}openPresentation(focus="first"){if(this.dropdownContained&&this.dropdownOwner){this.focusContained(focus);return}this.pendingFocus=focus,this.presentationOpen?(!this.submenuAnchor||this.presentationPositioned)&&this.focusRoving(focus):(this.presentationOpen=!0,this.submenuStateChange?.(!0))}closePresentation(options){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide(options);return}this.presentationOpen&&(this.presentationOpen=!1,this.submenuStateChange?.(!1),options?.focusTrigger&&this.submenuAnchor&&resolveAccessibleTrigger(this.submenuAnchor).focus())}syncItemsFromSlot(slot){const assigned=slot.assignedElements({flatten:!0}).filter(isLyraMenuItemElement);if(assigned.length===this.items.length&&assigned.every((item,index)=>item===this.items[index]))return;this.itemStateObserver?.disconnect();const previousItems=this.items,previouslyActive=this.activeIndex>=0?this.items[this.activeIndex]:void 0,focusedBefore=safeDeepActiveElement(this.ownerDocument),activeItemLostFocus=!!previouslyActive&&(focusedBefore===null||focusedBefore===this.ownerDocument.body||focusedBefore===previouslyActive||composedContains(previouslyActive,focusedBefore));this.items=assigned;const assignedItems=new Set(assigned);for(const item of previousItems)assignedItems.has(item)||this.releaseItemOwner(item);for(const item of this.items)this.acquireItemOwner(item);this.applyDropdownSize();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){const owner=this.ownerDocument;let observer;observer=new MutationObserverCtor(()=>{this.itemStateObserver!==observer||this.ownerDocument!==owner||this.onItemStateChange()}),this.itemStateObserver=observer;for(const item of this.items)this.itemStateObserver.observe(item,{attributes:!0,attributeFilter:["disabled","hidden","aria-hidden","inert"]})}if(this.activeIndex=previouslyActive?this.items.indexOf(previouslyActive):-1,this.syncPresentationState(),this.syncRegionState(),this.interactionOpen)if(this.activeIndex===-1){const successor=this.items.find(item=>this.isNavigable(item));previouslyActive&&successor?this.setActiveItem(successor,activeItemLostFocus):this.focusRoving(this.pendingFocus),activeItemLostFocus&&!this.items.some(item=>this.isNavigable(item))&&this.rehomeZeroSurvivorFocus()}else{const active=activeElementIn(this.ownerDocument);!(isUsableActiveElement(active)&&this.contains(active))&&activeItemLostFocus&&this.items[this.activeIndex].focus()}}acquireItemOwner(item){item[menuItemOwner]?.(this.owningMenu)}releaseItemOwner(item){item[menuItemOwner]?.(null,this.owningMenu)}uncheckRadioGroupSiblings(item,group){for(const sibling of this.items)sibling!==item&&sibling.type==="radio"&&sibling.group===group&&sibling.checked&&(sibling.checked=!1)}isNavigable(item){return!item.interactionDisabled&&isRovingTargetAvailable(item)}applyDropdownSize(){if(this.dropdownSize)for(const item of this.items)item.size=this.dropdownSize}rehomeZeroSurvivorFocus(){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide({focusTrigger:!0});return}if(this.submenuAnchor){this.closePresentation({focusTrigger:!0});return}const list=this.renderRoot.querySelector('[part~="list"]');list&&(list.tabIndex=-1,list.focus({preventScroll:!0}))}onOwnedItemSelect(item){if(!isLyraMenuItemElement(item)||!this.items.includes(item))return;!this.emit("lr-select",{item},{cancelable:!0}).defaultPrevented&&!this.dropdownStayOpenOnSelect&&this.dismissAfterSelection(!0)}dismissAfterSelection(focusTrigger){this.closeSubmenus(),this.dropdownContained?this.dropdownOwner&&this.dropdownOwner.hide({focusTrigger}):this.submenuAnchor&&this.closePresentation({focusTrigger})}applyRovingTabIndex(){this.items.forEach((item,i)=>{item.tabIndex=i===this.activeIndex?0:-1})}focusRoving(which){if(which==="none")return;const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const item=which==="first"?navigable[0]:navigable[navigable.length-1];item&&this.setActiveItem(item)}setActiveItem(item,moveFocus=!0){this.activeIndex=this.items.indexOf(item),this.applyRovingTabIndex(),this.closeSubmenus(item),moveFocus&&item.focus()}closeSubmenus(keep){for(const item of this.items)item!==keep&&item.submenuOpen&&item.closeSubmenu()}openSubmenuItem(){return this.items.find(item=>item.submenuOpen)}clearSubmenuTimers(){this.clearOwnedTimeout(this.submenuOpenTimer),this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuOpenTimer=void 0,this.submenuCloseTimer=void 0}ownItemFromEvent(e){let owner;for(const node of e.composedPath()){if(node===this)break;isLyraMenuItemElement(node)&&(owner=node)}return owner}isForeignEvent(e){for(const node of e.composedPath()){if(node===this)return!1;if(isLyraMenuElement(node))return!0}return!1}scheduleSubmenuClose(item){this.submenuCloseTimer||(this.submenuCloseTimer=this.scheduleOwnedTimeout(()=>{this.submenuCloseTimer=void 0,item.submenuOpen&&(composedContains(item,safeDeepActiveElement(this.ownerDocument))||item.closeSubmenu())},SUBMENU_CLOSE_DELAY))}popupPart(name){return this.renderRoot.querySelector(`[part="${name}"]`)}tabWouldLeavePopup(e){const header=this.popupPart("header"),footer=this.popupPart("footer"),listEl=this.popupPart("list"),backwards=e.shiftKey,active=safeDeepActiveElement(this.ownerDocument),headerStops=header?collectFocusableElements(header):[],footerStops=footer?collectFocusableElements(footer):[],listStops=listEl?collectFocusableElements(listEl):[],hasNeighbor=stops=>{const index=active?stops.indexOf(active):-1;return index===-1?!1:backwards?index>0:index<stops.length-1},path=e.composedPath();return footer&&path.includes(footer)?hasNeighbor(footerStops)?!1:backwards?listStops.length===0&&headerStops.length===0:!0:header&&path.includes(header)?hasNeighbor(headerStops)?!1:backwards?!0:listStops.length===0&&footerStops.length===0:!isLyraMenuItemElement(e.target)&&hasNeighbor(listStops)?!1:backwards?headerStops.length===0:footerStops.length===0}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentIndex=current?navigable.indexOf(current):-1,match=this.typeBuffer.match(navigable,currentIndex,item=>item.getTextLabel(),this.effectiveLocale);match!==null&&this.setActiveItem(navigable[match])}resetTypeAhead(){this.typeBuffer.clear()}get effectiveLabel(){const hostLabel=this.getAttribute("aria-label");return hostLabel!==null?hostLabel:this.label!==void 0?this.label:this.dropdownLabel!==void 0?this.dropdownLabel:this.localize("menuLabel")}renderContents(bindPointerOver=!0){return html`
2
2
  <div part="header">
3
3
  <slot name="header" @slotchange=${this.onRegionSlotChange}></slot>
4
4
  </div>
@@ -1 +1 @@
1
- import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{isRovingTargetAvailable,resolveListMove}from"../../../internal/list-navigation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{activateNonmodalOverlay,composedContains,deepActiveElement}from"../../../internal/nonmodal-overlay-manager.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{keyEventOwnedByInnerControl}from"../../../internal/hotkey.js";import{sizes}from"../../../internal/sizes.styles.js";import{tag}from"../../../internal/prefix.js";import{menubarItemOwner}from"./menubar-shared.js";import{styles}from"./menubar.styles.js";import{LYRA_DEFAULT_menuLabel}from"../../../internal/default-strings/shared.generated.js";class LyraMenubar extends LyraElement{static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel}}static{this.styles=[LyraElement.styles,sizes,styles]}constructor(){super(),this.topLayer=!1,this.size="m",this.frame="card",this.items=[],this.activeIndex=-1,this.expandedItem=null,this.typeBuffer=new TypeAheadBuffer(this),this.focusedItem=null,this.owner={menuStateChanged:(item,open)=>this.menuStateChanged(item,open),itemStateChanged:()=>this.syncItemState()},this.syncItems=()=>{const assigned=(this.renderRoot.querySelector("slot")?.assignedElements({flatten:!0})??[]).filter(element=>element.localName===tag("menubar-item"));if(assigned.length===this.items.length&&assigned.every((item,index)=>item===this.items[index]))return;const previous=this.items[this.activeIndex],oldIndex=this.activeIndex,active=deepActiveElement(this.ownerDocument),heldFocus=!!previous&&(active===previous||!!active&&composedContains(previous,active)||this.focusedItem===previous&&(!active||active===this.ownerDocument.body));for(const item of this.items)assigned.includes(item)||item[menubarItemOwner](null,this.owner);this.items=assigned;for(const item of this.items)item[menubarItemOwner](this.owner);this.observeItems(),previous&&assigned.includes(previous)&&this.isNavigable(previous)?this.setActive(previous):this.rehome(oldIndex,heldFocus),this.expandedItem&&!assigned.includes(this.expandedItem)&&this.collapse()},this.onDocumentFocus=()=>{const active=deepActiveElement(this.ownerDocument);(!active||!composedContains(this,active))&&(this.focusedItem=null,this.collapse())},this.onClick=event=>{const found=this.eventItem(event);if(!found||found.inMenu)return;const{item}=found;if(this.setActive(item,!0),!item.hasMenu){this.expandedItem&&this.collapse();return}this.expandedItem===item?this.collapse():this.expandedItem?this.carry(item):this.open(item,"none")},this.onPointerOver=event=>{if(!this.expandedItem||event.pointerType==="touch")return;const found=this.eventItem(event);found&&!found.inMenu&&found.item.hasMenu&&found.item!==this.expandedItem&&this.carry(found.item)},this.onKeyDown=event=>{if(event.defaultPrevented||event.isComposing||event.keyCode===229||event.altKey||event.ctrlKey||event.metaKey)return;const found=this.eventItem(event);if(!found)return;const{item,inMenu}=found;if(inMenu){if(!isHtmlElement(event.target)||![tag("menu-item"),tag("dropdown-item")].includes(event.target.localName)||keyEventOwnedByInnerControl(event,{container:event.target})||event.key!=="ArrowLeft"&&event.key!=="ArrowRight")return}else if(event.target!==item||keyEventOwnedByInnerControl(event,{container:item}))return;const navigable=this.items.filter(candidate=>this.isNavigable(candidate));if(!navigable.length)return;const index=navigable.indexOf(item);let next;const nextIndex=resolveListMove(event,{count:navigable.length,current:index,orientation:"horizontal",direction:this.effectiveDirection});if(nextIndex!==null)next=navigable[nextIndex];else if(["ArrowDown","ArrowUp","Enter"," "].includes(event.key)){item.hasMenu?(event.preventDefault(),this.open(item,event.key==="ArrowUp"?"last":"first")):(event.key==="Enter"||event.key===" ")&&(event.preventDefault(),item.click());return}else if(this.typeBuffer.accepts(event)){this.typeBuffer.add(event.key,this.effectiveLocale);const match=this.typeBuffer.match(navigable,index,item2=>item2.textLabel,this.effectiveLocale);match!==null&&(next=navigable[match])}next&&(event.preventDefault(),this.move(next))},this.addEventListener("keydown",this.onKeyDown),this.addEventListener("click",this.onClick),this.addEventListener("pointerover",this.onPointerOver),this.addEventListener("focusin",event=>{const item=this.items.find(candidate=>candidate===event.target);item&&this.isNavigable(item)&&(this.focusedItem=item,this.setActive(item))})}connectedCallback(){if(super.connectedCallback(),this.hasUpdated){for(const item of this.items)item[menubarItemOwner](this.owner);this.observeItems(),queueMicrotask(()=>{this.isConnected&&(this.syncItems(),this.syncItemState())})}}disconnectedCallback(){this.collapse(),this.typeBuffer.clear(),this.itemObserver?.disconnect(),this.itemObserver=void 0,this.ownerDocument.removeEventListener("focusin",this.onDocumentFocus,!0);for(const item of this.items)item[menubarItemOwner](null,this.owner);this.focusedItem=null,super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed),queueMicrotask(()=>{this.isConnected&&collectInitialSlotAssignment(this.renderRoot.querySelector("slot"),this.syncItems)})}isNavigable(item){return isRovingTargetAvailable(item)}observeItems(){this.itemObserver?.disconnect();const Observer=this.ownerDocument.defaultView?.MutationObserver;if(Observer){this.itemObserver=new Observer(()=>this.syncItemState());for(const item of this.items)this.itemObserver.observe(item,{attributes:!0,attributeFilter:["disabled","hidden","aria-hidden","inert"]})}}rehome(index,focus){const successor=this.items.find((item,current)=>current>=Math.max(0,index)&&this.isNavigable(item))??this.items.slice(0,Math.max(0,index)).reverse().find(item=>this.isNavigable(item));if(successor)this.setActive(successor,focus);else{this.activeIndex=-1;for(const item of this.items)item.tabIndex=-1}}syncItemState(){const active=this.items[this.activeIndex];if(!active||!this.isNavigable(active)){const focused=deepActiveElement(this.ownerDocument);this.rehome(this.activeIndex,!!active&&(focused===active||!!focused&&composedContains(active,focused)))}this.expandedItem&&(!this.isNavigable(this.expandedItem)||!this.expandedItem.hasMenu)&&this.collapse()}setActive(item,focus=!1){if(this.isNavigable(item)){this.activeIndex=this.items.indexOf(item);for(const candidate of this.items)candidate.tabIndex=candidate===item?0:-1;focus&&(this.focusedItem=item,item.focus({preventScroll:!0}))}}registerOverlay(){this.overlayHandle||(this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this,preferredInitialFocus:()=>this.expandedItem,onEscape:()=>this.collapse(),onTab:()=>this.collapse(),restoreFocusTo:()=>{const active=deepActiveElement(this.ownerDocument);return isHtmlElement(active)&&active!==this.ownerDocument.body&&active!==this.ownerDocument.documentElement?active:null}}),this.ownerDocument.addEventListener("focusin",this.onDocumentFocus,!0))}open(item,focus){const previous=this.expandedItem;this.expandedItem=item,previous&&previous!==item&&previous.closeMenu(),this.registerOverlay(),item.openMenu(focus)}carry(item){const previous=this.expandedItem;this.setActive(item,!0),item.hasMenu&&this.isNavigable(item)?(this.expandedItem=item,previous&&previous!==item&&previous.closeMenu(),item.openMenu("none")):this.collapse()}collapse(){const item=this.expandedItem;this.expandedItem=null,this.ownerDocument.removeEventListener("focusin",this.onDocumentFocus,!0);const handle=this.overlayHandle;this.overlayHandle=void 0,handle?.deactivate(),item&&item.closeMenu()}menuStateChanged(item,open){if(this.items.includes(item))if(open&&item!==this.expandedItem){const previous=this.expandedItem;this.expandedItem=item,previous&&previous.closeMenu(),this.registerOverlay()}else!open&&item===this.expandedItem&&this.collapse()}eventItem(event){const path=event.composedPath(),item=path.find(target=>this.items.includes(target));if(!item||!this.isNavigable(item))return;const preceding=path.slice(0,path.indexOf(item));return{item,path:preceding,inMenu:preceding.some(node=>isHtmlElement(node)&&node.localName===tag("menu"))}}move(item){this.expandedItem?this.carry(item):this.setActive(item,!0)}render(){return html`<div part="base" role="menubar" aria-label=${this.getAttribute("aria-label")??this.label??this.localize("menuLabel")}><slot @slotchange=${this.syncItems}></slot></div>`}}__decorate([property()],LyraMenubar.prototype,"label",void 0),__decorate([property({type:Boolean,attribute:"top-layer",reflect:!0})],LyraMenubar.prototype,"topLayer",void 0),__decorate([property({reflect:!0})],LyraMenubar.prototype,"size",void 0),__decorate([property({reflect:!0})],LyraMenubar.prototype,"frame",void 0);export{LyraMenubar};
1
+ import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{isRovingTargetAvailable,resolveListMove}from"../../../internal/list-navigation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{activateNonmodalOverlay,composedContains,deepActiveElement}from"../../../internal/nonmodal-overlay-manager.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{keyEventOwnedByInnerControl}from"../../../internal/hotkey.js";import{sizes}from"../../../internal/sizes.styles.js";import{tag}from"../../../internal/prefix.js";import{menubarItemOwner}from"./menubar-shared.js";import{styles}from"./menubar.styles.js";import{LYRA_DEFAULT_menuLabel}from"../../../internal/default-strings/shared.generated.js";class LyraMenubar extends LyraElement{static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel}}static{this.styles=[LyraElement.styles,sizes,styles]}constructor(){super(),this.topLayer=!1,this.size="m",this.frame="card",this.items=[],this.activeIndex=-1,this.expandedItem=null,this.typeBuffer=new TypeAheadBuffer(this),this.focusedItem=null,this.owner={menuStateChanged:(item,open)=>this.menuStateChanged(item,open),itemStateChanged:()=>this.syncItemState()},this.syncItems=()=>{const assigned=(this.renderRoot.querySelector("slot")?.assignedElements({flatten:!0})??[]).filter(element=>element.localName===tag("menubar-item"));if(assigned.length===this.items.length&&assigned.every((item,index)=>item===this.items[index]))return;const previous=this.items[this.activeIndex],oldIndex=this.activeIndex,active=deepActiveElement(this.ownerDocument),heldFocus=!!previous&&(active===previous||!!active&&composedContains(previous,active)||this.focusedItem===previous&&(!active||active===this.ownerDocument.body)),assignedItems=new Set(assigned);for(const item of this.items)assignedItems.has(item)||item[menubarItemOwner](null,this.owner);this.items=assigned;for(const item of this.items)item[menubarItemOwner](this.owner);this.observeItems(),previous&&assignedItems.has(previous)&&this.isNavigable(previous)?this.setActive(previous):this.rehome(oldIndex,heldFocus),this.expandedItem&&!assignedItems.has(this.expandedItem)&&this.collapse()},this.onDocumentFocus=()=>{const active=deepActiveElement(this.ownerDocument);(!active||!composedContains(this,active))&&(this.focusedItem=null,this.collapse())},this.onClick=event=>{const found=this.eventItem(event);if(!found||found.inMenu)return;const{item}=found;if(this.setActive(item,!0),!item.hasMenu){this.expandedItem&&this.collapse();return}this.expandedItem===item?this.collapse():this.expandedItem?this.carry(item):this.open(item,"none")},this.onPointerOver=event=>{if(!this.expandedItem||event.pointerType==="touch")return;const found=this.eventItem(event);found&&!found.inMenu&&found.item.hasMenu&&found.item!==this.expandedItem&&this.carry(found.item)},this.onKeyDown=event=>{if(event.defaultPrevented||event.isComposing||event.keyCode===229||event.altKey||event.ctrlKey||event.metaKey)return;const found=this.eventItem(event);if(!found)return;const{item,inMenu}=found;if(inMenu){if(!isHtmlElement(event.target)||![tag("menu-item"),tag("dropdown-item")].includes(event.target.localName)||keyEventOwnedByInnerControl(event,{container:event.target})||event.key!=="ArrowLeft"&&event.key!=="ArrowRight")return}else if(event.target!==item||keyEventOwnedByInnerControl(event,{container:item}))return;const navigable=this.items.filter(candidate=>this.isNavigable(candidate));if(!navigable.length)return;const index=navigable.indexOf(item);let next;const nextIndex=resolveListMove(event,{count:navigable.length,current:index,orientation:"horizontal",direction:this.effectiveDirection});if(nextIndex!==null)next=navigable[nextIndex];else if(["ArrowDown","ArrowUp","Enter"," "].includes(event.key)){item.hasMenu?(event.preventDefault(),this.open(item,event.key==="ArrowUp"?"last":"first")):(event.key==="Enter"||event.key===" ")&&(event.preventDefault(),item.click());return}else if(this.typeBuffer.accepts(event)){this.typeBuffer.add(event.key,this.effectiveLocale);const match=this.typeBuffer.match(navigable,index,item2=>item2.textLabel,this.effectiveLocale);match!==null&&(next=navigable[match])}next&&(event.preventDefault(),this.move(next))},this.addEventListener("keydown",this.onKeyDown),this.addEventListener("click",this.onClick),this.addEventListener("pointerover",this.onPointerOver),this.addEventListener("focusin",event=>{const item=this.items.find(candidate=>candidate===event.target);item&&this.isNavigable(item)&&(this.focusedItem=item,this.setActive(item))})}connectedCallback(){if(super.connectedCallback(),this.hasUpdated){for(const item of this.items)item[menubarItemOwner](this.owner);this.observeItems(),queueMicrotask(()=>{this.isConnected&&(this.syncItems(),this.syncItemState())})}}disconnectedCallback(){this.collapse(),this.typeBuffer.clear(),this.itemObserver?.disconnect(),this.itemObserver=void 0,this.ownerDocument.removeEventListener("focusin",this.onDocumentFocus,!0);for(const item of this.items)item[menubarItemOwner](null,this.owner);this.focusedItem=null,super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed),queueMicrotask(()=>{this.isConnected&&collectInitialSlotAssignment(this.renderRoot.querySelector("slot"),this.syncItems)})}isNavigable(item){return isRovingTargetAvailable(item)}observeItems(){this.itemObserver?.disconnect();const Observer=this.ownerDocument.defaultView?.MutationObserver;if(Observer){this.itemObserver=new Observer(()=>this.syncItemState());for(const item of this.items)this.itemObserver.observe(item,{attributes:!0,attributeFilter:["disabled","hidden","aria-hidden","inert"]})}}rehome(index,focus){const successor=this.items.find((item,current)=>current>=Math.max(0,index)&&this.isNavigable(item))??this.items.slice(0,Math.max(0,index)).reverse().find(item=>this.isNavigable(item));if(successor)this.setActive(successor,focus);else{this.activeIndex=-1;for(const item of this.items)item.tabIndex=-1}}syncItemState(){const active=this.items[this.activeIndex];if(!active||!this.isNavigable(active)){const focused=deepActiveElement(this.ownerDocument);this.rehome(this.activeIndex,!!active&&(focused===active||!!focused&&composedContains(active,focused)))}this.expandedItem&&(!this.isNavigable(this.expandedItem)||!this.expandedItem.hasMenu)&&this.collapse()}setActive(item,focus=!1){if(this.isNavigable(item)){this.activeIndex=this.items.indexOf(item);for(const candidate of this.items)candidate.tabIndex=candidate===item?0:-1;focus&&(this.focusedItem=item,item.focus({preventScroll:!0}))}}registerOverlay(){this.overlayHandle||(this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this,preferredInitialFocus:()=>this.expandedItem,onEscape:()=>this.collapse(),onTab:()=>this.collapse(),restoreFocusTo:()=>{const active=deepActiveElement(this.ownerDocument);return isHtmlElement(active)&&active!==this.ownerDocument.body&&active!==this.ownerDocument.documentElement?active:null}}),this.ownerDocument.addEventListener("focusin",this.onDocumentFocus,!0))}open(item,focus){const previous=this.expandedItem;this.expandedItem=item,previous&&previous!==item&&previous.closeMenu(),this.registerOverlay(),item.openMenu(focus)}carry(item){const previous=this.expandedItem;this.setActive(item,!0),item.hasMenu&&this.isNavigable(item)?(this.expandedItem=item,previous&&previous!==item&&previous.closeMenu(),item.openMenu("none")):this.collapse()}collapse(){const item=this.expandedItem;this.expandedItem=null,this.ownerDocument.removeEventListener("focusin",this.onDocumentFocus,!0);const handle=this.overlayHandle;this.overlayHandle=void 0,handle?.deactivate(),item&&item.closeMenu()}menuStateChanged(item,open){if(this.items.includes(item))if(open&&item!==this.expandedItem){const previous=this.expandedItem;this.expandedItem=item,previous&&previous.closeMenu(),this.registerOverlay()}else!open&&item===this.expandedItem&&this.collapse()}eventItem(event){const path=event.composedPath(),item=path.find(target=>this.items.includes(target));if(!item||!this.isNavigable(item))return;const preceding=path.slice(0,path.indexOf(item));return{item,path:preceding,inMenu:preceding.some(node=>isHtmlElement(node)&&node.localName===tag("menu"))}}move(item){this.expandedItem?this.carry(item):this.setActive(item,!0)}render(){return html`<div part="base" role="menubar" aria-label=${this.getAttribute("aria-label")??this.label??this.localize("menuLabel")}><slot @slotchange=${this.syncItems}></slot></div>`}}__decorate([property()],LyraMenubar.prototype,"label",void 0),__decorate([property({type:Boolean,attribute:"top-layer",reflect:!0})],LyraMenubar.prototype,"topLayer",void 0),__decorate([property({reflect:!0})],LyraMenubar.prototype,"size",void 0),__decorate([property({reflect:!0})],LyraMenubar.prototype,"frame",void 0);export{LyraMenubar};
@@ -105,7 +105,7 @@ current:boolean;private _open;
105
105
  * time; opening one closes the other with an `lr-toggle` whose source is `peer`.
106
106
  * @default false
107
107
  */
108
- get open():boolean;set open(next:boolean);private browserResolved;private closing;private readonly slotPresence;private readonly panelId;private interactionMode?;private liveOpen;private placement?;private placementKey;private placedTopLayer?;private overlayHandle?;private pendingShow;private pendingMorph?;private hideAnimation?;private hideAnimationStarted;private transitionToken;private morphCleanup?;private focusInPanel;private semanticFocusOrigin?;constructor();private get ownerContext();private get isLink();private get isTrigger();private get floatingLayout();private get baseElement();private get panelElement();private get canDisclose();connectedCallback():void;disconnectedCallback():void;
108
+ get open():boolean;set open(next:boolean);private browserResolved;private closing;private readonly slotPresence;private readonly panelId;private interactionMode?;private liveOpen;private placement?;private placementKey;private placedTopLayer?;private overlayHandle?;private pendingShow;private pendingMorph?;private hideAnimation?;private hideAnimationStarted;private transitionToken;private morphCleanup?;private focusInPanel;private semanticFocusOrigin?;private hrefChangedThisUpdate;constructor();private get ownerContext();private get isLink();private get isTrigger();private get floatingLayout();private get baseElement();private get panelElement();private get canDisclose();connectedCallback():void;disconnectedCallback():void;
109
109
  /** Moves focus to the link or button. */
110
110
  focus(options?:FocusOptions):void;
111
111
  /** Activates the link or button, exactly like a user click. */
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{deferredPlaceReady,loadAnchoredOverlayRuntime,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{maxCssTime}from"../../../internal/css-motion-time.js";import{chevronIcon}from"../../../internal/icons.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{activateNonmodalOverlay,composedContains,deepActiveElement}from"../../../internal/nonmodal-overlay-manager.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{safeLinkHref}from"../../../internal/safe-url.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{navigationMenuOwner,registerNavigationMenuItemController}from"../navigation-menu/navigation-menu-owner.js";import{styles}from"./navigation-menu-item.styles.js";const PLACEMENT_STYLE_PROPERTIES=["position","margin","left","top","--lr-positioner-available-inline-size","--lr-positioner-available-block-size"],SHOW_OFFSET="translateY(var(--lr-size-neg-0-25rem))";class LyraNavigationMenuItem extends LyraElement{static{this.styles=[LyraElement.styles,styles]}get open(){return this._open}set open(next){const value=!!next;if(value===this._open)return;const source=this.hasUpdated?"programmatic":null;value?this.openPanel("programmatic",source):this.closePanel(source)}constructor(){super(),this.href="",this.target="",this.rel="",this.current=!1,this._open=!1,this.browserResolved=!1,this.closing=!1,this.slotPresence=new SlotPresenceController(this),this.panelId=nextId("navigation-menu-panel"),this.liveOpen=!1,this.placementKey="",this.pendingShow=!1,this.hideAnimationStarted=!1,this.transitionToken=0,this.focusInPanel=!1,this.onFocusIn=event=>{const panel=this.panelElement,target=event.composedPath()[0];this.focusInPanel=panel!==null&&target!==void 0&&composedContains(panel,target)},this.onFocusOut=event=>{const next=event.relatedTarget;if(next===null)return;const panel=this.panelElement;(!panel||!composedContains(panel,next))&&(this.focusInPanel=!1)},this.onBaseClick=()=>{if(this.isLink)return;const context=this.ownerContext;if(context){context.activate(this);return}this.isTrigger&&(this._open?this.closePanel("user"):this.openPanel("programmatic","user"))},this.onHostKeyDown=event=>{event.key!=="Escape"||event.defaultPrevented||!this._open||this.ownerContext||(event.preventDefault(),this.onOverlayEscape())},new GlassScrollLayer(this,'[part="panel"]',()=>this.open),registerNavigationMenuItemController(this,{isTrigger:()=>this.isTrigger,isLink:()=>this.isLink,isOpen:()=>this._open,mode:()=>this._open?this.interactionMode:void 0,pin:()=>{this._open&&(this.interactionMode="pinned")},base:()=>this.baseElement,panel:()=>this.panelElement,open:(mode,source)=>this.openPanel(mode,source),close:(source,options)=>this.closePanel(source,options),isTopmost:()=>this.overlayHandle?.isTopmost()??!1,placementReady:()=>this.placementReady(),reposition:()=>{this.placementKey="",this.requestUpdate()}})}get ownerContext(){return navigationMenuOwner(this)}get isLink(){return!!safeLinkHref(this.href)}get isTrigger(){return!this.isLink&&this.slotPresence.has("panel")}get floatingLayout(){return this.ownerContext?.layout()==="bar"}get baseElement(){return this.renderRoot?.querySelector('[part~="base"]')??null}get panelElement(){return this.renderRoot?.querySelector('[part~="panel"]')??null}get canDisclose(){return this.isLink?!1:!this.browserResolved||this.slotPresence.has("panel")}connectedCallback(){super.connectedCallback(),this.addEventListener("focusin",this.onFocusIn),this.addEventListener("focusout",this.onFocusOut),this.addEventListener("keydown",this.onHostKeyDown),this.updateBrowserDerivedState(()=>{this.browserResolved=!0}),this.hasUpdated&&this._open&&(this.interactionMode="programmatic",this.requestUpdate())}disconnectedCallback(){this.removeEventListener("focusin",this.onFocusIn),this.removeEventListener("focusout",this.onFocusOut),this.removeEventListener("keydown",this.onHostKeyDown),this.cancelMorph(),this.stopPlacement(),this.releaseOverlay(!1),this.cancelHideAnimation(),this.closing=!1,this.focusInPanel=!1,this.semanticFocusOrigin=void 0,this._open&&this.interactionMode==="hover"?(this._open=!1,this.liveOpen=!1,this.interactionMode=void 0,this.requestUpdate("open",!0)):this._open&&(this.interactionMode="programmatic"),super.disconnectedCallback()}focus(options){const base=this.baseElement;base?base.focus(options):super.focus(options)}click(){this.baseElement?.click()}willUpdate(changed){if(super.willUpdate(changed),this._open&&!this.canDisclose&&(this.liveOpen?this.closePanel("programmatic",{repairFocus:!0,instant:!0}):(this._open=!1,this.interactionMode=void 0,this.pendingShow=!1,this.pendingMorph=void 0,this.requestUpdate("open",!0))),changed.has("href")){const previous=this.baseElement,nextKind=this.isLink?"a":"button";this.semanticFocusOrigin=previous&&previous.localName!==nextKind&&shadowFocusTarget(this)===previous?previous:void 0}}updated(changed){super.updated(changed),this.isConnected&&this.hasAttribute("open")!==this._open&&this.toggleAttribute("open",this._open),this.syncFloating(),this.syncHideAnimation();const focusOrigin=this.semanticFocusOrigin;if(this.semanticFocusOrigin=void 0,focusOrigin){const internalActive=shadowFocusTarget(this),documentActive=activeElementIn(this.ownerDocument);(internalActive===null||internalActive===focusOrigin)&&(documentActive===null||documentActive===this||documentActive===this.ownerDocument.body)&&this.baseElement?.focus()}}openPanel(mode,source){if(this._open)return mode==="pinned"&&this.interactionMode==="hover"&&(this.interactionMode="pinned"),!0;if(!this.canDisclose)return this.requestUpdate("open",!0),!1;const context=this.ownerContext,morph=context?.willOpen(this);return this.cancelHideAnimation(),this.closing=!1,this.interactionMode=mode,this.pendingMorph=morph,this.pendingShow=source!==null&&!morph,this._open=!0,this.requestUpdate("open",!1),this.queueToggle(!0,source),context?.changed(this,!0,source),!0}closePanel(source,options={}){if(!this._open)return;options.repairFocus!==!1&&this.panelHoldsFocus()&&(options.focusTarget??this.baseElement)?.focus({preventScroll:!0});const wasFloating=this.placement!==void 0||this.overlayHandle!==void 0;this.cancelMorph(),this.stopPlacement(),this.releaseOverlay(options.restoreFocus===!0);const animate=!options.instant&&wasFloating&&this.liveOpen&&this.isConnected&&this.floatingLayout;this.cancelHideAnimation(),this.closing=animate,this.pendingMorph=void 0,this.pendingShow=!1,this.interactionMode=void 0,this.liveOpen=!1,this.focusInPanel=!1,this._open=!1,this.requestUpdate("open",!0),this.queueToggle(!1,source),this.ownerContext?.changed(this,!1,source)}queueToggle(open,source){source!==null&&this.updateComplete.then(()=>{this.emit("lr-toggle",{expanded:open,source})})}panelHoldsFocus(){const panel=this.panelElement;if(!panel)return!1;const active=deepActiveElement(this.ownerDocument);return active&&composedContains(panel,active)?!0:this.focusInPanel&&(active===null||active===this.ownerDocument.body)}syncFloating(){const panel=this.panelElement,visible=this.isTrigger&&this.browserResolved&&this._open;if(visible&&(this.liveOpen=!0),!(visible&&this.isConnected&&this.floatingLayout)){this.stopPlacement(),this.overlayHandle&&this.releaseOverlay(!1),panel&&!this.closing&&(this.clearPlacementStyles(panel),visible&&panel.hasAttribute("data-lr-top-layer")&&loadAnchoredOverlayRuntime().then(runtime=>runtime.releaseTopLayer?.(panel),()=>{})),visible&&(this.pendingShow=!1,this.pendingMorph=void 0);return}if(!panel)return;const context=this.ownerContext,anchor=context.anchor(this);if(!anchor)return;const key=[anchor===this.baseElement?"item":"menu",context.distance(),context.topLayer(),this.effectiveDirection].join("|");(!this.placement||key!==this.placementKey)&&this.startPlacement(anchor,panel,key),this.overlayHandle?.isActive()||(this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.panelElement,onEscape:()=>this.onOverlayEscape(),restoreFocusTo:()=>this.baseElement}));const morph=this.pendingMorph,show=this.pendingShow;if(this.pendingMorph=void 0,this.pendingShow=!1,!morph&&!show)return;const handle=this.placement;handle?.ready.then(placed=>{!placed||handle!==this.placement||!this._open||(morph?this.runMorph(morph):this.runShowAnimation())})}startPlacement(anchor,panel,key){this.stopPlacement();const context=this.ownerContext,bridge=this.renderRoot.querySelector(".hover-bridge");this.placementKey=key;const topLayer=context.topLayer();this.placedTopLayer=syncTopLayerRelease(panel,this.placedTopLayer,topLayer),this.placement=deferredPlaceReady(anchor,panel,{placement:rtlAwarePlacement("bottom-start",this),...topLayerPlacement(topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed")),offset:context.distance(),hoverBridge:bridge??void 0})}stopPlacement(){const handle=this.placement;this.placement=void 0,this.placementKey="",handle?.()}releaseOverlay(restoreFocus){const handle=this.overlayHandle;this.overlayHandle=void 0,handle?.deactivate({restoreFocus})}clearPlacementStyles(panel){for(const property2 of PLACEMENT_STYLE_PROPERTIES)panel.style.removeProperty(property2)}onOverlayEscape(){const context=this.ownerContext;if(context){context.escape(this);return}const within=composedContains(this,deepActiveElement(this.ownerDocument));this.closePanel("user",{restoreFocus:within})}async placementReady(){return await this.updateComplete,this.placement?waitForDeferredPlacement(()=>this.placement):this._open}get registryHost(){return this.ownerContext?.owner??this}runShowAnimation(){const panel=this.panelElement;panel&&animateRegistered(this.registryHost,panel,"navigation-menu.show",this.effectiveDirection,{keyframes:[{opacity:0,transform:SHOW_OFFSET},{opacity:1,transform:"translateY(0)"}],durationProperties:["--lr-navigation-menu-show-duration","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]})}syncHideAnimation(){if(!this.closing||this.hideAnimationStarted)return;this.hideAnimationStarted=!0;const token=this.transitionToken,panel=this.panelElement,animation=panel?animateRegistered(this.registryHost,panel,"navigation-menu.hide",this.effectiveDirection,{keyframes:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:SHOW_OFFSET}],durationProperties:["--lr-navigation-menu-hide-duration","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]}):void 0;this.hideAnimation=animation;const settle=()=>{token===this.transitionToken&&(this.hideAnimation?.cancel(),this.hideAnimation=void 0,this.hideAnimationStarted=!1,this.closing=!1)};animation?animation.finished.then(settle,settle):queueMicrotask(settle)}cancelHideAnimation(){this.transitionToken++,this.hideAnimation?.cancel(),this.hideAnimation=void 0,this.hideAnimationStarted=!1}runMorph(morph){const panel=this.panelElement,content=panel?.querySelector(".panel-content");if(!panel||!content)return;const travel="var(--lr-size-1rem)",reversed=`calc(-1 * ${travel})`,from=morph.direction==="end"?travel:reversed,mirrored=morph.direction==="end"?reversed:travel;animateRegistered(this.registryHost,content,`navigation-menu.enter-from-${morph.direction}`,this.effectiveDirection,{keyframes:[{opacity:0,transform:`translateX(${from})`},{opacity:1,transform:"translateX(0)"}],rtlKeyframes:[{opacity:0,transform:`translateX(${mirrored})`},{opacity:1,transform:"translateX(0)"}],durationProperties:["--lr-navigation-menu-switch-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]});const view=this.ownerDocument.defaultView;if(!view||prefersReducedMotion(this))return;const to=panel.getBoundingClientRect();if(Math.abs(to.width-morph.from.width)<1&&Math.abs(to.height-morph.from.height)<1)return;this.cancelMorph();const natural=content.getBoundingClientRect().width;panel.setAttribute("data-morphing",""),panel.style.inlineSize=`${morph.from.width}px`,panel.style.blockSize=`${morph.from.height}px`,content.style.inlineSize=`${natural}px`;const style=view.getComputedStyle(panel),total=maxCssTime(style.transitionDuration)+maxCssTime(style.transitionDelay);let frame,timer;const onEnd=event=>{event.target===panel&&["inline-size","block-size","width","height"].includes(event.propertyName)&&cleanup()},cleanup=()=>{this.morphCleanup===cleanup&&(this.morphCleanup=void 0,frame!==void 0&&view.cancelAnimationFrame(frame),timer!==void 0&&view.clearTimeout(timer),panel.removeEventListener("transitionend",onEnd),panel.removeAttribute("data-morphing"),panel.style.removeProperty("inline-size"),panel.style.removeProperty("block-size"),content.style.removeProperty("inline-size"))};this.morphCleanup=cleanup,panel.addEventListener("transitionend",onEnd),frame=view.requestAnimationFrame(()=>{frame=void 0,this.morphCleanup===cleanup&&(panel.style.inlineSize=`${to.width}px`,panel.style.blockSize=`${to.height}px`,timer=view.setTimeout(cleanup,total+50))})}cancelMorph(){this.morphCleanup?.()}render(){const isLink=this.isLink,isTrigger=this.isTrigger,floating=this.floatingLayout,stacked=this.ownerContext?.layout()==="stacked",expanded=this._open&&this.browserResolved,panelVisible=isTrigger&&this.browserResolved&&(this._open||this.closing),ariaLabel=hostAriaLabel(this),parts=["base"];this.current&&parts.push("base-current"),isTrigger&&expanded&&parts.push("base-open");const label=html`<span part="start" ?hidden=${!this.slotPresence.has("start")}
1
+ import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{deferredPlaceReady,loadAnchoredOverlayRuntime,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{maxCssTime}from"../../../internal/css-motion-time.js";import{chevronIcon}from"../../../internal/icons.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{activateNonmodalOverlay,composedContains,deepActiveElement}from"../../../internal/nonmodal-overlay-manager.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{safeLinkHref}from"../../../internal/safe-url.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{navigationMenuOwner,registerNavigationMenuItemController}from"../navigation-menu/navigation-menu-owner.js";import{styles}from"./navigation-menu-item.styles.js";const PLACEMENT_STYLE_PROPERTIES=["position","margin","left","top","--lr-positioner-available-inline-size","--lr-positioner-available-block-size"],SHOW_OFFSET="translateY(var(--lr-size-neg-0-25rem))";class LyraNavigationMenuItem extends LyraElement{static{this.styles=[LyraElement.styles,styles]}get open(){return this._open}set open(next){const value=!!next;if(value===this._open)return;const source=this.hasUpdated?"programmatic":null;value?this.openPanel("programmatic",source):this.closePanel(source)}constructor(){super(),this.href="",this.target="",this.rel="",this.current=!1,this._open=!1,this.browserResolved=!1,this.closing=!1,this.slotPresence=new SlotPresenceController(this),this.panelId=nextId("navigation-menu-panel"),this.liveOpen=!1,this.placementKey="",this.pendingShow=!1,this.hideAnimationStarted=!1,this.transitionToken=0,this.focusInPanel=!1,this.hrefChangedThisUpdate=!1,this.onFocusIn=event=>{const panel=this.panelElement,target=event.composedPath()[0];this.focusInPanel=panel!==null&&target!==void 0&&composedContains(panel,target)},this.onFocusOut=event=>{const next=event.relatedTarget;if(next===null)return;const panel=this.panelElement;(!panel||!composedContains(panel,next))&&(this.focusInPanel=!1)},this.onBaseClick=()=>{if(this.isLink)return;const context=this.ownerContext;if(context){context.activate(this);return}this.isTrigger&&(this._open?this.closePanel("user"):this.openPanel("programmatic","user"))},this.onHostKeyDown=event=>{event.key!=="Escape"||event.defaultPrevented||!this._open||this.ownerContext||(event.preventDefault(),this.onOverlayEscape())},this.addController({hostUpdate:()=>{if(this._open&&!this.canDisclose&&(this.liveOpen?this.closePanel("programmatic",{repairFocus:!0,instant:!0}):(this._open=!1,this.interactionMode=void 0,this.pendingShow=!1,this.pendingMorph=void 0,this.requestUpdate("open",!0))),this.hrefChangedThisUpdate){const previous=this.baseElement,nextKind=this.isLink?"a":"button";this.semanticFocusOrigin=previous&&previous.localName!==nextKind&&shadowFocusTarget(this)===previous?previous:void 0}}}),new GlassScrollLayer(this,'[part="panel"]',()=>this.open),registerNavigationMenuItemController(this,{isTrigger:()=>this.isTrigger,isLink:()=>this.isLink,isOpen:()=>this._open,mode:()=>this._open?this.interactionMode:void 0,pin:()=>{this._open&&(this.interactionMode="pinned")},base:()=>this.baseElement,panel:()=>this.panelElement,open:(mode,source)=>this.openPanel(mode,source),close:(source,options)=>this.closePanel(source,options),isTopmost:()=>this.overlayHandle?.isTopmost()??!1,placementReady:()=>this.placementReady(),reposition:()=>{this.placementKey="",this.requestUpdate()}})}get ownerContext(){return navigationMenuOwner(this)}get isLink(){return!!safeLinkHref(this.href)}get isTrigger(){return!this.isLink&&this.slotPresence.has("panel")}get floatingLayout(){return this.ownerContext?.layout()==="bar"}get baseElement(){return this.renderRoot?.querySelector('[part~="base"]')??null}get panelElement(){return this.renderRoot?.querySelector('[part~="panel"]')??null}get canDisclose(){return this.isLink?!1:!this.browserResolved||this.slotPresence.has("panel")}connectedCallback(){super.connectedCallback(),this.addEventListener("focusin",this.onFocusIn),this.addEventListener("focusout",this.onFocusOut),this.addEventListener("keydown",this.onHostKeyDown),this.updateBrowserDerivedState(()=>{this.browserResolved=!0}),this.hasUpdated&&this._open&&(this.interactionMode="programmatic",this.requestUpdate())}disconnectedCallback(){this.removeEventListener("focusin",this.onFocusIn),this.removeEventListener("focusout",this.onFocusOut),this.removeEventListener("keydown",this.onHostKeyDown),this.cancelMorph(),this.stopPlacement(),this.releaseOverlay(!1),this.cancelHideAnimation(),this.closing=!1,this.focusInPanel=!1,this.semanticFocusOrigin=void 0,this._open&&this.interactionMode==="hover"?(this._open=!1,this.liveOpen=!1,this.interactionMode=void 0,this.requestUpdate("open",!0)):this._open&&(this.interactionMode="programmatic"),super.disconnectedCallback()}focus(options){const base=this.baseElement;base?base.focus(options):super.focus(options)}click(){this.baseElement?.click()}willUpdate(changed){super.willUpdate(changed),this.hrefChangedThisUpdate=changed.has("href")}updated(changed){super.updated(changed),this.isConnected&&this.hasAttribute("open")!==this._open&&this.toggleAttribute("open",this._open),this.syncFloating(),this.syncHideAnimation();const focusOrigin=this.semanticFocusOrigin;if(this.semanticFocusOrigin=void 0,focusOrigin){const internalActive=shadowFocusTarget(this),documentActive=activeElementIn(this.ownerDocument);(internalActive===null||internalActive===focusOrigin)&&(documentActive===null||documentActive===this||documentActive===this.ownerDocument.body)&&this.baseElement?.focus()}}openPanel(mode,source){if(this._open)return mode==="pinned"&&this.interactionMode==="hover"&&(this.interactionMode="pinned"),!0;if(!this.canDisclose)return this.requestUpdate("open",!0),!1;const context=this.ownerContext,morph=context?.willOpen(this);return this.cancelHideAnimation(),this.closing=!1,this.interactionMode=mode,this.pendingMorph=morph,this.pendingShow=source!==null&&!morph,this._open=!0,this.requestUpdate("open",!1),this.queueToggle(!0,source),context?.changed(this,!0,source),!0}closePanel(source,options={}){if(!this._open)return;options.repairFocus!==!1&&this.panelHoldsFocus()&&(options.focusTarget??this.baseElement)?.focus({preventScroll:!0});const wasFloating=this.placement!==void 0||this.overlayHandle!==void 0;this.cancelMorph(),this.stopPlacement(),this.releaseOverlay(options.restoreFocus===!0);const animate=!options.instant&&wasFloating&&this.liveOpen&&this.isConnected&&this.floatingLayout;this.cancelHideAnimation(),this.closing=animate,this.pendingMorph=void 0,this.pendingShow=!1,this.interactionMode=void 0,this.liveOpen=!1,this.focusInPanel=!1,this._open=!1,this.requestUpdate("open",!0),this.queueToggle(!1,source),this.ownerContext?.changed(this,!1,source)}queueToggle(open,source){source!==null&&this.updateComplete.then(()=>{this.emit("lr-toggle",{expanded:open,source})})}panelHoldsFocus(){const panel=this.panelElement;if(!panel)return!1;const active=deepActiveElement(this.ownerDocument);return active&&composedContains(panel,active)?!0:this.focusInPanel&&(active===null||active===this.ownerDocument.body)}syncFloating(){const panel=this.panelElement,visible=this.isTrigger&&this.browserResolved&&this._open;if(visible&&(this.liveOpen=!0),!(visible&&this.isConnected&&this.floatingLayout)){this.stopPlacement(),this.overlayHandle&&this.releaseOverlay(!1),panel&&!this.closing&&(this.clearPlacementStyles(panel),visible&&panel.hasAttribute("data-lr-top-layer")&&loadAnchoredOverlayRuntime().then(runtime=>runtime.releaseTopLayer?.(panel),()=>{})),visible&&(this.pendingShow=!1,this.pendingMorph=void 0);return}if(!panel)return;const context=this.ownerContext,anchor=context.anchor(this);if(!anchor)return;const key=[anchor===this.baseElement?"item":"menu",context.distance(),context.topLayer(),this.effectiveDirection].join("|");(!this.placement||key!==this.placementKey)&&this.startPlacement(anchor,panel,key),this.overlayHandle?.isActive()||(this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.panelElement,onEscape:()=>this.onOverlayEscape(),restoreFocusTo:()=>this.baseElement}));const morph=this.pendingMorph,show=this.pendingShow;if(this.pendingMorph=void 0,this.pendingShow=!1,!morph&&!show)return;const handle=this.placement;handle?.ready.then(placed=>{!placed||handle!==this.placement||!this._open||(morph?this.runMorph(morph):this.runShowAnimation())})}startPlacement(anchor,panel,key){this.stopPlacement();const context=this.ownerContext,bridge=this.renderRoot.querySelector(".hover-bridge");this.placementKey=key;const topLayer=context.topLayer();this.placedTopLayer=syncTopLayerRelease(panel,this.placedTopLayer,topLayer),this.placement=deferredPlaceReady(anchor,panel,{placement:rtlAwarePlacement("bottom-start",this),...topLayerPlacement(topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed")),offset:context.distance(),hoverBridge:bridge??void 0})}stopPlacement(){const handle=this.placement;this.placement=void 0,this.placementKey="",handle?.()}releaseOverlay(restoreFocus){const handle=this.overlayHandle;this.overlayHandle=void 0,handle?.deactivate({restoreFocus})}clearPlacementStyles(panel){for(const property2 of PLACEMENT_STYLE_PROPERTIES)panel.style.removeProperty(property2)}onOverlayEscape(){const context=this.ownerContext;if(context){context.escape(this);return}const within=composedContains(this,deepActiveElement(this.ownerDocument));this.closePanel("user",{restoreFocus:within})}async placementReady(){return await this.updateComplete,this.placement?waitForDeferredPlacement(()=>this.placement):this._open}get registryHost(){return this.ownerContext?.owner??this}runShowAnimation(){const panel=this.panelElement;panel&&animateRegistered(this.registryHost,panel,"navigation-menu.show",this.effectiveDirection,{keyframes:[{opacity:0,transform:SHOW_OFFSET},{opacity:1,transform:"translateY(0)"}],durationProperties:["--lr-navigation-menu-show-duration","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]})}syncHideAnimation(){if(!this.closing||this.hideAnimationStarted)return;this.hideAnimationStarted=!0;const token=this.transitionToken,panel=this.panelElement,animation=panel?animateRegistered(this.registryHost,panel,"navigation-menu.hide",this.effectiveDirection,{keyframes:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:SHOW_OFFSET}],durationProperties:["--lr-navigation-menu-hide-duration","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]}):void 0;this.hideAnimation=animation;const settle=()=>{token===this.transitionToken&&(this.hideAnimation?.cancel(),this.hideAnimation=void 0,this.hideAnimationStarted=!1,this.closing=!1)};animation?animation.finished.then(settle,settle):queueMicrotask(settle)}cancelHideAnimation(){this.transitionToken++,this.hideAnimation?.cancel(),this.hideAnimation=void 0,this.hideAnimationStarted=!1}runMorph(morph){const panel=this.panelElement,content=panel?.querySelector(".panel-content");if(!panel||!content)return;const travel="var(--lr-size-1rem)",reversed=`calc(-1 * ${travel})`,from=morph.direction==="end"?travel:reversed,mirrored=morph.direction==="end"?reversed:travel;animateRegistered(this.registryHost,content,`navigation-menu.enter-from-${morph.direction}`,this.effectiveDirection,{keyframes:[{opacity:0,transform:`translateX(${from})`},{opacity:1,transform:"translateX(0)"}],rtlKeyframes:[{opacity:0,transform:`translateX(${mirrored})`},{opacity:1,transform:"translateX(0)"}],durationProperties:["--lr-navigation-menu-switch-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]});const view=this.ownerDocument.defaultView;if(!view||prefersReducedMotion(this))return;const to=panel.getBoundingClientRect();if(Math.abs(to.width-morph.from.width)<1&&Math.abs(to.height-morph.from.height)<1)return;this.cancelMorph();const natural=content.getBoundingClientRect().width;panel.setAttribute("data-morphing",""),panel.style.inlineSize=`${morph.from.width}px`,panel.style.blockSize=`${morph.from.height}px`,content.style.inlineSize=`${natural}px`;const style=view.getComputedStyle(panel),total=maxCssTime(style.transitionDuration)+maxCssTime(style.transitionDelay);let frame,timer;const onEnd=event=>{event.target===panel&&["inline-size","block-size","width","height"].includes(event.propertyName)&&cleanup()},cleanup=()=>{this.morphCleanup===cleanup&&(this.morphCleanup=void 0,frame!==void 0&&view.cancelAnimationFrame(frame),timer!==void 0&&view.clearTimeout(timer),panel.removeEventListener("transitionend",onEnd),panel.removeAttribute("data-morphing"),panel.style.removeProperty("inline-size"),panel.style.removeProperty("block-size"),content.style.removeProperty("inline-size"))};this.morphCleanup=cleanup,panel.addEventListener("transitionend",onEnd),frame=view.requestAnimationFrame(()=>{frame=void 0,this.morphCleanup===cleanup&&(panel.style.inlineSize=`${to.width}px`,panel.style.blockSize=`${to.height}px`,timer=view.setTimeout(cleanup,total+50))})}cancelMorph(){this.morphCleanup?.()}render(){const isLink=this.isLink,isTrigger=this.isTrigger,floating=this.floatingLayout,stacked=this.ownerContext?.layout()==="stacked",expanded=this._open&&this.browserResolved,panelVisible=isTrigger&&this.browserResolved&&(this._open||this.closing),ariaLabel=hostAriaLabel(this),parts=["base"];this.current&&parts.push("base-current"),isTrigger&&expanded&&parts.push("base-open");const label=html`<span part="start" ?hidden=${!this.slotPresence.has("start")}
2
2
  ><slot name="start"></slot></span
3
3
  ><span part="label"><slot></slot></span
4
4
  ><span part="end" ?hidden=${!this.slotPresence.has("end")}><slot name="end"></slot></span
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{isAriaTrue}from"../../../internal/accessibility-visibility.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import{resolveCssLength}from"../../../internal/css-length.js";import{cancelDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{isComposedFocusAvailable}from"../../../internal/focus-navigation.js";import{menuIcon}from"../../../internal/icons.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteRange}from"../../../internal/numbers.js";import{activateOverlay,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{styles}from"./page.styles.js";import{LYRA_DEFAULT_closeNavigation,LYRA_DEFAULT_openNavigation,LYRA_DEFAULT_skipToContent}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_navigation}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_MOBILE_BREAKPOINT="768px";class LyraPage extends LyraElement{constructor(){super(...arguments),this.view="desktop",this.navOpen=!1,this.mobileBreakpoint="768px",this.navigationPlacement="start",this.disableNavigationToggle=!1,this.accessibleLabel=null,this.mainId=nextId("page-main"),this.navigationId=nextId("page-navigation"),this.drawerId=nextId("page-drawer"),this.skipTargetId=nextId("page-skip-target"),this.skipLabelId=nextId("page-skip-label"),this.fragmentTargetId=this.getAttribute("id")||this.skipTargetId,this.fragmentTabIndex=this.getAttribute("tabindex")??"-1",this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.hideNavigation()},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.hideNavigation(),this.navOpen&&this.view==="mobile"&&this.nativeModal.show()}}),this.navigationOpener=null,this.customToggles=[],this.customToggleOwnership=new Map,this.onWindowResize=()=>this.measureAllocation(),this.navigationDeferredReturn=()=>{const owner=this.navigationTriggerOwner,opener=owner?null:this.navigationOpener;if(this.navigationOpener=null,!(!owner&&!opener))return{candidates:()=>[owner?.isConnected?resolveAccessibleTrigger(owner):null,opener,this.disableNavigationToggle?null:this.renderRoot.querySelector('[part~="navigation-toggle"]'),this.mainElement],stranded:active=>!!this.drawerElement&&composedContains(this.drawerElement,active),isCurrent:()=>!this.navOpen}},this.resolveNavigationRestoreTarget=()=>{const owner=this.navigationTriggerOwner;if(owner?.isConnected){const accessible=resolveAccessibleTrigger(owner);if(isComposedFocusAvailable(accessible))return accessible}const builtIn=this.disableNavigationToggle?null:this.renderRoot.querySelector('[part~="navigation-toggle"]');return builtIn&&isComposedFocusAvailable(builtIn)?builtIn:this.mainElement&&isComposedFocusAvailable(this.mainElement)?this.mainElement:null},this.onDefaultToggleClick=event=>{this.rememberTriggerAndToggle(event.currentTarget)},this.onToggleSlotClick=event=>{const trigger=event.composedPath().find(candidate=>candidate?.nodeType===1&&candidate.getAttribute("slot")==="navigation-toggle");trigger&&this.customToggles.includes(trigger)&&!this.isUnavailableCustomToggle(trigger)&&this.rememberTriggerAndToggle(trigger)},this.onPageClick=event=>{const path=event.composedPath();if(path.some(candidate=>candidate?.nodeType===1&&candidate.getAttribute("slot")==="navigation-toggle"))return;const trigger=path.find(candidate=>candidate?.nodeType===1&&candidate.hasAttribute("data-toggle-nav"));trigger&&this.rememberTriggerAndToggle(trigger)},this.onBackdropClick=event=>{event.target===event.currentTarget&&this.overlayHandle?.dismissBackdrop()},this.onSkipClick=event=>{event.preventDefault(),this.mainElement?.focus(),this.mainElement?.scrollIntoView({block:"start"})}}static{this.defaultStrings={...super.defaultStrings,closeNavigation:LYRA_DEFAULT_closeNavigation,navigation:LYRA_DEFAULT_navigation,openNavigation:LYRA_DEFAULT_openNavigation,skipToContent:LYRA_DEFAULT_skipToContent}}static{this.knownUnobservedAttributes=["disable-sticky"]}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}connectedCallback(){super.connectedCallback(),this.measureAllocation(),this.observeAllocation(),this.hasUpdated&&this.view==="mobile"&&this.navOpen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.syncOverlay(),queueMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&queueMicrotask(()=>this.isConnected&&this.syncCustomToggle())}disconnectedCallback(){this.nativeModal.hide(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0,this.overlayHandle?.suspend(),cancelDeferredFocusReturn(this),this.releaseCustomToggleA11y(),super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed),this.measureAllocation(),this.observeAllocation()}willUpdate(changed){super.willUpdate(changed),this.view==="mobile"&&this.navOpen&&!this.overlayHandle&&this.nativeModal.prepare(),(this.view!=="mobile"||!this.navOpen)&&(this.nativeModal.hide(),this.nativeModal.prepare(!1)),changed.has("fragmentTargetId")&&!this.fragmentTargetId&&(this.fragmentTargetId=this.skipTargetId),changed.has("fragmentTabIndex")&&this.fragmentTabIndex===null&&(this.fragmentTabIndex="-1")}updated(changed){super.updated(changed),this.view==="mobile"&&this.navOpen&&this.nativeModal.show();const describedBy=this.view==="mobile"&&this.navOpen?this.getAttribute("aria-describedby"):null;for(const dialog of this.renderRoot.querySelectorAll('[part="drawer"], [data-native-modal-carrier]'))syncAriaDescribedByElements(this,dialog,describedBy);changed.has("mobileBreakpoint")&&changed.get("mobileBreakpoint")!==void 0&&this.measureAllocation(),this.overlayHandle!==void 0&&(!this.isConnected||this.view!=="mobile"||!this.navOpen)?(this.syncOverlay(changed),this.syncCustomToggle()):(this.syncCustomToggle(),this.syncOverlay(changed))}observeAllocation(){if(!this.isConnected)return;this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0;const view=this.ownerDocument.defaultView,ResizeObserverConstructor=view?.ResizeObserver;if(ResizeObserverConstructor){this.resizeObserver??=new ResizeObserverConstructor(entries=>{const entry=entries.find(candidate=>candidate.target===this)??entries[0],inlineSize=entry?.contentBoxSize?.[0]?.inlineSize??entry?.contentRect.width;inlineSize!==void 0&&view?.requestAnimationFrame(()=>{this.isConnected&&this.applyMeasuredInlineSize(inlineSize)})}),this.resizeObserver.observe(this);return}view&&(this.resizeView=view,view.addEventListener("resize",this.onWindowResize))}measureAllocation(){const width=this.getBoundingClientRect().width;width>0&&this.applyMeasuredInlineSize(width)}applyMeasuredInlineSize(width){if(!Number.isFinite(width)||width<0)return;const resolved=resolveCssLength(this.mobileBreakpoint,{host:this}),fallback=resolveCssLength(DEFAULT_MOBILE_BREAKPOINT,{host:this})??768,breakpoint=Math.max(0,resolved!==void 0&&Number.isFinite(resolved)?resolved:fallback),next=width<=breakpoint?"mobile":"desktop";next!==this.view&&(this.view=next)}syncOverlay(changed){if(this.isConnected&&this.view==="mobile"&&this.navOpen){if(this.overlayHandle?.isActive()){this.overlayHandle.resume(),this.navigationTriggerOwner&&this.overlayHandle.updateRestoreFocusTo(this.resolveNavigationRestoreTarget);return}const active=deepActiveElement(this.ownerDocument);this.navigationOpener=active&&typeof active.focus=="function"&&!(this.drawerElement&&composedContains(this.drawerElement,active))?active:null,this.overlayHandle=activateOverlay({host:this,panel:()=>this.drawerElement??null,modalRoot:()=>this.drawerElement??null,onEscape:()=>this.hideNavigation(),onBackdrop:()=>this.hideNavigation(),...this.navigationTriggerOwner?{restoreFocusTo:this.resolveNavigationRestoreTarget}:{},lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:this.navigationDeferredReturn}),this.overlayHandle.focusInitial();return}if(this.overlayHandle){const restoreFocus=!!(changed?.has("navOpen")&&!this.navOpen);this.overlayHandle.deactivate({restoreFocus}),this.overlayHandle=void 0}this.navOpen||(this.navigationTriggerOwner=void 0)}syncCustomToggle(){const nextToggles=(this.shadowRoot?.querySelector('slot[name="navigation-toggle"]')?.assignedElements({flatten:!0})??[]).filter(candidate=>candidate.nodeType===1&&candidate.getRootNode()!==this.shadowRoot),previous=this.customToggle;this.customToggles=nextToggles,this.customToggle=nextToggles[0];for(const[host,ownership]of this.customToggleOwnership)nextToggles.includes(host)||(ownership.accessibleAria?.release(),ownership.hostAria.release(),this.customToggleOwnership.delete(host));const localizedLabel=this.localize(this.navOpen?"closeNavigation":"openNavigation"),drawer=this.drawerElement;for(const host of nextToggles){const accessible=resolveAccessibleTrigger(host);let ownership=this.customToggleOwnership.get(host);ownership?accessible!==ownership.accessible&&(ownership.accessibleAria?.release(),ownership.accessibleAria=void 0,ownership.accessible=accessible,ownership.accessibleAuthoredLabel=accessible.hasAttribute("aria-label")?accessible.getAttribute("aria-label")??"":null):(ownership={accessible,accessibleAuthoredLabel:accessible.hasAttribute("aria-label")?accessible.getAttribute("aria-label")??"":null,hostAria:acquireAriaOwnership(null,{}),hostAuthoredLabel:host.hasAttribute("aria-label")?host.getAttribute("aria-label")??"":null},this.customToggleOwnership.set(host,ownership)),ownership.hostAria.update(host,{attributes:{"aria-haspopup":"dialog","aria-expanded":this.navOpen?"true":"false","aria-label":ownership.hostAuthoredLabel??localizedLabel},controls:drawer?[drawer]:[]});const distinctAccessible=accessible===host?null:accessible,accessibleContribution={attributes:{"aria-haspopup":"dialog","aria-expanded":this.navOpen?"true":"false","aria-label":ownership.accessibleAuthoredLabel??ownership.hostAuthoredLabel??localizedLabel},controls:drawer?[drawer]:[]};ownership.accessibleAria?ownership.accessibleAria.update(distinctAccessible,accessibleContribution):ownership.accessibleAria=acquireAriaOwnership(distinctAccessible,accessibleContribution)}this.navOpen&&this.navigationTriggerOwner&&!nextToggles.includes(this.navigationTriggerOwner)?(this.navigationTriggerOwner=this.customToggle,this.overlayHandle?.updateRestoreFocusTo(this.resolveNavigationRestoreTarget)):this.navOpen&&previous&&this.navigationTriggerOwner===previous&&this.overlayHandle?.updateRestoreFocusTo(this.resolveNavigationRestoreTarget)}releaseCustomToggleA11y(){for(const ownership of this.customToggleOwnership.values())ownership.accessibleAria?.release(),ownership.hostAria.release();this.customToggleOwnership.clear(),this.customToggle=void 0,this.customToggles=[]}isUnavailableCustomToggle(trigger){const accessible=resolveAccessibleTrigger(trigger);return[trigger,accessible].some(candidate=>candidate.hasAttribute("hidden")||candidate.hasAttribute("inert")||candidate.matches(":disabled")||isAriaTrue(candidate.getAttribute("aria-hidden"))||isAriaTrue(candidate.getAttribute("aria-disabled")))}rememberTriggerAndToggle(trigger){this.syncCustomToggle(),this.navOpen||(this.navigationTriggerOwner=trigger),this.toggleNavigation()}requestNavOpen(next){this.navOpen===next||this.emit("lr-nav-toggle-request",{open:next},{cancelable:!0}).defaultPrevented||(this.navOpen=next,this.emit("lr-nav-open-change",{open:next}))}showNavigation(){this.requestNavOpen(!0)}hideNavigation(){this.requestNavOpen(!1)}toggleNavigation(){this.requestNavOpen(!this.navOpen)}visiblePixelsInViewport(element){if(!element)return 0;const rect=element.getBoundingClientRect();if(!Number.isFinite(rect.top)||!Number.isFinite(rect.bottom))return 0;const candidateHeight=element.ownerDocument.defaultView?.innerHeight??element.ownerDocument.documentElement.clientHeight;if(!Number.isFinite(candidateHeight)||candidateHeight<=0)return 0;const viewportHeight=finiteRange(candidateHeight,0,0),visible=Math.min(rect.bottom,viewportHeight)-Math.max(rect.top,0);return finiteRange(visible,0,0,viewportHeight)}render(){const mobile=this.view==="mobile",overlayOpen=mobile&&this.navOpen,navigationLabel=this.accessibleLabel??this.localize("navigation");return html`
1
+ import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{isAriaTrue}from"../../../internal/accessibility-visibility.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import{resolveCssLength}from"../../../internal/css-length.js";import{cancelDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{isComposedFocusAvailable}from"../../../internal/focus-navigation.js";import{menuIcon}from"../../../internal/icons.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteRange}from"../../../internal/numbers.js";import{activateOverlay,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{styles}from"./page.styles.js";import{LYRA_DEFAULT_closeNavigation,LYRA_DEFAULT_openNavigation,LYRA_DEFAULT_skipToContent}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_navigation}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_MOBILE_BREAKPOINT="768px";class LyraPage extends LyraElement{constructor(){super(...arguments),this.view="desktop",this.navOpen=!1,this.mobileBreakpoint="768px",this.navigationPlacement="start",this.disableNavigationToggle=!1,this.accessibleLabel=null,this.mainId=nextId("page-main"),this.navigationId=nextId("page-navigation"),this.drawerId=nextId("page-drawer"),this.skipTargetId=nextId("page-skip-target"),this.skipLabelId=nextId("page-skip-label"),this.fragmentTargetId=this.getAttribute("id")||this.skipTargetId,this.fragmentTabIndex=this.getAttribute("tabindex")??"-1",this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.hideNavigation()},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.hideNavigation(),this.navOpen&&this.view==="mobile"&&this.nativeModal.show()}}),this.navigationOpener=null,this.customToggles=[],this.customToggleOwnership=new Map,this.onWindowResize=()=>this.measureAllocation(),this.navigationDeferredReturn=()=>{const owner=this.navigationTriggerOwner,opener=owner?null:this.navigationOpener;if(this.navigationOpener=null,!(!owner&&!opener))return{candidates:()=>[owner?.isConnected?resolveAccessibleTrigger(owner):null,opener,this.disableNavigationToggle?null:this.renderRoot.querySelector('[part~="navigation-toggle"]'),this.mainElement],stranded:active=>!!this.drawerElement&&composedContains(this.drawerElement,active),isCurrent:()=>!this.navOpen}},this.resolveNavigationRestoreTarget=()=>{const owner=this.navigationTriggerOwner;if(owner?.isConnected){const accessible=resolveAccessibleTrigger(owner);if(isComposedFocusAvailable(accessible))return accessible}const builtIn=this.disableNavigationToggle?null:this.renderRoot.querySelector('[part~="navigation-toggle"]');return builtIn&&isComposedFocusAvailable(builtIn)?builtIn:this.mainElement&&isComposedFocusAvailable(this.mainElement)?this.mainElement:null},this.onDefaultToggleClick=event=>{this.rememberTriggerAndToggle(event.currentTarget)},this.onToggleSlotClick=event=>{const trigger=event.composedPath().find(candidate=>candidate?.nodeType===1&&candidate.getAttribute("slot")==="navigation-toggle");trigger&&this.customToggles.includes(trigger)&&!this.isUnavailableCustomToggle(trigger)&&this.rememberTriggerAndToggle(trigger)},this.onPageClick=event=>{const path=event.composedPath();if(path.some(candidate=>candidate?.nodeType===1&&candidate.getAttribute("slot")==="navigation-toggle"))return;const trigger=path.find(candidate=>candidate?.nodeType===1&&candidate.hasAttribute("data-toggle-nav"));trigger&&this.rememberTriggerAndToggle(trigger)},this.onBackdropClick=event=>{event.target===event.currentTarget&&this.overlayHandle?.dismissBackdrop()},this.onSkipClick=event=>{event.preventDefault(),this.mainElement?.focus(),this.mainElement?.scrollIntoView({block:"start"})}}static{this.defaultStrings={...super.defaultStrings,closeNavigation:LYRA_DEFAULT_closeNavigation,navigation:LYRA_DEFAULT_navigation,openNavigation:LYRA_DEFAULT_openNavigation,skipToContent:LYRA_DEFAULT_skipToContent}}static{this.knownUnobservedAttributes=["disable-sticky"]}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}connectedCallback(){super.connectedCallback(),this.measureAllocation(),this.observeAllocation(),this.hasUpdated&&this.view==="mobile"&&this.navOpen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.syncOverlay(),queueMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&queueMicrotask(()=>this.isConnected&&this.syncCustomToggle())}disconnectedCallback(){this.nativeModal.hide(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0,this.overlayHandle?.suspend(),cancelDeferredFocusReturn(this),this.releaseCustomToggleA11y(),super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed),this.measureAllocation(),this.observeAllocation()}willUpdate(changed){super.willUpdate(changed),this.view==="mobile"&&this.navOpen&&!this.overlayHandle&&this.nativeModal.prepare(),(this.view!=="mobile"||!this.navOpen)&&(this.nativeModal.hide(),this.nativeModal.prepare(!1)),changed.has("fragmentTargetId")&&!this.fragmentTargetId&&(this.fragmentTargetId=this.skipTargetId),changed.has("fragmentTabIndex")&&this.fragmentTabIndex===null&&(this.fragmentTabIndex="-1")}updated(changed){super.updated(changed),this.view==="mobile"&&this.navOpen&&this.nativeModal.show();const describedBy=this.view==="mobile"&&this.navOpen?this.getAttribute("aria-describedby"):null;for(const dialog of this.renderRoot.querySelectorAll('[part="drawer"], [data-native-modal-carrier]'))syncAriaDescribedByElements(this,dialog,describedBy);changed.has("mobileBreakpoint")&&changed.get("mobileBreakpoint")!==void 0&&this.measureAllocation(),this.overlayHandle!==void 0&&(!this.isConnected||this.view!=="mobile"||!this.navOpen)?(this.syncOverlay(changed),this.syncCustomToggle()):(this.syncCustomToggle(),this.syncOverlay(changed))}observeAllocation(){if(!this.isConnected)return;this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0;const view=this.ownerDocument.defaultView,ResizeObserverConstructor=view?.ResizeObserver;if(ResizeObserverConstructor){this.resizeObserver??=new ResizeObserverConstructor(entries=>{const entry=entries.find(candidate=>candidate.target===this)??entries[0],inlineSize=entry?.contentBoxSize?.[0]?.inlineSize??entry?.contentRect.width;inlineSize!==void 0&&view?.requestAnimationFrame(()=>{this.isConnected&&this.applyMeasuredInlineSize(inlineSize)})}),this.resizeObserver.observe(this);return}view&&(this.resizeView=view,view.addEventListener("resize",this.onWindowResize))}measureAllocation(){const width=this.getBoundingClientRect().width;width>0&&this.applyMeasuredInlineSize(width)}applyMeasuredInlineSize(width){if(!Number.isFinite(width)||width<0)return;const resolved=resolveCssLength(this.mobileBreakpoint,{host:this}),fallback=resolveCssLength(DEFAULT_MOBILE_BREAKPOINT,{host:this})??768,breakpoint=Math.max(0,resolved!==void 0&&Number.isFinite(resolved)?resolved:fallback),next=width<=breakpoint?"mobile":"desktop";next!==this.view&&(this.view=next)}syncOverlay(changed){if(this.isConnected&&this.view==="mobile"&&this.navOpen){if(this.overlayHandle?.isActive()){this.overlayHandle.resume(),this.navigationTriggerOwner&&this.overlayHandle.updateRestoreFocusTo(this.resolveNavigationRestoreTarget);return}const active=deepActiveElement(this.ownerDocument);this.navigationOpener=active&&typeof active.focus=="function"&&!(this.drawerElement&&composedContains(this.drawerElement,active))?active:null,this.overlayHandle=activateOverlay({host:this,panel:()=>this.drawerElement??null,modalRoot:()=>this.drawerElement??null,onEscape:()=>this.hideNavigation(),onBackdrop:()=>this.hideNavigation(),...this.navigationTriggerOwner?{restoreFocusTo:this.resolveNavigationRestoreTarget}:{},lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:this.navigationDeferredReturn}),this.overlayHandle.focusInitial();return}if(this.overlayHandle){const restoreFocus=!!(changed?.has("navOpen")&&!this.navOpen);this.overlayHandle.deactivate({restoreFocus}),this.overlayHandle=void 0}this.navOpen||(this.navigationTriggerOwner=void 0)}syncCustomToggle(){const nextToggles=(this.shadowRoot?.querySelector('slot[name="navigation-toggle"]')?.assignedElements({flatten:!0})??[]).filter(candidate=>candidate.nodeType===1&&candidate.getRootNode()!==this.shadowRoot),previous=this.customToggle;this.customToggles=nextToggles,this.customToggle=nextToggles[0];const nextToggleSet=new Set(nextToggles);for(const[host,ownership]of this.customToggleOwnership)nextToggleSet.has(host)||(ownership.accessibleAria?.release(),ownership.hostAria.release(),this.customToggleOwnership.delete(host));const localizedLabel=this.localize(this.navOpen?"closeNavigation":"openNavigation"),drawer=this.drawerElement;for(const host of nextToggles){const accessible=resolveAccessibleTrigger(host);let ownership=this.customToggleOwnership.get(host);ownership?accessible!==ownership.accessible&&(ownership.accessibleAria?.release(),ownership.accessibleAria=void 0,ownership.accessible=accessible,ownership.accessibleAuthoredLabel=accessible.hasAttribute("aria-label")?accessible.getAttribute("aria-label")??"":null):(ownership={accessible,accessibleAuthoredLabel:accessible.hasAttribute("aria-label")?accessible.getAttribute("aria-label")??"":null,hostAria:acquireAriaOwnership(null,{}),hostAuthoredLabel:host.hasAttribute("aria-label")?host.getAttribute("aria-label")??"":null},this.customToggleOwnership.set(host,ownership)),ownership.hostAria.update(host,{attributes:{"aria-haspopup":"dialog","aria-expanded":this.navOpen?"true":"false","aria-label":ownership.hostAuthoredLabel??localizedLabel},controls:drawer?[drawer]:[]});const distinctAccessible=accessible===host?null:accessible,accessibleContribution={attributes:{"aria-haspopup":"dialog","aria-expanded":this.navOpen?"true":"false","aria-label":ownership.accessibleAuthoredLabel??ownership.hostAuthoredLabel??localizedLabel},controls:drawer?[drawer]:[]};ownership.accessibleAria?ownership.accessibleAria.update(distinctAccessible,accessibleContribution):ownership.accessibleAria=acquireAriaOwnership(distinctAccessible,accessibleContribution)}this.navOpen&&this.navigationTriggerOwner&&!nextToggles.includes(this.navigationTriggerOwner)?(this.navigationTriggerOwner=this.customToggle,this.overlayHandle?.updateRestoreFocusTo(this.resolveNavigationRestoreTarget)):this.navOpen&&previous&&this.navigationTriggerOwner===previous&&this.overlayHandle?.updateRestoreFocusTo(this.resolveNavigationRestoreTarget)}releaseCustomToggleA11y(){for(const ownership of this.customToggleOwnership.values())ownership.accessibleAria?.release(),ownership.hostAria.release();this.customToggleOwnership.clear(),this.customToggle=void 0,this.customToggles=[]}isUnavailableCustomToggle(trigger){const accessible=resolveAccessibleTrigger(trigger);return[trigger,accessible].some(candidate=>candidate.hasAttribute("hidden")||candidate.hasAttribute("inert")||candidate.matches(":disabled")||isAriaTrue(candidate.getAttribute("aria-hidden"))||isAriaTrue(candidate.getAttribute("aria-disabled")))}rememberTriggerAndToggle(trigger){this.syncCustomToggle(),this.navOpen||(this.navigationTriggerOwner=trigger),this.toggleNavigation()}requestNavOpen(next){this.navOpen===next||this.emit("lr-nav-toggle-request",{open:next},{cancelable:!0}).defaultPrevented||(this.navOpen=next,this.emit("lr-nav-open-change",{open:next}))}showNavigation(){this.requestNavOpen(!0)}hideNavigation(){this.requestNavOpen(!1)}toggleNavigation(){this.requestNavOpen(!this.navOpen)}visiblePixelsInViewport(element){if(!element)return 0;const rect=element.getBoundingClientRect();if(!Number.isFinite(rect.top)||!Number.isFinite(rect.bottom))return 0;const candidateHeight=element.ownerDocument.defaultView?.innerHeight??element.ownerDocument.documentElement.clientHeight;if(!Number.isFinite(candidateHeight)||candidateHeight<=0)return 0;const viewportHeight=finiteRange(candidateHeight,0,0),visible=Math.min(rect.bottom,viewportHeight)-Math.max(rect.top,0);return finiteRange(visible,0,0,viewportHeight)}render(){const mobile=this.view==="mobile",overlayOpen=mobile&&this.navOpen,navigationLabel=this.accessibleLabel??this.localize("navigation");return html`
2
2
  <div part="base page" @click=${this.onPageClick}>
3
3
  <a
4
4
  part="skip-to-content"