_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
components/src/material/core/tokens/m3/definitions/unused/_md-comp-filled-tonal-icon-button.scss_0_3565
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-shape'; @use './md-sys-state'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-state': md-sys-state.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'secondary-container'), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-full'), 'container-size': if($exclude-hardcoded-values, null, 40px), 'disabled-container-color': map.get($deps, 'md-sys-color', 'on-surface'), 'disabled-container-opacity': if($exclude-hardcoded-values, null, 0.12), 'disabled-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'disabled-icon-opacity': if($exclude-hardcoded-values, null, 0.38), 'focus-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'focus-state-layer-opacity': map.get($deps, 'md-sys-state', 'focus-state-layer-opacity'), 'hover-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'icon-size': if($exclude-hardcoded-values, null, 24px), 'pressed-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'pressed-state-layer-opacity': map.get($deps, 'md-sys-state', 'pressed-state-layer-opacity'), 'selected-container-color': map.get($deps, 'md-sys-color', 'secondary-container'), 'toggle-selected-focus-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'toggle-selected-focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'toggle-selected-hover-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'toggle-selected-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'toggle-selected-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'toggle-selected-pressed-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'toggle-selected-pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'toggle-unselected-focus-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'toggle-unselected-focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'toggle-unselected-hover-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'toggle-unselected-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'toggle-unselected-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'toggle-unselected-pressed-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'toggle-unselected-pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'unselected-container-color': map.get($deps, 'md-sys-color', 'surface-variant') ); }
{ "end_byte": 3565, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-filled-tonal-icon-button.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-outlined-select.scss_0_2177
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-state'; @use './md-sys-typescale'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-state': md-sys-state.values(), 'md-sys-typescale': md-sys-typescale.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'menu-cascading-menu-indicator-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'menu-cascading-menu-indicator-icon-size': if($exclude-hardcoded-values, null, 24px), 'menu-container-color': map.get($deps, 'md-sys-color', 'surface'), 'menu-container-elevation': map.get($deps, 'md-sys-elevation', 'level2'), 'menu-container-shadow-color': map.get($deps, 'md-sys-color', 'shadow'), 'menu-container-shape': map.get($deps, 'md-sys-shape', 'corner-extra-small'), 'menu-container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'menu-divider-color': map.get($deps, 'md-sys-color', 'surface-variant'), 'menu-divider-height': if($exclude-hardcoded-values, null, 1px), 'menu-list-item-container-height': if($exclude-hardcoded-values, null, 48px), 'menu-list-item-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'menu-list-item-label-text-font': map.get($deps, 'md-sys-typescale', 'label-large-font'), 'menu-list-item-label-text-line-height': map.get($deps, 'md-sys-typescale', 'label-large-line-height'), 'menu-list-item-label-text-size': map.get($deps, 'md-sys-typescale', 'label-large-size'), 'menu-list-item-label-text-tracking': map.get($deps, 'md-sys-typescale', 'label-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.outlined-select.menu.list-item.label-text.tracking cannot be represented // in the "font" property shorthand. Consider using the discrete properties instead.
{ "end_byte": 2177, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-outlined-select.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-outlined-select.scss_2182_9619
'menu-list-item-label-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'label-large-weight') map.get($deps, 'md-sys-typescale', 'label-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'label-large-line-height' ) map.get($deps, 'md-sys-typescale', 'label-large-font') ), 'menu-list-item-label-text-weight': map.get($deps, 'md-sys-typescale', 'label-large-weight'), 'menu-list-item-selected-container-color': map.get($deps, 'md-sys-color', 'surface-variant'), 'menu-list-item-with-leading-icon-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'menu-list-item-with-leading-icon-leading-icon-size': if($exclude-hardcoded-values, null, 24px), 'menu-list-item-with-trailing-icon-trailing-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'menu-list-item-with-trailing-icon-trailing-icon-size': if($exclude-hardcoded-values, null, 24px), 'text-field-container-color': map.get($deps, 'md-sys-color', 'surface-variant'), 'text-field-container-shape': map.get($deps, 'md-sys-shape', 'corner-extra-small'), 'text-field-disabled-input-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-disabled-input-text-opacity': if($exclude-hardcoded-values, null, 0.38), 'text-field-disabled-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-disabled-label-text-opacity': if($exclude-hardcoded-values, null, 0.38), 'text-field-disabled-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-disabled-leading-icon-opacity': if($exclude-hardcoded-values, null, 0.38), 'text-field-disabled-outline-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-disabled-outline-opacity': if($exclude-hardcoded-values, null, 0.12), 'text-field-disabled-outline-width': if($exclude-hardcoded-values, null, 1px), 'text-field-disabled-supporting-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-disabled-supporting-text-opacity': if($exclude-hardcoded-values, null, 0.38), 'text-field-disabled-trailing-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-disabled-trailing-icon-opacity': if($exclude-hardcoded-values, null, 0.38), 'text-field-error-focus-input-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-error-focus-label-text-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-focus-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-error-focus-outline-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-focus-supporting-text-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-focus-trailing-icon-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-hover-input-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-error-hover-label-text-color': map.get($deps, 'md-sys-color', 'on-error-container'), 'text-field-error-hover-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-error-hover-outline-color': map.get($deps, 'md-sys-color', 'on-error-container'), 'text-field-error-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-error-hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'text-field-error-hover-supporting-text-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-hover-trailing-icon-color': map.get($deps, 'md-sys-color', 'on-error-container'), 'text-field-error-input-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-error-label-text-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-error-outline-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-supporting-text-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-trailing-icon-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-focus-input-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-focus-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'text-field-focus-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-focus-outline-color': map.get($deps, 'md-sys-color', 'primary'), 'text-field-focus-outline-width': if($exclude-hardcoded-values, null, 2px), 'text-field-focus-supporting-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-focus-trailing-icon-color': map.get($deps, 'md-sys-color', 'primary'), 'text-field-hover-input-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-hover-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-hover-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-hover-outline-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-hover-outline-width': if($exclude-hardcoded-values, null, 1px), 'text-field-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'text-field-hover-supporting-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-hover-trailing-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-input-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-input-text-font': map.get($deps, 'md-sys-typescale', 'body-large-font'), 'text-field-input-text-line-height': map.get($deps, 'md-sys-typescale', 'body-large-line-height'), 'text-field-input-text-size': map.get($deps, 'md-sys-typescale', 'body-large-size'), 'text-field-input-text-tracking': map.get($deps, 'md-sys-typescale', 'body-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.outlined-select.text-field.input-text.tracking cannot be represented in // the "font" property shorthand. Consider using the discrete properties instead. 'text-field-input-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'body-large-weight') map.get($deps, 'md-sys-typescale', 'body-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'body-large-line-height' ) map.get($deps, 'md-sys-typescale', 'body-large-font') ), 'text-field-input-text-weight': map.get($deps, 'md-sys-typescale', 'body-large-weight'), 'text-field-label-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-label-text-font': map.get($deps, 'md-sys-typescale', 'body-large-font'),
{ "end_byte": 9619, "start_byte": 2182, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-outlined-select.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-outlined-select.scss_9624_12728
'text-field-label-text-line-height': map.get($deps, 'md-sys-typescale', 'body-large-line-height'), 'text-field-label-text-populated-line-height': map.get($deps, 'md-sys-typescale', 'body-small-line-height'), 'text-field-label-text-populated-size': map.get($deps, 'md-sys-typescale', 'body-small-size'), 'text-field-label-text-size': map.get($deps, 'md-sys-typescale', 'body-large-size'), 'text-field-label-text-tracking': map.get($deps, 'md-sys-typescale', 'body-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.outlined-select.text-field.label-text.tracking cannot be represented in // the "font" property shorthand. Consider using the discrete properties instead. 'text-field-label-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'body-large-weight') map.get($deps, 'md-sys-typescale', 'body-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'body-large-line-height' ) map.get($deps, 'md-sys-typescale', 'body-large-font') ), 'text-field-label-text-weight': map.get($deps, 'md-sys-typescale', 'body-large-weight'), 'text-field-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-leading-icon-size': if($exclude-hardcoded-values, null, 24px), 'text-field-outline-color': map.get($deps, 'md-sys-color', 'outline'), 'text-field-outline-width': if($exclude-hardcoded-values, null, 1px), 'text-field-supporting-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-supporting-text-font': map.get($deps, 'md-sys-typescale', 'body-small-font'), 'text-field-supporting-text-line-height': map.get($deps, 'md-sys-typescale', 'body-small-line-height'), 'text-field-supporting-text-size': map.get($deps, 'md-sys-typescale', 'body-small-size'), 'text-field-supporting-text-tracking': map.get($deps, 'md-sys-typescale', 'body-small-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.outlined-select.text-field.supporting-text.tracking cannot be represented // in the "font" property shorthand. Consider using the discrete properties instead. 'text-field-supporting-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'body-small-weight') map.get($deps, 'md-sys-typescale', 'body-small-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'body-small-line-height' ) map.get($deps, 'md-sys-typescale', 'body-small-font') ), 'text-field-supporting-text-weight': map.get($deps, 'md-sys-typescale', 'body-small-weight'), 'text-field-trailing-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-trailing-icon-size': if($exclude-hardcoded-values, null, 24px) ); }
{ "end_byte": 12728, "start_byte": 9624, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-outlined-select.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-time-input.scss_0_1439
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-state'; @use './md-sys-typescale'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-state': md-sys-state.values(), 'md-sys-typescale': md-sys-typescale.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level3'), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-extra-large'), 'headline-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'headline-font': map.get($deps, 'md-sys-typescale', 'label-medium-font'), 'headline-line-height': map.get($deps, 'md-sys-typescale', 'label-medium-line-height'), 'headline-size': map.get($deps, 'md-sys-typescale', 'label-medium-size'), 'headline-tracking': map.get($deps, 'md-sys-typescale', 'label-medium-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.time-input.headline.tracking cannot be represented in the "font" property // shorthand. Consider using the discrete properties instead.
{ "end_byte": 1439, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-time-input.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-time-input.scss_1444_9373
'headline-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'label-medium-weight') map.get($deps, 'md-sys-typescale', 'label-medium-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'label-medium-line-height' ) map.get($deps, 'md-sys-typescale', 'label-medium-font') ), 'headline-weight': map.get($deps, 'md-sys-typescale', 'label-medium-weight'), 'period-selector-container-height': if($exclude-hardcoded-values, null, 72px), 'period-selector-container-shape': map.get($deps, 'md-sys-shape', 'corner-small'), 'period-selector-container-width': if($exclude-hardcoded-values, null, 52px), 'period-selector-focus-state-layer-opacity': map.get($deps, 'md-sys-state', 'focus-state-layer-opacity'), 'period-selector-hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'period-selector-label-text-font': map.get($deps, 'md-sys-typescale', 'title-medium-font'), 'period-selector-label-text-line-height': map.get($deps, 'md-sys-typescale', 'title-medium-line-height'), 'period-selector-label-text-size': map.get($deps, 'md-sys-typescale', 'title-medium-size'), 'period-selector-label-text-tracking': map.get($deps, 'md-sys-typescale', 'title-medium-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.time-input.period-selector.label-text.tracking cannot be represented in // the "font" property shorthand. Consider using the discrete properties instead. 'period-selector-label-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'title-medium-weight') map.get($deps, 'md-sys-typescale', 'title-medium-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'title-medium-line-height' ) map.get($deps, 'md-sys-typescale', 'title-medium-font') ), 'period-selector-label-text-weight': map.get($deps, 'md-sys-typescale', 'title-medium-weight'), 'period-selector-outline-color': map.get($deps, 'md-sys-color', 'outline'), 'period-selector-outline-width': if($exclude-hardcoded-values, null, 1px), 'period-selector-pressed-state-layer-opacity': map.get($deps, 'md-sys-state', 'pressed-state-layer-opacity'), 'period-selector-selected-container-color': map.get($deps, 'md-sys-color', 'tertiary-container'), 'period-selector-selected-focus-label-text-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'period-selector-selected-focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'period-selector-selected-hover-label-text-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'period-selector-selected-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'period-selector-selected-label-text-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'period-selector-selected-pressed-label-text-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'period-selector-selected-pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'period-selector-unselected-focus-label-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'period-selector-unselected-focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'period-selector-unselected-hover-label-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'period-selector-unselected-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'period-selector-unselected-label-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'period-selector-unselected-pressed-label-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'period-selector-unselected-pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'time-input-field-container-color': map.get($deps, 'md-sys-color', 'surface-variant'), 'time-input-field-container-height': if($exclude-hardcoded-values, null, 72px), 'time-input-field-container-shape': map.get($deps, 'md-sys-shape', 'corner-small'), 'time-input-field-container-width': if($exclude-hardcoded-values, null, 96px), 'time-input-field-focus-container-color': map.get($deps, 'md-sys-color', 'primary-container'), 'time-input-field-focus-label-text-color': map.get($deps, 'md-sys-color', 'on-primary-container'), 'time-input-field-focus-outline-color': map.get($deps, 'md-sys-color', 'primary'), 'time-input-field-focus-outline-width': if($exclude-hardcoded-values, null, 2px), 'time-input-field-hover-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'time-input-field-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'time-input-field-hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'time-input-field-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'time-input-field-label-text-font': map.get($deps, 'md-sys-typescale', 'display-medium-font'), 'time-input-field-label-text-line-height': map.get($deps, 'md-sys-typescale', 'display-medium-line-height'), 'time-input-field-label-text-size': map.get($deps, 'md-sys-typescale', 'display-medium-size'), 'time-input-field-label-text-tracking': map.get($deps, 'md-sys-typescale', 'display-medium-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.time-input.time-input-field.label-text.tracking cannot be represented // in the "font" property shorthand. Consider using the discrete properties instead. 'time-input-field-label-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'display-medium-weight') map.get($deps, 'md-sys-typescale', 'display-medium-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'display-medium-line-height' ) map.get($deps, 'md-sys-typescale', 'display-medium-font') ), 'time-input-field-label-text-weight': map.get($deps, 'md-sys-typescale', 'display-medium-weight'), 'time-input-field-separator-color': map.get($deps, 'md-sys-color', 'on-surface'), 'time-input-field-separator-font': map.get($deps, 'md-sys-typescale', 'display-large-font'), 'time-input-field-separator-line-height': map.get($deps, 'md-sys-typescale', 'display-large-line-height'), 'time-input-field-separator-size': map.get($deps, 'md-sys-typescale', 'display-large-size'), 'time-input-field-separator-tracking': map.get($deps, 'md-sys-typescale', 'display-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.time-input.time-input-field.separator.tracking cannot be represented // in the "font" property shorthand. Consider using the discrete properties instead. 'time-input-field-separator-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'display-large-weight') map.get($deps, 'md-sys-typescale', 'display-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'display-large-line-height' ) map.get($deps, 'md-sys-typescale', 'display-large-font') ),
{ "end_byte": 9373, "start_byte": 1444, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-time-input.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-time-input.scss_9378_10832
'time-input-field-separator-weight': map.get($deps, 'md-sys-typescale', 'display-large-weight'), 'time-input-field-supporting-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'time-input-field-supporting-text-font': map.get($deps, 'md-sys-typescale', 'body-small-font'), 'time-input-field-supporting-text-line-height': map.get($deps, 'md-sys-typescale', 'body-small-line-height'), 'time-input-field-supporting-text-size': map.get($deps, 'md-sys-typescale', 'body-small-size'), 'time-input-field-supporting-text-tracking': map.get($deps, 'md-sys-typescale', 'body-small-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.time-input.time-input-field.supporting-text.tracking cannot be represented // in the "font" property shorthand. Consider using the discrete properties instead. 'time-input-field-supporting-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'body-small-weight') map.get($deps, 'md-sys-typescale', 'body-small-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'body-small-line-height' ) map.get($deps, 'md-sys-typescale', 'body-small-font') ), 'time-input-field-supporting-text-weight': map.get($deps, 'md-sys-typescale', 'body-small-weight') ); }
{ "end_byte": 10832, "start_byte": 9378, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-time-input.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-carousel-item.scss_0_2487
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-state'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-state': md-sys-state.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level0'), 'container-shadow-color': map.get($deps, 'md-sys-color', 'shadow'), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-extra-large'), 'container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'disabled-container-color': map.get($deps, 'md-sys-color', 'surface'), 'disabled-container-elevation': map.get($deps, 'md-sys-elevation', 'level0'), 'disabled-container-opacity': if($exclude-hardcoded-values, null, 0.38), 'focus-container-elevation': map.get($deps, 'md-sys-elevation', 'level0'), 'focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'focus-state-layer-opacity': map.get($deps, 'md-sys-state', 'focus-state-layer-opacity'), 'hover-container-elevation': map.get($deps, 'md-sys-elevation', 'level1'), 'hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'pressed-container-elevation': map.get($deps, 'md-sys-elevation', 'level0'), 'pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'pressed-state-layer-opacity': map.get($deps, 'md-sys-state', 'pressed-state-layer-opacity'), 'with-outline-disabled-outline-color': map.get($deps, 'md-sys-color', 'outline'), 'with-outline-disabled-outline-opacity': if($exclude-hardcoded-values, null, 0.12), 'with-outline-focus-outline-color': map.get($deps, 'md-sys-color', 'on-surface'), 'with-outline-hover-outline-color': map.get($deps, 'md-sys-color', 'outline'), 'with-outline-outline-color': map.get($deps, 'md-sys-color', 'outline'), 'with-outline-outline-width': if($exclude-hardcoded-values, null, 1), 'with-outline-pressed-outline-color': map.get($deps, 'md-sys-color', 'outline') ); }
{ "end_byte": 2487, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-carousel-item.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-bottom-app-bar.scss_0_791
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level2'), 'container-height': if($exclude-hardcoded-values, null, 80px), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-none'), 'container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint') ); }
{ "end_byte": 791, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-bottom-app-bar.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-rich-tooltip.scss_0_5331
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-state'; @use './md-sys-typescale'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-state': md-sys-state.values(), 'md-sys-typescale': md-sys-typescale.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'action-focus-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'action-focus-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'action-focus-state-layer-opacity': map.get($deps, 'md-sys-state', 'focus-state-layer-opacity'), 'action-hover-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'action-hover-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'action-hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'action-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'action-label-text-font': map.get($deps, 'md-sys-typescale', 'label-large-font'), 'action-label-text-line-height': map.get($deps, 'md-sys-typescale', 'label-large-line-height'), 'action-label-text-size': map.get($deps, 'md-sys-typescale', 'label-large-size'), 'action-label-text-tracking': map.get($deps, 'md-sys-typescale', 'label-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.rich-tooltip.action.label-text.tracking cannot be represented in the // "font" property shorthand. Consider using the discrete properties instead. 'action-label-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'label-large-weight') map.get($deps, 'md-sys-typescale', 'label-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'label-large-line-height' ) map.get($deps, 'md-sys-typescale', 'label-large-font') ), 'action-label-text-weight': map.get($deps, 'md-sys-typescale', 'label-large-weight'), 'action-pressed-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'action-pressed-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'action-pressed-state-layer-opacity': map.get($deps, 'md-sys-state', 'pressed-state-layer-opacity'), 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level2'), 'container-shadow-color': map.get($deps, 'md-sys-color', 'shadow'), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-small'), 'container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'subhead-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'subhead-font': map.get($deps, 'md-sys-typescale', 'title-small-font'), 'subhead-line-height': map.get($deps, 'md-sys-typescale', 'title-small-line-height'), 'subhead-size': map.get($deps, 'md-sys-typescale', 'title-small-size'), 'subhead-tracking': map.get($deps, 'md-sys-typescale', 'title-small-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.rich-tooltip.subhead.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'subhead-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'title-small-weight') map.get($deps, 'md-sys-typescale', 'title-small-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'title-small-line-height' ) map.get($deps, 'md-sys-typescale', 'title-small-font') ), 'subhead-weight': map.get($deps, 'md-sys-typescale', 'title-small-weight'), 'supporting-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'supporting-text-font': map.get($deps, 'md-sys-typescale', 'body-medium-font'), 'supporting-text-line-height': map.get($deps, 'md-sys-typescale', 'body-medium-line-height'), 'supporting-text-size': map.get($deps, 'md-sys-typescale', 'body-medium-size'), 'supporting-text-tracking': map.get($deps, 'md-sys-typescale', 'body-medium-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.rich-tooltip.supporting-text.tracking cannot be represented in the // "font" property shorthand. Consider using the discrete properties instead. 'supporting-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'body-medium-weight') map.get($deps, 'md-sys-typescale', 'body-medium-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'body-medium-line-height' ) map.get($deps, 'md-sys-typescale', 'body-medium-font') ), 'supporting-text-weight': map.get($deps, 'md-sys-typescale', 'body-medium-weight') ); }
{ "end_byte": 5331, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-rich-tooltip.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-full-screen-dialog.scss_0_4740
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-state'; @use './md-sys-typescale'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-state': md-sys-state.values(), 'md-sys-typescale': md-sys-typescale.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level0'), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-none'), 'header-action-focus-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'header-action-focus-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'header-action-focus-state-layer-opacity': map.get($deps, 'md-sys-state', 'focus-state-layer-opacity'), 'header-action-hover-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'header-action-hover-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'header-action-hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'header-action-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'header-action-label-text-font': map.get($deps, 'md-sys-typescale', 'label-large-font'), 'header-action-label-text-line-height': map.get($deps, 'md-sys-typescale', 'label-large-line-height'), 'header-action-label-text-size': map.get($deps, 'md-sys-typescale', 'label-large-size'), 'header-action-label-text-tracking': map.get($deps, 'md-sys-typescale', 'label-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.full-screen-dialog.header.action.label-text.tracking cannot be // represented in the "font" property shorthand. Consider using the discrete properties instead. 'header-action-label-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'label-large-weight') map.get($deps, 'md-sys-typescale', 'label-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'label-large-line-height' ) map.get($deps, 'md-sys-typescale', 'label-large-font') ), 'header-action-label-text-weight': map.get($deps, 'md-sys-typescale', 'label-large-weight'), 'header-action-pressed-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'header-action-pressed-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'header-action-pressed-state-layer-opacity': map.get($deps, 'md-sys-state', 'pressed-state-layer-opacity'), 'header-container-color': map.get($deps, 'md-sys-color', 'surface'), 'header-container-elevation': map.get($deps, 'md-sys-elevation', 'level0'), 'header-container-height': if($exclude-hardcoded-values, null, 56px), 'header-container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'header-headline-color': map.get($deps, 'md-sys-color', 'on-surface'), 'header-headline-font': map.get($deps, 'md-sys-typescale', 'title-large-font'), 'header-headline-line-height': map.get($deps, 'md-sys-typescale', 'title-large-line-height'), 'header-headline-size': map.get($deps, 'md-sys-typescale', 'title-large-size'), 'header-headline-tracking': map.get($deps, 'md-sys-typescale', 'title-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.full-screen-dialog.header.headline.tracking cannot be represented in // the "font" property shorthand. Consider using the discrete properties instead. 'header-headline-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'title-large-weight') map.get($deps, 'md-sys-typescale', 'title-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'title-large-line-height' ) map.get($deps, 'md-sys-typescale', 'title-large-font') ), 'header-headline-weight': map.get($deps, 'md-sys-typescale', 'title-large-weight'), 'header-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'header-icon-size': if($exclude-hardcoded-values, null, 24px), 'header-on-scroll-container-elevation': map.get($deps, 'md-sys-elevation', 'level2') ); }
{ "end_byte": 4740, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-full-screen-dialog.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-extended-fab-surface.scss_0_3840
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-state'; @use './md-sys-typescale'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-state': md-sys-state.values(), 'md-sys-typescale': md-sys-typescale.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level3'), 'container-height': if($exclude-hardcoded-values, null, 56px), 'container-shadow-color': map.get($deps, 'md-sys-color', 'shadow'), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-large'), 'container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'focus-container-elevation': map.get($deps, 'md-sys-elevation', 'level3'), 'focus-icon-color': map.get($deps, 'md-sys-color', 'primary'), 'focus-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'focus-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'focus-state-layer-opacity': map.get($deps, 'md-sys-state', 'focus-state-layer-opacity'), 'hover-container-elevation': map.get($deps, 'md-sys-elevation', 'level4'), 'hover-icon-color': map.get($deps, 'md-sys-color', 'primary'), 'hover-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'hover-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'icon-color': map.get($deps, 'md-sys-color', 'primary'), 'icon-size': if($exclude-hardcoded-values, null, 24px), 'label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'label-text-font': map.get($deps, 'md-sys-typescale', 'label-large-font'), 'label-text-line-height': map.get($deps, 'md-sys-typescale', 'label-large-line-height'), 'label-text-size': map.get($deps, 'md-sys-typescale', 'label-large-size'), 'label-text-tracking': map.get($deps, 'md-sys-typescale', 'label-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.extended-fab.surface.label-text.tracking cannot be represented in // the "font" property shorthand. Consider using the discrete properties instead. 'label-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'label-large-weight') map.get($deps, 'md-sys-typescale', 'label-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'label-large-line-height' ) map.get($deps, 'md-sys-typescale', 'label-large-font') ), 'label-text-weight': map.get($deps, 'md-sys-typescale', 'label-large-weight'), 'lowered-container-elevation': map.get($deps, 'md-sys-elevation', 'level1'), 'lowered-focus-container-elevation': map.get($deps, 'md-sys-elevation', 'level1'), 'lowered-hover-container-elevation': map.get($deps, 'md-sys-elevation', 'level2'), 'lowered-pressed-container-elevation': map.get($deps, 'md-sys-elevation', 'level1'), 'pressed-container-elevation': map.get($deps, 'md-sys-elevation', 'level3'), 'pressed-icon-color': map.get($deps, 'md-sys-color', 'primary'), 'pressed-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'pressed-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'pressed-state-layer-opacity': map.get($deps, 'md-sys-state', 'pressed-state-layer-opacity') ); }
{ "end_byte": 3840, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-extended-fab-surface.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-top-app-bar-small.scss_0_2385
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-typescale'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-typescale': md-sys-typescale.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level0'), 'container-height': if($exclude-hardcoded-values, null, 64px), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-none'), 'container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'headline-color': map.get($deps, 'md-sys-color', 'on-surface'), 'headline-font': map.get($deps, 'md-sys-typescale', 'title-large-font'), 'headline-line-height': map.get($deps, 'md-sys-typescale', 'title-large-line-height'), 'headline-size': map.get($deps, 'md-sys-typescale', 'title-large-size'), 'headline-tracking': map.get($deps, 'md-sys-typescale', 'title-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.top-app-bar.small.headline.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'headline-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'title-large-weight') map.get($deps, 'md-sys-typescale', 'title-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'title-large-line-height' ) map.get($deps, 'md-sys-typescale', 'title-large-font') ), 'headline-weight': map.get($deps, 'md-sys-typescale', 'title-large-weight'), 'leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'leading-icon-size': if($exclude-hardcoded-values, null, 24px), 'on-scroll-container-elevation': map.get($deps, 'md-sys-elevation', 'level2'), 'trailing-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'trailing-icon-size': if($exclude-hardcoded-values, null, 24px) ); }
{ "end_byte": 2385, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-top-app-bar-small.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-top-app-bar-small-centered.scss_0_2523
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-typescale'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-typescale': md-sys-typescale.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'avatar-shape': map.get($deps, 'md-sys-shape', 'corner-full'), 'avatar-size': if($exclude-hardcoded-values, null, 30px), 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level0'), 'container-height': if($exclude-hardcoded-values, null, 64px), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-none'), 'container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'headline-color': map.get($deps, 'md-sys-color', 'on-surface'), 'headline-font': map.get($deps, 'md-sys-typescale', 'title-large-font'), 'headline-line-height': map.get($deps, 'md-sys-typescale', 'title-large-line-height'), 'headline-size': map.get($deps, 'md-sys-typescale', 'title-large-size'), 'headline-tracking': map.get($deps, 'md-sys-typescale', 'title-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.top-app-bar.small.centered.headline.tracking cannot be represented // in the "font" property shorthand. Consider using the discrete properties instead. 'headline-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'title-large-weight') map.get($deps, 'md-sys-typescale', 'title-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'title-large-line-height' ) map.get($deps, 'md-sys-typescale', 'title-large-font') ), 'headline-weight': map.get($deps, 'md-sys-typescale', 'title-large-weight'), 'leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'leading-icon-size': if($exclude-hardcoded-values, null, 24px), 'on-scroll-container-elevation': map.get($deps, 'md-sys-elevation', 'level2'), 'trailing-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'trailing-icon-size': if($exclude-hardcoded-values, null, 24px) ); }
{ "end_byte": 2523, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-top-app-bar-small-centered.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-date-input-modal.scss_0_3625
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-typescale'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-typescale': md-sys-typescale.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level3'), 'container-height': if($exclude-hardcoded-values, null, 512px), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-extra-large'), 'container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'container-width': if($exclude-hardcoded-values, null, 328px), 'header-container-height': if($exclude-hardcoded-values, null, 120px), 'header-container-width': if($exclude-hardcoded-values, null, 328px), 'header-headline-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'header-headline-font': map.get($deps, 'md-sys-typescale', 'headline-large-font'), 'header-headline-line-height': map.get($deps, 'md-sys-typescale', 'headline-large-line-height'), 'header-headline-size': map.get($deps, 'md-sys-typescale', 'headline-large-size'), 'header-headline-tracking': map.get($deps, 'md-sys-typescale', 'headline-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.date-input.modal.header.headline.tracking cannot be represented // in the "font" property shorthand. Consider using the discrete properties instead. 'header-headline-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'headline-large-weight') map.get($deps, 'md-sys-typescale', 'headline-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'headline-large-line-height' ) map.get($deps, 'md-sys-typescale', 'headline-large-font') ), 'header-headline-weight': map.get($deps, 'md-sys-typescale', 'headline-large-weight'), 'header-supporting-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'header-supporting-text-font': map.get($deps, 'md-sys-typescale', 'label-large-font'), 'header-supporting-text-line-height': map.get($deps, 'md-sys-typescale', 'label-large-line-height'), 'header-supporting-text-size': map.get($deps, 'md-sys-typescale', 'label-large-size'), 'header-supporting-text-tracking': map.get($deps, 'md-sys-typescale', 'label-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.date-input.modal.header.supporting-text.tracking cannot be represented // in the "font" property shorthand. Consider using the discrete properties instead. 'header-supporting-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'label-large-weight') map.get($deps, 'md-sys-typescale', 'label-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'label-large-line-height' ) map.get($deps, 'md-sys-typescale', 'label-large-font') ), 'header-supporting-text-weight': map.get($deps, 'md-sys-typescale', 'label-large-weight') ); }
{ "end_byte": 3625, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-date-input-modal.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-filled-select.scss_0_2175
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-state'; @use './md-sys-typescale'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-state': md-sys-state.values(), 'md-sys-typescale': md-sys-typescale.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'menu-cascading-menu-indicator-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'menu-cascading-menu-indicator-icon-size': if($exclude-hardcoded-values, null, 24px), 'menu-container-color': map.get($deps, 'md-sys-color', 'surface'), 'menu-container-elevation': map.get($deps, 'md-sys-elevation', 'level2'), 'menu-container-shadow-color': map.get($deps, 'md-sys-color', 'shadow'), 'menu-container-shape': map.get($deps, 'md-sys-shape', 'corner-extra-small'), 'menu-container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'menu-divider-color': map.get($deps, 'md-sys-color', 'surface-variant'), 'menu-divider-height': if($exclude-hardcoded-values, null, 1px), 'menu-list-item-container-height': if($exclude-hardcoded-values, null, 48px), 'menu-list-item-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'menu-list-item-label-text-font': map.get($deps, 'md-sys-typescale', 'label-large-font'), 'menu-list-item-label-text-line-height': map.get($deps, 'md-sys-typescale', 'label-large-line-height'), 'menu-list-item-label-text-size': map.get($deps, 'md-sys-typescale', 'label-large-size'), 'menu-list-item-label-text-tracking': map.get($deps, 'md-sys-typescale', 'label-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.filled-select.menu.list-item.label-text.tracking cannot be represented // in the "font" property shorthand. Consider using the discrete properties instead.
{ "end_byte": 2175, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-filled-select.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-filled-select.scss_2180_9425
'menu-list-item-label-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'label-large-weight') map.get($deps, 'md-sys-typescale', 'label-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'label-large-line-height' ) map.get($deps, 'md-sys-typescale', 'label-large-font') ), 'menu-list-item-label-text-weight': map.get($deps, 'md-sys-typescale', 'label-large-weight'), 'menu-list-item-selected-container-color': map.get($deps, 'md-sys-color', 'surface-variant'), 'menu-list-item-with-leading-icon-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'menu-list-item-with-leading-icon-leading-icon-size': if($exclude-hardcoded-values, null, 24px), 'menu-list-item-with-trailing-icon-trailing-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'menu-list-item-with-trailing-icon-trailing-icon-size': if($exclude-hardcoded-values, null, 24px), 'text-field-active-indicator-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-active-indicator-height': if($exclude-hardcoded-values, null, 1px), 'text-field-container-color': map.get($deps, 'md-sys-color', 'surface-variant'), 'text-field-container-shape': map.get($deps, 'md-sys-shape', 'corner-extra-small-top'), 'text-field-disabled-active-indicator-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-disabled-active-indicator-height': if($exclude-hardcoded-values, null, 1px), 'text-field-disabled-active-indicator-opacity': if($exclude-hardcoded-values, null, 0.38), 'text-field-disabled-container-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-disabled-container-opacity': if($exclude-hardcoded-values, null, 0.04), 'text-field-disabled-input-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-disabled-input-text-opacity': if($exclude-hardcoded-values, null, 0.38), 'text-field-disabled-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-disabled-label-text-opacity': if($exclude-hardcoded-values, null, 0.38), 'text-field-disabled-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-disabled-leading-icon-opacity': if($exclude-hardcoded-values, null, 0.38), 'text-field-disabled-supporting-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-disabled-supporting-text-opacity': if($exclude-hardcoded-values, null, 0.38), 'text-field-disabled-trailing-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-disabled-trailing-icon-opacity': if($exclude-hardcoded-values, null, 0.38), 'text-field-error-active-indicator-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-focus-active-indicator-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-focus-input-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-error-focus-label-text-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-focus-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-error-focus-supporting-text-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-focus-trailing-icon-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-hover-active-indicator-color': map.get($deps, 'md-sys-color', 'on-error-container'), 'text-field-error-hover-input-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-error-hover-label-text-color': map.get($deps, 'md-sys-color', 'on-error-container'), 'text-field-error-hover-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-error-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-error-hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'text-field-error-hover-supporting-text-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-hover-trailing-icon-color': map.get($deps, 'md-sys-color', 'on-error-container'), 'text-field-error-input-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-error-label-text-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-error-supporting-text-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-error-trailing-icon-color': map.get($deps, 'md-sys-color', 'error'), 'text-field-focus-active-indicator-color': map.get($deps, 'md-sys-color', 'primary'), 'text-field-focus-active-indicator-height': if($exclude-hardcoded-values, null, 2px), 'text-field-focus-input-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-focus-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'text-field-focus-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-focus-supporting-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-focus-trailing-icon-color': map.get($deps, 'md-sys-color', 'primary'), 'text-field-hover-active-indicator-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-hover-active-indicator-height': if($exclude-hardcoded-values, null, 1px), 'text-field-hover-input-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-hover-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-hover-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'text-field-hover-supporting-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-hover-trailing-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-input-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'text-field-input-text-font': map.get($deps, 'md-sys-typescale', 'body-large-font'), 'text-field-input-text-line-height': map.get($deps, 'md-sys-typescale', 'body-large-line-height'), 'text-field-input-text-size': map.get($deps, 'md-sys-typescale', 'body-large-size'), 'text-field-input-text-tracking': map.get($deps, 'md-sys-typescale', 'body-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.filled-select.text-field.input-text.tracking cannot be represented in // the "font" property shorthand. Consider using the discrete properties instead.
{ "end_byte": 9425, "start_byte": 2180, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-filled-select.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-filled-select.scss_9430_13072
'text-field-input-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'body-large-weight') map.get($deps, 'md-sys-typescale', 'body-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'body-large-line-height' ) map.get($deps, 'md-sys-typescale', 'body-large-font') ), 'text-field-input-text-weight': map.get($deps, 'md-sys-typescale', 'body-large-weight'), 'text-field-label-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-label-text-font': map.get($deps, 'md-sys-typescale', 'body-large-font'), 'text-field-label-text-line-height': map.get($deps, 'md-sys-typescale', 'body-large-line-height'), 'text-field-label-text-populated-line-height': map.get($deps, 'md-sys-typescale', 'body-small-line-height'), 'text-field-label-text-populated-size': map.get($deps, 'md-sys-typescale', 'body-small-size'), 'text-field-label-text-size': map.get($deps, 'md-sys-typescale', 'body-large-size'), 'text-field-label-text-tracking': map.get($deps, 'md-sys-typescale', 'body-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.filled-select.text-field.label-text.tracking cannot be represented in // the "font" property shorthand. Consider using the discrete properties instead. 'text-field-label-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'body-large-weight') map.get($deps, 'md-sys-typescale', 'body-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'body-large-line-height' ) map.get($deps, 'md-sys-typescale', 'body-large-font') ), 'text-field-label-text-weight': map.get($deps, 'md-sys-typescale', 'body-large-weight'), 'text-field-leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-leading-icon-size': if($exclude-hardcoded-values, null, 20px), 'text-field-supporting-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-supporting-text-font': map.get($deps, 'md-sys-typescale', 'body-small-font'), 'text-field-supporting-text-line-height': map.get($deps, 'md-sys-typescale', 'body-small-line-height'), 'text-field-supporting-text-size': map.get($deps, 'md-sys-typescale', 'body-small-size'), 'text-field-supporting-text-tracking': map.get($deps, 'md-sys-typescale', 'body-small-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.filled-select.text-field.supporting-text.tracking cannot be represented // in the "font" property shorthand. Consider using the discrete properties instead. 'text-field-supporting-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'body-small-weight') map.get($deps, 'md-sys-typescale', 'body-small-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'body-small-line-height' ) map.get($deps, 'md-sys-typescale', 'body-small-font') ), 'text-field-supporting-text-weight': map.get($deps, 'md-sys-typescale', 'body-small-weight'), 'text-field-trailing-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'text-field-trailing-icon-size': if($exclude-hardcoded-values, null, 24px) ); }
{ "end_byte": 13072, "start_byte": 9430, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-filled-select.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-divider.scss_0_400
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; $_default: ( 'md-sys-color': md-sys-color.values-light(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'color': map.get($deps, 'md-sys-color', 'outline-variant'), 'thickness': if($exclude-hardcoded-values, null, 1px) ); }
{ "end_byte": 400, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-divider.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-fab-branded.scss_0_2184
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-state'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-state': md-sys-state.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level3'), 'container-height': if($exclude-hardcoded-values, null, 56px), 'container-shadow-color': map.get($deps, 'md-sys-color', 'shadow'), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-large'), 'container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'container-width': if($exclude-hardcoded-values, null, 56px), 'focus-container-elevation': map.get($deps, 'md-sys-elevation', 'level3'), 'focus-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'focus-state-layer-opacity': map.get($deps, 'md-sys-state', 'focus-state-layer-opacity'), 'hover-container-elevation': map.get($deps, 'md-sys-elevation', 'level4'), 'hover-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'icon-size': if($exclude-hardcoded-values, null, 36px), 'lowered-container-elevation': map.get($deps, 'md-sys-elevation', 'level1'), 'lowered-focus-container-elevation': map.get($deps, 'md-sys-elevation', 'level1'), 'lowered-hover-container-elevation': map.get($deps, 'md-sys-elevation', 'level2'), 'lowered-pressed-container-elevation': map.get($deps, 'md-sys-elevation', 'level1'), 'pressed-container-elevation': map.get($deps, 'md-sys-elevation', 'level3'), 'pressed-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'pressed-state-layer-opacity': map.get($deps, 'md-sys-state', 'pressed-state-layer-opacity') ); }
{ "end_byte": 2184, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-fab-branded.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-menu.scss_0_868
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), ); @function values($deps: $_default) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level2'), 'container-shadow-color': map.get($deps, 'md-sys-color', 'shadow'), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-extra-small'), 'container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'list-item-selected-container-color': map.get($deps, 'md-sys-color', 'surface-variant') ); }
{ "end_byte": 868, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-menu.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-sheet-floating.scss_0_697
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), ); @function values($deps: $_default) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level1'), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-extra-large'), 'container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint') ); }
{ "end_byte": 697, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-sheet-floating.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-top-app-bar-large.scss_0_2339
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-typescale'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-typescale': md-sys-typescale.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level0'), 'container-height': if($exclude-hardcoded-values, null, 152px), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-none'), 'container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'headline-color': map.get($deps, 'md-sys-color', 'on-surface'), 'headline-font': map.get($deps, 'md-sys-typescale', 'headline-medium-font'), 'headline-line-height': map.get($deps, 'md-sys-typescale', 'headline-medium-line-height'), 'headline-size': map.get($deps, 'md-sys-typescale', 'headline-medium-size'), 'headline-tracking': map.get($deps, 'md-sys-typescale', 'headline-medium-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.top-app-bar.large.headline.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'headline-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'headline-medium-weight') map.get($deps, 'md-sys-typescale', 'headline-medium-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'headline-medium-line-height' ) map.get($deps, 'md-sys-typescale', 'headline-medium-font') ), 'headline-weight': map.get($deps, 'md-sys-typescale', 'headline-medium-weight'), 'leading-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'leading-icon-size': if($exclude-hardcoded-values, null, 24px), 'trailing-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'trailing-icon-size': if($exclude-hardcoded-values, null, 24px) ); }
{ "end_byte": 2339, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-top-app-bar-large.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-fab-tertiary-large.scss_0_2491
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-state'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-state': md-sys-state.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'tertiary-container'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level3'), 'container-height': if($exclude-hardcoded-values, null, 96px), 'container-shadow-color': map.get($deps, 'md-sys-color', 'shadow'), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-extra-large'), 'container-width': if($exclude-hardcoded-values, null, 96px), 'focus-container-elevation': map.get($deps, 'md-sys-elevation', 'level3'), 'focus-icon-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'focus-state-layer-opacity': map.get($deps, 'md-sys-state', 'focus-state-layer-opacity'), 'hover-container-elevation': map.get($deps, 'md-sys-elevation', 'level4'), 'hover-icon-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'icon-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'icon-size': if($exclude-hardcoded-values, null, 36px), 'lowered-container-elevation': map.get($deps, 'md-sys-elevation', 'level1'), 'lowered-focus-container-elevation': map.get($deps, 'md-sys-elevation', 'level1'), 'lowered-hover-container-elevation': map.get($deps, 'md-sys-elevation', 'level2'), 'lowered-pressed-container-elevation': map.get($deps, 'md-sys-elevation', 'level1'), 'pressed-container-elevation': map.get($deps, 'md-sys-elevation', 'level3'), 'pressed-icon-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'pressed-state-layer-opacity': map.get($deps, 'md-sys-state', 'pressed-state-layer-opacity') ); }
{ "end_byte": 2491, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-fab-tertiary-large.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-sheet-bottom.scss_0_1287
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'docked-container-color': map.get($deps, 'md-sys-color', 'surface'), 'docked-container-shape': map.get($deps, 'md-sys-shape', 'corner-extra-large-top'), 'docked-container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'docked-drag-handle-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'docked-drag-handle-height': if($exclude-hardcoded-values, null, 4px), 'docked-drag-handle-opacity': if($exclude-hardcoded-values, null, 0.4), 'docked-drag-handle-width': if($exclude-hardcoded-values, null, 32px), 'docked-minimized-container-shape': map.get($deps, 'md-sys-shape', 'corner-none'), 'docked-modal-container-elevation': map.get($deps, 'md-sys-elevation', 'level1'), 'docked-standard-container-elevation': map.get($deps, 'md-sys-elevation', 'level1') ); }
{ "end_byte": 1287, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-sheet-bottom.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-scrim.scss_0_409
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; $_default: ( 'md-sys-color': md-sys-color.values-light(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'scrim'), 'container-opacity': if($exclude-hardcoded-values, null, 0.32) ); }
{ "end_byte": 409, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-scrim.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-navigation-rail.scss_0_5802
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-state'; @use './md-sys-typescale'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-state': md-sys-state.values(), 'md-sys-typescale': md-sys-typescale.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'active-indicator-color': map.get($deps, 'md-sys-color', 'secondary-container'), 'active-indicator-height': if($exclude-hardcoded-values, null, 32px), 'active-indicator-shape': map.get($deps, 'md-sys-shape', 'corner-full'), 'active-indicator-width': if($exclude-hardcoded-values, null, 56px), 'active-focus-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'active-focus-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'active-focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'active-hover-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'active-hover-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'active-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'active-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'active-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'active-label-text-weight': map.get($deps, 'md-sys-typescale', 'label-medium-weight-prominent'), 'active-pressed-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'active-pressed-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'active-pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level0'), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-none'), 'container-width': if($exclude-hardcoded-values, null, 80px), 'focus-state-layer-opacity': map.get($deps, 'md-sys-state', 'focus-state-layer-opacity'), 'hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'icon-size': if($exclude-hardcoded-values, null, 24px), 'inactive-focus-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'inactive-focus-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'inactive-focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'inactive-hover-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'inactive-hover-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'inactive-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'inactive-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'inactive-label-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'inactive-pressed-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'inactive-pressed-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'inactive-pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'label-text-font': map.get($deps, 'md-sys-typescale', 'label-medium-font'), 'label-text-line-height': map.get($deps, 'md-sys-typescale', 'label-medium-line-height'), 'label-text-size': map.get($deps, 'md-sys-typescale', 'label-medium-size'), 'label-text-tracking': map.get($deps, 'md-sys-typescale', 'label-medium-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.navigation-rail.label-text.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'label-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'label-medium-weight') map.get($deps, 'md-sys-typescale', 'label-medium-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'label-medium-line-height' ) map.get($deps, 'md-sys-typescale', 'label-medium-font') ), 'label-text-weight': map.get($deps, 'md-sys-typescale', 'label-medium-weight'), 'menu-focus-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'menu-focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'menu-focus-state-layer-opacity': map.get($deps, 'md-sys-state', 'focus-state-layer-opacity'), 'menu-hover-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'menu-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'menu-hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'menu-icon-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'menu-icon-size': if($exclude-hardcoded-values, null, 24px), 'menu-pressed-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'menu-pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'menu-pressed-state-layer-opacity': map.get($deps, 'md-sys-state', 'pressed-state-layer-opacity'), 'no-label-active-indicator-height': if($exclude-hardcoded-values, null, 56px), 'no-label-active-indicator-shape': map.get($deps, 'md-sys-shape', 'corner-full'), 'pressed-state-layer-opacity': map.get($deps, 'md-sys-state', 'pressed-state-layer-opacity') ); }
{ "end_byte": 5802, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-navigation-rail.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-sheet-side.scss_0_3526
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-state'; @use './md-sys-typescale'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-state': md-sys-state.values(), 'md-sys-typescale': md-sys-typescale.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'detached-container-shape': map.get($deps, 'md-sys-shape', 'corner-large'), 'docked-action-focus-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'docked-action-focus-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'docked-action-focus-state-layer-opacity': map.get($deps, 'md-sys-state', 'focus-state-layer-opacity'), 'docked-action-hover-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'docked-action-hover-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'docked-action-hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'docked-action-pressed-label-text-color': map.get($deps, 'md-sys-color', 'primary'), 'docked-action-pressed-state-layer-color': map.get($deps, 'md-sys-color', 'primary'), 'docked-action-pressed-state-layer-opacity': map.get($deps, 'md-sys-state', 'pressed-state-layer-opacity'), 'docked-container-color': map.get($deps, 'md-sys-color', 'surface'), 'docked-container-height': if($exclude-hardcoded-values, null, 100%), 'docked-container-shape': map.get($deps, 'md-sys-shape', 'corner-none'), 'docked-container-surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'docked-container-width': if($exclude-hardcoded-values, null, 256px), 'docked-divider-color': map.get($deps, 'md-sys-color', 'outline'), 'docked-headline-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'docked-headline-font': map.get($deps, 'md-sys-typescale', 'title-large-font'), 'docked-headline-line-height': map.get($deps, 'md-sys-typescale', 'title-large-line-height'), 'docked-headline-size': map.get($deps, 'md-sys-typescale', 'title-large-size'), 'docked-headline-tracking': map.get($deps, 'md-sys-typescale', 'title-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.sheet.side.docked.headline.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'docked-headline-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'title-large-weight') map.get($deps, 'md-sys-typescale', 'title-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'title-large-line-height' ) map.get($deps, 'md-sys-typescale', 'title-large-font') ), 'docked-headline-weight': map.get($deps, 'md-sys-typescale', 'title-large-weight'), 'docked-modal-container-elevation': map.get($deps, 'md-sys-elevation', 'level1'), 'docked-modal-container-shape': map.get($deps, 'md-sys-shape', 'corner-large-start'), 'docked-standard-container-elevation': map.get($deps, 'md-sys-elevation', 'level0') ); }
{ "end_byte": 3526, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-sheet-side.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-filled-tonal-button.scss_0_4232
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-state'; @use './md-sys-typescale'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-state': md-sys-state.values(), 'md-sys-typescale': md-sys-typescale.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'container-color': map.get($deps, 'md-sys-color', 'secondary-container'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level0'), 'container-height': if($exclude-hardcoded-values, null, 40px), 'container-shadow-color': map.get($deps, 'md-sys-color', 'shadow'), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-full'), 'disabled-container-color': map.get($deps, 'md-sys-color', 'on-surface'), 'disabled-container-elevation': map.get($deps, 'md-sys-elevation', 'level0'), 'disabled-container-opacity': if($exclude-hardcoded-values, null, 0.12), 'disabled-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'disabled-label-text-opacity': if($exclude-hardcoded-values, null, 0.38), 'focus-container-elevation': map.get($deps, 'md-sys-elevation', 'level0'), 'focus-label-text-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'focus-state-layer-opacity': map.get($deps, 'md-sys-state', 'focus-state-layer-opacity'), 'hover-container-elevation': map.get($deps, 'md-sys-elevation', 'level1'), 'hover-label-text-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'label-text-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'label-text-font': map.get($deps, 'md-sys-typescale', 'label-large-font'), 'label-text-line-height': map.get($deps, 'md-sys-typescale', 'label-large-line-height'), 'label-text-size': map.get($deps, 'md-sys-typescale', 'label-large-size'), 'label-text-tracking': map.get($deps, 'md-sys-typescale', 'label-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.filled-tonal-button.label-text.tracking cannot be represented in the // "font" property shorthand. Consider using the discrete properties instead. 'label-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'label-large-weight') map.get($deps, 'md-sys-typescale', 'label-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'label-large-line-height' ) map.get($deps, 'md-sys-typescale', 'label-large-font') ), 'label-text-weight': map.get($deps, 'md-sys-typescale', 'label-large-weight'), 'pressed-container-elevation': map.get($deps, 'md-sys-elevation', 'level0'), 'pressed-label-text-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'pressed-state-layer-opacity': map.get($deps, 'md-sys-state', 'pressed-state-layer-opacity'), 'with-icon-disabled-icon-color': map.get($deps, 'md-sys-color', 'on-surface'), 'with-icon-disabled-icon-opacity': if($exclude-hardcoded-values, null, 0.38), 'with-icon-focus-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'with-icon-hover-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'with-icon-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container'), 'with-icon-icon-size': if($exclude-hardcoded-values, null, 18px), 'with-icon-pressed-icon-color': map.get($deps, 'md-sys-color', 'on-secondary-container') ); }
{ "end_byte": 4232, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-filled-tonal-button.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-time-picker.scss_0_1369
// // Design system display name: Material 3 // Design system version: v0.161 // @use 'sass:map'; @use './md-sys-color'; @use './md-sys-elevation'; @use './md-sys-shape'; @use './md-sys-state'; @use './md-sys-typescale'; $_default: ( 'md-sys-color': md-sys-color.values-light(), 'md-sys-elevation': md-sys-elevation.values(), 'md-sys-shape': md-sys-shape.values(), 'md-sys-state': md-sys-state.values(), 'md-sys-typescale': md-sys-typescale.values(), ); @function values($deps: $_default, $exclude-hardcoded-values: false) { @return ( 'clock-dial-color': map.get($deps, 'md-sys-color', 'surface-variant'), 'clock-dial-container-size': if($exclude-hardcoded-values, null, 256px), 'clock-dial-label-text-font': map.get($deps, 'md-sys-typescale', 'body-large-font'), 'clock-dial-label-text-line-height': map.get($deps, 'md-sys-typescale', 'body-large-line-height'), 'clock-dial-label-text-size': map.get($deps, 'md-sys-typescale', 'body-large-size'), 'clock-dial-label-text-tracking': map.get($deps, 'md-sys-typescale', 'body-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.time-picker.clock-dial.label-text.tracking cannot be represented in the // "font" property shorthand. Consider using the discrete properties instead.
{ "end_byte": 1369, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-time-picker.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-time-picker.scss_1374_9141
'clock-dial-label-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'body-large-weight') map.get($deps, 'md-sys-typescale', 'body-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'body-large-line-height' ) map.get($deps, 'md-sys-typescale', 'body-large-font') ), 'clock-dial-label-text-weight': map.get($deps, 'md-sys-typescale', 'body-large-weight'), 'clock-dial-selected-label-text-color': map.get($deps, 'md-sys-color', 'on-primary'), 'clock-dial-selector-center-container-color': map.get($deps, 'md-sys-color', 'primary'), 'clock-dial-selector-center-container-shape': map.get($deps, 'md-sys-shape', 'corner-full'), 'clock-dial-selector-center-container-size': if($exclude-hardcoded-values, null, 8px), 'clock-dial-selector-handle-container-color': map.get($deps, 'md-sys-color', 'primary'), 'clock-dial-selector-handle-container-shape': map.get($deps, 'md-sys-shape', 'corner-full'), 'clock-dial-selector-handle-container-size': if($exclude-hardcoded-values, null, 48px), 'clock-dial-selector-track-container-color': map.get($deps, 'md-sys-color', 'primary'), 'clock-dial-selector-track-container-width': if($exclude-hardcoded-values, null, 2px), 'clock-dial-shape': map.get($deps, 'md-sys-shape', 'corner-full'), 'clock-dial-unselected-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'container-color': map.get($deps, 'md-sys-color', 'surface'), 'container-elevation': map.get($deps, 'md-sys-elevation', 'level3'), 'container-shape': map.get($deps, 'md-sys-shape', 'corner-extra-large'), 'headline-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'headline-font': map.get($deps, 'md-sys-typescale', 'label-medium-font'), 'headline-line-height': map.get($deps, 'md-sys-typescale', 'label-medium-line-height'), 'headline-size': map.get($deps, 'md-sys-typescale', 'label-medium-size'), 'headline-tracking': map.get($deps, 'md-sys-typescale', 'label-medium-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.time-picker.headline.tracking cannot be represented in the "font" property // shorthand. Consider using the discrete properties instead. 'headline-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'label-medium-weight') map.get($deps, 'md-sys-typescale', 'label-medium-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'label-medium-line-height' ) map.get($deps, 'md-sys-typescale', 'label-medium-font') ), 'headline-weight': map.get($deps, 'md-sys-typescale', 'label-medium-weight'), 'period-selector-container-shape': map.get($deps, 'md-sys-shape', 'corner-small'), 'period-selector-focus-state-layer-opacity': map.get($deps, 'md-sys-state', 'focus-state-layer-opacity'), 'period-selector-horizontal-container-height': if($exclude-hardcoded-values, null, 38px), 'period-selector-horizontal-container-width': if($exclude-hardcoded-values, null, 216px), 'period-selector-hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'period-selector-label-text-font': map.get($deps, 'md-sys-typescale', 'title-medium-font'), 'period-selector-label-text-line-height': map.get($deps, 'md-sys-typescale', 'title-medium-line-height'), 'period-selector-label-text-size': map.get($deps, 'md-sys-typescale', 'title-medium-size'), 'period-selector-label-text-tracking': map.get($deps, 'md-sys-typescale', 'title-medium-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.time-picker.period-selector.label-text.tracking cannot be represented in // the "font" property shorthand. Consider using the discrete properties instead. 'period-selector-label-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'title-medium-weight') map.get($deps, 'md-sys-typescale', 'title-medium-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'title-medium-line-height' ) map.get($deps, 'md-sys-typescale', 'title-medium-font') ), 'period-selector-label-text-weight': map.get($deps, 'md-sys-typescale', 'title-medium-weight'), 'period-selector-outline-color': map.get($deps, 'md-sys-color', 'outline'), 'period-selector-outline-width': if($exclude-hardcoded-values, null, 1px), 'period-selector-pressed-state-layer-opacity': map.get($deps, 'md-sys-state', 'pressed-state-layer-opacity'), 'period-selector-selected-container-color': map.get($deps, 'md-sys-color', 'tertiary-container'), 'period-selector-selected-focus-label-text-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'period-selector-selected-focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'period-selector-selected-hover-label-text-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'period-selector-selected-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'period-selector-selected-label-text-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'period-selector-selected-pressed-label-text-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'period-selector-selected-pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-tertiary-container'), 'period-selector-unselected-focus-label-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'period-selector-unselected-focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'period-selector-unselected-hover-label-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'period-selector-unselected-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'period-selector-unselected-label-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'period-selector-unselected-pressed-label-text-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'period-selector-unselected-pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface-variant'), 'period-selector-vertical-container-height': if($exclude-hardcoded-values, null, 80px), 'period-selector-vertical-container-width': if($exclude-hardcoded-values, null, 52px), 'surface-tint-layer-color': map.get($deps, 'md-sys-color', 'surface-tint'), 'time-selector-24h-vertical-container-width': if($exclude-hardcoded-values, null, 114px), 'time-selector-container-height': if($exclude-hardcoded-values, null, 80px), 'time-selector-container-shape': map.get($deps, 'md-sys-shape', 'corner-small'), 'time-selector-container-width': if($exclude-hardcoded-values, null, 96px), 'time-selector-focus-state-layer-opacity': map.get($deps, 'md-sys-state', 'focus-state-layer-opacity'), 'time-selector-hover-state-layer-opacity': map.get($deps, 'md-sys-state', 'hover-state-layer-opacity'), 'time-selector-label-text-font': map.get($deps, 'md-sys-typescale', 'display-large-font'), 'time-selector-label-text-line-height': map.get($deps, 'md-sys-typescale', 'display-large-line-height'),
{ "end_byte": 9141, "start_byte": 1374, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-time-picker.scss" }
components/src/material/core/tokens/m3/definitions/unused/_md-comp-time-picker.scss_9146_13321
'time-selector-label-text-size': map.get($deps, 'md-sys-typescale', 'display-large-size'), 'time-selector-label-text-tracking': map.get($deps, 'md-sys-typescale', 'display-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.time-picker.time-selector.label-text.tracking cannot be represented in // the "font" property shorthand. Consider using the discrete properties instead. 'time-selector-label-text-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'display-large-weight') map.get($deps, 'md-sys-typescale', 'display-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'display-large-line-height' ) map.get($deps, 'md-sys-typescale', 'display-large-font') ), 'time-selector-label-text-weight': map.get($deps, 'md-sys-typescale', 'display-large-weight'), 'time-selector-pressed-state-layer-opacity': map.get($deps, 'md-sys-state', 'pressed-state-layer-opacity'), 'time-selector-selected-container-color': map.get($deps, 'md-sys-color', 'primary-container'), 'time-selector-selected-focus-label-text-color': map.get($deps, 'md-sys-color', 'on-primary-container'), 'time-selector-selected-focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-primary-container'), 'time-selector-selected-hover-label-text-color': map.get($deps, 'md-sys-color', 'on-primary-container'), 'time-selector-selected-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-primary-container'), 'time-selector-selected-label-text-color': map.get($deps, 'md-sys-color', 'on-primary-container'), 'time-selector-selected-pressed-label-text-color': map.get($deps, 'md-sys-color', 'on-primary-container'), 'time-selector-selected-pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-primary-container'), 'time-selector-separator-color': map.get($deps, 'md-sys-color', 'on-surface'), 'time-selector-separator-font': map.get($deps, 'md-sys-typescale', 'display-large-font'), 'time-selector-separator-line-height': map.get($deps, 'md-sys-typescale', 'display-large-line-height'), 'time-selector-separator-size': map.get($deps, 'md-sys-typescale', 'display-large-size'), 'time-selector-separator-tracking': map.get($deps, 'md-sys-typescale', 'display-large-tracking'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.comp.time-picker.time-selector.separator.tracking cannot be represented in the // "font" property shorthand. Consider using the discrete properties instead. 'time-selector-separator-type': if( $exclude-hardcoded-values, null, map.get($deps, 'md-sys-typescale', 'display-large-weight') map.get($deps, 'md-sys-typescale', 'display-large-size') #{'/'} map.get( $deps, 'md-sys-typescale', 'display-large-line-height' ) map.get($deps, 'md-sys-typescale', 'display-large-font') ), 'time-selector-separator-weight': map.get($deps, 'md-sys-typescale', 'display-large-weight'), 'time-selector-unselected-container-color': map.get($deps, 'md-sys-color', 'surface-variant'), 'time-selector-unselected-focus-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'time-selector-unselected-focus-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'time-selector-unselected-hover-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'time-selector-unselected-hover-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface'), 'time-selector-unselected-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'time-selector-unselected-pressed-label-text-color': map.get($deps, 'md-sys-color', 'on-surface'), 'time-selector-unselected-pressed-state-layer-color': map.get($deps, 'md-sys-color', 'on-surface') ); }
{ "end_byte": 13321, "start_byte": 9146, "url": "https://github.com/angular/components/blob/main/src/material/core/tokens/m3/definitions/unused/_md-comp-time-picker.scss" }
components/src/material/core/internal-form-field/internal-form-field.ts_0_1059
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ChangeDetectionStrategy, Component, Input, ViewEncapsulation} from '@angular/core'; /** * Internal shared component used as a container in form field controls. * Not to be confused with `mat-form-field` which MDC calls a "text field". * @docs-private */ @Component({ // Use a `div` selector to match the old markup closer. selector: 'div[mat-internal-form-field]', template: '<ng-content></ng-content>', styleUrl: 'internal-form-field.css', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, host: { 'class': 'mdc-form-field mat-internal-form-field', '[class.mdc-form-field--align-end]': 'labelPosition === "before"', }, }) export class _MatInternalFormField { /** Position of the label relative to the content. */ @Input({required: true}) labelPosition: 'before' | 'after'; }
{ "end_byte": 1059, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/internal-form-field/internal-form-field.ts" }
components/src/material/core/internal-form-field/internal-form-field.scss_0_719
@use '../style/vendor-prefixes'; .mat-internal-form-field { @include vendor-prefixes.smooth-font(); display: inline-flex; align-items: center; vertical-align: middle; & > label { margin-left: 0; margin-right: auto; padding-left: 4px; padding-right: 0; order: 0; } [dir='rtl'] & > label { margin-left: auto; margin-right: 0; padding-left: 0; padding-right: 4px; } } .mdc-form-field--align-end { & > label { margin-left: auto; margin-right: 0; padding-left: 0; padding-right: 4px; order: -1; } [dir='rtl'] .mdc-form-field--align-end & label { margin-left: 0; margin-right: auto; padding-left: 4px; padding-right: 0; } }
{ "end_byte": 719, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/core/internal-form-field/internal-form-field.scss" }
components/src/material/autocomplete/_autocomplete-theme.scss_0_3151
@use 'sass:map'; @use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @use '../core/typography/typography'; @use '../core/style/sass-utils'; @use '../core/tokens/token-utils'; @use '../core/tokens/m2/mat/autocomplete' as tokens-mat-autocomplete; @mixin base($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, base)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mat-autocomplete.$prefix, tokens-mat-autocomplete.get-unthemable-tokens() ); } } } @mixin color($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, color)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mat-autocomplete.$prefix, tokens-mat-autocomplete.get-color-tokens($theme) ); } } } @mixin typography($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, typography)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mat-autocomplete.$prefix, tokens-mat-autocomplete.get-typography-tokens($theme) ); } } } @mixin density($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, density)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mat-autocomplete.$prefix, tokens-mat-autocomplete.get-density-tokens($theme) ); } } } /// Defines the tokens that will be available in the `overrides` mixin and for docs extraction. @function _define-overrides() { @return ( ( namespace: tokens-mat-autocomplete.$prefix, tokens: tokens-mat-autocomplete.get-token-slots(), ), ); } @mixin overrides($tokens: ()) { @include token-utils.batch-create-token-values($tokens, _define-overrides()...); } @mixin theme($theme) { @include theming.private-check-duplicate-theme-styles($theme, 'mat-autocomplete') { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme)); } @else { @include base($theme); @if inspection.theme-has($theme, color) { @include color($theme); } @if inspection.theme-has($theme, density) { @include density($theme); } @if inspection.theme-has($theme, typography) { @include typography($theme); } } } } @mixin _theme-from-tokens($tokens) { @include validation.selector-defined( 'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector' ); @if ($tokens != ()) { @include token-utils.create-token-values( tokens-mat-autocomplete.$prefix, map.get($tokens, tokens-mat-autocomplete.$prefix) ); } }
{ "end_byte": 3151, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/_autocomplete-theme.scss" }
components/src/material/autocomplete/autocomplete.ts_0_3453
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, ElementRef, EventEmitter, InjectionToken, Input, OnDestroy, Output, QueryList, TemplateRef, ViewChild, ViewEncapsulation, booleanAttribute, inject, } from '@angular/core'; import {AnimationEvent} from '@angular/animations'; import { MAT_OPTGROUP, MAT_OPTION_PARENT_COMPONENT, MatOptgroup, MatOption, ThemePalette, } from '@angular/material/core'; import {ActiveDescendantKeyManager} from '@angular/cdk/a11y'; import {Platform} from '@angular/cdk/platform'; import {panelAnimation} from './animations'; import {Subscription} from 'rxjs'; /** * Autocomplete IDs need to be unique across components, so this counter exists outside of * the component definition. */ let _uniqueAutocompleteIdCounter = 0; /** Event object that is emitted when an autocomplete option is selected. */ export class MatAutocompleteSelectedEvent { constructor( /** Reference to the autocomplete panel that emitted the event. */ public source: MatAutocomplete, /** Option that was selected. */ public option: MatOption, ) {} } /** Event object that is emitted when an autocomplete option is activated. */ export interface MatAutocompleteActivatedEvent { /** Reference to the autocomplete panel that emitted the event. */ source: MatAutocomplete; /** Option that was selected. */ option: MatOption | null; } /** Default `mat-autocomplete` options that can be overridden. */ export interface MatAutocompleteDefaultOptions { /** Whether the first option should be highlighted when an autocomplete panel is opened. */ autoActiveFirstOption?: boolean; /** Whether the active option should be selected as the user is navigating. */ autoSelectActiveOption?: boolean; /** * Whether the user is required to make a selection when * they're interacting with the autocomplete. */ requireSelection?: boolean; /** Class or list of classes to be applied to the autocomplete's overlay panel. */ overlayPanelClass?: string | string[]; /** Wheter icon indicators should be hidden for single-selection. */ hideSingleSelectionIndicator?: boolean; } /** Injection token to be used to override the default options for `mat-autocomplete`. */ export const MAT_AUTOCOMPLETE_DEFAULT_OPTIONS = new InjectionToken<MatAutocompleteDefaultOptions>( 'mat-autocomplete-default-options', { providedIn: 'root', factory: MAT_AUTOCOMPLETE_DEFAULT_OPTIONS_FACTORY, }, ); /** @docs-private */ export function MAT_AUTOCOMPLETE_DEFAULT_OPTIONS_FACTORY(): MatAutocompleteDefaultOptions { return { autoActiveFirstOption: false, autoSelectActiveOption: false, hideSingleSelectionIndicator: false, requireSelection: false, }; } /** Autocomplete component. */ @Component({ selector: 'mat-autocomplete', templateUrl: 'autocomplete.html', styleUrl: 'autocomplete.css', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, exportAs: 'matAutocomplete', host: { 'class': 'mat-mdc-autocomplete', }, providers: [{provide: MAT_OPTION_PARENT_COMPONENT, useExisting: MatAutocomplete}], animations: [panelAnimation], }) export
{ "end_byte": 3453, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.ts" }
components/src/material/autocomplete/autocomplete.ts_3454_12177
class MatAutocomplete implements AfterContentInit, OnDestroy { private _changeDetectorRef = inject(ChangeDetectorRef); private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef); protected _defaults = inject<MatAutocompleteDefaultOptions>(MAT_AUTOCOMPLETE_DEFAULT_OPTIONS); private _activeOptionChanges = Subscription.EMPTY; /** Emits when the panel animation is done. Null if the panel doesn't animate. */ _animationDone = new EventEmitter<AnimationEvent>(); /** Manages active item in option list based on key events. */ _keyManager: ActiveDescendantKeyManager<MatOption>; /** Whether the autocomplete panel should be visible, depending on option length. */ showPanel: boolean = false; /** Whether the autocomplete panel is open. */ get isOpen(): boolean { return this._isOpen && this.showPanel; } _isOpen: boolean = false; /** Latest trigger that opened the autocomplete. */ _latestOpeningTrigger: unknown; /** @docs-private Sets the theme color of the panel. */ _setColor(value: ThemePalette) { this._color = value; this._changeDetectorRef.markForCheck(); } /** @docs-private theme color of the panel */ protected _color: ThemePalette; // The @ViewChild query for TemplateRef here needs to be static because some code paths // lead to the overlay being created before change detection has finished for this component. // Notably, another component may trigger `focus` on the autocomplete-trigger. /** @docs-private */ @ViewChild(TemplateRef, {static: true}) template: TemplateRef<any>; /** Element for the panel containing the autocomplete options. */ @ViewChild('panel') panel: ElementRef; /** Reference to all options within the autocomplete. */ @ContentChildren(MatOption, {descendants: true}) options: QueryList<MatOption>; /** Reference to all option groups within the autocomplete. */ @ContentChildren(MAT_OPTGROUP, {descendants: true}) optionGroups: QueryList<MatOptgroup>; /** Aria label of the autocomplete. */ @Input('aria-label') ariaLabel: string; /** Input that can be used to specify the `aria-labelledby` attribute. */ @Input('aria-labelledby') ariaLabelledby: string; /** Function that maps an option's control value to its display value in the trigger. */ @Input() displayWith: ((value: any) => string) | null = null; /** * Whether the first option should be highlighted when the autocomplete panel is opened. * Can be configured globally through the `MAT_AUTOCOMPLETE_DEFAULT_OPTIONS` token. */ @Input({transform: booleanAttribute}) autoActiveFirstOption: boolean; /** Whether the active option should be selected as the user is navigating. */ @Input({transform: booleanAttribute}) autoSelectActiveOption: boolean; /** * Whether the user is required to make a selection when they're interacting with the * autocomplete. If the user moves away from the autocomplete without selecting an option from * the list, the value will be reset. If the user opens the panel and closes it without * interacting or selecting a value, the initial value will be kept. */ @Input({transform: booleanAttribute}) requireSelection: boolean; /** * Specify the width of the autocomplete panel. Can be any CSS sizing value, otherwise it will * match the width of its host. */ @Input() panelWidth: string | number; /** Whether ripples are disabled within the autocomplete panel. */ @Input({transform: booleanAttribute}) disableRipple: boolean; /** Event that is emitted whenever an option from the list is selected. */ @Output() readonly optionSelected: EventEmitter<MatAutocompleteSelectedEvent> = new EventEmitter<MatAutocompleteSelectedEvent>(); /** Event that is emitted when the autocomplete panel is opened. */ @Output() readonly opened: EventEmitter<void> = new EventEmitter<void>(); /** Event that is emitted when the autocomplete panel is closed. */ @Output() readonly closed: EventEmitter<void> = new EventEmitter<void>(); /** Emits whenever an option is activated. */ @Output() readonly optionActivated: EventEmitter<MatAutocompleteActivatedEvent> = new EventEmitter<MatAutocompleteActivatedEvent>(); /** * Takes classes set on the host mat-autocomplete element and applies them to the panel * inside the overlay container to allow for easy styling. */ @Input('class') set classList(value: string | string[]) { this._classList = value; this._elementRef.nativeElement.className = ''; } _classList: string | string[]; /** Whether checkmark indicator for single-selection options is hidden. */ @Input({transform: booleanAttribute}) get hideSingleSelectionIndicator(): boolean { return this._hideSingleSelectionIndicator; } set hideSingleSelectionIndicator(value: boolean) { this._hideSingleSelectionIndicator = value; this._syncParentProperties(); } private _hideSingleSelectionIndicator: boolean; /** Syncs the parent state with the individual options. */ _syncParentProperties(): void { if (this.options) { for (const option of this.options) { option._changeDetectorRef.markForCheck(); } } } /** Unique ID to be used by autocomplete trigger's "aria-owns" property. */ id: string = `mat-autocomplete-${_uniqueAutocompleteIdCounter++}`; /** * Tells any descendant `mat-optgroup` to use the inert a11y pattern. * @docs-private */ readonly inertGroups: boolean; constructor(...args: unknown[]); constructor() { const platform = inject(Platform); // TODO(crisbeto): the problem that the `inertGroups` option resolves is only present on // Safari using VoiceOver. We should occasionally check back to see whether the bug // wasn't resolved in VoiceOver, and if it has, we can remove this and the `inertGroups` // option altogether. this.inertGroups = platform?.SAFARI || false; this.autoActiveFirstOption = !!this._defaults.autoActiveFirstOption; this.autoSelectActiveOption = !!this._defaults.autoSelectActiveOption; this.requireSelection = !!this._defaults.requireSelection; this._hideSingleSelectionIndicator = this._defaults.hideSingleSelectionIndicator ?? false; } ngAfterContentInit() { this._keyManager = new ActiveDescendantKeyManager<MatOption>(this.options) .withWrap() .skipPredicate(this._skipPredicate); this._activeOptionChanges = this._keyManager.change.subscribe(index => { if (this.isOpen) { this.optionActivated.emit({source: this, option: this.options.toArray()[index] || null}); } }); // Set the initial visibility state. this._setVisibility(); } ngOnDestroy() { this._keyManager?.destroy(); this._activeOptionChanges.unsubscribe(); this._animationDone.complete(); } /** * Sets the panel scrollTop. This allows us to manually scroll to display options * above or below the fold, as they are not actually being focused when active. */ _setScrollTop(scrollTop: number): void { if (this.panel) { this.panel.nativeElement.scrollTop = scrollTop; } } /** Returns the panel's scrollTop. */ _getScrollTop(): number { return this.panel ? this.panel.nativeElement.scrollTop : 0; } /** Panel should hide itself when the option list is empty. */ _setVisibility() { this.showPanel = !!this.options.length; this._changeDetectorRef.markForCheck(); } /** Emits the `select` event. */ _emitSelectEvent(option: MatOption): void { const event = new MatAutocompleteSelectedEvent(this, option); this.optionSelected.emit(event); } /** Gets the aria-labelledby for the autocomplete panel. */ _getPanelAriaLabelledby(labelId: string | null): string | null { if (this.ariaLabel) { return null; } const labelExpression = labelId ? labelId + ' ' : ''; return this.ariaLabelledby ? labelExpression + this.ariaLabelledby : labelId; } // `skipPredicate` determines if key manager should avoid putting a given option in the tab // order. Allow disabled list items to receive focus via keyboard to align with WAI ARIA // recommendation. // // Normally WAI ARIA's instructions are to exclude disabled items from the tab order, but it // makes a few exceptions for compound widgets. // // From [Developing a Keyboard Interface]( // https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/): // "For the following composite widget elements, keep them focusable when disabled: Options in a // Listbox..." // // The user can focus disabled options using the keyboard, but the user cannot click disabled // options. protected _skipPredicate() { return false; } }
{ "end_byte": 12177, "start_byte": 3454, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.ts" }
components/src/material/autocomplete/module.ts_0_1095
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {MatCommonModule, MatOptionModule} from '@angular/material/core'; import {CdkScrollableModule} from '@angular/cdk/scrolling'; import {OverlayModule} from '@angular/cdk/overlay'; import {MatAutocomplete} from './autocomplete'; import { MatAutocompleteTrigger, MAT_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY_PROVIDER, } from './autocomplete-trigger'; import {MatAutocompleteOrigin} from './autocomplete-origin'; @NgModule({ imports: [ OverlayModule, MatOptionModule, MatCommonModule, MatAutocomplete, MatAutocompleteTrigger, MatAutocompleteOrigin, ], exports: [ CdkScrollableModule, MatAutocomplete, MatOptionModule, MatCommonModule, MatAutocompleteTrigger, MatAutocompleteOrigin, ], providers: [MAT_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY_PROVIDER], }) export class MatAutocompleteModule {}
{ "end_byte": 1095, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/module.ts" }
components/src/material/autocomplete/autocomplete-origin.ts_0_625
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Directive, ElementRef, inject} from '@angular/core'; /** * Directive applied to an element to make it usable * as a connection point for an autocomplete panel. */ @Directive({ selector: '[matAutocompleteOrigin]', exportAs: 'matAutocompleteOrigin', }) export class MatAutocompleteOrigin { elementRef = inject<ElementRef<HTMLElement>>(ElementRef); constructor(...args: unknown[]); constructor() {} }
{ "end_byte": 625, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete-origin.ts" }
components/src/material/autocomplete/autocomplete.zone.spec.ts_0_5775
import {OverlayModule} from '@angular/cdk/overlay'; import {dispatchFakeEvent} from '@angular/cdk/testing/private'; import { Component, NgZone, OnDestroy, Provider, QueryList, Type, ViewChild, ViewChildren, provideZoneChangeDetection, } from '@angular/core'; import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {Subscription} from 'rxjs'; import {MatOption} from '../core'; import {MatFormField, MatFormFieldModule} from '../form-field'; import {MatInputModule} from '../input'; import {MatAutocomplete} from './autocomplete'; import {MatAutocompleteTrigger} from './autocomplete-trigger'; import {MatAutocompleteModule} from './module'; describe('MatAutocomplete Zone.js integration', () => { // Creates a test component fixture. function createComponent<T>(component: Type<T>, providers: Provider[] = []) { TestBed.configureTestingModule({ imports: [ MatAutocompleteModule, MatFormFieldModule, MatInputModule, FormsModule, ReactiveFormsModule, NoopAnimationsModule, OverlayModule, ], providers: [provideZoneChangeDetection(), ...providers], declarations: [component], }); return TestBed.createComponent<T>(component); } describe('panel toggling', () => { let fixture: ComponentFixture<SimpleAutocomplete>; beforeEach(() => { fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); }); it('should show the panel when the first open is after the initial zone stabilization', waitForAsync(() => { // Note that we're running outside the Angular zone, in order to be able // to test properly without the subscription from `_subscribeToClosingActions` // giving us a false positive. fixture.ngZone!.runOutsideAngular(() => { fixture.componentInstance.trigger.openPanel(); Promise.resolve().then(() => { expect(fixture.componentInstance.panel.showPanel) .withContext(`Expected panel to be visible.`) .toBe(true); }); }); })); }); it('should emit from `autocomplete.closed` after click outside inside the NgZone', waitForAsync(async () => { const inZoneSpy = jasmine.createSpy('in zone spy'); const fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const subscription = fixture.componentInstance.trigger.autocomplete.closed.subscribe(() => inZoneSpy(NgZone.isInAngularZone()), ); await new Promise(r => setTimeout(r)); dispatchFakeEvent(document, 'click'); expect(inZoneSpy).toHaveBeenCalledWith(true); subscription.unsubscribe(); })); }); const SIMPLE_AUTOCOMPLETE_TEMPLATE = ` <mat-form-field [floatLabel]="floatLabel" [style.width.px]="width" [color]="theme"> @if (hasLabel) { <mat-label>State</mat-label> } <input matInput placeholder="State" [matAutocomplete]="auto" [matAutocompletePosition]="position" [matAutocompleteDisabled]="autocompleteDisabled" [formControl]="stateCtrl"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete" [class]="panelClass" [displayWith]="displayFn" [disableRipple]="disableRipple" [requireSelection]="requireSelection" [aria-label]="ariaLabel" [aria-labelledby]="ariaLabelledby" (opened)="openedSpy()" (closed)="closedSpy()"> @for (state of filteredStates; track state) { <mat-option [value]="state" [style.height.px]="state.height" [disabled]="state.disabled"> <span>{{ state.code }}: {{ state.name }}</span> </mat-option> } </mat-autocomplete> `; @Component({template: SIMPLE_AUTOCOMPLETE_TEMPLATE, standalone: false}) class SimpleAutocomplete implements OnDestroy { stateCtrl = new FormControl<{name: string; code: string} | string | null>(null); filteredStates: any[]; valueSub: Subscription; floatLabel = 'auto'; position = 'auto'; width: number; disableRipple = false; autocompleteDisabled = false; hasLabel = true; requireSelection = false; ariaLabel: string; ariaLabelledby: string; panelClass = 'class-one class-two'; theme: string; openedSpy = jasmine.createSpy('autocomplete opened spy'); closedSpy = jasmine.createSpy('autocomplete closed spy'); @ViewChild(MatAutocompleteTrigger, {static: true}) trigger: MatAutocompleteTrigger; @ViewChild(MatAutocomplete) panel: MatAutocomplete; @ViewChild(MatFormField) formField: MatFormField; @ViewChildren(MatOption) options: QueryList<MatOption>; states: {code: string; name: string; height?: number; disabled?: boolean}[] = [ {code: 'AL', name: 'Alabama'}, {code: 'CA', name: 'California'}, {code: 'FL', name: 'Florida'}, {code: 'KS', name: 'Kansas'}, {code: 'MA', name: 'Massachusetts'}, {code: 'NY', name: 'New York'}, {code: 'OR', name: 'Oregon'}, {code: 'PA', name: 'Pennsylvania'}, {code: 'TN', name: 'Tennessee'}, {code: 'VA', name: 'Virginia'}, {code: 'WY', name: 'Wyoming'}, ]; constructor() { this.filteredStates = this.states; this.valueSub = this.stateCtrl.valueChanges.subscribe(val => { this.filteredStates = val ? this.states.filter(s => s.name.match(new RegExp(val as string, 'gi'))) : this.states; }); } displayFn(value: any): string { return value ? value.name : value; } ngOnDestroy() { this.valueSub.unsubscribe(); } }
{ "end_byte": 5775, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.zone.spec.ts" }
components/src/material/autocomplete/public-api.ts_0_492
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './module'; export * from './autocomplete'; export * from './autocomplete-origin'; export * from './autocomplete-trigger'; // Re-export these since they're required to be used together with `mat-autocomplete`. export {MatOption, MatOptgroup} from '@angular/material/core';
{ "end_byte": 492, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/public-api.ts" }
components/src/material/autocomplete/autocomplete.md_0_8000
The autocomplete is a normal text input enhanced by a panel of suggested options. ### Simple autocomplete Start by creating the autocomplete panel and the options displayed inside it. Each option should be defined by a `mat-option` tag. Set each option's value property to whatever you'd like the value of the text input to be when that option is selected. <!-- example({"example":"autocomplete-simple", "file":"autocomplete-simple-example.html", "region":"mat-autocomplete"}) --> Next, create the input and set the `matAutocomplete` input to refer to the template reference we assigned to the autocomplete. Let's assume you're using the `formControl` directive from `ReactiveFormsModule` to track the value of the input. > Note: It is possible to use template-driven forms instead, if you prefer. We use reactive forms in this example because it makes subscribing to changes in the input's value easy. For this example, be sure to import `ReactiveFormsModule` from `@angular/forms` into your `NgModule`. If you are unfamiliar with using reactive forms, you can read more about the subject in the [Angular documentation](https://angular.dev/guide/forms/reactive-forms). Now we'll need to link the text input to its panel. We can do this by exporting the autocomplete panel instance into a local template variable (here we called it "auto"), and binding that variable to the input's `matAutocomplete` property. <!-- example({"example":"autocomplete-simple", "file":"autocomplete-simple-example.html", "region":"input"}) --> ### Adding a custom filter At this point, the autocomplete panel should be toggleable on focus and options should be selectable. But if we want our options to filter when we type, we need to add a custom filter. You can filter the options in any way you like based on the text input\*. Here we will perform a simple string test on the option value to see if it matches the input value, starting from the option's first letter. We already have access to the built-in `valueChanges` Observable on the `FormControl`, so we can simply map the text input's values to the suggested options by passing them through this filter. The resulting Observable, `filteredOptions`, can be added to the template in place of the `options` property using the `async` pipe. Below we are also priming our value change stream with an empty string so that the options are filtered by that value on init (before there are any value changes). \*For optimal accessibility, you may want to consider adding text guidance on the page to explain filter criteria. This is especially helpful for screenreader users if you're using a non-standard filter that doesn't limit matches to the beginning of the string. <!-- example(autocomplete-filter) --> ### Setting separate control and display values If you want the option's control value (what is saved in the form) to be different than the option's display value (what is displayed in the text field), you'll need to set the `displayWith` property on your autocomplete element. A common use case for this might be if you want to save your data as an object, but display just one of the option's string properties. To make this work, create a function on your component class that maps the control value to the desired display value. Then bind it to the autocomplete's `displayWith` property. <!-- example(autocomplete-display) --> ### Require an option to be selected By default, the autocomplete will accept the value that the user typed into the input field. Instead, if you want to instead ensure that an option from the autocomplete was selected, you can enable the `requireSelection` input on `mat-autocomplete`. This will change the behavior of the autocomplete in the following ways: 1. If the user opens the autocomplete, changes its value, but doesn't select anything, the autocomplete value will be reset back to `null`. 2. If the user opens and closes the autocomplete without changing the value, the old value will be preserved. This behavior can be configured globally using the `MAT_AUTOCOMPLETE_DEFAULT_OPTIONS` injection token. <!-- example(autocomplete-require-selection) --> ### Automatically highlighting the first option If your use case requires for the first autocomplete option to be highlighted when the user opens the panel, you can do so by setting the `autoActiveFirstOption` input on the `mat-autocomplete` component. This behavior can be configured globally using the `MAT_AUTOCOMPLETE_DEFAULT_OPTIONS` injection token. <!-- example(autocomplete-auto-active-first-option) --> ### Autocomplete on a custom input element While `mat-autocomplete` supports attaching itself to a `mat-form-field`, you can also set it on any other `input` element using the `matAutocomplete` attribute. This allows you to customize what the input looks like without having to bring in the extra functionality from `mat-form-field`. <!-- example(autocomplete-plain-input) --> ### Attaching the autocomplete panel to a different element By default the autocomplete panel will be attached to your input element, however in some cases you may want it to attach to a different container element. You can change the element that the autocomplete is attached to using the `matAutocompleteOrigin` directive together with the `matAutocompleteConnectedTo` input: ```html <div class="custom-wrapper-example" matAutocompleteOrigin #origin="matAutocompleteOrigin"> <input matInput [formControl]="myControl" [matAutocomplete]="auto" [matAutocompleteConnectedTo]="origin"> </div> <mat-autocomplete #auto="matAutocomplete"> @for (option of options; track option) { <mat-option [value]="option">{{option}}</mat-option> } </mat-autocomplete> ``` ### Keyboard interaction | Keyboard shortcut | Action | |----------------------------------------|----------------------------------------------------------------| | <kbd>Down Arrow</kbd> | Navigate to the next option. | | <kbd>Up Arrow</kbd> | Navigate to the previous option. | | <kbd>Enter</kbd> | Select the active option. | | <kbd>Escape</kbd> | Close the autocomplete panel. | | <kbd>Alt</kbd> + <kbd>Up Arrow</kbd> | Close the autocomplete panel. | | <kbd>Alt</kbd> + <kbd>Down Arrow</kbd> | Open the autocomplete panel if there are any matching options. | ### Option groups `mat-option` can be collected into groups using the `mat-optgroup` element: <!-- example({"example":"autocomplete-optgroup", "file":"autocomplete-optgroup-example.html", "region":"mat-autocomplete"}) --> ### Accessibility `MatAutocomplete` implements the ARIA combobox interaction pattern. The text input trigger specifies `role="combobox"` while the content of the pop-up applies `role="listbox"`. Because of this listbox pattern, you should _not_ put other interactive controls, such as buttons or checkboxes, inside an autocomplete option. Nesting interactive controls like this interferes with most assistive technology. Always provide an accessible label for the autocomplete. This can be done by using a `<mat-label>` inside of `<mat-form-field>`, a native `<label>` element, the `aria-label` attribute, or the `aria-labelledby` attribute. `MatAutocomplete` preserves focus on the text trigger, using `aria-activedescendant` to support navigation though the autocomplete options. By default, `MatAutocomplete` displays a checkmark to identify the selected item. While you can hide the checkmark indicator via `hideSingleSelectionIndicator`, this makes the component less accessible by making it harder or impossible for users to visually identify selected items.
{ "end_byte": 8000, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.md" }
components/src/material/autocomplete/README.md_0_73
See documentation on [material.angular.io](https://material.angular.io/).
{ "end_byte": 73, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/README.md" }
components/src/material/autocomplete/autocomplete.spec.ts_0_2349
import {Directionality} from '@angular/cdk/bidi'; import {DOWN_ARROW, ENTER, ESCAPE, SPACE, TAB, UP_ARROW} from '@angular/cdk/keycodes'; import {Overlay, OverlayContainer, OverlayModule} from '@angular/cdk/overlay'; import {_supportsShadowDom} from '@angular/cdk/platform'; import {ScrollDispatcher} from '@angular/cdk/scrolling'; import { clearElement, createKeyboardEvent, dispatchEvent, dispatchFakeEvent, dispatchKeyboardEvent, dispatchMouseEvent, typeInElement, } from '@angular/cdk/testing/private'; import { ChangeDetectionStrategy, Component, ElementRef, OnDestroy, OnInit, Provider, QueryList, Type, ViewChild, ViewChildren, ViewEncapsulation, } from '@angular/core'; import { ComponentFixture, TestBed, fakeAsync, flush, inject, tick, waitForAsync, } from '@angular/core/testing'; import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms'; import {MatOption, MatOptionSelectionChange} from '@angular/material/core'; import {MatFormField, MatFormFieldModule} from '@angular/material/form-field'; import {MatInputModule} from '@angular/material/input'; import {By} from '@angular/platform-browser'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {EMPTY, Observable, Subject, Subscription} from 'rxjs'; import {map, startWith} from 'rxjs/operators'; import { MAT_AUTOCOMPLETE_DEFAULT_OPTIONS, MAT_AUTOCOMPLETE_SCROLL_STRATEGY, MatAutocomplete, MatAutocompleteDefaultOptions, MatAutocompleteModule, MatAutocompleteOrigin, MatAutocompleteSelectedEvent, MatAutocompleteTrigger, getMatAutocompleteMissingPanelError, } from './index'; describe('MatAutocomplete', () => { let overlayContainerElement: HTMLElement; // Creates a test component fixture. function createComponent<T>(component: Type<T>, providers: Provider[] = []) { TestBed.configureTestingModule({ imports: [ MatAutocompleteModule, MatFormFieldModule, MatInputModule, FormsModule, ReactiveFormsModule, NoopAnimationsModule, OverlayModule, ], providers, declarations: [component], }); inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainerElement = oc.getContainerElement(); })(); return TestBed.createComponent<T>(component); }
{ "end_byte": 2349, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_2353_12133
describe('panel toggling', () => { let fixture: ComponentFixture<SimpleAutocomplete>; let input: HTMLInputElement; beforeEach(() => { fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); input = fixture.debugElement.query(By.css('input'))!.nativeElement; }); it('should open the panel when the input is focused', () => { expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected panel state to start out closed.`) .toBe(false); dispatchFakeEvent(input, 'focusin'); fixture.detectChanges(); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected panel state to read open when input is focused.`) .toBe(true); expect(overlayContainerElement.textContent) .withContext(`Expected panel to display when input is focused.`) .toContain('Alabama'); expect(overlayContainerElement.textContent) .withContext(`Expected panel to display when input is focused.`) .toContain('California'); }); it('should not open the panel on focus if the input is readonly', fakeAsync(() => { const trigger = fixture.componentInstance.trigger; input.readOnly = true; fixture.detectChanges(); expect(trigger.panelOpen) .withContext('Expected panel state to start out closed.') .toBe(false); dispatchFakeEvent(input, 'focusin'); flush(); fixture.detectChanges(); expect(trigger.panelOpen).withContext('Expected panel to stay closed.').toBe(false); })); it('should not open using the arrow keys when the input is readonly', fakeAsync(() => { const trigger = fixture.componentInstance.trigger; input.readOnly = true; fixture.detectChanges(); expect(trigger.panelOpen) .withContext('Expected panel state to start out closed.') .toBe(false); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); flush(); fixture.detectChanges(); expect(trigger.panelOpen).withContext('Expected panel to stay closed.').toBe(false); })); it('should open the panel programmatically', () => { expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected panel state to start out closed.`) .toBe(false); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected panel state to read open when opened programmatically.`) .toBe(true); expect(overlayContainerElement.textContent) .withContext(`Expected panel to display when opened programmatically.`) .toContain('Alabama'); expect(overlayContainerElement.textContent) .withContext(`Expected panel to display when opened programmatically.`) .toContain('California'); }); it('should close the panel when the user clicks away', waitForAsync(async () => { dispatchFakeEvent(input, 'focusin'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); dispatchFakeEvent(document, 'click'); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected clicking outside the panel to set its state to closed.`) .toBe(false); expect(overlayContainerElement.textContent) .withContext(`Expected clicking outside the panel to close the panel.`) .toEqual(''); })); it('should close the panel when the user clicks away via auxiliary button', waitForAsync(async () => { dispatchFakeEvent(input, 'focusin'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); dispatchFakeEvent(document, 'auxclick'); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected clicking outside the panel to set its state to closed.`) .toBe(false); expect(overlayContainerElement.textContent) .withContext(`Expected clicking outside the panel to close the panel.`) .toEqual(''); })); it('should close the panel when the user taps away on a touch device', fakeAsync(() => { dispatchFakeEvent(input, 'focus'); fixture.detectChanges(); flush(); dispatchFakeEvent(document, 'touchend'); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected tapping outside the panel to set its state to closed.`) .toBe(false); expect(overlayContainerElement.textContent) .withContext(`Expected tapping outside the panel to close the panel.`) .toEqual(''); })); it('should close the panel when an option is clicked', waitForAsync(async () => { dispatchFakeEvent(input, 'focusin'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const option = overlayContainerElement.querySelector('mat-option') as HTMLElement; option.click(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected clicking an option to set the panel state to closed.`) .toBe(false); expect(overlayContainerElement.textContent) .withContext(`Expected clicking an option to close the panel.`) .toEqual(''); })); it('should close the panel when a newly created option is clicked', waitForAsync(async () => { dispatchFakeEvent(input, 'focusin'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); // Filter down the option list to a subset of original options ('Alabama', 'California') typeInElement(input, 'al'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); let options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; options[0].click(); // Changing value from 'Alabama' to 'al' to re-populate the option list, // ensuring that 'California' is created new. dispatchFakeEvent(input, 'focusin'); clearElement(input); typeInElement(input, 'al'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); options = overlayContainerElement.querySelectorAll('mat-option') as NodeListOf<HTMLElement>; options[1].click(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected clicking a new option to set the panel state to closed.`) .toBe(false); expect(overlayContainerElement.textContent) .withContext(`Expected clicking a new option to close the panel.`) .toEqual(''); })); it('should close the panel programmatically', fakeAsync(() => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); fixture.componentInstance.trigger.closePanel(); fixture.detectChanges(); tick(); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected closing programmatically to set the panel state to closed.`) .toBe(false); expect(overlayContainerElement.textContent) .withContext(`Expected closing programmatically to close the panel.`) .toEqual(''); })); it('should not throw when attempting to close the panel of a destroyed autocomplete', () => { const trigger = fixture.componentInstance.trigger; trigger.openPanel(); fixture.detectChanges(); fixture.destroy(); expect(() => trigger.closePanel()).not.toThrow(); }); it('should hide the panel when the options list is empty', fakeAsync(() => { dispatchFakeEvent(input, 'focusin'); fixture.detectChanges(); const panel = overlayContainerElement.querySelector( '.mat-mdc-autocomplete-panel', ) as HTMLElement; expect(panel.classList) .withContext(`Expected panel to start out visible.`) .toContain('mat-mdc-autocomplete-visible'); // Filter down the option list such that no options match the value typeInElement(input, 'af'); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(panel.classList) .withContext(`Expected panel to hide itself when empty.`) .toContain('mat-mdc-autocomplete-hidden'); })); it('should keep the label floating until the panel closes', waitForAsync(async () => { fixture.componentInstance.trigger.openPanel(); expect(fixture.componentInstance.formField.floatLabel) .withContext('Expected label to float as soon as panel opens.') .toEqual('always'); await new Promise(r => setTimeout(r)); fixture.detectChanges(); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; options[1].click(); fixture.detectChanges(); expect(fixture.componentInstance.formField.floatLabel) .withContext('Expected label to return to auto state after panel closes.') .toEqual('auto'); })); it('should not open the panel when the `input` event is invoked on a non-focused input', () => { expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected panel state to start out closed.`) .toBe(false); input.value = 'Alabama'; dispatchFakeEvent(input, 'input'); fixture.detectChanges(); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected panel state to stay closed.`) .toBe(false); });
{ "end_byte": 12133, "start_byte": 2353, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_12139_22873
it('should not mess with label placement if set to never', fakeAsync(() => { fixture.componentInstance.floatLabel = 'never'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); expect(fixture.componentInstance.formField.floatLabel) .withContext('Expected label to stay static.') .toEqual('never'); flush(); fixture.detectChanges(); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; options[1].click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.formField.floatLabel) .withContext('Expected label to stay in static state after close.') .toEqual('never'); })); it('should not mess with label placement if set to always', fakeAsync(() => { fixture.componentInstance.floatLabel = 'always'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); expect(fixture.componentInstance.formField.floatLabel) .withContext('Expected label to stay elevated on open.') .toEqual('always'); flush(); fixture.detectChanges(); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; options[1].click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.formField.floatLabel) .withContext('Expected label to stay elevated after close.') .toEqual('always'); })); it('should toggle the visibility when typing and closing the panel', fakeAsync(() => { fixture.componentInstance.trigger.openPanel(); tick(); fixture.detectChanges(); expect(overlayContainerElement.querySelector('.mat-mdc-autocomplete-panel')!.classList) .withContext('Expected panel to be visible.') .toContain('mat-mdc-autocomplete-visible'); typeInElement(input, 'x'); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(overlayContainerElement.querySelector('.mat-mdc-autocomplete-panel')!.classList) .withContext('Expected panel to be hidden.') .toContain('mat-mdc-autocomplete-hidden'); fixture.componentInstance.trigger.closePanel(); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); clearElement(input); typeInElement(input, 'al'); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(overlayContainerElement.querySelector('.mat-mdc-autocomplete-panel')!.classList) .withContext('Expected panel to be visible.') .toContain('mat-mdc-autocomplete-visible'); })); it('should animate the label when the input is focused', () => { const inputContainer = fixture.componentInstance.formField; spyOn(inputContainer, '_animateAndLockLabel'); expect(inputContainer._animateAndLockLabel).not.toHaveBeenCalled(); dispatchFakeEvent(fixture.debugElement.query(By.css('input'))!.nativeElement, 'focusin'); expect(inputContainer._animateAndLockLabel).toHaveBeenCalled(); }); it('should provide the open state of the panel', fakeAsync(() => { expect(fixture.componentInstance.panel.isOpen).toBeFalsy( `Expected the panel to be unopened initially.`, ); dispatchFakeEvent(input, 'focusin'); fixture.detectChanges(); flush(); expect(fixture.componentInstance.panel.isOpen).toBeTruthy( `Expected the panel to be opened on focus.`, ); })); it('should emit an event when the panel is opened', () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); expect(fixture.componentInstance.openedSpy).toHaveBeenCalled(); }); it('should not emit the `opened` event when no options are being shown', () => { fixture.componentInstance.filteredStates = fixture.componentInstance.states = []; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); expect(fixture.componentInstance.openedSpy).not.toHaveBeenCalled(); }); it('should emit the `opened` event if the options come in after the panel is shown', fakeAsync(() => { fixture.componentInstance.filteredStates = fixture.componentInstance.states = []; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); expect(fixture.componentInstance.openedSpy).not.toHaveBeenCalled(); fixture.componentInstance.filteredStates = fixture.componentInstance.states = [ {name: 'California', code: 'CA'}, ]; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(fixture.componentInstance.openedSpy).toHaveBeenCalled(); })); it('should not emit the opened event multiple times while typing', fakeAsync(() => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); expect(fixture.componentInstance.openedSpy).toHaveBeenCalledTimes(1); typeInElement(input, 'Alabam'); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(fixture.componentInstance.openedSpy).toHaveBeenCalledTimes(1); })); it('should emit an event when the panel is closed', () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); fixture.componentInstance.trigger.closePanel(); fixture.detectChanges(); expect(fixture.componentInstance.closedSpy).toHaveBeenCalled(); }); it('should not emit the `closed` event when no options were shown', () => { fixture.componentInstance.filteredStates = fixture.componentInstance.states = []; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); fixture.componentInstance.trigger.closePanel(); fixture.detectChanges(); expect(fixture.componentInstance.closedSpy).not.toHaveBeenCalled(); }); it('should not be able to open the panel if the autocomplete is disabled', () => { expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected panel state to start out closed.`) .toBe(false); fixture.componentInstance.autocompleteDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); dispatchFakeEvent(input, 'focusin'); fixture.detectChanges(); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected panel to remain closed.`) .toBe(false); }); it('should continue to update the model if the autocomplete is disabled', () => { fixture.componentInstance.autocompleteDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); typeInElement(input, 'hello'); fixture.detectChanges(); expect(fixture.componentInstance.stateCtrl.value).toBe('hello'); }); it('should set aria-haspopup depending on whether the autocomplete is disabled', () => { expect(input.getAttribute('aria-haspopup')).toBe('listbox'); fixture.componentInstance.autocompleteDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(input.hasAttribute('aria-haspopup')).toBe(false); }); it('should reopen the panel when clicking on the input', fakeAsync(() => { const trigger = fixture.componentInstance.trigger; input.focus(); flush(); fixture.detectChanges(); expect(document.activeElement).withContext('Expected input to be focused.').toBe(input); expect(trigger.panelOpen).withContext('Expected panel to be open.').toBe(true); trigger.closePanel(); fixture.detectChanges(); expect(document.activeElement) .withContext('Expected input to continue to be focused.') .toBe(input); expect(trigger.panelOpen).withContext('Expected panel to be closed.').toBe(false); input.click(); flush(); fixture.detectChanges(); expect(trigger.panelOpen).withContext('Expected panel to reopen on click.').toBe(true); })); }); it('should not close the panel when clicking on the input', waitForAsync(async () => { const fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; dispatchFakeEvent(input, 'focusin'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.trigger.panelOpen) .withContext('Expected panel to be opened on focus.') .toBe(true); input.click(); fixture.detectChanges(); expect(fixture.componentInstance.trigger.panelOpen) .withContext('Expected panel to remain opened after clicking on the input.') .toBe(true); })); it('should not close the panel when clicking on the input inside shadow DOM', waitForAsync(async () => { // This test is only relevant for Shadow DOM-capable browsers. if (!_supportsShadowDom()) { return; } const fixture = createComponent(SimpleAutocompleteShadowDom); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; dispatchFakeEvent(input, 'focusin'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.trigger.panelOpen) .withContext('Expected panel to be opened on focus.') .toBe(true); input.click(); fixture.detectChanges(); expect(fixture.componentInstance.trigger.panelOpen) .withContext('Expected panel to remain opened after clicking on the input.') .toBe(true); })); it('should have the correct text direction in RTL', () => { const rtlFixture = createComponent(SimpleAutocomplete, [ {provide: Directionality, useFactory: () => ({value: 'rtl', change: EMPTY})}, ]); rtlFixture.detectChanges(); rtlFixture.componentInstance.trigger.openPanel(); rtlFixture.detectChanges(); const boundingBox = overlayContainerElement.querySelector( '.cdk-overlay-connected-position-bounding-box', )!; expect(boundingBox.getAttribute('dir')).toEqual('rtl'); });
{ "end_byte": 22873, "start_byte": 12139, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_22877_26848
it('should update the panel direction if it changes for the trigger', () => { const dirProvider = {value: 'rtl', change: EMPTY}; const rtlFixture = createComponent(SimpleAutocomplete, [ {provide: Directionality, useFactory: () => dirProvider}, ]); rtlFixture.detectChanges(); rtlFixture.componentInstance.trigger.openPanel(); rtlFixture.detectChanges(); let boundingBox = overlayContainerElement.querySelector( '.cdk-overlay-connected-position-bounding-box', )!; expect(boundingBox.getAttribute('dir')).toEqual('rtl'); rtlFixture.componentInstance.trigger.closePanel(); rtlFixture.detectChanges(); dirProvider.value = 'ltr'; rtlFixture.componentInstance.trigger.openPanel(); rtlFixture.detectChanges(); boundingBox = overlayContainerElement.querySelector( '.cdk-overlay-connected-position-bounding-box', )!; expect(boundingBox.getAttribute('dir')).toEqual('ltr'); }); it('should be able to set a custom value for the `autocomplete` attribute', () => { const fixture = createComponent(AutocompleteWithNativeAutocompleteAttribute); const input = fixture.nativeElement.querySelector('input'); fixture.detectChanges(); expect(input.getAttribute('autocomplete')).toBe('changed'); }); it('should not throw when typing in an element with a null and disabled autocomplete', () => { const fixture = createComponent(InputWithoutAutocompleteAndDisabled); fixture.detectChanges(); expect(() => { dispatchKeyboardEvent(fixture.nativeElement.querySelector('input'), 'keydown', SPACE); fixture.detectChanges(); }).not.toThrow(); }); it('should clear the selected option if it no longer matches the input text while typing', waitForAsync(async () => { const fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); // Select an option and reopen the panel. (overlayContainerElement.querySelector('mat-option') as HTMLElement).click(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.options.first.selected).toBe(true); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; input.value = ''; typeInElement(input, 'Ala'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.options.first.selected).toBe(false); })); it('should not clear the selected option if it no longer matches the input text while typing with requireSelection', waitForAsync(async () => { const fixture = createComponent(SimpleAutocomplete); fixture.componentInstance.requireSelection = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); // Select an option and reopen the panel. (overlayContainerElement.querySelector('mat-option') as HTMLElement).click(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.options.first.selected).toBe(true); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; input.value = ''; typeInElement(input, 'Ala'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.options.first.selected).toBe(true); }));
{ "end_byte": 26848, "start_byte": 22877, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_26852_37282
describe('forms integration', () => { let fixture: ComponentFixture<SimpleAutocomplete>; let input: HTMLInputElement; beforeEach(() => { fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); input = fixture.debugElement.query(By.css('input'))!.nativeElement; }); it('should update control value as user types with input value', waitForAsync(async () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); typeInElement(input, 'a'); fixture.detectChanges(); expect(fixture.componentInstance.stateCtrl.value) .withContext('Expected control value to be updated as user types.') .toEqual('a'); typeInElement(input, 'l'); fixture.detectChanges(); expect(fixture.componentInstance.stateCtrl.value) .withContext('Expected control value to be updated as user types.') .toEqual('al'); })); it('should update control value when autofilling', () => { // Simulate the browser autofilling the input by setting a value and // dispatching an `input` event while the input is out of focus. expect(document.activeElement).not.toBe(input, 'Expected input not to have focus.'); input.value = 'Alabama'; dispatchFakeEvent(input, 'input'); fixture.detectChanges(); expect(fixture.componentInstance.stateCtrl.value) .withContext('Expected value to be propagated to the form control.') .toBe('Alabama'); }); it('should update control value when option is selected with option value', waitForAsync(async () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; options[1].click(); fixture.detectChanges(); expect(fixture.componentInstance.stateCtrl.value) .withContext('Expected control value to equal the selected option value.') .toEqual({code: 'CA', name: 'California'}); })); it('should update the control back to a string if user types after an option is selected', waitForAsync(async () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; options[1].click(); fixture.detectChanges(); clearElement(input); typeInElement(input, 'Californi'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.stateCtrl.value) .withContext('Expected control value to revert back to string.') .toEqual('Californi'); })); it('should fill the text field with display value when an option is selected', waitForAsync(async () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; options[1].click(); fixture.detectChanges(); expect(input.value) .withContext(`Expected text field to fill with selected value.`) .toContain('California'); })); it('should fill the text field with value if displayWith is not set', waitForAsync(async () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.componentInstance.panel.displayWith = null; fixture.componentInstance.options.toArray()[1].value = 'test value'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; options[1].click(); fixture.detectChanges(); expect(input.value) .withContext(`Expected input to fall back to selected option's value.`) .toContain('test value'); })); it('should fill the text field correctly if value is set to obj programmatically', fakeAsync(() => { fixture.componentInstance.stateCtrl.setValue({code: 'AL', name: 'Alabama'}); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(input.value) .withContext(`Expected input to fill with matching option's viewValue.`) .toContain('Alabama'); })); it('should clear the text field if value is reset programmatically', fakeAsync(() => { typeInElement(input, 'Alabama'); fixture.detectChanges(); tick(); fixture.componentInstance.stateCtrl.reset(); tick(); fixture.detectChanges(); tick(); expect(input.value).withContext(`Expected input value to be empty after reset.`).toEqual(''); })); it('should clear the previous selection when reactive form field is reset programmatically', waitForAsync(async () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; const clickedOption = options[0]; const option = fixture.componentInstance.options.first; clickedOption.click(); fixture.detectChanges(); expect(fixture.componentInstance.stateCtrl.value).toEqual({code: 'AL', name: 'Alabama'}); expect(option.selected).toBe(true); fixture.componentInstance.stateCtrl.reset(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.stateCtrl.value).toEqual(null); expect(option.selected).toBe(false); })); it('should disable input in view when disabled programmatically', () => { const formFieldElement = fixture.debugElement.query( By.css('.mat-mdc-form-field'), )!.nativeElement; expect(input.disabled) .withContext(`Expected input to start out enabled in view.`) .toBe(false); expect(formFieldElement.classList.contains('mat-form-field-disabled')) .withContext(`Expected input underline to start out with normal styles.`) .toBe(false); fixture.componentInstance.stateCtrl.disable(); fixture.detectChanges(); expect(input.disabled) .withContext(`Expected input to be disabled in view when disabled programmatically.`) .toBe(true); expect(formFieldElement.classList.contains('mat-form-field-disabled')) .withContext(`Expected input underline to display disabled styles.`) .toBe(true); }); it('should mark the autocomplete control as dirty as user types', () => { expect(fixture.componentInstance.stateCtrl.dirty) .withContext(`Expected control to start out pristine.`) .toBe(false); typeInElement(input, 'a'); fixture.detectChanges(); expect(fixture.componentInstance.stateCtrl.dirty) .withContext(`Expected control to become dirty when the user types into the input.`) .toBe(true); }); it('should mark the autocomplete control as dirty when an option is selected', waitForAsync(async () => { expect(fixture.componentInstance.stateCtrl.dirty) .withContext(`Expected control to start out pristine.`) .toBe(false); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; options[1].click(); fixture.detectChanges(); expect(fixture.componentInstance.stateCtrl.dirty) .withContext(`Expected control to become dirty when an option was selected.`) .toBe(true); })); it('should not mark the control dirty when the value is set programmatically', () => { expect(fixture.componentInstance.stateCtrl.dirty) .withContext(`Expected control to start out pristine.`) .toBe(false); fixture.componentInstance.stateCtrl.setValue('AL'); fixture.detectChanges(); expect(fixture.componentInstance.stateCtrl.dirty) .withContext(`Expected control to stay pristine if value is set programmatically.`) .toBe(false); }); it('should mark the autocomplete control as touched on blur', () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); expect(fixture.componentInstance.stateCtrl.touched) .withContext(`Expected control to start out untouched.`) .toBe(false); dispatchFakeEvent(input, 'blur'); fixture.detectChanges(); expect(fixture.componentInstance.stateCtrl.touched) .withContext(`Expected control to become touched on blur.`) .toBe(true); }); it('should disable the input when used with a value accessor and without `matInput`', () => { fixture.destroy(); TestBed.resetTestingModule(); const plainFixture = createComponent(PlainAutocompleteInputWithFormControl); plainFixture.detectChanges(); input = plainFixture.nativeElement.querySelector('input'); expect(input.disabled).toBe(false); plainFixture.componentInstance.formControl.disable(); plainFixture.detectChanges(); expect(input.disabled).toBe(true); }); }); describe('with theming', () => { let fixture: ComponentFixture<SimpleAutocomplete>; beforeEach(() => { fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); }); it('should transfer the theme to the autocomplete panel', () => { fixture.componentInstance.theme = 'warn'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panel = overlayContainerElement.querySelector( '.mat-mdc-autocomplete-panel', )! as HTMLElement; expect(panel.classList).toContain('mat-warn'); }); });
{ "end_byte": 37282, "start_byte": 26852, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_37286_47065
describe('keyboard events', () => { let fixture: ComponentFixture<SimpleAutocomplete>; let input: HTMLInputElement; let DOWN_ARROW_EVENT: KeyboardEvent; let UP_ARROW_EVENT: KeyboardEvent; let ENTER_EVENT: KeyboardEvent; beforeEach(waitForAsync(async () => { fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); input = fixture.debugElement.query(By.css('input'))!.nativeElement; DOWN_ARROW_EVENT = createKeyboardEvent('keydown', DOWN_ARROW); UP_ARROW_EVENT = createKeyboardEvent('keydown', UP_ARROW); ENTER_EVENT = createKeyboardEvent('keydown', ENTER); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); })); it('should not focus the option when DOWN key is pressed', () => { spyOn(fixture.componentInstance.options.first, 'focus'); fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); expect(fixture.componentInstance.options.first.focus).not.toHaveBeenCalled(); }); it('should not close the panel when DOWN key is pressed', () => { fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected panel state to stay open when DOWN key is pressed.`) .toBe(true); expect(overlayContainerElement.textContent) .withContext(`Expected panel to keep displaying when DOWN key is pressed.`) .toContain('Alabama'); expect(overlayContainerElement.textContent) .withContext(`Expected panel to keep displaying when DOWN key is pressed.`) .toContain('California'); }); it('should set the active item to the first option when DOWN key is pressed', () => { const componentInstance = fixture.componentInstance; const optionEls = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; expect(componentInstance.trigger.panelOpen) .withContext('Expected first down press to open the pane.') .toBe(true); componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); expect(componentInstance.trigger.activeOption === componentInstance.options.first) .withContext('Expected first option to be active.') .toBe(true); expect(optionEls[0].classList).toContain('mat-mdc-option-active'); expect(optionEls[1].classList).not.toContain('mat-mdc-option-active'); componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); expect(componentInstance.trigger.activeOption === componentInstance.options.toArray()[1]) .withContext('Expected second option to be active.') .toBe(true); expect(optionEls[0].classList).not.toContain('mat-mdc-option-active'); expect(optionEls[1].classList).toContain('mat-mdc-option-active'); }); it('should set the active item to the last option when UP key is pressed', () => { const componentInstance = fixture.componentInstance; const optionEls = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; expect(componentInstance.trigger.panelOpen) .withContext('Expected first up press to open the pane.') .toBe(true); componentInstance.trigger._handleKeydown(UP_ARROW_EVENT); fixture.detectChanges(); expect(componentInstance.trigger.activeOption === componentInstance.options.last) .withContext('Expected last option to be active.') .toBe(true); expect(optionEls[10].classList).toContain('mat-mdc-option-active'); expect(optionEls[0].classList).not.toContain('mat-mdc-option-active'); componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); expect(componentInstance.trigger.activeOption === componentInstance.options.first) .withContext('Expected first option to be active.') .toBe(true); expect(optionEls[0].classList).toContain('mat-mdc-option-active'); }); it('should set the active item properly after filtering', fakeAsync(() => { const componentInstance = fixture.componentInstance; componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); tick(); fixture.detectChanges(); })); it('should set the active item properly after filtering', () => { const componentInstance = fixture.componentInstance; typeInElement(input, 'o'); fixture.detectChanges(); componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); const optionEls = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; expect(componentInstance.trigger.activeOption === componentInstance.options.first) .withContext('Expected first option to be active.') .toBe(true); expect(optionEls[0].classList).toContain('mat-mdc-option-active'); expect(optionEls[1].classList).not.toContain('mat-mdc-option-active'); }); it('should fill the text field when an option is selected with ENTER', fakeAsync(() => { fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); flush(); fixture.detectChanges(); fixture.componentInstance.trigger._handleKeydown(ENTER_EVENT); fixture.detectChanges(); flush(); expect(input.value) .withContext(`Expected text field to fill with selected value on ENTER.`) .toContain('Alabama'); })); it('should prevent the default enter key action', fakeAsync(() => { fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); flush(); fixture.componentInstance.trigger._handleKeydown(ENTER_EVENT); flush(); expect(ENTER_EVENT.defaultPrevented) .withContext('Expected the default action to have been prevented.') .toBe(true); })); it('should not prevent the default enter action for a closed panel after a user action', () => { fixture.componentInstance.trigger._handleKeydown(UP_ARROW_EVENT); fixture.detectChanges(); fixture.componentInstance.trigger.closePanel(); fixture.detectChanges(); fixture.componentInstance.trigger._handleKeydown(ENTER_EVENT); expect(ENTER_EVENT.defaultPrevented) .withContext('Default action should not be prevented.') .toBe(false); }); it('should not interfere with the ENTER key when pressing a modifier', fakeAsync(() => { const trigger = fixture.componentInstance.trigger; expect(input.value).withContext('Expected input to start off blank.').toBeFalsy(); expect(trigger.panelOpen).withContext('Expected panel to start off open.').toBe(true); fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); flush(); fixture.detectChanges(); Object.defineProperty(ENTER_EVENT, 'altKey', {get: () => true}); fixture.componentInstance.trigger._handleKeydown(ENTER_EVENT); fixture.detectChanges(); expect(trigger.panelOpen).withContext('Expected panel to remain open.').toBe(true); expect(input.value).withContext('Expected input to remain blank.').toBeFalsy(); expect(ENTER_EVENT.defaultPrevented) .withContext('Expected the default ENTER action not to have been prevented.') .toBe(false); })); it('should fill the text field, not select an option, when SPACE is entered', () => { typeInElement(input, 'New'); fixture.detectChanges(); const SPACE_EVENT = createKeyboardEvent('keydown', SPACE); fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); fixture.componentInstance.trigger._handleKeydown(SPACE_EVENT); fixture.detectChanges(); expect(input.value) .not.withContext(`Expected option not to be selected on SPACE.`) .toContain('New York'); }); it('should mark the control dirty when selecting an option from the keyboard', fakeAsync(() => { expect(fixture.componentInstance.stateCtrl.dirty) .withContext(`Expected control to start out pristine.`) .toBe(false); fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); flush(); fixture.componentInstance.trigger._handleKeydown(ENTER_EVENT); fixture.detectChanges(); flush(); expect(fixture.componentInstance.stateCtrl.dirty) .withContext(`Expected control to become dirty when option was selected by ENTER.`) .toBe(true); })); it('should open the panel again when typing after making a selection', fakeAsync(() => { fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); flush(); fixture.componentInstance.trigger._handleKeydown(ENTER_EVENT); fixture.detectChanges(); tick(); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected panel state to read closed after ENTER key.`) .toBe(false); expect(overlayContainerElement.textContent) .withContext(`Expected panel to close after ENTER key.`) .toEqual(''); dispatchFakeEvent(input, 'focusin'); clearElement(input); typeInElement(input, 'Alabama'); fixture.detectChanges(); tick(); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected panel state to read open when typing in input.`) .toBe(true); expect(overlayContainerElement.textContent) .withContext(`Expected panel to display when typing in input.`) .toContain('Alabama'); }));
{ "end_byte": 47065, "start_byte": 37286, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_47071_55635
it('should not open the panel if the `input` event was dispatched with changing the value', fakeAsync(() => { const trigger = fixture.componentInstance.trigger; dispatchFakeEvent(input, 'focusin'); typeInElement(input, 'A'); fixture.detectChanges(); tick(); expect(trigger.panelOpen).withContext('Expected panel to be open.').toBe(true); trigger.closePanel(); fixture.detectChanges(); expect(trigger.panelOpen).withContext('Expected panel to be closed.').toBe(false); // Dispatch the event without actually changing the value // to simulate what happen in some cases on IE. dispatchFakeEvent(input, 'input'); fixture.detectChanges(); tick(); expect(trigger.panelOpen).withContext('Expected panel to stay closed.').toBe(false); })); it('should scroll to active options below the fold', () => { const trigger = fixture.componentInstance.trigger; const scrollContainer = document.querySelector( '.cdk-overlay-pane .mat-mdc-autocomplete-panel', )!; trigger._handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); expect(scrollContainer.scrollTop).withContext(`Expected panel not to scroll.`).toEqual(0); // These down arrows will set the 6th option active, below the fold. [1, 2, 3, 4, 5].forEach(() => trigger._handleKeydown(DOWN_ARROW_EVENT)); // Expect option bottom minus the panel height plus padding (288 - 256 + 8 = 40) // Expect option bottom minus the panel height plus padding (288 - 256 + 8 = 40) expect(scrollContainer.scrollTop) .withContext(`Expected panel to reveal the sixth option.`) .toEqual(40); }); it('should scroll to active options below if the option height is variable', () => { // Make every other option a bit taller than the base of 48. fixture.componentInstance.states.forEach((state, index) => { if (index % 2 === 0) { state.height = 64; } }); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const trigger = fixture.componentInstance.trigger; const scrollContainer = document.querySelector( '.cdk-overlay-pane .mat-mdc-autocomplete-panel', )!; trigger._handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); expect(scrollContainer.scrollTop).withContext(`Expected panel not to scroll.`).toEqual(0); // These down arrows will set the 6th option active, below the fold. [1, 2, 3, 4, 5].forEach(() => trigger._handleKeydown(DOWN_ARROW_EVENT)); // Expect option bottom minus the panel height (336 - 256 + 8 = 88) // Expect option bottom minus the panel height (336 - 256 + 8 = 88) expect(scrollContainer.scrollTop) .withContext(`Expected panel to reveal the sixth option.`) .toEqual(88); }); it('should scroll to active options on UP arrow', () => { const scrollContainer = document.querySelector( '.cdk-overlay-pane .mat-mdc-autocomplete-panel', )!; const initialScrollTop = scrollContainer.scrollTop; fixture.componentInstance.trigger._handleKeydown(UP_ARROW_EVENT); fixture.detectChanges(); expect(scrollContainer.scrollTop) .withContext(`Expected panel to reveal last option.`) .toBeGreaterThan(initialScrollTop); }); it('should not scroll to active options that are fully in the panel', () => { const trigger = fixture.componentInstance.trigger; const scrollContainer = document.querySelector( '.cdk-overlay-pane .mat-mdc-autocomplete-panel', )!; trigger._handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); expect(scrollContainer.scrollTop).withContext(`Expected panel not to scroll.`).toEqual(0); // These down arrows will set the 6th option active, below the fold. [1, 2, 3, 4, 5].forEach(() => trigger._handleKeydown(DOWN_ARROW_EVENT)); // Expect option bottom minus the panel height plus the padding (288 - 256 + 8 = 40) // Expect option bottom minus the panel height plus the padding (288 - 256 + 8 = 40) expect(scrollContainer.scrollTop) .withContext(`Expected panel to reveal the sixth option.`) .toEqual(40); // These up arrows will set the 2nd option active [4, 3, 2, 1].forEach(() => trigger._handleKeydown(UP_ARROW_EVENT)); // Expect no scrolling to have occurred. Still showing bottom of 6th option. // Expect no scrolling to have occurred. Still showing bottom of 6th option. expect(scrollContainer.scrollTop) .withContext(`Expected panel not to scroll up since sixth option still fully visible.`) .toEqual(40); }); it('should scroll to active options that are above the panel', () => { const trigger = fixture.componentInstance.trigger; const scrollContainer = document.querySelector( '.cdk-overlay-pane .mat-mdc-autocomplete-panel', )!; trigger._handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); expect(scrollContainer.scrollTop).withContext(`Expected panel not to scroll.`).toEqual(0); // These down arrows will set the 7th option active, below the fold. [1, 2, 3, 4, 5, 6].forEach(() => trigger._handleKeydown(DOWN_ARROW_EVENT)); // These up arrows will set the 2nd option active [5, 4, 3, 2, 1].forEach(() => trigger._handleKeydown(UP_ARROW_EVENT)); // Expect to show the top of the 2nd option at the top of the panel // Expect to show the top of the 2nd option at the top of the panel expect(scrollContainer.scrollTop) .withContext(`Expected panel to scroll up when option is above panel.`) .toEqual(56); }); it('should close the panel when pressing escape', fakeAsync(() => { const trigger = fixture.componentInstance.trigger; input.focus(); flush(); fixture.detectChanges(); expect(document.activeElement).withContext('Expected input to be focused.').toBe(input); expect(trigger.panelOpen).withContext('Expected panel to be open.').toBe(true); dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); fixture.detectChanges(); flush(); expect(document.activeElement) .withContext('Expected input to continue to be focused.') .toBe(input); expect(trigger.panelOpen).withContext('Expected panel to be closed.').toBe(false); })); it('should prevent the default action when pressing escape', () => { const escapeEvent = dispatchKeyboardEvent(input, 'keydown', ESCAPE); fixture.detectChanges(); expect(escapeEvent.defaultPrevented).toBe(true); }); it('should not close the panel when pressing escape with a modifier', fakeAsync(() => { const trigger = fixture.componentInstance.trigger; input.focus(); flush(); fixture.detectChanges(); expect(document.activeElement).withContext('Expected input to be focused.').toBe(input); expect(trigger.panelOpen).withContext('Expected panel to be open.').toBe(true); const event = dispatchKeyboardEvent(document.body, 'keydown', ESCAPE, undefined, {alt: true}); fixture.detectChanges(); expect(document.activeElement) .withContext('Expected input to continue to be focused.') .toBe(input); expect(trigger.panelOpen).withContext('Expected panel to stay open.').toBe(true); expect(event.defaultPrevented) .withContext('Expected default action not to be prevented.') .toBe(false); })); it('should close the panel when pressing ALT + UP_ARROW', fakeAsync(() => { const trigger = fixture.componentInstance.trigger; const upArrowEvent = createKeyboardEvent('keydown', UP_ARROW, undefined, {alt: true}); spyOn(upArrowEvent, 'stopPropagation').and.callThrough(); input.focus(); flush(); fixture.detectChanges(); expect(document.activeElement).withContext('Expected input to be focused.').toBe(input); expect(trigger.panelOpen).withContext('Expected panel to be open.').toBe(true); dispatchEvent(document.body, upArrowEvent); fixture.detectChanges(); flush(); expect(document.activeElement) .withContext('Expected input to continue to be focused.') .toBe(input); expect(trigger.panelOpen).withContext('Expected panel to be closed.').toBe(false); expect(upArrowEvent.stopPropagation).toHaveBeenCalled(); }));
{ "end_byte": 55635, "start_byte": 47071, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_55641_59903
it('should close the panel when tabbing away from a trigger without results', fakeAsync(() => { fixture.componentInstance.states = []; fixture.componentInstance.filteredStates = []; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); input.focus(); flush(); expect(overlayContainerElement.querySelector('.mat-mdc-autocomplete-panel')) .withContext('Expected panel to be rendered.') .toBeTruthy(); dispatchKeyboardEvent(input, 'keydown', TAB); fixture.detectChanges(); tick(); expect(overlayContainerElement.querySelector('.mat-mdc-autocomplete-panel')) .withContext('Expected panel to be removed.') .toBeFalsy(); })); it('should not close when a click event occurs on the outside while the panel has focus', fakeAsync(() => { const trigger = fixture.componentInstance.trigger; input.focus(); flush(); fixture.detectChanges(); expect(document.activeElement).toBe(input, 'Expected input to be focused.'); expect(trigger.panelOpen).toBe(true, 'Expected panel to be open.'); dispatchMouseEvent(document.body, 'click'); fixture.detectChanges(); expect(document.activeElement).toBe(input, 'Expected input to continue to be focused.'); expect(trigger.panelOpen).toBe(true, 'Expected panel to stay open.'); })); it('should reset the active option when closing with the escape key', fakeAsync(() => { const trigger = fixture.componentInstance.trigger; trigger.openPanel(); fixture.detectChanges(); tick(); expect(trigger.panelOpen).withContext('Expected panel to be open.').toBe(true); expect(!!trigger.activeOption).withContext('Expected no active option.').toBe(false); // Press the down arrow a few times. [1, 2, 3].forEach(() => { trigger._handleKeydown(DOWN_ARROW_EVENT); tick(); fixture.detectChanges(); }); // Note that this casts to a boolean, in order to prevent Jasmine // from crashing when trying to stringify the option if the test fails. // Note that this casts to a boolean, in order to prevent Jasmine // from crashing when trying to stringify the option if the test fails. expect(!!trigger.activeOption).withContext('Expected to find an active option.').toBe(true); dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); tick(); expect(!!trigger.activeOption).withContext('Expected no active options.').toBe(false); })); it('should reset the active option when closing by selecting with enter', fakeAsync(() => { const trigger = fixture.componentInstance.trigger; trigger.openPanel(); fixture.detectChanges(); tick(); expect(trigger.panelOpen).withContext('Expected panel to be open.').toBe(true); expect(!!trigger.activeOption).withContext('Expected no active option.').toBe(false); // Press the down arrow a few times. [1, 2, 3].forEach(() => { trigger._handleKeydown(DOWN_ARROW_EVENT); tick(); fixture.detectChanges(); }); // Note that this casts to a boolean, in order to prevent Jasmine // from crashing when trying to stringify the option if the test fails. // Note that this casts to a boolean, in order to prevent Jasmine // from crashing when trying to stringify the option if the test fails. expect(!!trigger.activeOption).withContext('Expected to find an active option.').toBe(true); trigger._handleKeydown(ENTER_EVENT); tick(); expect(!!trigger.activeOption).withContext('Expected no active options.').toBe(false); })); it('should not prevent the default action when a modifier key is pressed', () => { ['metaKey', 'ctrlKey', 'altKey', 'shiftKey'].forEach(name => { const event = createKeyboardEvent('keydown', DOWN_ARROW); Object.defineProperty(event, name, {get: () => true}); fixture.componentInstance.trigger._handleKeydown(event); fixture.detectChanges(); expect(event.defaultPrevented) .withContext(`Expected autocomplete not to block ${name} key`) .toBe(false); }); }); });
{ "end_byte": 59903, "start_byte": 55641, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_59907_66295
describe('option groups', () => { let DOWN_ARROW_EVENT: KeyboardEvent; let UP_ARROW_EVENT: KeyboardEvent; beforeEach(() => { DOWN_ARROW_EVENT = createKeyboardEvent('keydown', DOWN_ARROW); UP_ARROW_EVENT = createKeyboardEvent('keydown', UP_ARROW); }); it('should scroll to active options below the fold', waitForAsync(async () => { const fixture = createComponent(AutocompleteWithGroups); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); const container = document.querySelector('.mat-mdc-autocomplete-panel') as HTMLElement; fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(container.scrollTop).withContext('Expected the panel not to scroll.').toBe(0); // Press the down arrow five times. for (const _unused of [1, 2, 3, 4, 5]) { fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); await new Promise(r => setTimeout(r)); } // <option bottom> - <panel height> + <2x group labels> + panel padding = 136 // 288 - 256 + 96 + 8 = 128 // <option bottom> - <panel height> + <2x group labels> + panel padding = 136 // 288 - 256 + 96 + 8 = 128 expect(container.scrollTop) .withContext('Expected panel to reveal the sixth option.') .toBe(136); })); it('should scroll to active options on UP arrow', waitForAsync(async () => { const fixture = createComponent(AutocompleteWithGroups); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); const container = document.querySelector('.mat-mdc-autocomplete-panel') as HTMLElement; fixture.componentInstance.trigger._handleKeydown(UP_ARROW_EVENT); await new Promise(r => setTimeout(r)); fixture.detectChanges(); // <option bottom> - <panel height> + <3x group label> + panel padding = 472 // 576 - 256 + 144 + 8 = 472 // <option bottom> - <panel height> + <3x group label> + panel padding = 472 // 576 - 256 + 144 + 8 = 472 expect(container.scrollTop).withContext('Expected panel to reveal last option.').toBe(472); })); it('should scroll to active options that are above the panel', fakeAsync(() => { const fixture = createComponent(AutocompleteWithGroups); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); tick(); fixture.detectChanges(); const container = document.querySelector('.mat-mdc-autocomplete-panel') as HTMLElement; fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); tick(); fixture.detectChanges(); expect(container.scrollTop).withContext('Expected panel not to scroll.').toBe(0); // These down arrows will set the 7th option active, below the fold. [1, 2, 3, 4, 5, 6].forEach(() => { fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); tick(); }); // These up arrows will set the 2nd option active [5, 4, 3, 2, 1].forEach(() => { fixture.componentInstance.trigger._handleKeydown(UP_ARROW_EVENT); tick(); }); // Expect to show the top of the 2nd option at the top of the panel. // It is offset by 56, because there's a group label above it plus the panel padding. // Expect to show the top of the 2nd option at the top of the panel. // It is offset by 56, because there's a group label above it plus the panel padding. expect(container.scrollTop) .withContext('Expected panel to scroll up when option is above panel.') .toBe(104); })); it('should scroll back to the top when reaching the first option with preceding group label', fakeAsync(() => { const fixture = createComponent(AutocompleteWithGroups); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); tick(); fixture.detectChanges(); const container = document.querySelector('.mat-mdc-autocomplete-panel') as HTMLElement; fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); tick(); fixture.detectChanges(); expect(container.scrollTop).withContext('Expected the panel not to scroll.').toBe(0); // Press the down arrow five times. [1, 2, 3, 4, 5].forEach(() => { fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); tick(); }); // Press the up arrow five times. [1, 2, 3, 4, 5].forEach(() => { fixture.componentInstance.trigger._handleKeydown(UP_ARROW_EVENT); tick(); }); expect(container.scrollTop).withContext('Expected panel to be scrolled to the top.').toBe(0); })); it('should scroll to active option when group is indirect descendant', waitForAsync(async () => { const fixture = createComponent(AutocompleteWithIndirectGroups); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); const container = document.querySelector('.mat-mdc-autocomplete-panel') as HTMLElement; fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(container.scrollTop).withContext('Expected the panel not to scroll.').toBe(0); // Press the down arrow five times. for (const _unused of [1, 2, 3, 4, 5]) { fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); await new Promise(r => setTimeout(r)); } // <option bottom> - <panel height> + <2x group labels> + panel padding = 128 // 288 - 256 + 96 + 8 = 136 // <option bottom> - <panel height> + <2x group labels> + panel padding = 128 // 288 - 256 + 96 + 8 = 136 expect(container.scrollTop) .withContext('Expected panel to reveal the sixth option.') .toBe(136); })); });
{ "end_byte": 66295, "start_byte": 59907, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_66299_75005
describe('aria', () => { let fixture: ComponentFixture<SimpleAutocomplete>; let input: HTMLInputElement; beforeEach(() => { fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); input = fixture.debugElement.query(By.css('input'))!.nativeElement; }); it('should set role of input to combobox', () => { expect(input.getAttribute('role')) .withContext('Expected role of input to be combobox.') .toEqual('combobox'); }); it('should set role of autocomplete panel to listbox', () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panel = fixture.debugElement.query( By.css('.mat-mdc-autocomplete-panel'), )!.nativeElement; expect(panel.getAttribute('role')) .withContext('Expected role of the panel to be listbox.') .toEqual('listbox'); }); it('should point the aria-labelledby of the panel to the field label', () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panel = fixture.debugElement.query( By.css('.mat-mdc-autocomplete-panel'), )!.nativeElement; const labelId = fixture.nativeElement.querySelector('label').id; expect(panel.getAttribute('aria-labelledby')).toBe(labelId); expect(panel.hasAttribute('aria-label')).toBe(false); }); it('should add a custom aria-labelledby to the panel', () => { fixture.componentInstance.ariaLabelledby = 'myLabelId'; fixture.changeDetectorRef.markForCheck(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panel = fixture.debugElement.query( By.css('.mat-mdc-autocomplete-panel'), )!.nativeElement; const labelId = fixture.nativeElement.querySelector('label').id; expect(panel.getAttribute('aria-labelledby')).toBe(`${labelId} myLabelId`); expect(panel.hasAttribute('aria-label')).toBe(false); }); it('should trim aria-labelledby if the input does not have a label', () => { fixture.componentInstance.hasLabel = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.ariaLabelledby = 'myLabelId'; fixture.changeDetectorRef.markForCheck(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panel = fixture.debugElement.query( By.css('.mat-mdc-autocomplete-panel'), )!.nativeElement; expect(panel.getAttribute('aria-labelledby')).toBe(`myLabelId`); }); it('should clear aria-labelledby from the panel if an aria-label is set', () => { fixture.componentInstance.ariaLabel = 'My label'; fixture.changeDetectorRef.markForCheck(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panel = fixture.debugElement.query( By.css('.mat-mdc-autocomplete-panel'), )!.nativeElement; expect(panel.getAttribute('aria-label')).toBe('My label'); expect(panel.hasAttribute('aria-labelledby')).toBe(false); }); it('should clear aria-labelledby if the form field does not have a label', () => { fixture.componentInstance.hasLabel = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panel = fixture.debugElement.query( By.css('.mat-mdc-autocomplete-panel'), )!.nativeElement; expect(panel.hasAttribute('aria-labelledby')).toBe(false); }); it('should support setting a custom aria-label', () => { fixture.componentInstance.ariaLabel = 'Custom Label'; fixture.changeDetectorRef.markForCheck(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panel = fixture.debugElement.query( By.css('.mat-mdc-autocomplete-panel'), )!.nativeElement; expect(panel.getAttribute('aria-label')).toEqual('Custom Label'); expect(panel.hasAttribute('aria-labelledby')).toBe(false); }); it('should set aria-autocomplete to list', () => { expect(input.getAttribute('aria-autocomplete')) .withContext('Expected aria-autocomplete attribute to equal list.') .toEqual('list'); }); it('should set aria-activedescendant based on the active option', fakeAsync(() => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); expect(input.hasAttribute('aria-activedescendant')) .withContext('Expected aria-activedescendant to be absent if no active item.') .toBe(false); const DOWN_ARROW_EVENT = createKeyboardEvent('keydown', DOWN_ARROW); fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); tick(); fixture.detectChanges(); expect(input.getAttribute('aria-activedescendant')) .withContext('Expected aria-activedescendant to match the active item after 1 down arrow.') .toEqual(fixture.componentInstance.options.first.id); fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); tick(); fixture.detectChanges(); expect(input.getAttribute('aria-activedescendant')) .withContext('Expected aria-activedescendant to match the active item after 2 down arrows.') .toEqual(fixture.componentInstance.options.toArray()[1].id); })); it('should set aria-expanded based on whether the panel is open', () => { expect(input.getAttribute('aria-expanded')) .withContext('Expected aria-expanded to be false while panel is closed.') .toBe('false'); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); expect(input.getAttribute('aria-expanded')) .withContext('Expected aria-expanded to be true while panel is open.') .toBe('true'); fixture.componentInstance.trigger.closePanel(); fixture.detectChanges(); expect(input.getAttribute('aria-expanded')) .withContext('Expected aria-expanded to be false when panel closes again.') .toBe('false'); }); it('should set aria-expanded properly when the panel is hidden', fakeAsync(() => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); expect(input.getAttribute('aria-expanded')) .withContext('Expected aria-expanded to be true while panel is open.') .toBe('true'); typeInElement(input, 'zz'); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(input.getAttribute('aria-expanded')) .withContext('Expected aria-expanded to be false when panel hides itself.') .toBe('false'); })); it('should set aria-controls based on the attached autocomplete', () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panel = fixture.debugElement.query( By.css('.mat-mdc-autocomplete-panel'), )!.nativeElement; expect(input.getAttribute('aria-controls')) .withContext('Expected aria-controls to match attached autocomplete.') .toBe(panel.getAttribute('id')); }); it('should not set aria-controls while the autocomplete is closed', () => { expect(input.getAttribute('aria-controls')).toBeFalsy(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); expect(input.getAttribute('aria-controls')).toBeTruthy(); }); it('should restore focus to the input when clicking to select a value', waitForAsync(async () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const option = overlayContainerElement.querySelector('mat-option') as HTMLElement; // Focus the option manually since the synthetic click may not do it. option.focus(); option.click(); fixture.detectChanges(); expect(document.activeElement) .withContext('Expected focus to be restored to the input.') .toBe(input); })); it('should remove autocomplete-specific aria attributes when autocomplete is disabled', () => { fixture.componentInstance.autocompleteDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(input.getAttribute('role')).toBeFalsy(); expect(input.getAttribute('aria-autocomplete')).toBeFalsy(); expect(input.getAttribute('aria-expanded')).toBeFalsy(); expect(input.getAttribute('aria-owns')).toBeFalsy(); }); });
{ "end_byte": 75005, "start_byte": 66299, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_75009_84505
describe('Fallback positions', () => { it('should use below positioning by default', waitForAsync(async () => { let fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); let inputReference = fixture.debugElement.query(By.css('.mdc-text-field'))!.nativeElement; fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); const inputBottom = inputReference.getBoundingClientRect().bottom; const panel = overlayContainerElement.querySelector('.mat-mdc-autocomplete-panel')!; const panelTop = panel.getBoundingClientRect().top; expect(Math.floor(inputBottom)) .withContext(`Expected panel top to match input bottom by default.`) .toEqual(Math.floor(panelTop)); expect(panel.classList).not.toContain('mat-mdc-autocomplete-panel-above'); })); it('should reposition the panel on scroll', () => { let scrolledSubject = new Subject(); let spacer = document.createElement('div'); let fixture = createComponent(SimpleAutocomplete, [ { provide: ScrollDispatcher, useValue: {scrolled: () => scrolledSubject}, }, ]); fixture.detectChanges(); let inputReference = fixture.debugElement.query(By.css('.mdc-text-field'))!.nativeElement; spacer.style.height = '1000px'; document.body.appendChild(spacer); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); window.scroll(0, 100); scrolledSubject.next(); fixture.detectChanges(); const inputBottom = inputReference.getBoundingClientRect().bottom; const panel = overlayContainerElement.querySelector('.cdk-overlay-pane')!; const panelTop = panel.getBoundingClientRect().top; expect(Math.floor(inputBottom)) .withContext('Expected panel top to match input bottom after scrolling.') .toEqual(Math.floor(panelTop)); spacer.remove(); window.scroll(0, 0); }); it('should fall back to above position if panel cannot fit below', waitForAsync(async () => { let fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); let inputReference = fixture.debugElement.query(By.css('.mdc-text-field'))!.nativeElement; // Push the autocomplete trigger down so it won't have room to open "below" inputReference.style.bottom = '0'; inputReference.style.position = 'fixed'; fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); const inputTop = inputReference.getBoundingClientRect().top; const panel = overlayContainerElement.querySelector('.cdk-overlay-pane')!; const panelBottom = panel.getBoundingClientRect().bottom; expect(Math.floor(inputTop)) .withContext(`Expected panel to fall back to above position.`) .toEqual(Math.floor(panelBottom)); expect(panel.classList).toContain('mat-mdc-autocomplete-panel-above'); })); it('should allow the panel to expand when the number of results increases', waitForAsync(async () => { let fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement; let inputReference = fixture.debugElement.query(By.css('.mdc-text-field'))!.nativeElement; // Push the element down so it has a little bit of space, but not enough to render. inputReference.style.bottom = '10px'; inputReference.style.position = 'fixed'; // Type enough to only show one option. typeInElement(inputEl, 'California'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); let panel = overlayContainerElement.querySelector('.cdk-overlay-pane')!; let initialPanelHeight = panel.getBoundingClientRect().height; fixture.componentInstance.trigger.closePanel(); fixture.detectChanges(); // Change the text so we get more than one result. clearElement(inputEl); typeInElement(inputEl, 'C'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); panel = overlayContainerElement.querySelector('.cdk-overlay-pane')!; expect(panel.getBoundingClientRect().height).toBeGreaterThan(initialPanelHeight); })); it('should align panel properly when filtering in "above" position', waitForAsync(async () => { let fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); let input = fixture.debugElement.query(By.css('input'))!.nativeElement; let inputReference = fixture.debugElement.query(By.css('.mdc-text-field'))!.nativeElement; // Push the autocomplete trigger down so it won't have room to open "below" inputReference.style.bottom = '0'; inputReference.style.position = 'fixed'; fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); typeInElement(input, 'f'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const inputTop = inputReference.getBoundingClientRect().top; const panel = overlayContainerElement.querySelector('.mat-mdc-autocomplete-panel')!; const panelBottom = panel.getBoundingClientRect().bottom; expect(Math.floor(inputTop)) .withContext(`Expected panel to stay aligned after filtering.`) .toEqual(Math.floor(panelBottom)); })); it( 'should fall back to above position when requested if options are added while ' + 'the panel is open', waitForAsync(async () => { let fixture = createComponent(SimpleAutocomplete); fixture.componentInstance.states = fixture.componentInstance.states.slice(0, 1); fixture.componentInstance.filteredStates = fixture.componentInstance.states.slice(); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement; let inputReference = fixture.debugElement.query(By.css('.mdc-text-field'))!.nativeElement; // Push the element down so it has a little bit of space, but not enough to render. inputReference.style.bottom = '100px'; inputReference.style.position = 'fixed'; dispatchFakeEvent(inputEl, 'focusin'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); let panel = overlayContainerElement.querySelector('.mat-mdc-autocomplete-panel')!; let inputRect = inputReference.getBoundingClientRect(); let panelRect = panel.getBoundingClientRect(); expect(Math.floor(panelRect.top)) .withContext(`Expected panel top to be below input before repositioning.`) .toBe(Math.floor(inputRect.bottom)); for (let i = 0; i < 20; i++) { fixture.componentInstance.filteredStates.push({code: 'FK', name: 'Fake State'}); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); } // Request a position update now that there are too many suggestions to fit in the viewport. fixture.componentInstance.trigger.updatePosition(); inputRect = inputReference.getBoundingClientRect(); panelRect = panel.getBoundingClientRect(); expect(Math.floor(panelRect.bottom)) .withContext(`Expected panel to fall back to above position after repositioning.`) .toBe(Math.floor(inputRect.top)); await new Promise(r => setTimeout(r)); }), ); it('should not throw if a panel reposition is requested while the panel is closed', () => { let fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); expect(() => fixture.componentInstance.trigger.updatePosition()).not.toThrow(); }); it('should be able to force below position even if there is not enough space', waitForAsync(async () => { let fixture = createComponent(SimpleAutocomplete); fixture.componentInstance.position = 'below'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); let inputReference = fixture.debugElement.query(By.css('.mdc-text-field'))!.nativeElement; // Push the autocomplete trigger down so it won't have room to open below. inputReference.style.bottom = '0'; inputReference.style.position = 'fixed'; fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); const inputBottom = inputReference.getBoundingClientRect().bottom; const panel = overlayContainerElement.querySelector('.cdk-overlay-pane')!; const panelTop = panel.getBoundingClientRect().top; expect(Math.floor(inputBottom)) .withContext('Expected panel to be below the input.') .toEqual(Math.floor(panelTop)); expect(panel.classList).not.toContain('mat-mdc-autocomplete-panel-above'); }));
{ "end_byte": 84505, "start_byte": 75009, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_84511_87457
it('should be able to force above position even if there is not enough space', waitForAsync(async () => { let fixture = createComponent(SimpleAutocomplete); fixture.componentInstance.position = 'above'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); let inputReference = fixture.debugElement.query(By.css('.mdc-text-field'))!.nativeElement; // Push the autocomplete trigger up so it won't have room to open above. inputReference.style.top = '0'; inputReference.style.position = 'fixed'; fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); const inputTop = inputReference.getBoundingClientRect().top; const panel = overlayContainerElement.querySelector('.cdk-overlay-pane')!; const panelBottom = panel.getBoundingClientRect().bottom; expect(Math.floor(inputTop)) .withContext('Expected panel to be above the input.') .toEqual(Math.floor(panelBottom)); expect(panel.classList).toContain('mat-mdc-autocomplete-panel-above'); })); it('should handle the position being changed after the first open', waitForAsync(async () => { let fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); let inputReference = fixture.debugElement.query(By.css('.mdc-text-field'))!.nativeElement; let openPanel = async () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); }; // Push the autocomplete trigger down so it won't have room to open below. inputReference.style.bottom = '0'; inputReference.style.position = 'fixed'; await openPanel(); let inputRect = inputReference.getBoundingClientRect(); let panel = overlayContainerElement.querySelector('.cdk-overlay-pane')!; let panelRect = panel.getBoundingClientRect(); expect(Math.floor(inputRect.top)) .withContext('Expected panel to be above the input.') .toEqual(Math.floor(panelRect.bottom)); expect(panel.classList).toContain('mat-mdc-autocomplete-panel-above'); fixture.componentInstance.trigger.closePanel(); fixture.detectChanges(); fixture.componentInstance.position = 'below'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); await openPanel(); inputRect = inputReference.getBoundingClientRect(); panel = overlayContainerElement.querySelector('.cdk-overlay-pane')!; panelRect = panel.getBoundingClientRect(); expect(Math.floor(inputRect.bottom)) .withContext('Expected panel to be below the input.') .toEqual(Math.floor(panelRect.top)); expect(panel.classList).not.toContain('mat-mdc-autocomplete-panel-above'); })); });
{ "end_byte": 87457, "start_byte": 84511, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_87461_96795
describe('Option selection', () => { let fixture: ComponentFixture<SimpleAutocomplete>; beforeEach(() => { fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); }); it('should deselect any other selected option', waitForAsync(async () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); let options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; options[0].click(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); let componentOptions = fixture.componentInstance.options.toArray(); expect(componentOptions[0].selected) .withContext(`Clicked option should be selected.`) .toBe(true); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); options = overlayContainerElement.querySelectorAll('mat-option') as NodeListOf<HTMLElement>; options[1].click(); fixture.detectChanges(); expect(componentOptions[0].selected) .withContext(`Previous option should not be selected.`) .toBe(false); expect(componentOptions[1].selected) .withContext(`New Clicked option should be selected.`) .toBe(true); })); it('should call deselect only on the previous selected option', waitForAsync(async () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); let options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; options[0].click(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); let componentOptions = fixture.componentInstance.options.toArray(); componentOptions.forEach(option => spyOn(option, 'deselect')); expect(componentOptions[0].selected) .withContext(`Clicked option should be selected.`) .toBe(true); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); options = overlayContainerElement.querySelectorAll('mat-option') as NodeListOf<HTMLElement>; options[1].click(); fixture.detectChanges(); expect(componentOptions[0].deselect).toHaveBeenCalled(); componentOptions.slice(1).forEach(option => expect(option.deselect).not.toHaveBeenCalled()); })); it('should be able to preselect the first option', waitForAsync(async () => { fixture.componentInstance.trigger.autocomplete.autoActiveFirstOption = true; fixture.changeDetectorRef.markForCheck(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('mat-option')[0].classList) .withContext('Expected first option to be highlighted.') .toContain('mat-mdc-option-active'); })); it( 'should skip to the next enabled option if the first one is disabled ' + 'when using `autoActiveFirstOption`', waitForAsync(async () => { const testComponent = fixture.componentInstance; testComponent.trigger.autocomplete.autoActiveFirstOption = true; testComponent.states[0].disabled = true; testComponent.states[1].disabled = true; testComponent.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('mat-option')[2].classList) .withContext('Expected third option to be highlighted.') .toContain('mat-mdc-option-active'); }), ); it('should not activate any option if all options are disabled', waitForAsync(async () => { const testComponent = fixture.componentInstance; testComponent.trigger.autocomplete.autoActiveFirstOption = true; for (const state of testComponent.states) { state.disabled = true; } testComponent.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); const selectedOptions = overlayContainerElement.querySelectorAll( 'mat-option.mat-mdc-option-active', ); expect(selectedOptions.length).withContext('expected no options to be active').toBe(0); })); it('should remove aria-activedescendant when panel is closed with autoActiveFirstOption', waitForAsync(async () => { const input: HTMLElement = fixture.nativeElement.querySelector('input'); expect(input.hasAttribute('aria-activedescendant')) .withContext('Expected no active descendant on init.') .toBe(false); fixture.componentInstance.trigger.autocomplete.autoActiveFirstOption = true; fixture.changeDetectorRef.markForCheck(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(input.getAttribute('aria-activedescendant')) .withContext('Expected active descendant while open.') .toBeTruthy(); fixture.componentInstance.trigger.closePanel(); fixture.detectChanges(); expect(input.hasAttribute('aria-activedescendant')) .withContext('Expected no active descendant when closed.') .toBe(false); })); it('should be able to preselect the first option when the floating label is disabled', waitForAsync(async () => { fixture.componentInstance.floatLabel = 'never'; fixture.componentInstance.trigger.autocomplete.autoActiveFirstOption = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); // Note: should not have a detectChanges call here // in order for the test to fail when it's supposed to. expect(overlayContainerElement.querySelectorAll('mat-option')[0].classList) .withContext('Expected first option to be highlighted.') .toContain('mat-mdc-option-active'); })); it('should be able to configure preselecting the first option globally', waitForAsync(async () => { fixture.destroy(); TestBed.resetTestingModule(); fixture = createComponent(SimpleAutocomplete, [ {provide: MAT_AUTOCOMPLETE_DEFAULT_OPTIONS, useValue: {autoActiveFirstOption: true}}, ]); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('mat-option')[0].classList) .withContext('Expected first option to be highlighted.') .toContain('mat-mdc-option-active'); })); it('should handle `optionSelections` being accessed too early', waitForAsync(async () => { fixture.destroy(); fixture = TestBed.createComponent(SimpleAutocomplete); let spy = jasmine.createSpy('option selection spy'); let subscription: Subscription; expect(fixture.componentInstance.trigger.autocomplete).toBeFalsy(); expect(() => { subscription = fixture.componentInstance.trigger.optionSelections.subscribe(spy); }).not.toThrow(); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const option = overlayContainerElement.querySelector('mat-option') as HTMLElement; option.click(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(spy).toHaveBeenCalledWith(jasmine.any(MatOptionSelectionChange)); subscription!.unsubscribe(); })); it('should emit to `optionSelections` if the list of options changes', waitForAsync(async () => { const spy = jasmine.createSpy('option selection spy'); const subscription = fixture.componentInstance.trigger.optionSelections.subscribe(spy); const openAndSelectFirstOption = async () => { fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); (overlayContainerElement.querySelector('mat-option') as HTMLElement).click(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); }; fixture.componentInstance.states = [{code: 'OR', name: 'Oregon'}]; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); await openAndSelectFirstOption(); expect(spy).toHaveBeenCalledTimes(1); fixture.componentInstance.states = [{code: 'WV', name: 'West Virginia'}]; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); await openAndSelectFirstOption(); expect(spy).toHaveBeenCalledTimes(2); subscription!.unsubscribe(); }));
{ "end_byte": 96795, "start_byte": 87461, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_96801_106099
it('should reposition the panel when the amount of options changes', waitForAsync(async () => { const flushPosition = async () => { fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); // Safari seems to require an extra round that other browsers don't. await new Promise(r => setTimeout(r)); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); }; await flushPosition(); let formField = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement; let inputReference = formField.querySelector('.mdc-text-field'); let input = inputReference.querySelector('input'); formField.style.bottom = '100px'; formField.style.position = 'fixed'; typeInElement(input, 'Cali'); await flushPosition(); const inputBottom = inputReference.getBoundingClientRect().bottom; const panel = overlayContainerElement.querySelector('.mat-mdc-autocomplete-panel')!; const panelTop = panel.getBoundingClientRect().top; expect(Math.floor(inputBottom)) .withContext(`Expected panel top to match input bottom when there is only one option.`) .toBe(Math.floor(panelTop)); clearElement(input); await flushPosition(); const inputTop = inputReference.getBoundingClientRect().top; const panelBottom = panel.getBoundingClientRect().bottom; expect(Math.floor(inputTop)) .withContext(`Expected panel switch to the above position if the options no longer fit.`) .toBe(Math.floor(panelBottom)); })); it('should clear the selected option when the input value is cleared', waitForAsync(async () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const input = fixture.nativeElement.querySelector('input'); const option = overlayContainerElement.querySelector('mat-option') as HTMLElement; const optionInstance = fixture.componentInstance.options.first; const spy = jasmine.createSpy('selectionChange spy'); option.click(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('Alabama'); expect(optionInstance.selected).toBe(true); const subscription = optionInstance.onSelectionChange.subscribe(spy); clearElement(input); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe(''); expect(optionInstance.selected).toBe(false); expect(spy).not.toHaveBeenCalled(); subscription.unsubscribe(); })); it('should accept the user selection if they click on an option while selection is required', waitForAsync(async () => { const input = fixture.nativeElement.querySelector('input'); const {stateCtrl, trigger, states} = fixture.componentInstance; fixture.componentInstance.requireSelection = true; fixture.changeDetectorRef.markForCheck(); stateCtrl.setValue(states[1]); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('California'); expect(stateCtrl.value).toEqual({code: 'CA', name: 'California'}); trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; const spy = jasmine.createSpy('optionSelected spy'); const subscription = trigger.optionSelections.subscribe(spy); options[5].click(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('Oregon'); expect(stateCtrl.value).toEqual({code: 'OR', name: 'Oregon'}); expect(spy).toHaveBeenCalledTimes(1); subscription.unsubscribe(); })); it('should accept the user selection if they press enter on an option while selection is required', waitForAsync(async () => { const input = fixture.nativeElement.querySelector('input'); const {stateCtrl, trigger, states} = fixture.componentInstance; fixture.componentInstance.requireSelection = true; fixture.changeDetectorRef.markForCheck(); stateCtrl.setValue(states[1]); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('California'); expect(stateCtrl.value).toEqual({code: 'CA', name: 'California'}); trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; const spy = jasmine.createSpy('optionSelected spy'); const subscription = trigger.optionSelections.subscribe(spy); dispatchKeyboardEvent(options[5], 'keydown', ENTER); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('Oregon'); expect(stateCtrl.value).toEqual({code: 'OR', name: 'Oregon'}); expect(spy).toHaveBeenCalledTimes(1); subscription.unsubscribe(); })); it('should accept the user selection if autoSelectActiveOption is enabled', waitForAsync(async () => { const input = fixture.nativeElement.querySelector('input'); const {stateCtrl, trigger, states} = fixture.componentInstance; fixture.componentInstance.requireSelection = true; trigger.autocomplete.autoSelectActiveOption = true; fixture.changeDetectorRef.markForCheck(); stateCtrl.setValue(states[1]); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('California'); expect(stateCtrl.value).toEqual({code: 'CA', name: 'California'}); trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); for (let i = 0; i < 5; i++) { dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); } dispatchFakeEvent(document, 'click'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('New York'); expect(stateCtrl.value).toEqual({code: 'NY', name: 'New York'}); })); it('should clear the value if selection is required and the user interacted with the panel without selecting anything', waitForAsync(async () => { const input = fixture.nativeElement.querySelector('input'); const {stateCtrl, trigger, states} = fixture.componentInstance; fixture.componentInstance.requireSelection = true; fixture.changeDetectorRef.markForCheck(); stateCtrl.setValue(states[1]); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('California'); expect(stateCtrl.value).toEqual({code: 'CA', name: 'California'}); trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const spy = jasmine.createSpy('optionSelected spy'); const subscription = trigger.optionSelections.subscribe(spy); input.value = 'Cali'; dispatchKeyboardEvent(input, 'input'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('Cali'); expect(stateCtrl.value).toEqual({code: 'CA', name: 'California'}); expect(spy).not.toHaveBeenCalled(); dispatchFakeEvent(document, 'click'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe(''); expect(stateCtrl.value).toBe(null); expect(spy).not.toHaveBeenCalled(); subscription.unsubscribe(); })); it('should preserve the value if a selection is required, but the user opened and closed the panel without interacting with it', waitForAsync(async () => { const input = fixture.nativeElement.querySelector('input'); const {stateCtrl, trigger, states} = fixture.componentInstance; fixture.componentInstance.requireSelection = true; fixture.changeDetectorRef.markForCheck(); stateCtrl.setValue(states[1]); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('California'); expect(stateCtrl.value).toEqual({code: 'CA', name: 'California'}); trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const spy = jasmine.createSpy('optionSelected spy'); const subscription = trigger.optionSelections.subscribe(spy); dispatchFakeEvent(document, 'click'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('California'); expect(stateCtrl.value).toEqual({code: 'CA', name: 'California'}); expect(spy).not.toHaveBeenCalled(); subscription.unsubscribe(); }));
{ "end_byte": 106099, "start_byte": 96801, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_106105_114154
it('should preserve the value if a selection is required, and there are no options', waitForAsync(async () => { const input = fixture.nativeElement.querySelector('input'); const {stateCtrl, trigger, states} = fixture.componentInstance; fixture.componentInstance.requireSelection = true; fixture.changeDetectorRef.markForCheck(); stateCtrl.setValue(states[1]); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('California'); expect(stateCtrl.value).toEqual({code: 'CA', name: 'California'}); fixture.componentInstance.states = fixture.componentInstance.filteredStates = []; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const spy = jasmine.createSpy('optionSelected spy'); const subscription = trigger.optionSelections.subscribe(spy); dispatchFakeEvent(document, 'click'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('California'); expect(stateCtrl.value).toEqual({code: 'CA', name: 'California'}); expect(spy).not.toHaveBeenCalled(); subscription.unsubscribe(); })); it('should clear the value if requireSelection is enabled and the user edits the input before clicking away', waitForAsync(async () => { const input = fixture.nativeElement.querySelector('input'); const {stateCtrl, trigger} = fixture.componentInstance; fixture.componentInstance.requireSelection = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); // Simulate opening the input and clicking the first option. trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); (overlayContainerElement.querySelector('mat-option') as HTMLElement).click(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(trigger.panelOpen).toBe(false); expect(input.value).toBe('Alabama'); expect(stateCtrl.value).toEqual({code: 'AL', name: 'Alabama'}); // Simulate pressing backspace while focus is still on the input. dispatchFakeEvent(input, 'keydown'); input.value = 'Alabam'; fixture.detectChanges(); dispatchFakeEvent(input, 'input'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(trigger.panelOpen).toBe(true); expect(input.value).toBe('Alabam'); expect(stateCtrl.value).toEqual({code: 'AL', name: 'Alabama'}); // Simulate clicking away. input.blur(); dispatchFakeEvent(document, 'click'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(trigger.panelOpen).toBe(false); expect(input.value).toBe(''); expect(stateCtrl.value).toBe(null); })); }); describe('panel closing', () => { let fixture: ComponentFixture<SimpleAutocomplete>; let input: HTMLInputElement; let trigger: MatAutocompleteTrigger; let closingActionSpy: jasmine.Spy; let closingActionsSub: Subscription; beforeEach(fakeAsync(() => { fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); trigger = fixture.componentInstance.trigger; closingActionSpy = jasmine.createSpy('closing action listener'); closingActionsSub = trigger.panelClosingActions.subscribe(closingActionSpy); input = fixture.debugElement.query(By.css('input'))!.nativeElement; fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); flush(); })); afterEach(() => { closingActionsSub.unsubscribe(); }); it('should emit panel close event when clicking away', () => { expect(closingActionSpy).not.toHaveBeenCalled(); dispatchFakeEvent(document, 'click'); expect(closingActionSpy).toHaveBeenCalledWith(null); }); it('should emit panel close event when tabbing out', () => { const tabEvent = createKeyboardEvent('keydown', TAB); input.focus(); expect(closingActionSpy).not.toHaveBeenCalled(); trigger._handleKeydown(tabEvent); expect(closingActionSpy).toHaveBeenCalledWith(null); }); it('should not emit when tabbing away from a closed panel', waitForAsync(async () => { const tabEvent = createKeyboardEvent('keydown', TAB); input.focus(); await new Promise(r => setTimeout(r)); trigger._handleKeydown(tabEvent); // Ensure that it emitted once while the panel was open. expect(closingActionSpy).toHaveBeenCalledTimes(1); trigger._handleKeydown(tabEvent); // Ensure that it didn't emit again when tabbing out again. expect(closingActionSpy).toHaveBeenCalledTimes(1); })); it('should emit panel close event when selecting an option', () => { const option = overlayContainerElement.querySelector('mat-option') as HTMLElement; expect(closingActionSpy).not.toHaveBeenCalled(); option.click(); expect(closingActionSpy).toHaveBeenCalledWith(jasmine.any(MatOptionSelectionChange)); }); it('should close the panel when pressing escape', () => { expect(closingActionSpy).not.toHaveBeenCalled(); dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); expect(closingActionSpy).toHaveBeenCalledWith(null); }); // TODO(mmalerba): This test previously only passed because it wasn't properly flushed. // We should figure out if this is indeed the desired behavior, and if so fix the // implementation. // tslint:disable-next-line:ban xit('should not prevent escape key propagation when there are no options', waitForAsync(async () => { fixture.componentInstance.filteredStates = fixture.componentInstance.states = []; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const event = createKeyboardEvent('keydown', ESCAPE); spyOn(event, 'stopPropagation').and.callThrough(); dispatchEvent(document.body, event); fixture.detectChanges(); expect(event.stopPropagation).not.toHaveBeenCalled(); })); }); describe('without matInput', () => { let fixture: ComponentFixture<AutocompleteWithNativeInput>; beforeEach(() => { fixture = createComponent(AutocompleteWithNativeInput); fixture.detectChanges(); }); it('should not throw when clicking outside', fakeAsync(() => { dispatchFakeEvent(fixture.debugElement.query(By.css('input'))!.nativeElement, 'focus'); fixture.detectChanges(); flush(); expect(() => dispatchFakeEvent(document, 'click')).not.toThrow(); })); }); describe('with panel classes in the default options', () => { it('should apply them if provided as string', () => { const fixture = createComponent(SimpleAutocomplete, [ {provide: MAT_AUTOCOMPLETE_DEFAULT_OPTIONS, useValue: {overlayPanelClass: 'default1'}}, ]); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panelClassList = overlayContainerElement.querySelector('.cdk-overlay-pane')!.classList; expect(panelClassList).toContain('default1'); }); it('should apply them if provided as array', () => { const fixture = createComponent(SimpleAutocomplete, [ { provide: MAT_AUTOCOMPLETE_DEFAULT_OPTIONS, useValue: {overlayPanelClass: ['default1', 'default2']}, }, ]); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panelClassList = overlayContainerElement.querySelector('.cdk-overlay-pane')!.classList; expect(panelClassList).toContain('default1'); expect(panelClassList).toContain('default2'); }); });
{ "end_byte": 114154, "start_byte": 106105, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_114158_121213
describe('misc', () => { it('should allow basic use without any forms directives', () => { expect(() => { const fixture = createComponent(AutocompleteWithoutForms); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; typeInElement(input, 'd'); fixture.detectChanges(); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; expect(options.length).toBe(1); }).not.toThrowError(); }); it('should display an empty input when the value is undefined with ngModel', () => { const fixture = createComponent(AutocompleteWithNgModel); fixture.detectChanges(); expect(fixture.debugElement.query(By.css('input'))!.nativeElement.value).toBe(''); }); it('should display the number when the selected option is the number zero', fakeAsync(() => { const fixture = createComponent(AutocompleteWithNumbers); fixture.componentInstance.selectedNumber = 0; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); tick(); expect(fixture.debugElement.query(By.css('input'))!.nativeElement.value).toBe('0'); })); it('should work when input is wrapped in ngIf', () => { const fixture = createComponent(NgIfAutocomplete); fixture.detectChanges(); dispatchFakeEvent(fixture.debugElement.query(By.css('input'))!.nativeElement, 'focusin'); fixture.detectChanges(); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected panel state to read open when input is focused.`) .toBe(true); expect(overlayContainerElement.textContent) .withContext(`Expected panel to display when input is focused.`) .toContain('One'); expect(overlayContainerElement.textContent) .withContext(`Expected panel to display when input is focused.`) .toContain('Two'); }); it('should filter properly with ngIf after setting the active item', () => { const fixture = createComponent(NgIfAutocomplete); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const DOWN_ARROW_EVENT = createKeyboardEvent('keydown', DOWN_ARROW); fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; typeInElement(input, 'o'); fixture.detectChanges(); expect(fixture.componentInstance.matOptions.length).toBe(2); }); it('should throw if the user attempts to open the panel too early', () => { const fixture = createComponent(AutocompleteWithoutPanel); fixture.detectChanges(); expect(() => { fixture.componentInstance.trigger.openPanel(); }).toThrow(getMatAutocompleteMissingPanelError()); }); it('should not throw on init, even if the panel is not defined', fakeAsync(() => { expect(() => { const fixture = createComponent(AutocompleteWithoutPanel); fixture.componentInstance.control.setValue('Something'); fixture.detectChanges(); tick(); }).not.toThrow(); })); it('should transfer the mat-autocomplete classes to the panel element', fakeAsync(() => { const fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); tick(); fixture.detectChanges(); const autocomplete = fixture.debugElement.nativeElement.querySelector('mat-autocomplete'); const panel = overlayContainerElement.querySelector('.mat-mdc-autocomplete-panel')!; expect(autocomplete.classList).not.toContain('class-one'); expect(autocomplete.classList).not.toContain('class-two'); expect(panel.classList).toContain('class-one'); expect(panel.classList).toContain('class-two'); })); it('should remove old classes when the panel class changes', fakeAsync(() => { const fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); tick(); fixture.detectChanges(); const classList = overlayContainerElement.querySelector( '.mat-mdc-autocomplete-panel', )!.classList; expect(classList).toContain('mat-mdc-autocomplete-visible'); expect(classList).toContain('class-one'); expect(classList).toContain('class-two'); fixture.componentInstance.panelClass = 'class-three class-four'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(classList).not.toContain('class-one'); expect(classList).not.toContain('class-two'); expect(classList).toContain('mat-mdc-autocomplete-visible'); expect(classList).toContain('class-three'); expect(classList).toContain('class-four'); })); it('should reset correctly when closed programmatically', waitForAsync(async () => { const scrolledSubject = new Subject(); const fixture = createComponent(SimpleAutocomplete, [ { provide: ScrollDispatcher, useValue: {scrolled: () => scrolledSubject}, }, { provide: MAT_AUTOCOMPLETE_SCROLL_STRATEGY, useFactory: (overlay: Overlay) => () => overlay.scrollStrategies.close(), deps: [Overlay], }, ]); fixture.detectChanges(); const trigger = fixture.componentInstance.trigger; trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(trigger.panelOpen).withContext('Expected panel to be open.').toBe(true); scrolledSubject.next(); fixture.detectChanges(); expect(trigger.panelOpen).withContext('Expected panel to be closed.').toBe(false); })); it('should handle autocomplete being attached to number inputs', () => { const fixture = createComponent(AutocompleteWithNumberInputAndNgModel); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; typeInElement(input, '1337'); fixture.detectChanges(); expect(fixture.componentInstance.selectedValue).toBe(1337); }); it('should not focus the option when DOWN key is pressed', () => { const fixture = createComponent(SimpleAutocomplete); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; fixture.detectChanges(); const spy = spyOn(console, 'error'); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); // Note: for some reason the error here gets logged using console.error, rather than being // thrown, hence why we use a spy to assert against it, rather than `.not.toThrow`. expect(spy).not.toHaveBeenCalled(); }); });
{ "end_byte": 121213, "start_byte": 114158, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_121217_131249
describe('automatically selecting the active option', () => { let fixture: ComponentFixture<SimpleAutocomplete>; beforeEach(() => { fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); fixture.componentInstance.trigger.autocomplete.autoSelectActiveOption = true; fixture.changeDetectorRef.markForCheck(); }); it( 'should update the input value as the user is navigating, without changing the model ' + 'value or closing the panel', waitForAsync(async () => { const {trigger, stateCtrl, closedSpy} = fixture.componentInstance; const input: HTMLInputElement = fixture.nativeElement.querySelector('input'); trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(stateCtrl.value).toBeFalsy(); expect(input.value).toBeFalsy(); expect(trigger.panelOpen).toBe(true); expect(closedSpy).not.toHaveBeenCalled(); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(stateCtrl.value).toBeFalsy(); expect(input.value).toBe('Alabama'); expect(trigger.panelOpen).toBe(true); expect(closedSpy).not.toHaveBeenCalled(); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(stateCtrl.value).toBeFalsy(); expect(input.value).toBe('California'); expect(trigger.panelOpen).toBe(true); expect(closedSpy).not.toHaveBeenCalled(); }), ); it('should revert back to the last typed value if the user presses escape', waitForAsync(async () => { const {trigger, stateCtrl, closedSpy} = fixture.componentInstance; const input: HTMLInputElement = fixture.nativeElement.querySelector('input'); trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); typeInElement(input, 'al'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(stateCtrl.value).toBe('al'); expect(input.value).toBe('al'); expect(trigger.panelOpen).toBe(true); expect(closedSpy).not.toHaveBeenCalled(); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(stateCtrl.value).toBe('al'); expect(input.value).toBe('Alabama'); expect(trigger.panelOpen).toBe(true); expect(closedSpy).not.toHaveBeenCalled(); dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); fixture.detectChanges(); expect(stateCtrl.value).toBe('al'); expect(input.value).toBe('al'); expect(trigger.panelOpen).toBe(false); expect(closedSpy).toHaveBeenCalledTimes(1); })); it('should emit a closed event if no option is displayed', fakeAsync(() => { const {openedSpy, closedSpy} = fixture.componentInstance; const input: HTMLInputElement = fixture.nativeElement.querySelector('input'); typeInElement(input, 'Alabama'); // Valid option fixture.detectChanges(); tick(); expect(openedSpy).toHaveBeenCalledTimes(1); expect(closedSpy).toHaveBeenCalledTimes(0); typeInElement(input, '_x'); // Invalidate option to 'Alabama_x' fixture.detectChanges(); tick(); expect(openedSpy).toHaveBeenCalledTimes(1); expect(closedSpy).toHaveBeenCalledTimes(1); })); it( 'should clear the input if the user presses escape while there was a pending ' + 'auto selection and there is no previous value', waitForAsync(async () => { const {trigger, stateCtrl} = fixture.componentInstance; const input: HTMLInputElement = fixture.nativeElement.querySelector('input'); trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(stateCtrl.value).toBeFalsy(); expect(input.value).toBeFalsy(); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(stateCtrl.value).toBeFalsy(); expect(input.value).toBe('Alabama'); dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); fixture.detectChanges(); expect(stateCtrl.value).toBeFalsy(); expect(input.value).toBeFalsy(); }), ); it('should propagate the auto-selected value if the user clicks away', waitForAsync(async () => { const {trigger, stateCtrl} = fixture.componentInstance; const input: HTMLInputElement = fixture.nativeElement.querySelector('input'); trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(stateCtrl.value).toBeFalsy(); expect(input.value).toBeFalsy(); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(stateCtrl.value).toBeFalsy(); expect(input.value).toBe('Alabama'); dispatchFakeEvent(document, 'click'); fixture.detectChanges(); expect(stateCtrl.value).toEqual({code: 'AL', name: 'Alabama'}); expect(input.value).toBe('Alabama'); })); it('should propagate the auto-selected value if the user tabs away', waitForAsync(async () => { const {trigger, stateCtrl} = fixture.componentInstance; const input: HTMLInputElement = fixture.nativeElement.querySelector('input'); trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(stateCtrl.value).toBeFalsy(); expect(input.value).toBeFalsy(); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(stateCtrl.value).toBeFalsy(); expect(input.value).toBe('Alabama'); dispatchKeyboardEvent(input, 'keydown', TAB); fixture.detectChanges(); expect(stateCtrl.value).toEqual({code: 'AL', name: 'Alabama'}); expect(input.value).toBe('Alabama'); })); it('should propagate the auto-selected value if the user presses enter on it', waitForAsync(async () => { const {trigger, stateCtrl} = fixture.componentInstance; const input: HTMLInputElement = fixture.nativeElement.querySelector('input'); trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(stateCtrl.value).toBeFalsy(); expect(input.value).toBeFalsy(); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(stateCtrl.value).toBeFalsy(); expect(input.value).toBe('Alabama'); dispatchKeyboardEvent(input, 'keydown', ENTER); fixture.detectChanges(); expect(stateCtrl.value).toEqual({code: 'AL', name: 'Alabama'}); expect(input.value).toBe('Alabama'); })); it('should allow the user to click on an option different from the auto-selected one', waitForAsync(async () => { const {trigger, stateCtrl} = fixture.componentInstance; const input: HTMLInputElement = fixture.nativeElement.querySelector('input'); trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(stateCtrl.value).toBeFalsy(); expect(input.value).toBeFalsy(); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(stateCtrl.value).toBeFalsy(); expect(input.value).toBe('Alabama'); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; options[2].click(); fixture.detectChanges(); expect(stateCtrl.value).toEqual({code: 'FL', name: 'Florida'}); expect(input.value).toBe('Florida'); })); }); it('should have correct width when opened', () => { const widthFixture = createComponent(SimpleAutocomplete); widthFixture.componentInstance.width = 300; widthFixture.changeDetectorRef.markForCheck(); widthFixture.detectChanges(); widthFixture.componentInstance.trigger.openPanel(); widthFixture.detectChanges(); const overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; // Firefox, Edge return a decimal value for width, so we need to parse and round it to verify expect(Math.ceil(parseFloat(overlayPane.style.width as string))).toBe(300); widthFixture.componentInstance.trigger.closePanel(); widthFixture.detectChanges(); widthFixture.componentInstance.width = 500; widthFixture.changeDetectorRef.markForCheck(); widthFixture.detectChanges(); widthFixture.componentInstance.trigger.openPanel(); widthFixture.detectChanges(); // Firefox, Edge return a decimal value for width, so we need to parse and round it to verify expect(Math.ceil(parseFloat(overlayPane.style.width as string))).toBe(500); }); it('should update the width while the panel is open', () => { const widthFixture = createComponent(SimpleAutocomplete); widthFixture.componentInstance.width = 300; widthFixture.changeDetectorRef.markForCheck(); widthFixture.detectChanges(); widthFixture.componentInstance.trigger.openPanel(); widthFixture.detectChanges(); const overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; const input = widthFixture.debugElement.query(By.css('input'))!.nativeElement; expect(Math.ceil(parseFloat(overlayPane.style.width as string))).toBe(300); widthFixture.componentInstance.width = 500; widthFixture.changeDetectorRef.markForCheck(); widthFixture.detectChanges(); input.focus(); dispatchFakeEvent(input, 'input'); widthFixture.detectChanges(); expect(Math.ceil(parseFloat(overlayPane.style.width as string))).toBe(500); });
{ "end_byte": 131249, "start_byte": 121217, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_131253_141040
it('should not reopen a closed autocomplete when returning to a blurred tab', () => { const fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); const trigger = fixture.componentInstance.trigger; const input = fixture.debugElement.query(By.css('input'))!.nativeElement; input.focus(); fixture.detectChanges(); expect(trigger.panelOpen).withContext('Expected panel to be open.').toBe(true); trigger.closePanel(); fixture.detectChanges(); expect(trigger.panelOpen).withContext('Expected panel to be closed.').toBe(false); // Simulate the user going to a different tab. dispatchFakeEvent(window, 'blur'); input.blur(); fixture.detectChanges(); // Simulate the user coming back. dispatchFakeEvent(window, 'focus'); input.focus(); fixture.detectChanges(); expect(trigger.panelOpen).withContext('Expected panel to remain closed.').toBe(false); }); it('should update the panel width if the window is resized', fakeAsync(() => { const widthFixture = createComponent(SimpleAutocomplete); widthFixture.componentInstance.width = 300; widthFixture.changeDetectorRef.markForCheck(); widthFixture.detectChanges(); widthFixture.componentInstance.trigger.openPanel(); widthFixture.detectChanges(); const overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(Math.ceil(parseFloat(overlayPane.style.width as string))).toBe(300); widthFixture.componentInstance.width = 400; widthFixture.changeDetectorRef.markForCheck(); widthFixture.detectChanges(); dispatchFakeEvent(window, 'resize'); tick(20); expect(Math.ceil(parseFloat(overlayPane.style.width as string))).toBe(400); })); it('should have panel width match host width by default', () => { const widthFixture = createComponent(SimpleAutocomplete); widthFixture.componentInstance.width = 300; widthFixture.changeDetectorRef.markForCheck(); widthFixture.detectChanges(); widthFixture.componentInstance.trigger.openPanel(); widthFixture.detectChanges(); const overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(Math.ceil(parseFloat(overlayPane.style.width as string))).toBe(300); }); it('should have panel width set to string value', () => { const widthFixture = createComponent(SimpleAutocomplete); widthFixture.componentInstance.width = 300; widthFixture.changeDetectorRef.markForCheck(); widthFixture.detectChanges(); widthFixture.componentInstance.trigger.autocomplete.panelWidth = 'auto'; widthFixture.changeDetectorRef.markForCheck(); widthFixture.componentInstance.trigger.openPanel(); widthFixture.detectChanges(); const overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.width).toBe('auto'); }); it('should have panel width set to number value', () => { const widthFixture = createComponent(SimpleAutocomplete); widthFixture.componentInstance.width = 300; widthFixture.changeDetectorRef.markForCheck(); widthFixture.detectChanges(); widthFixture.componentInstance.trigger.autocomplete.panelWidth = 400; widthFixture.changeDetectorRef.markForCheck(); widthFixture.componentInstance.trigger.openPanel(); widthFixture.detectChanges(); const overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(Math.ceil(parseFloat(overlayPane.style.width as string))).toBe(400); }); it('should show the panel when the options are initialized later within a component with OnPush change detection', fakeAsync(() => { let fixture = createComponent(AutocompleteWithOnPushDelay); fixture.detectChanges(); flush(); dispatchFakeEvent(fixture.debugElement.query(By.css('input'))!.nativeElement, 'focusin'); tick(1000); fixture.detectChanges(); tick(); Promise.resolve().then(() => { let panel = overlayContainerElement.querySelector( '.mat-mdc-autocomplete-panel', ) as HTMLElement; let visibleClass = 'mat-mdc-autocomplete-visible'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(panel.classList).withContext(`Expected panel to be visible.`).toContain(visibleClass); }); })); it('should emit an event when an option is selected', waitForAsync(async () => { let fixture = createComponent(AutocompleteWithSelectEvent); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); let options = overlayContainerElement.querySelectorAll('mat-option') as NodeListOf<HTMLElement>; let spy = fixture.componentInstance.optionSelected; options[1].click(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(spy).toHaveBeenCalledTimes(1); let event = spy.calls.mostRecent().args[0] as MatAutocompleteSelectedEvent; expect(event.source).toBe(fixture.componentInstance.autocomplete); expect(event.option.value).toBe('Washington'); })); it('should refocus the input after the selection event is emitted', waitForAsync(async () => { const events: string[] = []; const fixture = createComponent(AutocompleteWithSelectEvent); fixture.detectChanges(); const input = fixture.nativeElement.querySelector('input'); fixture.componentInstance.trigger.openPanel(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; spyOn(input, 'focus').and.callFake(() => events.push('focus')); fixture.componentInstance.optionSelected.and.callFake(() => events.push('select')); options[1].click(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(events).toEqual(['select', 'focus']); })); it('should emit an event when a newly-added option is selected', fakeAsync(() => { let fixture = createComponent(AutocompleteWithSelectEvent); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); tick(); fixture.detectChanges(); fixture.componentInstance.states.push('Puerto Rico'); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); tick(); fixture.detectChanges(); let options = overlayContainerElement.querySelectorAll('mat-option') as NodeListOf<HTMLElement>; let spy = fixture.componentInstance.optionSelected; options[3].click(); tick(); fixture.detectChanges(); expect(spy).toHaveBeenCalledTimes(1); let event = spy.calls.mostRecent().args[0] as MatAutocompleteSelectedEvent; expect(event.source).toBe(fixture.componentInstance.autocomplete); expect(event.option.value).toBe('Puerto Rico'); })); it('should emit an event when an option is activated', waitForAsync(async () => { const fixture = createComponent(AutocompleteWithActivatedEvent); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); const input = fixture.nativeElement.querySelector('input'); const spy = fixture.componentInstance.optionActivated; const autocomplete = fixture.componentInstance.autocomplete; const options = fixture.componentInstance.options.toArray(); expect(spy).not.toHaveBeenCalled(); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(spy.calls.mostRecent().args[0]).toEqual({source: autocomplete, option: options[0]}); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(spy.calls.mostRecent().args[0]).toEqual({source: autocomplete, option: options[1]}); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(spy.calls.mostRecent().args[0]).toEqual({source: autocomplete, option: options[2]}); })); it('should not emit the optionActivated event when the active option is reset', waitForAsync(async () => { const fixture = createComponent(AutocompleteWithActivatedEvent); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); const input = fixture.nativeElement.querySelector('input'); const spy = fixture.componentInstance.optionActivated; expect(spy).not.toHaveBeenCalled(); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(spy).toHaveBeenCalledTimes(1); dispatchKeyboardEvent(input, 'keydown', ESCAPE); fixture.detectChanges(); expect(spy).toHaveBeenCalledTimes(1); })); it('should be able to set a custom panel connection element', waitForAsync(async () => { const fixture = createComponent(AutocompleteWithDifferentOrigin); fixture.detectChanges(); fixture.componentInstance.connectedTo = fixture.componentInstance.alternateOrigin; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const overlayRect = overlayContainerElement .querySelector('.cdk-overlay-pane')! .getBoundingClientRect(); const originRect = fixture.nativeElement.querySelector('.origin').getBoundingClientRect(); expect(Math.floor(overlayRect.top)) .withContext('Expected autocomplete panel to align with the bottom of the new origin.') .toBe(Math.floor(originRect.bottom)); }));
{ "end_byte": 141040, "start_byte": 131253, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_141044_150353
it('should be able to change the origin after the panel has been opened', waitForAsync(async () => { const fixture = createComponent(AutocompleteWithDifferentOrigin); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.componentInstance.trigger.closePanel(); fixture.detectChanges(); fixture.componentInstance.connectedTo = fixture.componentInstance.alternateOrigin; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const overlayRect = overlayContainerElement .querySelector('.cdk-overlay-pane')! .getBoundingClientRect(); const originRect = fixture.nativeElement.querySelector('.origin').getBoundingClientRect(); expect(Math.floor(overlayRect.top)) .withContext('Expected autocomplete panel to align with the bottom of the new origin.') .toBe(Math.floor(originRect.bottom)); })); it('should be able to re-type the same value when it is reset while open', fakeAsync(() => { const fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; const formControl = fixture.componentInstance.stateCtrl; typeInElement(input, 'Cal'); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(formControl.value) .withContext('Expected initial value to be propagated to model') .toBe('Cal'); formControl.setValue(''); fixture.detectChanges(); expect(input.value).withContext('Expected input value to reset when model is reset').toBe(''); typeInElement(input, 'Cal'); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(formControl.value) .withContext('Expected new value to be propagated to model') .toBe('Cal'); })); it('should not close when clicking inside alternate origin', waitForAsync(async () => { const fixture = createComponent(AutocompleteWithDifferentOrigin); fixture.detectChanges(); fixture.componentInstance.connectedTo = fixture.componentInstance.alternateOrigin; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.trigger.panelOpen).toBe(true); const origin = fixture.nativeElement.querySelector('.origin'); origin.click(); fixture.detectChanges(); expect(fixture.componentInstance.trigger.panelOpen).toBe(true); })); describe('a11y', () => { it('should display checkmark for selection by default', () => { const fixture = createComponent(AutocompleteWithNgModel); fixture.componentInstance.selectedState = 'New York'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); dispatchFakeEvent(document.querySelector('mat-option')!, 'click'); fixture.detectChanges(); const selectedOption = document.querySelector('mat-option[aria-selected="true"]'); expect(selectedOption).withContext('Expected an option to be selected.').not.toBeNull(); expect(selectedOption?.querySelector('.mat-pseudo-checkbox.mat-pseudo-checkbox-minimal')) .withContext( 'Expected selection option to have a pseudo-checkbox with "minimal" appearance.', ) .toBeTruthy(); }); }); describe('with token to hide single selection indicator', () => { it('should not display checkmark', () => { const defaultOptions: MatAutocompleteDefaultOptions = { hideSingleSelectionIndicator: true, }; const fixture = createComponent(AutocompleteWithNgModel, [ {provide: MAT_AUTOCOMPLETE_DEFAULT_OPTIONS, useValue: defaultOptions}, ]); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); dispatchFakeEvent(document.querySelector('mat-option')!, 'click'); fixture.detectChanges(); const selectedOption = document.querySelector('mat-option[aria-selected="true"]'); expect(selectedOption).withContext('Expected an option to be selected.').not.toBeNull(); expect(document.querySelectorAll('.mat-pseudo-checkbox').length).toBe(0); }); }); describe('when used inside a modal', () => { let fixture: ComponentFixture<AutocompleteInsideAModal>; beforeEach(() => { fixture = createComponent(AutocompleteInsideAModal); fixture.detectChanges(); }); it('should add the id of the autocomplete panel to the aria-owns of the modal', () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panelId = fixture.componentInstance.autocomplete.id; const modalElement = fixture.componentInstance.modal.nativeElement; expect(modalElement.getAttribute('aria-owns')?.split(' ')) .withContext('expecting modal to own the autocommplete panel') .toContain(panelId); }); it('should remove the aria-owns attribute of the modal when the autocomplete panel closes', () => { fixture.componentInstance.trigger.openPanel(); fixture.componentInstance.trigger.closePanel(); fixture.detectChanges(); const modalElement = fixture.componentInstance.modal.nativeElement; expect(modalElement.getAttribute('aria-owns')).toBeFalsy(); }); it('should readd the aria-owns attribute of the modal when the autocomplete panel opens again', () => { fixture.componentInstance.trigger.openPanel(); fixture.componentInstance.trigger.closePanel(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panelId = fixture.componentInstance.autocomplete.id; const modalElement = fixture.componentInstance.modal.nativeElement; expect(modalElement.getAttribute('aria-owns')?.split(' ')) .withContext('expecting modal to own the autocommplete panel') .toContain(panelId); }); }); }); const SIMPLE_AUTOCOMPLETE_TEMPLATE = ` <mat-form-field [floatLabel]="floatLabel" [style.width.px]="width" [color]="theme"> @if (hasLabel) { <mat-label>State</mat-label> } <input matInput placeholder="State" [matAutocomplete]="auto" [matAutocompletePosition]="position" [matAutocompleteDisabled]="autocompleteDisabled" [formControl]="stateCtrl"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete" [class]="panelClass" [displayWith]="displayFn" [disableRipple]="disableRipple" [requireSelection]="requireSelection" [aria-label]="ariaLabel" [aria-labelledby]="ariaLabelledby" (opened)="openedSpy()" (closed)="closedSpy()"> @for (state of filteredStates; track state) { <mat-option [value]="state" [style.height.px]="state.height" [disabled]="state.disabled"> <span>{{ state.code }}: {{ state.name }}</span> </mat-option> } </mat-autocomplete> `; @Component({template: SIMPLE_AUTOCOMPLETE_TEMPLATE, standalone: false}) class SimpleAutocomplete implements OnDestroy { stateCtrl = new FormControl<{name: string; code: string} | string | null>(null); filteredStates: any[]; valueSub: Subscription; floatLabel = 'auto'; position = 'auto'; width: number; disableRipple = false; autocompleteDisabled = false; hasLabel = true; requireSelection = false; ariaLabel: string; ariaLabelledby: string; panelClass = 'class-one class-two'; theme: string; openedSpy = jasmine.createSpy('autocomplete opened spy'); closedSpy = jasmine.createSpy('autocomplete closed spy'); @ViewChild(MatAutocompleteTrigger, {static: true}) trigger: MatAutocompleteTrigger; @ViewChild(MatAutocomplete) panel: MatAutocomplete; @ViewChild(MatFormField) formField: MatFormField; @ViewChildren(MatOption) options: QueryList<MatOption>; states: {code: string; name: string; height?: number; disabled?: boolean}[] = [ {code: 'AL', name: 'Alabama'}, {code: 'CA', name: 'California'}, {code: 'FL', name: 'Florida'}, {code: 'KS', name: 'Kansas'}, {code: 'MA', name: 'Massachusetts'}, {code: 'NY', name: 'New York'}, {code: 'OR', name: 'Oregon'}, {code: 'PA', name: 'Pennsylvania'}, {code: 'TN', name: 'Tennessee'}, {code: 'VA', name: 'Virginia'}, {code: 'WY', name: 'Wyoming'}, ]; constructor() { this.filteredStates = this.states; this.valueSub = this.stateCtrl.valueChanges.subscribe(val => { this.filteredStates = val ? this.states.filter(s => s.name.match(new RegExp(val as string, 'gi'))) : this.states; }); } displayFn(value: any): string { return value ? value.name : value; } ngOnDestroy() { this.valueSub.unsubscribe(); } } @Component({ template: SIMPLE_AUTOCOMPLETE_TEMPLATE, encapsulation: ViewEncapsulation.ShadowDom, standalone: false, }) class SimpleAutocompleteShadowDom extends SimpleAutocomplete {}
{ "end_byte": 150353, "start_byte": 141044, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_150355_158462
@Component({ template: ` @if (isVisible) { <mat-form-field> <input matInput placeholder="Choose" [matAutocomplete]="auto" [formControl]="optionCtrl"> </mat-form-field> } <mat-autocomplete #auto="matAutocomplete"> @for (option of filteredOptions | async; track option) { <mat-option [value]="option"> {{option}} </mat-option> } </mat-autocomplete> `, standalone: false, }) class NgIfAutocomplete { optionCtrl = new FormControl(''); filteredOptions: Observable<any>; isVisible = true; options = ['One', 'Two', 'Three']; @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; @ViewChildren(MatOption) matOptions: QueryList<MatOption>; constructor() { this.filteredOptions = this.optionCtrl.valueChanges.pipe( startWith(null), map(val => { return val ? this.options.filter(option => new RegExp(val, 'gi').test(option)) : this.options.slice(); }), ); } } @Component({ template: ` <mat-form-field> <input matInput placeholder="State" [matAutocomplete]="auto" (input)="onInput($event.target?.value)"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> @for (state of filteredStates; track state) { <mat-option [value]="state"> <span> {{ state }} </span> </mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithoutForms { filteredStates: any[]; states = ['Alabama', 'California', 'Florida']; constructor() { this.filteredStates = this.states.slice(); } onInput(value: any) { this.filteredStates = this.states.filter(s => new RegExp(value, 'gi').test(s)); } } @Component({ template: ` <mat-form-field> <input matInput placeholder="State" [matAutocomplete]="auto" [(ngModel)]="selectedState" (ngModelChange)="onInput($event)"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> @for (state of filteredStates; track state) { <mat-option [value]="state"> <span>{{ state }}</span> </mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithNgModel { filteredStates: any[]; selectedState: string; states = ['New York', 'Washington', 'Oregon']; @ViewChild(MatAutocompleteTrigger, {static: true}) trigger: MatAutocompleteTrigger; constructor() { this.filteredStates = this.states.slice(); } onInput(value: any) { this.filteredStates = this.states.filter(s => new RegExp(value, 'gi').test(s)); } } @Component({ template: ` <mat-form-field> <input matInput placeholder="Number" [matAutocomplete]="auto" [(ngModel)]="selectedNumber"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> @for (number of numbers; track number) { <mat-option [value]="number"> <span>{{ number }}</span> </mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithNumbers { selectedNumber: number; numbers = [0, 1, 2]; } @Component({ changeDetection: ChangeDetectionStrategy.OnPush, template: ` <mat-form-field> <input type="text" matInput [matAutocomplete]="auto"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> @for (option of options; track option) { <mat-option [value]="option">{{ option }}</mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithOnPushDelay implements OnInit { @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; options: string[]; ngOnInit() { setTimeout(() => { this.options = ['One']; }, 1000); } } @Component({ template: ` <input placeholder="Choose" [matAutocomplete]="auto" [formControl]="optionCtrl"> <mat-autocomplete #auto="matAutocomplete"> @for (option of filteredOptions | async; track option) { <mat-option [value]="option">{{option}}</mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithNativeInput { optionCtrl = new FormControl(''); filteredOptions: Observable<any>; options = ['En', 'To', 'Tre', 'Fire', 'Fem']; @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; @ViewChildren(MatOption) matOptions: QueryList<MatOption>; constructor() { this.filteredOptions = this.optionCtrl.valueChanges.pipe( startWith(null), map(val => { return val ? this.options.filter(option => new RegExp(val, 'gi').test(option)) : this.options.slice(); }), ); } } @Component({ template: `<input placeholder="Choose" [matAutocomplete]="auto" [formControl]="control">`, standalone: false, }) class AutocompleteWithoutPanel { @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; control = new FormControl(''); } @Component({ template: ` <mat-form-field> <input matInput placeholder="State" [matAutocomplete]="auto" [(ngModel)]="selectedState"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> @for (group of stateGroups; track group) { <mat-optgroup [label]="group.title"> @for (state of group.states; track state) { <mat-option [value]="state"> <span>{{ state }}</span> </mat-option> } </mat-optgroup> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithGroups { @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; selectedState: string; stateGroups = [ { title: 'One', states: ['Alabama', 'California', 'Florida', 'Oregon'], }, { title: 'Two', states: ['Kansas', 'Massachusetts', 'New York', 'Pennsylvania'], }, { title: 'Three', states: ['Tennessee', 'Virginia', 'Wyoming', 'Alaska'], }, ]; } @Component({ template: ` <mat-form-field> <input matInput placeholder="State" [matAutocomplete]="auto" [(ngModel)]="selectedState"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> @if (true) { @for (group of stateGroups; track group) { <mat-optgroup [label]="group.title"> @for (state of group.states; track state) { <mat-option [value]="state"> <span>{{ state }}</span> </mat-option> } </mat-optgroup> } } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithIndirectGroups extends AutocompleteWithGroups {} @Component({ template: ` <mat-form-field> <input matInput placeholder="State" [matAutocomplete]="auto" [(ngModel)]="selectedState"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete" (optionSelected)="optionSelected($event)"> @for (state of states; track state) { <mat-option [value]="state"> <span>{{ state }}</span> </mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithSelectEvent { selectedState: string; states = ['New York', 'Washington', 'Oregon']; optionSelected = jasmine.createSpy('optionSelected callback'); @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; @ViewChild(MatAutocomplete) autocomplete: MatAutocomplete; } @Component({ template: ` <input [formControl]="formControl" [matAutocomplete]="auto"/> <mat-autocomplete #auto="matAutocomplete"></mat-autocomplete> `, standalone: false, }) class PlainAutocompleteInputWithFormControl { formControl = new FormControl(''); } @Component({ template: ` <mat-form-field> <input type="number" matInput [matAutocomplete]="auto" [(ngModel)]="selectedValue"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> @for (value of values; track value) { <mat-option [value]="value">{{value}}</mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithNumberInputAndNgModel { selectedValue: number; values = [1, 2, 3]; }
{ "end_byte": 158462, "start_byte": 150355, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete.spec.ts_158464_161792
@Component({ template: ` <div> <mat-form-field> <input matInput [matAutocomplete]="auto" [matAutocompleteConnectedTo]="connectedTo" [(ngModel)]="selectedValue"> </mat-form-field> </div> <div class="origin" matAutocompleteOrigin #origin="matAutocompleteOrigin" style="margin-top: 50px"> Connection element </div> <mat-autocomplete #auto="matAutocomplete"> @for (value of values; track value) { <mat-option [value]="value">{{value}}</mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithDifferentOrigin { @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; @ViewChild(MatAutocompleteOrigin) alternateOrigin: MatAutocompleteOrigin; selectedValue: string; values = ['one', 'two', 'three']; connectedTo?: MatAutocompleteOrigin; } @Component({ template: ` <input autocomplete="changed" [(ngModel)]="value" [matAutocomplete]="auto"/> <mat-autocomplete #auto="matAutocomplete"></mat-autocomplete> `, standalone: false, }) class AutocompleteWithNativeAutocompleteAttribute { value: string; } @Component({ template: '<input [matAutocomplete]="null" matAutocompleteDisabled>', standalone: false, }) class InputWithoutAutocompleteAndDisabled {} @Component({ template: ` <mat-form-field> <input matInput [matAutocomplete]="auto"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete" (optionActivated)="optionActivated($event)"> @for (state of states; track state) { <mat-option [value]="state">{{ state }}</mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithActivatedEvent { states = ['California', 'West Virginia', 'Florida']; optionActivated = jasmine.createSpy('optionActivated callback'); @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; @ViewChild(MatAutocomplete) autocomplete: MatAutocomplete; @ViewChildren(MatOption) options: QueryList<MatOption>; } @Component({ selector: 'autocomplete-inside-a-modal', template: ` <button cdkOverlayOrigin #trigger="cdkOverlayOrigin">open dialog</button> <ng-template cdkConnectedOverlay [cdkConnectedOverlayOpen]="true" [cdkConnectedOverlayOrigin]="trigger"> <div role="dialog" [attr.aria-modal]="'true'" #modal> <mat-form-field> <mat-label>Food</mat-label> <input matInput [matAutocomplete]="reactiveAuto" [formControl]="formControl"> </mat-form-field> <mat-autocomplete #reactiveAuto="matAutocomplete"> @for (food of foods; track food; let index = $index) { <mat-option [value]="food">{{food.viewValue}}</mat-option> } </mat-autocomplete> </div> </ng-template> `, standalone: false, }) class AutocompleteInsideAModal { foods = [ {value: 'steak-0', viewValue: 'Steak'}, {value: 'pizza-1', viewValue: 'Pizza'}, {value: 'tacos-2', viewValue: 'Tacos'}, ]; formControl = new FormControl(); @ViewChild(MatAutocomplete) autocomplete: MatAutocomplete; @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; @ViewChildren(MatOption) options: QueryList<MatOption>; @ViewChild('modal') modal: ElementRef; }
{ "end_byte": 161792, "start_byte": 158464, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.spec.ts" }
components/src/material/autocomplete/autocomplete-trigger.ts_0_4474
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {addAriaReferencedId, removeAriaReferencedId} from '@angular/cdk/a11y'; import {Directionality} from '@angular/cdk/bidi'; import {DOWN_ARROW, ENTER, ESCAPE, TAB, UP_ARROW, hasModifierKey} from '@angular/cdk/keycodes'; import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout'; import { ConnectedPosition, FlexibleConnectedPositionStrategy, Overlay, OverlayConfig, OverlayRef, PositionStrategy, ScrollStrategy, } from '@angular/cdk/overlay'; import {_getEventTarget} from '@angular/cdk/platform'; import {TemplatePortal} from '@angular/cdk/portal'; import {ViewportRuler} from '@angular/cdk/scrolling'; import {DOCUMENT} from '@angular/common'; import { AfterViewInit, ChangeDetectorRef, Directive, ElementRef, InjectionToken, Injector, Input, NgZone, OnChanges, OnDestroy, SimpleChanges, ViewContainerRef, afterNextRender, booleanAttribute, forwardRef, inject, } from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import { MatOption, MatOptionSelectionChange, _countGroupLabelsBeforeOption, _getOptionScrollPosition, } from '@angular/material/core'; import {MAT_FORM_FIELD, MatFormField} from '@angular/material/form-field'; import {Observable, Subject, Subscription, defer, fromEvent, merge, of as observableOf} from 'rxjs'; import {delay, filter, map, startWith, switchMap, take, tap} from 'rxjs/operators'; import { MAT_AUTOCOMPLETE_DEFAULT_OPTIONS, MatAutocomplete, MatAutocompleteDefaultOptions, } from './autocomplete'; import {MatAutocompleteOrigin} from './autocomplete-origin'; /** * Provider that allows the autocomplete to register as a ControlValueAccessor. * @docs-private */ export const MAT_AUTOCOMPLETE_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MatAutocompleteTrigger), multi: true, }; /** * Creates an error to be thrown when attempting to use an autocomplete trigger without a panel. * @docs-private */ export function getMatAutocompleteMissingPanelError(): Error { return Error( 'Attempting to open an undefined instance of `mat-autocomplete`. ' + 'Make sure that the id passed to the `matAutocomplete` is correct and that ' + "you're attempting to open it after the ngAfterContentInit hook.", ); } /** Injection token that determines the scroll handling while the autocomplete panel is open. */ export const MAT_AUTOCOMPLETE_SCROLL_STRATEGY = new InjectionToken<() => ScrollStrategy>( 'mat-autocomplete-scroll-strategy', { providedIn: 'root', factory: () => { const overlay = inject(Overlay); return () => overlay.scrollStrategies.reposition(); }, }, ); /** @docs-private */ export function MAT_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy { return () => overlay.scrollStrategies.reposition(); } /** @docs-private */ export const MAT_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY_PROVIDER = { provide: MAT_AUTOCOMPLETE_SCROLL_STRATEGY, deps: [Overlay], useFactory: MAT_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY, }; /** Base class with all of the `MatAutocompleteTrigger` functionality. */ @Directive({ selector: `input[matAutocomplete], textarea[matAutocomplete]`, host: { 'class': 'mat-mdc-autocomplete-trigger', '[attr.autocomplete]': 'autocompleteAttribute', '[attr.role]': 'autocompleteDisabled ? null : "combobox"', '[attr.aria-autocomplete]': 'autocompleteDisabled ? null : "list"', '[attr.aria-activedescendant]': '(panelOpen && activeOption) ? activeOption.id : null', '[attr.aria-expanded]': 'autocompleteDisabled ? null : panelOpen.toString()', '[attr.aria-controls]': '(autocompleteDisabled || !panelOpen) ? null : autocomplete?.id', '[attr.aria-haspopup]': 'autocompleteDisabled ? null : "listbox"', // Note: we use `focusin`, as opposed to `focus`, in order to open the panel // a little earlier. This avoids issues where IE delays the focusing of the input. '(focusin)': '_handleFocus()', '(blur)': '_onTouched()', '(input)': '_handleInput($event)', '(keydown)': '_handleKeydown($event)', '(click)': '_handleClick()', }, exportAs: 'matAutocompleteTrigger', providers: [MAT_AUTOCOMPLETE_VALUE_ACCESSOR], }) export
{ "end_byte": 4474, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete-trigger.ts" }
components/src/material/autocomplete/autocomplete-trigger.ts_4475_13041
class MatAutocompleteTrigger implements ControlValueAccessor, AfterViewInit, OnChanges, OnDestroy { private _element = inject<ElementRef<HTMLInputElement>>(ElementRef); private _overlay = inject(Overlay); private _viewContainerRef = inject(ViewContainerRef); private _zone = inject(NgZone); private _changeDetectorRef = inject(ChangeDetectorRef); private _dir = inject(Directionality, {optional: true}); private _formField = inject<MatFormField | null>(MAT_FORM_FIELD, {optional: true, host: true}); private _document = inject(DOCUMENT); private _viewportRuler = inject(ViewportRuler); private _defaults = inject<MatAutocompleteDefaultOptions | null>( MAT_AUTOCOMPLETE_DEFAULT_OPTIONS, {optional: true}, ); private _overlayRef: OverlayRef | null; private _portal: TemplatePortal; private _componentDestroyed = false; private _scrollStrategy = inject(MAT_AUTOCOMPLETE_SCROLL_STRATEGY); private _keydownSubscription: Subscription | null; private _outsideClickSubscription: Subscription | null; /** Old value of the native input. Used to work around issues with the `input` event on IE. */ private _previousValue: string | number | null; /** Value of the input element when the panel was attached (even if there are no options). */ private _valueOnAttach: string | number | null; /** Value on the previous keydown event. */ private _valueOnLastKeydown: string | null; /** Strategy that is used to position the panel. */ private _positionStrategy: FlexibleConnectedPositionStrategy; /** Whether or not the label state is being overridden. */ private _manuallyFloatingLabel = false; /** The subscription for closing actions (some are bound to document). */ private _closingActionsSubscription: Subscription; /** Subscription to viewport size changes. */ private _viewportSubscription = Subscription.EMPTY; /** Implements BreakpointObserver to be used to detect handset landscape */ private _breakpointObserver = inject(BreakpointObserver); private _handsetLandscapeSubscription = Subscription.EMPTY; /** * Whether the autocomplete can open the next time it is focused. Used to prevent a focused, * closed autocomplete from being reopened if the user switches to another browser tab and then * comes back. */ private _canOpenOnNextFocus = true; /** Value inside the input before we auto-selected an option. */ private _valueBeforeAutoSelection: string | undefined; /** * Current option that we have auto-selected as the user is navigating, * but which hasn't been propagated to the model value yet. */ private _pendingAutoselectedOption: MatOption | null; /** Stream of keyboard events that can close the panel. */ private readonly _closeKeyEventStream = new Subject<void>(); /** * Event handler for when the window is blurred. Needs to be an * arrow function in order to preserve the context. */ private _windowBlurHandler = () => { // If the user blurred the window while the autocomplete is focused, it means that it'll be // refocused when they come back. In this case we want to skip the first focus event, if the // pane was closed, in order to avoid reopening it unintentionally. this._canOpenOnNextFocus = this._document.activeElement !== this._element.nativeElement || this.panelOpen; }; /** `View -> model callback called when value changes` */ _onChange: (value: any) => void = () => {}; /** `View -> model callback called when autocomplete has been touched` */ _onTouched = () => {}; /** The autocomplete panel to be attached to this trigger. */ @Input('matAutocomplete') autocomplete: MatAutocomplete; /** * Position of the autocomplete panel relative to the trigger element. A position of `auto` * will render the panel underneath the trigger if there is enough space for it to fit in * the viewport, otherwise the panel will be shown above it. If the position is set to * `above` or `below`, the panel will always be shown above or below the trigger. no matter * whether it fits completely in the viewport. */ @Input('matAutocompletePosition') position: 'auto' | 'above' | 'below' = 'auto'; /** * Reference relative to which to position the autocomplete panel. * Defaults to the autocomplete trigger element. */ @Input('matAutocompleteConnectedTo') connectedTo: MatAutocompleteOrigin; /** * `autocomplete` attribute to be set on the input element. * @docs-private */ @Input('autocomplete') autocompleteAttribute: string = 'off'; /** * Whether the autocomplete is disabled. When disabled, the element will * act as a regular input and the user won't be able to open the panel. */ @Input({alias: 'matAutocompleteDisabled', transform: booleanAttribute}) autocompleteDisabled: boolean; private _initialized = new Subject(); private _injector = inject(Injector); constructor(...args: unknown[]); constructor() {} /** Class to apply to the panel when it's above the input. */ private _aboveClass = 'mat-mdc-autocomplete-panel-above'; ngAfterViewInit() { this._initialized.next(); this._initialized.complete(); const window = this._getWindow(); if (typeof window !== 'undefined') { this._zone.runOutsideAngular(() => window.addEventListener('blur', this._windowBlurHandler)); } } ngOnChanges(changes: SimpleChanges) { if (changes['position'] && this._positionStrategy) { this._setStrategyPositions(this._positionStrategy); if (this.panelOpen) { this._overlayRef!.updatePosition(); } } } ngOnDestroy() { const window = this._getWindow(); if (typeof window !== 'undefined') { window.removeEventListener('blur', this._windowBlurHandler); } this._handsetLandscapeSubscription.unsubscribe(); this._viewportSubscription.unsubscribe(); this._componentDestroyed = true; this._destroyPanel(); this._closeKeyEventStream.complete(); this._clearFromModal(); } /** Whether or not the autocomplete panel is open. */ get panelOpen(): boolean { return this._overlayAttached && this.autocomplete.showPanel; } private _overlayAttached: boolean = false; /** Opens the autocomplete suggestion panel. */ openPanel(): void { this._openPanelInternal(); } /** Closes the autocomplete suggestion panel. */ closePanel(): void { this._resetLabel(); if (!this._overlayAttached) { return; } if (this.panelOpen) { // Only emit if the panel was visible. // `afterNextRender` always runs outside of the Angular zone, so all the subscriptions from // `_subscribeToClosingActions()` are also outside of the Angular zone. // We should manually run in Angular zone to update UI after panel closing. this._zone.run(() => { this.autocomplete.closed.emit(); }); } // Only reset if this trigger is the latest one that opened the // autocomplete since another may have taken it over. if (this.autocomplete._latestOpeningTrigger === this) { this.autocomplete._isOpen = false; this.autocomplete._latestOpeningTrigger = null; } this._overlayAttached = false; this._pendingAutoselectedOption = null; if (this._overlayRef && this._overlayRef.hasAttached()) { this._overlayRef.detach(); this._closingActionsSubscription.unsubscribe(); } this._updatePanelState(); // Note that in some cases this can end up being called after the component is destroyed. // Add a check to ensure that we don't try to run change detection on a destroyed view. if (!this._componentDestroyed) { // We need to trigger change detection manually, because // `fromEvent` doesn't seem to do it at the proper time. // This ensures that the label is reset when the // user clicks outside. this._changeDetectorRef.detectChanges(); } // Remove aria-owns attribute when the autocomplete is no longer visible. if (this._trackedModal) { removeAriaReferencedId(this._trackedModal, 'aria-owns', this.autocomplete.id); } } /** * Updates the position of the autocomplete suggestion panel to ensure that it fits all options * within the viewport. */ updatePosition(): void { if (this._overlayAttached) { this._overlayRef!.updatePosition(); } } /** * A stream of actions that should close the autocomplete panel, including * when an option is selected, on blur, and when TAB is pressed. */
{ "end_byte": 13041, "start_byte": 4475, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete-trigger.ts" }
components/src/material/autocomplete/autocomplete-trigger.ts_13044_21773
get panelClosingActions(): Observable<MatOptionSelectionChange | null> { return merge( this.optionSelections, this.autocomplete._keyManager.tabOut.pipe(filter(() => this._overlayAttached)), this._closeKeyEventStream, this._getOutsideClickStream(), this._overlayRef ? this._overlayRef.detachments().pipe(filter(() => this._overlayAttached)) : observableOf(), ).pipe( // Normalize the output so we return a consistent type. map(event => (event instanceof MatOptionSelectionChange ? event : null)), ); } /** Stream of changes to the selection state of the autocomplete options. */ readonly optionSelections: Observable<MatOptionSelectionChange> = defer(() => { const options = this.autocomplete ? this.autocomplete.options : null; if (options) { return options.changes.pipe( startWith(options), switchMap(() => merge(...options.map(option => option.onSelectionChange))), ); } // If there are any subscribers before `ngAfterViewInit`, the `autocomplete` will be undefined. // Return a stream that we'll replace with the real one once everything is in place. return this._initialized.pipe(switchMap(() => this.optionSelections)); }) as Observable<MatOptionSelectionChange>; /** The currently active option, coerced to MatOption type. */ get activeOption(): MatOption | null { if (this.autocomplete && this.autocomplete._keyManager) { return this.autocomplete._keyManager.activeItem; } return null; } /** Stream of clicks outside of the autocomplete panel. */ private _getOutsideClickStream(): Observable<any> { return merge( fromEvent(this._document, 'click') as Observable<MouseEvent>, fromEvent(this._document, 'auxclick') as Observable<MouseEvent>, fromEvent(this._document, 'touchend') as Observable<TouchEvent>, ).pipe( filter(event => { // If we're in the Shadow DOM, the event target will be the shadow root, so we have to // fall back to check the first element in the path of the click event. const clickTarget = _getEventTarget<HTMLElement>(event)!; const formField = this._formField ? this._formField.getConnectedOverlayOrigin().nativeElement : null; const customOrigin = this.connectedTo ? this.connectedTo.elementRef.nativeElement : null; return ( this._overlayAttached && clickTarget !== this._element.nativeElement && // Normally focus moves inside `mousedown` so this condition will almost always be // true. Its main purpose is to handle the case where the input is focused from an // outside click which propagates up to the `body` listener within the same sequence // and causes the panel to close immediately (see #3106). this._document.activeElement !== this._element.nativeElement && (!formField || !formField.contains(clickTarget)) && (!customOrigin || !customOrigin.contains(clickTarget)) && !!this._overlayRef && !this._overlayRef.overlayElement.contains(clickTarget) ); }), ); } // Implemented as part of ControlValueAccessor. writeValue(value: any): void { Promise.resolve(null).then(() => this._assignOptionValue(value)); } // Implemented as part of ControlValueAccessor. registerOnChange(fn: (value: any) => {}): void { this._onChange = fn; } // Implemented as part of ControlValueAccessor. registerOnTouched(fn: () => {}) { this._onTouched = fn; } // Implemented as part of ControlValueAccessor. setDisabledState(isDisabled: boolean) { this._element.nativeElement.disabled = isDisabled; } _handleKeydown(event: KeyboardEvent): void { const keyCode = event.keyCode; const hasModifier = hasModifierKey(event); // Prevent the default action on all escape key presses. This is here primarily to bring IE // in line with other browsers. By default, pressing escape on IE will cause it to revert // the input value to the one that it had on focus, however it won't dispatch any events // which means that the model value will be out of sync with the view. if (keyCode === ESCAPE && !hasModifier) { event.preventDefault(); } this._valueOnLastKeydown = this._element.nativeElement.value; if (this.activeOption && keyCode === ENTER && this.panelOpen && !hasModifier) { this.activeOption._selectViaInteraction(); this._resetActiveItem(); event.preventDefault(); } else if (this.autocomplete) { const prevActiveItem = this.autocomplete._keyManager.activeItem; const isArrowKey = keyCode === UP_ARROW || keyCode === DOWN_ARROW; if (keyCode === TAB || (isArrowKey && !hasModifier && this.panelOpen)) { this.autocomplete._keyManager.onKeydown(event); } else if (isArrowKey && this._canOpen()) { this._openPanelInternal(this._valueOnLastKeydown); } if (isArrowKey || this.autocomplete._keyManager.activeItem !== prevActiveItem) { this._scrollToOption(this.autocomplete._keyManager.activeItemIndex || 0); if (this.autocomplete.autoSelectActiveOption && this.activeOption) { if (!this._pendingAutoselectedOption) { this._valueBeforeAutoSelection = this._valueOnLastKeydown; } this._pendingAutoselectedOption = this.activeOption; this._assignOptionValue(this.activeOption.value); } } } } _handleInput(event: KeyboardEvent): void { let target = event.target as HTMLInputElement; let value: number | string | null = target.value; // Based on `NumberValueAccessor` from forms. if (target.type === 'number') { value = value == '' ? null : parseFloat(value); } // If the input has a placeholder, IE will fire the `input` event on page load, // focus and blur, in addition to when the user actually changed the value. To // filter out all of the extra events, we save the value on focus and between // `input` events, and we check whether it changed. // See: https://connect.microsoft.com/IE/feedback/details/885747/ if (this._previousValue !== value) { this._previousValue = value; this._pendingAutoselectedOption = null; // If selection is required we don't write to the CVA while the user is typing. // At the end of the selection either the user will have picked something // or we'll reset the value back to null. if (!this.autocomplete || !this.autocomplete.requireSelection) { this._onChange(value); } if (!value) { this._clearPreviousSelectedOption(null, false); } else if (this.panelOpen && !this.autocomplete.requireSelection) { // Note that we don't reset this when `requireSelection` is enabled, // because the option will be reset when the panel is closed. const selectedOption = this.autocomplete.options?.find(option => option.selected); if (selectedOption) { const display = this._getDisplayValue(selectedOption.value); if (value !== display) { selectedOption.deselect(false); } } } if (this._canOpen() && this._document.activeElement === event.target) { // When the `input` event fires, the input's value will have already changed. This means // that if we take the `this._element.nativeElement.value` directly, it'll be one keystroke // behind. This can be a problem when the user selects a value, changes a character while // the input still has focus and then clicks away (see #28432). To work around it, we // capture the value in `keydown` so we can use it here. const valueOnAttach = this._valueOnLastKeydown ?? this._element.nativeElement.value; this._valueOnLastKeydown = null; this._openPanelInternal(valueOnAttach); } } } _handleFocus(): void { if (!this._canOpenOnNextFocus) { this._canOpenOnNextFocus = true; } else if (this._canOpen()) { this._previousValue = this._element.nativeElement.value; this._attachOverlay(this._previousValue); this._floatLabel(true); } } _handleClick(): void { if (this._canOpen() && !this.panelOpen) { this._openPanelInternal(); } } /** * In "auto" mode, the label will animate down as soon as focus is lost. * This causes the value to jump when selecting an option with the mouse. * This method manually floats the label until the panel can be closed. * @param shouldAnimate Whether the label should be animated when it is floated. */
{ "end_byte": 21773, "start_byte": 13044, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete-trigger.ts" }
components/src/material/autocomplete/autocomplete-trigger.ts_21776_28996
private _floatLabel(shouldAnimate = false): void { if (this._formField && this._formField.floatLabel === 'auto') { if (shouldAnimate) { this._formField._animateAndLockLabel(); } else { this._formField.floatLabel = 'always'; } this._manuallyFloatingLabel = true; } } /** If the label has been manually elevated, return it to its normal state. */ private _resetLabel(): void { if (this._manuallyFloatingLabel) { if (this._formField) { this._formField.floatLabel = 'auto'; } this._manuallyFloatingLabel = false; } } /** * This method listens to a stream of panel closing actions and resets the * stream every time the option list changes. */ private _subscribeToClosingActions(): Subscription { const initialRender = new Observable(subscriber => { afterNextRender( () => { subscriber.next(); }, {injector: this._injector}, ); }); const optionChanges = this.autocomplete.options.changes.pipe( tap(() => this._positionStrategy.reapplyLastPosition()), // Defer emitting to the stream until the next tick, because changing // bindings in here will cause "changed after checked" errors. delay(0), ); // When the options are initially rendered, and when the option list changes... return ( merge(initialRender, optionChanges) .pipe( // create a new stream of panelClosingActions, replacing any previous streams // that were created, and flatten it so our stream only emits closing events... switchMap(() => this._zone.run(() => { // `afterNextRender` always runs outside of the Angular zone, thus we have to re-enter // the Angular zone. This will lead to change detection being called outside of the Angular // zone and the `autocomplete.opened` will also emit outside of the Angular. const wasOpen = this.panelOpen; this._resetActiveItem(); this._updatePanelState(); this._changeDetectorRef.detectChanges(); if (this.panelOpen) { this._overlayRef!.updatePosition(); } if (wasOpen !== this.panelOpen) { // If the `panelOpen` state changed, we need to make sure to emit the `opened` or // `closed` event, because we may not have emitted it. This can happen // - if the users opens the panel and there are no options, but the // options come in slightly later or as a result of the value changing, // - if the panel is closed after the user entered a string that did not match any // of the available options, // - if a valid string is entered after an invalid one. if (this.panelOpen) { this._emitOpened(); } else { this.autocomplete.closed.emit(); } } return this.panelClosingActions; }), ), // when the first closing event occurs... take(1), ) // set the value, close the panel, and complete. .subscribe(event => this._setValueAndClose(event)) ); } /** * Emits the opened event once it's known that the panel will be shown and stores * the state of the trigger right before the opening sequence was finished. */ private _emitOpened() { this.autocomplete.opened.emit(); } /** Destroys the autocomplete suggestion panel. */ private _destroyPanel(): void { if (this._overlayRef) { this.closePanel(); this._overlayRef.dispose(); this._overlayRef = null; } } /** Given a value, returns the string that should be shown within the input. */ private _getDisplayValue<T>(value: T): T | string { const autocomplete = this.autocomplete; return autocomplete && autocomplete.displayWith ? autocomplete.displayWith(value) : value; } private _assignOptionValue(value: any): void { const toDisplay = this._getDisplayValue(value); if (value == null) { this._clearPreviousSelectedOption(null, false); } // Simply falling back to an empty string if the display value is falsy does not work properly. // The display value can also be the number zero and shouldn't fall back to an empty string. this._updateNativeInputValue(toDisplay != null ? toDisplay : ''); } private _updateNativeInputValue(value: string): void { // If it's used within a `MatFormField`, we should set it through the property so it can go // through change detection. if (this._formField) { this._formField._control.value = value; } else { this._element.nativeElement.value = value; } this._previousValue = value; } /** * This method closes the panel, and if a value is specified, also sets the associated * control to that value. It will also mark the control as dirty if this interaction * stemmed from the user. */ private _setValueAndClose(event: MatOptionSelectionChange | null): void { const panel = this.autocomplete; const toSelect = event ? event.source : this._pendingAutoselectedOption; if (toSelect) { this._clearPreviousSelectedOption(toSelect); this._assignOptionValue(toSelect.value); // TODO(crisbeto): this should wait until the animation is done, otherwise the value // gets reset while the panel is still animating which looks glitchy. It'll likely break // some tests to change it at this point. this._onChange(toSelect.value); panel._emitSelectEvent(toSelect); this._element.nativeElement.focus(); } else if ( panel.requireSelection && this._element.nativeElement.value !== this._valueOnAttach ) { this._clearPreviousSelectedOption(null); this._assignOptionValue(null); // Wait for the animation to finish before clearing the form control value, otherwise // the options might change while the animation is running which looks glitchy. if (panel._animationDone) { panel._animationDone.pipe(take(1)).subscribe(() => this._onChange(null)); } else { this._onChange(null); } } this.closePanel(); } /** * Clear any previous selected option and emit a selection change event for this option */ private _clearPreviousSelectedOption(skip: MatOption | null, emitEvent?: boolean) { // Null checks are necessary here, because the autocomplete // or its options may not have been assigned yet. this.autocomplete?.options?.forEach(option => { if (option !== skip && option.selected) { option.deselect(emitEvent); } }); } private _openPanelInternal(valueOnAttach = this._element.nativeElement.value) { this._attachOverlay(valueOnAttach); this._floatLabel(); // Add aria-owns attribute when the autocomplete becomes visible. if (this._trackedModal) { const panelId = this.autocomplete.id; addAriaReferencedId(this._trackedModal, 'aria-owns', panelId); } }
{ "end_byte": 28996, "start_byte": 21776, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete-trigger.ts" }
components/src/material/autocomplete/autocomplete-trigger.ts_29000_37767
private _attachOverlay(valueOnAttach: string): void { if (!this.autocomplete && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw getMatAutocompleteMissingPanelError(); } let overlayRef = this._overlayRef; if (!overlayRef) { this._portal = new TemplatePortal(this.autocomplete.template, this._viewContainerRef, { id: this._formField?.getLabelId(), }); overlayRef = this._overlay.create(this._getOverlayConfig()); this._overlayRef = overlayRef; this._viewportSubscription = this._viewportRuler.change().subscribe(() => { if (this.panelOpen && overlayRef) { overlayRef.updateSize({width: this._getPanelWidth()}); } }); // Subscribe to the breakpoint events stream to detect when screen is in // handsetLandscape. this._handsetLandscapeSubscription = this._breakpointObserver .observe(Breakpoints.HandsetLandscape) .subscribe(result => { const isHandsetLandscape = result.matches; // Check if result.matches Breakpoints.HandsetLandscape. Apply HandsetLandscape // settings to prevent overlay cutoff in that breakpoint. Fixes b/284148377 if (isHandsetLandscape) { this._positionStrategy .withFlexibleDimensions(true) .withGrowAfterOpen(true) .withViewportMargin(8); } else { this._positionStrategy .withFlexibleDimensions(false) .withGrowAfterOpen(false) .withViewportMargin(0); } }); } else { // Update the trigger, panel width and direction, in case anything has changed. this._positionStrategy.setOrigin(this._getConnectedElement()); overlayRef.updateSize({width: this._getPanelWidth()}); } if (overlayRef && !overlayRef.hasAttached()) { overlayRef.attach(this._portal); this._valueOnAttach = valueOnAttach; this._valueOnLastKeydown = null; this._closingActionsSubscription = this._subscribeToClosingActions(); } const wasOpen = this.panelOpen; this.autocomplete._isOpen = this._overlayAttached = true; this.autocomplete._latestOpeningTrigger = this; this.autocomplete._setColor(this._formField?.color); this._updatePanelState(); this._applyModalPanelOwnership(); // We need to do an extra `panelOpen` check in here, because the // autocomplete won't be shown if there are no options. if (this.panelOpen && wasOpen !== this.panelOpen) { this._emitOpened(); } } /** Handles keyboard events coming from the overlay panel. */ private _handlePanelKeydown = (event: KeyboardEvent) => { // Close when pressing ESCAPE or ALT + UP_ARROW, based on the a11y guidelines. // See: https://www.w3.org/TR/wai-aria-practices-1.1/#textbox-keyboard-interaction if ( (event.keyCode === ESCAPE && !hasModifierKey(event)) || (event.keyCode === UP_ARROW && hasModifierKey(event, 'altKey')) ) { // If the user had typed something in before we autoselected an option, and they decided // to cancel the selection, restore the input value to the one they had typed in. if (this._pendingAutoselectedOption) { this._updateNativeInputValue(this._valueBeforeAutoSelection ?? ''); this._pendingAutoselectedOption = null; } this._closeKeyEventStream.next(); this._resetActiveItem(); // We need to stop propagation, otherwise the event will eventually // reach the input itself and cause the overlay to be reopened. event.stopPropagation(); event.preventDefault(); } }; /** Updates the panel's visibility state and any trigger state tied to id. */ private _updatePanelState() { this.autocomplete._setVisibility(); // Note that here we subscribe and unsubscribe based on the panel's visiblity state, // because the act of subscribing will prevent events from reaching other overlays and // we don't want to block the events if there are no options. if (this.panelOpen) { const overlayRef = this._overlayRef!; if (!this._keydownSubscription) { // Use the `keydownEvents` in order to take advantage of // the overlay event targeting provided by the CDK overlay. this._keydownSubscription = overlayRef.keydownEvents().subscribe(this._handlePanelKeydown); } if (!this._outsideClickSubscription) { // Subscribe to the pointer events stream so that it doesn't get picked up by other overlays. // TODO(crisbeto): we should switch `_getOutsideClickStream` eventually to use this stream, // but the behvior isn't exactly the same and it ends up breaking some internal tests. this._outsideClickSubscription = overlayRef.outsidePointerEvents().subscribe(); } } else { this._keydownSubscription?.unsubscribe(); this._outsideClickSubscription?.unsubscribe(); this._keydownSubscription = this._outsideClickSubscription = null; } } private _getOverlayConfig(): OverlayConfig { return new OverlayConfig({ positionStrategy: this._getOverlayPosition(), scrollStrategy: this._scrollStrategy(), width: this._getPanelWidth(), direction: this._dir ?? undefined, panelClass: this._defaults?.overlayPanelClass, }); } private _getOverlayPosition(): PositionStrategy { // Set default Overlay Position const strategy = this._overlay .position() .flexibleConnectedTo(this._getConnectedElement()) .withFlexibleDimensions(false) .withPush(false); this._setStrategyPositions(strategy); this._positionStrategy = strategy; return strategy; } /** Sets the positions on a position strategy based on the directive's input state. */ private _setStrategyPositions(positionStrategy: FlexibleConnectedPositionStrategy) { // Note that we provide horizontal fallback positions, even though by default the dropdown // width matches the input, because consumers can override the width. See #18854. const belowPositions: ConnectedPosition[] = [ {originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top'}, {originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top'}, ]; // The overlay edge connected to the trigger should have squared corners, while // the opposite end has rounded corners. We apply a CSS class to swap the // border-radius based on the overlay position. const panelClass = this._aboveClass; const abovePositions: ConnectedPosition[] = [ {originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom', panelClass}, {originX: 'end', originY: 'top', overlayX: 'end', overlayY: 'bottom', panelClass}, ]; let positions: ConnectedPosition[]; if (this.position === 'above') { positions = abovePositions; } else if (this.position === 'below') { positions = belowPositions; } else { positions = [...belowPositions, ...abovePositions]; } positionStrategy.withPositions(positions); } private _getConnectedElement(): ElementRef<HTMLElement> { if (this.connectedTo) { return this.connectedTo.elementRef; } return this._formField ? this._formField.getConnectedOverlayOrigin() : this._element; } private _getPanelWidth(): number | string { return this.autocomplete.panelWidth || this._getHostWidth(); } /** Returns the width of the input element, so the panel width can match it. */ private _getHostWidth(): number { return this._getConnectedElement().nativeElement.getBoundingClientRect().width; } /** * Reset the active item to -1. This is so that pressing arrow keys will activate the correct * option. * * If the consumer opted-in to automatically activatating the first option, activate the first * *enabled* option. */ private _resetActiveItem(): void { const autocomplete = this.autocomplete; if (autocomplete.autoActiveFirstOption) { // Find the index of the first *enabled* option. Avoid calling `_keyManager.setActiveItem` // because it activates the first option that passes the skip predicate, rather than the // first *enabled* option. let firstEnabledOptionIndex = -1; for (let index = 0; index < autocomplete.options.length; index++) { const option = autocomplete.options.get(index)!; if (!option.disabled) { firstEnabledOptionIndex = index; break; } } autocomplete._keyManager.setActiveItem(firstEnabledOptionIndex); } else { autocomplete._keyManager.setActiveItem(-1); } } /** Determines whether the panel can be opened. */
{ "end_byte": 37767, "start_byte": 29000, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete-trigger.ts" }
components/src/material/autocomplete/autocomplete-trigger.ts_37770_42342
private _canOpen(): boolean { const element = this._element.nativeElement; return !element.readOnly && !element.disabled && !this.autocompleteDisabled; } /** Use defaultView of injected document if available or fallback to global window reference */ private _getWindow(): Window { return this._document?.defaultView || window; } /** Scrolls to a particular option in the list. */ private _scrollToOption(index: number): void { // Given that we are not actually focusing active options, we must manually adjust scroll // to reveal options below the fold. First, we find the offset of the option from the top // of the panel. If that offset is below the fold, the new scrollTop will be the offset - // the panel height + the option height, so the active option will be just visible at the // bottom of the panel. If that offset is above the top of the visible panel, the new scrollTop // will become the offset. If that offset is visible within the panel already, the scrollTop is // not adjusted. const autocomplete = this.autocomplete; const labelCount = _countGroupLabelsBeforeOption( index, autocomplete.options, autocomplete.optionGroups, ); if (index === 0 && labelCount === 1) { // If we've got one group label before the option and we're at the top option, // scroll the list to the top. This is better UX than scrolling the list to the // top of the option, because it allows the user to read the top group's label. autocomplete._setScrollTop(0); } else if (autocomplete.panel) { const option = autocomplete.options.toArray()[index]; if (option) { const element = option._getHostElement(); const newScrollPosition = _getOptionScrollPosition( element.offsetTop, element.offsetHeight, autocomplete._getScrollTop(), autocomplete.panel.nativeElement.offsetHeight, ); autocomplete._setScrollTop(newScrollPosition); } } } /** * Track which modal we have modified the `aria-owns` attribute of. When the combobox trigger is * inside an aria-modal, we apply aria-owns to the parent modal with the `id` of the options * panel. Track the modal we have changed so we can undo the changes on destroy. */ private _trackedModal: Element | null = null; /** * If the autocomplete trigger is inside of an `aria-modal` element, connect * that modal to the options panel with `aria-owns`. * * For some browser + screen reader combinations, when navigation is inside * of an `aria-modal` element, the screen reader treats everything outside * of that modal as hidden or invisible. * * This causes a problem when the combobox trigger is _inside_ of a modal, because the * options panel is rendered _outside_ of that modal, preventing screen reader navigation * from reaching the panel. * * We can work around this issue by applying `aria-owns` to the modal with the `id` of * the options panel. This effectively communicates to assistive technology that the * options panel is part of the same interaction as the modal. * * At time of this writing, this issue is present in VoiceOver. * See https://github.com/angular/components/issues/20694 */ private _applyModalPanelOwnership() { // TODO(http://github.com/angular/components/issues/26853): consider de-duplicating this with // the `LiveAnnouncer` and any other usages. // // Note that the selector here is limited to CDK overlays at the moment in order to reduce the // section of the DOM we need to look through. This should cover all the cases we support, but // the selector can be expanded if it turns out to be too narrow. const modal = this._element.nativeElement.closest( 'body > .cdk-overlay-container [aria-modal="true"]', ); if (!modal) { // Most commonly, the autocomplete trigger is not inside a modal. return; } const panelId = this.autocomplete.id; if (this._trackedModal) { removeAriaReferencedId(this._trackedModal, 'aria-owns', panelId); } addAriaReferencedId(modal, 'aria-owns', panelId); this._trackedModal = modal; } /** Clears the references to the listbox overlay element from the modal it was added to. */ private _clearFromModal() { if (this._trackedModal) { const panelId = this.autocomplete.id; removeAriaReferencedId(this._trackedModal, 'aria-owns', panelId); this._trackedModal = null; } } }
{ "end_byte": 42342, "start_byte": 37770, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete-trigger.ts" }
components/src/material/autocomplete/BUILD.bazel_0_1946
load( "//tools:defaults.bzl", "extract_tokens", "markdown_to_html", "ng_module", "ng_test_library", "ng_web_test_suite", "sass_binary", "sass_library", ) package(default_visibility = ["//visibility:public"]) ng_module( name = "autocomplete", srcs = glob( ["**/*.ts"], exclude = [ "**/*.spec.ts", ], ), assets = [ ":autocomplete_scss", ] + glob(["**/*.html"]), deps = [ "//src/cdk/a11y", "//src/cdk/coercion", "//src/cdk/overlay", "//src/cdk/scrolling", "//src/material/core", "//src/material/form-field", "@npm//@angular/common", ], ) sass_library( name = "autocomplete_scss_lib", srcs = glob(["**/_*.scss"]), deps = [ "//src/material/core:core_scss_lib", ], ) sass_binary( name = "autocomplete_scss", src = "autocomplete.scss", deps = [ "//src/cdk:sass_lib", "//src/material/core:core_scss_lib", ], ) ng_test_library( name = "autocomplete_tests_lib", srcs = glob( ["**/*.spec.ts"], exclude = [ "**/*.e2e.spec.ts", ], ), deps = [ ":autocomplete", "//src/cdk/bidi", "//src/cdk/keycodes", "//src/cdk/overlay", "//src/cdk/platform", "//src/cdk/scrolling", "//src/cdk/testing/private", "//src/material/core", "//src/material/form-field", "//src/material/input", "@npm//@angular/forms", "@npm//@angular/platform-browser", "@npm//rxjs", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":autocomplete_tests_lib", ], ) markdown_to_html( name = "overview", srcs = [":autocomplete.md"], ) extract_tokens( name = "tokens", srcs = [":autocomplete_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "end_byte": 1946, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/BUILD.bazel" }
components/src/material/autocomplete/autocomplete.html_0_703
<ng-template let-formFieldId="id"> <div class="mat-mdc-autocomplete-panel mdc-menu-surface mdc-menu-surface--open" role="listbox" [id]="id" [class]="_classList" [class.mat-mdc-autocomplete-visible]="showPanel" [class.mat-mdc-autocomplete-hidden]="!showPanel" [class.mat-primary]="_color === 'primary'" [class.mat-accent]="_color === 'accent'" [class.mat-warn]="_color === 'warn'" [attr.aria-label]="ariaLabel || null" [attr.aria-labelledby]="_getPanelAriaLabelledby(formFieldId)" [@panelAnimation]="isOpen ? 'visible' : 'hidden'" (@panelAnimation.done)="_animationDone.next($event)" #panel> <ng-content></ng-content> </div> </ng-template>
{ "end_byte": 703, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.html" }
components/src/material/autocomplete/index.ts_0_234
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './public-api';
{ "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/index.ts" }
components/src/material/autocomplete/animations.ts_0_931
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { animate, AnimationTriggerMetadata, group, state, style, transition, trigger, } from '@angular/animations'; // Animation values come from // TODO(mmalerba): Ideally find a way to import the values from MDC's code. export const panelAnimation: AnimationTriggerMetadata = trigger('panelAnimation', [ state( 'void, hidden', style({ opacity: 0, transform: 'scaleY(0.8)', }), ), transition(':enter, hidden => visible', [ group([ animate('0.03s linear', style({opacity: 1})), animate('0.12s cubic-bezier(0, 0, 0.2, 1)', style({transform: 'scaleY(1)'})), ]), ]), transition(':leave, visible => hidden', [animate('0.075s linear', style({opacity: 0}))]), ]);
{ "end_byte": 931, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/animations.ts" }
components/src/material/autocomplete/autocomplete.scss_0_1782
@use '@angular/cdk'; @use '../core/tokens/token-utils'; @use '../core/tokens/m2/mat/autocomplete' as tokens-mat-autocomplete; // Even though we don't use the MDC styles, we need to keep the classes in the // DOM for the Gmat versions to work. We need to bump up the specificity here // so that it's higher than MDC's styles. div.mat-mdc-autocomplete-panel { width: 100%; // Ensures that the panel matches the overlay width. max-height: 256px; // Prevents lists with a lot of option from growing too high. visibility: hidden; transform-origin: center top; overflow: auto; padding: 8px 0; box-sizing: border-box; // Workaround in case other MDC menu surface styles bleed in. position: static; @include token-utils.use-tokens( tokens-mat-autocomplete.$prefix, tokens-mat-autocomplete.get-token-slots()) { @include token-utils.create-token-slot(border-radius, container-shape); @include token-utils.create-token-slot(box-shadow, container-elevation-shadow); @include token-utils.create-token-slot(background-color, background-color); } @include cdk.high-contrast { outline: solid 1px; } .cdk-overlay-pane:not(.mat-mdc-autocomplete-panel-above) & { border-top-left-radius: 0; border-top-right-radius: 0; } .mat-mdc-autocomplete-panel-above & { border-bottom-left-radius: 0; border-bottom-right-radius: 0; transform-origin: center bottom; } // These classes are used to toggle the panel visibility depending on whether it has any options. &.mat-mdc-autocomplete-visible { visibility: visible; } &.mat-mdc-autocomplete-hidden { visibility: hidden; pointer-events: none; } } // Prevent the overlay host node from affecting its surrounding layout. mat-autocomplete { display: none; }
{ "end_byte": 1782, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/autocomplete.scss" }
components/src/material/autocomplete/testing/autocomplete-harness-filters.ts_0_637
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {BaseHarnessFilters} from '@angular/cdk/testing'; /** A set of criteria that can be used to filter a list of `MatAutocompleteHarness` instances. */ export interface AutocompleteHarnessFilters extends BaseHarnessFilters { /** Only find instances whose associated input element matches the given value. */ value?: string | RegExp; /** Only find instances which match the given disabled state. */ disabled?: boolean; }
{ "end_byte": 637, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/testing/autocomplete-harness-filters.ts" }
components/src/material/autocomplete/testing/autocomplete-harness.ts_0_4928
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {coerceBooleanProperty} from '@angular/cdk/coercion'; import { ComponentHarness, ComponentHarnessConstructor, HarnessPredicate, TestElement, } from '@angular/cdk/testing'; import { MatOptgroupHarness, MatOptionHarness, OptgroupHarnessFilters, OptionHarnessFilters, } from '@angular/material/core/testing'; import {AutocompleteHarnessFilters} from './autocomplete-harness-filters'; export class MatAutocompleteHarness extends ComponentHarness { private _documentRootLocator = this.documentRootLocatorFactory(); /** The selector for the host element of a `MatAutocomplete` instance. */ static hostSelector = '.mat-mdc-autocomplete-trigger'; /** * Gets a `HarnessPredicate` that can be used to search for an autocomplete with specific * attributes. * @param options Options for filtering which autocomplete instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with<T extends MatAutocompleteHarness>( this: ComponentHarnessConstructor<T>, options: AutocompleteHarnessFilters = {}, ): HarnessPredicate<T> { return new HarnessPredicate(this, options) .addOption('value', options.value, (harness, value) => HarnessPredicate.stringMatches(harness.getValue(), value), ) .addOption('disabled', options.disabled, async (harness, disabled) => { return (await harness.isDisabled()) === disabled; }); } /** Gets the value of the autocomplete input. */ async getValue(): Promise<string> { return (await this.host()).getProperty<string>('value'); } /** Whether the autocomplete input is disabled. */ async isDisabled(): Promise<boolean> { const disabled = (await this.host()).getAttribute('disabled'); return coerceBooleanProperty(await disabled); } /** Focuses the autocomplete input. */ async focus(): Promise<void> { return (await this.host()).focus(); } /** Blurs the autocomplete input. */ async blur(): Promise<void> { return (await this.host()).blur(); } /** Whether the autocomplete input is focused. */ async isFocused(): Promise<boolean> { return (await this.host()).isFocused(); } /** Enters text into the autocomplete. */ async enterText(value: string): Promise<void> { return (await this.host()).sendKeys(value); } /** Clears the input value. */ async clear(): Promise<void> { return (await this.host()).clear(); } /** Gets the options inside the autocomplete panel. */ async getOptions(filters?: Omit<OptionHarnessFilters, 'ancestor'>): Promise<MatOptionHarness[]> { if (!(await this.isOpen())) { throw new Error('Unable to retrieve options for autocomplete. Autocomplete panel is closed.'); } return this._documentRootLocator.locatorForAll( MatOptionHarness.with({ ...(filters || {}), ancestor: await this._getPanelSelector(), } as OptionHarnessFilters), )(); } /** Gets the option groups inside the autocomplete panel. */ async getOptionGroups( filters?: Omit<OptgroupHarnessFilters, 'ancestor'>, ): Promise<MatOptgroupHarness[]> { if (!(await this.isOpen())) { throw new Error( 'Unable to retrieve option groups for autocomplete. Autocomplete panel is closed.', ); } return this._documentRootLocator.locatorForAll( MatOptgroupHarness.with({ ...(filters || {}), ancestor: await this._getPanelSelector(), } as OptgroupHarnessFilters), )(); } /** Selects the first option matching the given filters. */ async selectOption(filters: OptionHarnessFilters): Promise<void> { await this.focus(); // Focus the input to make sure the autocomplete panel is shown. const options = await this.getOptions(filters); if (!options.length) { throw Error(`Could not find a mat-option matching ${JSON.stringify(filters)}`); } await options[0].click(); } /** Whether the autocomplete is open. */ async isOpen(): Promise<boolean> { const panel = await this._getPanel(); return !!panel && (await panel.hasClass(`mat-mdc-autocomplete-visible`)); } /** Gets the panel associated with this autocomplete trigger. */ private async _getPanel(): Promise<TestElement | null> { // Technically this is static, but it needs to be in a // function, because the autocomplete's panel ID can changed. return this._documentRootLocator.locatorForOptional(await this._getPanelSelector())(); } /** Gets the selector that can be used to find the autocomplete trigger's panel. */ protected async _getPanelSelector(): Promise<string> { return `#${await (await this.host()).getAttribute('aria-controls')}`; } }
{ "end_byte": 4928, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/testing/autocomplete-harness.ts" }
components/src/material/autocomplete/testing/public-api.ts_0_292
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './autocomplete-harness'; export * from './autocomplete-harness-filters';
{ "end_byte": 292, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/testing/public-api.ts" }
components/src/material/autocomplete/testing/autocomplete-harness.spec.ts_0_8265
import {Component} from '@angular/core'; import {MatAutocompleteModule} from '@angular/material/autocomplete'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {HarnessLoader} from '@angular/cdk/testing'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {MatAutocompleteHarness} from './autocomplete-harness'; describe('MatAutocompleteHarness', () => { let fixture: ComponentFixture<AutocompleteHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ imports: [NoopAnimationsModule, MatAutocompleteModule, AutocompleteHarnessTest], }); fixture = TestBed.createComponent(AutocompleteHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); it('should load all autocomplete harnesses', async () => { const inputs = await loader.getAllHarnesses(MatAutocompleteHarness); expect(inputs.length).toBe(5); }); it('should load harness for autocomplete with value', async () => { const ac = await loader.getHarness(MatAutocompleteHarness.with({value: /Prefilled/})); const id = await (await ac.host()).getAttribute('id'); expect(id).toBe('prefilled'); }); it('should be able to get value of the input', async () => { const input = await loader.getHarness(MatAutocompleteHarness.with({selector: '#prefilled'})); expect(await input.getValue()).toBe('Prefilled value'); }); it('should get disabled state', async () => { const enabled = await loader.getHarness(MatAutocompleteHarness.with({selector: '#plain'})); const disabled = await loader.getHarness(MatAutocompleteHarness.with({selector: '#disabled'})); expect(await enabled.isDisabled()).toBe(false); expect(await disabled.isDisabled()).toBe(true); }); it('should filter by whether an autocomplete is disabled', async () => { const enabledInputs = await loader.getAllHarnesses( MatAutocompleteHarness.with({disabled: false}), ); const disabledInputs = await loader.getAllHarnesses( MatAutocompleteHarness.with({disabled: true}), ); expect(enabledInputs.length).toBe(4); expect(disabledInputs.length).toBe(1); }); it('should focus and blur an input', async () => { const input = await loader.getHarness(MatAutocompleteHarness.with({selector: '#plain'})); expect(await input.isFocused()).toBe(false); await input.focus(); expect(await input.isFocused()).toBe(true); await input.blur(); expect(await input.isFocused()).toBe(false); }); it('should be able to type in an input', async () => { const input = await loader.getHarness(MatAutocompleteHarness.with({selector: '#plain'})); await input.enterText('Hello there'); expect(await input.getValue()).toBe('Hello there'); }); it('should be able to clear the input', async () => { const input = await loader.getHarness(MatAutocompleteHarness.with({selector: '#plain'})); await input.enterText('Hello there'); expect(await input.getValue()).toBe('Hello there'); await input.clear(); expect(await input.getValue()).toBe(''); }); it('should be able to get the autocomplete panel options', async () => { const input = await loader.getHarness(MatAutocompleteHarness.with({selector: '#plain'})); await input.focus(); const options = await input.getOptions(); expect(options.length).toBe(11); expect(await options[5].getText()).toBe('New York'); }); it('should be able to get filtered options', async () => { const input = await loader.getHarness(MatAutocompleteHarness.with({selector: '#plain'})); await input.focus(); const options = await input.getOptions({text: /New/}); expect(options.length).toBe(1); expect(await options[0].getText()).toBe('New York'); }); it('should be able to get the autocomplete panel groups', async () => { const input = await loader.getHarness(MatAutocompleteHarness.with({selector: '#grouped'})); await input.focus(); const groups = await input.getOptionGroups(); const options = await input.getOptions(); expect(groups.length).toBe(3); expect(options.length).toBe(14); }); it('should be able to get the autocomplete panel groups', async () => { const input = await loader.getHarness(MatAutocompleteHarness.with({selector: '#plain'})); await input.focus(); const input2 = await loader.getHarness(MatAutocompleteHarness.with({selector: '#grouped'})); await input2.focus(); const options = await input.getOptions(); const options2 = await input2.getOptions(); expect(options.length).toBe(11); expect(options2.length).toBe(14); }); it('should be able to get filtered panel groups', async () => { const input = await loader.getHarness(MatAutocompleteHarness.with({selector: '#grouped'})); await input.focus(); const groups = await input.getOptionGroups({labelText: 'Two'}); expect(groups.length).toBe(1); expect(await groups[0].getLabelText()).toBe('Two'); }); it('should be able to get whether the autocomplete is open', async () => { const input = await loader.getHarness(MatAutocompleteHarness.with({selector: '#plain'})); expect(await input.isOpen()).toBe(false); await input.focus(); expect(await input.isOpen()).toBe(true); }); it('should be able to select option', async () => { const input = await loader.getHarness(MatAutocompleteHarness.with({selector: '#plain'})); await input.selectOption({text: 'New York'}); expect(await input.getValue()).toBe('NY'); }); it('should throw when selecting an option that is not available', async () => { const input = await loader.getHarness(MatAutocompleteHarness.with({selector: '#plain'})); await input.enterText('New'); await expectAsync(input.selectOption({text: 'Texas'})).toBeRejectedWithError( /Could not find a mat-option matching {"text":"Texas"}/, ); }); }); @Component({ template: ` <mat-autocomplete #autocomplete="matAutocomplete"> @for (state of states; track state) { <mat-option [value]="state.code">{{ state.name }}</mat-option> } </mat-autocomplete> <mat-autocomplete #groupedAutocomplete="matAutocomplete"> @for (group of stateGroups; track group) { <mat-optgroup [label]="group.name"> @for (state of group.states; track state) { <mat-option [value]="state.code">{{ state.name }}</mat-option> } </mat-optgroup> } </mat-autocomplete> <input id="plain" [matAutocomplete]="autocomplete"> <input id="disabled" disabled [matAutocomplete]="autocomplete"> <textarea id="textarea" [matAutocomplete]="autocomplete"></textarea> <input id="prefilled" [matAutocomplete]="autocomplete" value="Prefilled value"> <input id="grouped" [matAutocomplete]="groupedAutocomplete"> `, standalone: true, imports: [MatAutocompleteModule], }) class AutocompleteHarnessTest { states = [ {code: 'AL', name: 'Alabama'}, {code: 'CA', name: 'California'}, {code: 'FL', name: 'Florida'}, {code: 'KS', name: 'Kansas'}, {code: 'MA', name: 'Massachusetts'}, {code: 'NY', name: 'New York'}, {code: 'OR', name: 'Oregon'}, {code: 'PA', name: 'Pennsylvania'}, {code: 'TN', name: 'Tennessee'}, {code: 'VA', name: 'Virginia'}, {code: 'WY', name: 'Wyoming'}, ]; stateGroups = [ { name: 'One', states: [ {code: 'IA', name: 'Iowa'}, {code: 'KS', name: 'Kansas'}, {code: 'KY', name: 'Kentucky'}, {code: 'LA', name: 'Louisiana'}, {code: 'ME', name: 'Maine'}, ], }, { name: 'Two', states: [ {code: 'RI', name: 'Rhode Island'}, {code: 'SC', name: 'South Carolina'}, {code: 'SD', name: 'South Dakota'}, {code: 'TN', name: 'Tennessee'}, {code: 'TX', name: 'Texas'}, ], }, { name: 'Three', states: [ {code: 'UT', name: 'Utah'}, {code: 'WA', name: 'Washington'}, {code: 'WV', name: 'West Virginia'}, {code: 'WI', name: 'Wisconsin'}, ], }, ]; }
{ "end_byte": 8265, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/testing/autocomplete-harness.spec.ts" }
components/src/material/autocomplete/testing/BUILD.bazel_0_828
load("//tools:defaults.bzl", "ng_test_library", "ng_web_test_suite", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "testing", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "//src/cdk/coercion", "//src/cdk/testing", "//src/material/core/testing", ], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), ) ng_test_library( name = "unit_tests_lib", srcs = glob(["**/*.spec.ts"]), deps = [ ":testing", "//src/cdk/testing", "//src/cdk/testing/testbed", "//src/material/autocomplete", "@npm//@angular/forms", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_tests_lib"], )
{ "end_byte": 828, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/testing/BUILD.bazel" }
components/src/material/autocomplete/testing/index.ts_0_234
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './public-api';
{ "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/autocomplete/testing/index.ts" }
components/src/material/sort/sort-direction.ts_0_253
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export type SortDirection = 'asc' | 'desc' | '';
{ "end_byte": 253, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort-direction.ts" }
components/src/material/sort/sort-header.html_0_2259
<!-- We set the `tabindex` on an element inside the table header, rather than the header itself, because of a bug in NVDA where having a `tabindex` on a `th` breaks keyboard navigation in the table (see https://github.com/nvaccess/nvda/issues/7718). This allows for the header to both be focusable, and have screen readers read out its `aria-sort` state. We prefer this approach over having a button with an `aria-label` inside the header, because the button's `aria-label` will be read out as the user is navigating the table's cell (see #13012). The approach is based off of: https://dequeuniversity.com/library/aria/tables/sf-sortable-grid --> <div class="mat-sort-header-container mat-focus-indicator" [class.mat-sort-header-sorted]="_isSorted()" [class.mat-sort-header-position-before]="arrowPosition === 'before'" [attr.tabindex]="_isDisabled() ? null : 0" [attr.role]="_isDisabled() ? null : 'button'"> <!-- TODO(crisbeto): this div isn't strictly necessary, but we have to keep it due to a large number of screenshot diff failures. It should be removed eventually. Note that the difference isn't visible with a shorter header, but once it breaks up into multiple lines, this element causes it to be center-aligned, whereas removing it will keep the text to the left. --> <div class="mat-sort-header-content"> <ng-content></ng-content> </div> <!-- Disable animations while a current animation is running --> @if (_renderArrow()) { <div class="mat-sort-header-arrow" [@arrowOpacity]="_getArrowViewState()" [@arrowPosition]="_getArrowViewState()" [@allowChildren]="_getArrowDirectionState()" (@arrowPosition.start)="_disableViewStateAnimation = true" (@arrowPosition.done)="_disableViewStateAnimation = false"> <div class="mat-sort-header-stem"></div> <div class="mat-sort-header-indicator" [@indicator]="_getArrowDirectionState()"> <div class="mat-sort-header-pointer-left" [@leftPointer]="_getArrowDirectionState()"></div> <div class="mat-sort-header-pointer-right" [@rightPointer]="_getArrowDirectionState()"></div> <div class="mat-sort-header-pointer-middle"></div> </div> </div> } </div>
{ "end_byte": 2259, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort-header.html" }
components/src/material/sort/sort-header-intl.ts_0_1189
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Injectable, SkipSelf, Optional} from '@angular/core'; import {Subject} from 'rxjs'; /** * To modify the labels and text displayed, create a new instance of MatSortHeaderIntl and * include it in a custom provider. */ @Injectable({providedIn: 'root'}) export class MatSortHeaderIntl { /** * Stream that emits whenever the labels here are changed. Use this to notify * components if the labels have changed after initialization. */ readonly changes: Subject<void> = new Subject<void>(); } /** @docs-private */ export function MAT_SORT_HEADER_INTL_PROVIDER_FACTORY(parentIntl: MatSortHeaderIntl) { return parentIntl || new MatSortHeaderIntl(); } /** @docs-private */ export const MAT_SORT_HEADER_INTL_PROVIDER = { // If there is already an MatSortHeaderIntl available, use that. Otherwise, provide a new one. provide: MatSortHeaderIntl, deps: [[new Optional(), new SkipSelf(), MatSortHeaderIntl]], useFactory: MAT_SORT_HEADER_INTL_PROVIDER_FACTORY, };
{ "end_byte": 1189, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort-header-intl.ts" }
components/src/material/sort/sort-animations.ts_0_4682
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { animate, state, style, transition, trigger, keyframes, AnimationTriggerMetadata, query, animateChild, } from '@angular/animations'; import {AnimationCurves, AnimationDurations} from '@angular/material/core'; const SORT_ANIMATION_TRANSITION = AnimationDurations.ENTERING + ' ' + AnimationCurves.STANDARD_CURVE; /** * Animations used by MatSort. * @docs-private */ export const matSortAnimations: { readonly indicator: AnimationTriggerMetadata; readonly leftPointer: AnimationTriggerMetadata; readonly rightPointer: AnimationTriggerMetadata; readonly arrowOpacity: AnimationTriggerMetadata; readonly arrowPosition: AnimationTriggerMetadata; readonly allowChildren: AnimationTriggerMetadata; } = { /** Animation that moves the sort indicator. */ indicator: trigger('indicator', [ state('active-asc, asc', style({transform: 'translateY(0px)'})), // 10px is the height of the sort indicator, minus the width of the pointers state('active-desc, desc', style({transform: 'translateY(10px)'})), transition('active-asc <=> active-desc', animate(SORT_ANIMATION_TRANSITION)), ]), /** Animation that rotates the left pointer of the indicator based on the sorting direction. */ leftPointer: trigger('leftPointer', [ state('active-asc, asc', style({transform: 'rotate(-45deg)'})), state('active-desc, desc', style({transform: 'rotate(45deg)'})), transition('active-asc <=> active-desc', animate(SORT_ANIMATION_TRANSITION)), ]), /** Animation that rotates the right pointer of the indicator based on the sorting direction. */ rightPointer: trigger('rightPointer', [ state('active-asc, asc', style({transform: 'rotate(45deg)'})), state('active-desc, desc', style({transform: 'rotate(-45deg)'})), transition('active-asc <=> active-desc', animate(SORT_ANIMATION_TRANSITION)), ]), /** Animation that controls the arrow opacity. */ arrowOpacity: trigger('arrowOpacity', [ state('desc-to-active, asc-to-active, active', style({opacity: 1})), state('desc-to-hint, asc-to-hint, hint', style({opacity: 0.54})), state( 'hint-to-desc, active-to-desc, desc, hint-to-asc, active-to-asc, asc, void', style({opacity: 0}), ), // Transition between all states except for immediate transitions transition('* => asc, * => desc, * => active, * => hint, * => void', animate('0ms')), transition('* <=> *', animate(SORT_ANIMATION_TRANSITION)), ]), /** * Animation for the translation of the arrow as a whole. States are separated into two * groups: ones with animations and others that are immediate. Immediate states are asc, desc, * peek, and active. The other states define a specific animation (source-to-destination) * and are determined as a function of their prev user-perceived state and what the next state * should be. */ arrowPosition: trigger('arrowPosition', [ // Hidden Above => Hint Center transition( '* => desc-to-hint, * => desc-to-active', animate( SORT_ANIMATION_TRANSITION, keyframes([style({transform: 'translateY(-25%)'}), style({transform: 'translateY(0)'})]), ), ), // Hint Center => Hidden Below transition( '* => hint-to-desc, * => active-to-desc', animate( SORT_ANIMATION_TRANSITION, keyframes([style({transform: 'translateY(0)'}), style({transform: 'translateY(25%)'})]), ), ), // Hidden Below => Hint Center transition( '* => asc-to-hint, * => asc-to-active', animate( SORT_ANIMATION_TRANSITION, keyframes([style({transform: 'translateY(25%)'}), style({transform: 'translateY(0)'})]), ), ), // Hint Center => Hidden Above transition( '* => hint-to-asc, * => active-to-asc', animate( SORT_ANIMATION_TRANSITION, keyframes([style({transform: 'translateY(0)'}), style({transform: 'translateY(-25%)'})]), ), ), state( 'desc-to-hint, asc-to-hint, hint, desc-to-active, asc-to-active, active', style({transform: 'translateY(0)'}), ), state('hint-to-desc, active-to-desc, desc', style({transform: 'translateY(-25%)'})), state('hint-to-asc, active-to-asc, asc', style({transform: 'translateY(25%)'})), ]), /** Necessary trigger that calls animate on children animations. */ allowChildren: trigger('allowChildren', [ transition('* <=> *', [query('@*', animateChild(), {optional: true})]), ]), };
{ "end_byte": 4682, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort-animations.ts" }
components/src/material/sort/sort-header.scss_0_3549
@use '@angular/cdk'; @use '../core/tokens/m2/mat/sort' as tokens-mat-sort; @use '../core/tokens/token-utils'; @use '../core/focus-indicators/private'; $header-arrow-margin: 6px; $header-arrow-container-size: 12px; $header-arrow-stem-size: 10px; $header-arrow-pointer-length: 6px; $header-arrow-thickness: 2px; $header-arrow-hint-opacity: 0.38; .mat-sort-header-container { display: flex; cursor: pointer; align-items: center; letter-spacing: normal; // Needs to be reset since we don't want an outline around the inner // div which is focusable. We have our own alternate focus styling. outline: 0; // Usually we could rely on the arrow showing up to be focus indication, but if a header is // active, the arrow will always be shown so the user has no way of telling the difference. [mat-sort-header].cdk-keyboard-focused &, [mat-sort-header].cdk-program-focused & { border-bottom: solid 1px currentColor; } .mat-sort-header-disabled & { cursor: default; } // For the sort-header element, default inset/offset values are necessary to ensure that // the focus indicator is sufficiently contrastive and renders appropriately. &::before { $border-width: var(--mat-focus-indicator-border-width, #{private.$default-border-width}); $offset: calc(#{$border-width} + 2px); margin: calc(#{$offset} * -1); } } .mat-sort-header-content { text-align: center; display: flex; align-items: center; } .mat-sort-header-position-before { flex-direction: row-reverse; } .mat-sort-header-arrow { height: $header-arrow-container-size; width: $header-arrow-container-size; min-width: $header-arrow-container-size; position: relative; display: flex; @include token-utils.use-tokens(tokens-mat-sort.$prefix, tokens-mat-sort.get-token-slots()) { @include token-utils.create-token-slot(color, arrow-color); } // Start off at 0 since the arrow may become visible while parent are animating. // This will be overwritten when the arrow animations kick in. See #11819. opacity: 0; &, [dir='rtl'] .mat-sort-header-position-before & { margin: 0 0 0 $header-arrow-margin; } .mat-sort-header-position-before &, [dir='rtl'] & { margin: 0 $header-arrow-margin 0 0; } } .mat-sort-header-stem { background: currentColor; height: $header-arrow-stem-size; width: $header-arrow-thickness; margin: auto; display: flex; align-items: center; @include cdk.high-contrast { width: 0; border-left: solid $header-arrow-thickness; } } .mat-sort-header-indicator { width: 100%; height: $header-arrow-thickness; display: flex; align-items: center; position: absolute; top: 0; left: 0; } .mat-sort-header-pointer-middle { margin: auto; height: $header-arrow-thickness; width: $header-arrow-thickness; background: currentColor; transform: rotate(45deg); @include cdk.high-contrast { width: 0; height: 0; border-top: solid $header-arrow-thickness; border-left: solid $header-arrow-thickness; } } .mat-sort-header-pointer-left, .mat-sort-header-pointer-right { background: currentColor; width: $header-arrow-pointer-length; height: $header-arrow-thickness; position: absolute; top: 0; @include cdk.high-contrast { width: 0; height: 0; border-left: solid $header-arrow-pointer-length; border-top: solid $header-arrow-thickness; } } .mat-sort-header-pointer-left { transform-origin: right; left: 0; } .mat-sort-header-pointer-right { transform-origin: left; right: 0; }
{ "end_byte": 3549, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort-header.scss" }
components/src/material/sort/sort-errors.ts_0_887
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** @docs-private */ export function getSortDuplicateSortableIdError(id: string): Error { return Error(`Cannot have two MatSortables with the same id (${id}).`); } /** @docs-private */ export function getSortHeaderNotContainedWithinSortError(): Error { return Error(`MatSortHeader must be placed within a parent element with the MatSort directive.`); } /** @docs-private */ export function getSortHeaderMissingIdError(): Error { return Error(`MatSortHeader must be provided with a unique id.`); } /** @docs-private */ export function getSortInvalidDirectionError(direction: string): Error { return Error(`${direction} is not a valid sort direction ('asc' or 'desc').`); }
{ "end_byte": 887, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort-errors.ts" }
components/src/material/sort/sort-module.ts_0_626
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {MatSortHeader} from './sort-header'; import {MatSort} from './sort'; import {MAT_SORT_HEADER_INTL_PROVIDER} from './sort-header-intl'; import {MatCommonModule} from '@angular/material/core'; @NgModule({ imports: [MatCommonModule, MatSort, MatSortHeader], exports: [MatSort, MatSortHeader], providers: [MAT_SORT_HEADER_INTL_PROVIDER], }) export class MatSortModule {}
{ "end_byte": 626, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort-module.ts" }
components/src/material/sort/public-api.ts_0_395
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './sort-module'; export * from './sort-direction'; export * from './sort-header'; export * from './sort-header-intl'; export * from './sort'; export * from './sort-animations';
{ "end_byte": 395, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sort/public-api.ts" }
components/src/material/sort/sort.spec.ts_0_967
import {CollectionViewer, DataSource} from '@angular/cdk/collections'; import {CdkTableModule} from '@angular/cdk/table'; import { createFakeEvent, createMouseEvent, dispatchMouseEvent, wrappedErrorMessage, } from '@angular/cdk/testing/private'; import {Component, ElementRef, ViewChild, inject} from '@angular/core'; import {ComponentFixture, TestBed, fakeAsync, tick, waitForAsync} from '@angular/core/testing'; import {MatTableModule} from '@angular/material/table'; import {By} from '@angular/platform-browser'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {Observable} from 'rxjs'; import {map} from 'rxjs/operators'; import { MAT_SORT_DEFAULT_OPTIONS, MatSort, MatSortHeader, MatSortModule, Sort, SortDirection, } from './index'; import { getSortDuplicateSortableIdError, getSortHeaderMissingIdError, getSortHeaderNotContainedWithinSortError, getSortInvalidDirectionError, } from './sort-errors';
{ "end_byte": 967, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort.spec.ts" }
components/src/material/sort/sort.spec.ts_969_10272
describe('MatSort', () => { describe('without default options', () => { let fixture: ComponentFixture<SimpleMatSortApp>; let component: SimpleMatSortApp; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ MatSortModule, MatTableModule, CdkTableModule, NoopAnimationsModule, SimpleMatSortApp, CdkTableMatSortApp, MatTableMatSortApp, MatSortHeaderMissingMatSortApp, MatSortDuplicateMatSortableIdsApp, MatSortableMissingIdApp, MatSortableInvalidDirection, MatSortableInvalidDirection, MatSortWithArrowPosition, ], }); })); beforeEach(() => { fixture = TestBed.createComponent(SimpleMatSortApp); component = fixture.componentInstance; fixture.detectChanges(); }); it('should have the sort headers register and deregister themselves', () => { const sortables = component.matSort.sortables; expect(sortables.size).toBe(4); expect(sortables.get('defaultA')).toBe(component.defaultA); expect(sortables.get('defaultB')).toBe(component.defaultB); fixture.destroy(); expect(sortables.size).toBe(0); }); it('should mark itself as initialized', fakeAsync(() => { let isMarkedInitialized = false; component.matSort.initialized.subscribe(() => (isMarkedInitialized = true)); tick(); expect(isMarkedInitialized).toBeTruthy(); })); it('should use the column definition if used within a cdk table', () => { const cdkTableMatSortAppFixture = TestBed.createComponent(CdkTableMatSortApp); const cdkTableMatSortAppComponent = cdkTableMatSortAppFixture.componentInstance; cdkTableMatSortAppFixture.detectChanges(); const sortables = cdkTableMatSortAppComponent.matSort.sortables; expect(sortables.size).toBe(3); expect(sortables.has('column_a')).toBe(true); expect(sortables.has('column_b')).toBe(true); expect(sortables.has('column_c')).toBe(true); }); it('should use the column definition if used within an mat table', () => { const matTableMatSortAppFixture = TestBed.createComponent(MatTableMatSortApp); const matTableMatSortAppComponent = matTableMatSortAppFixture.componentInstance; matTableMatSortAppFixture.detectChanges(); const sortables = matTableMatSortAppComponent.matSort.sortables; expect(sortables.size).toBe(3); expect(sortables.has('column_a')).toBe(true); expect(sortables.has('column_b')).toBe(true); expect(sortables.has('column_c')).toBe(true); }); describe('checking correct arrow direction and view state for its various states', () => { let expectedStates: Map<string, {viewState: string; arrowDirection: string}>; beforeEach(() => { // Starting state for the view and directions - note that overrideStart is reversed to be // desc expectedStates = new Map<string, {viewState: string; arrowDirection: string}>([ ['defaultA', {viewState: 'asc', arrowDirection: 'asc'}], ['defaultB', {viewState: 'asc', arrowDirection: 'asc'}], ['overrideStart', {viewState: 'desc', arrowDirection: 'desc'}], ['overrideDisableClear', {viewState: 'asc', arrowDirection: 'asc'}], ]); component.expectViewAndDirectionStates(expectedStates); }); it('should be correct when mousing over headers and leaving on mouseleave', () => { // Mousing over the first sort should set the view state to hint (asc) component.dispatchMouseEvent('defaultA', 'mouseenter'); expectedStates.set('defaultA', {viewState: 'asc-to-hint', arrowDirection: 'asc'}); component.expectViewAndDirectionStates(expectedStates); // Mousing away from the first sort should hide the arrow component.dispatchMouseEvent('defaultA', 'mouseleave'); expectedStates.set('defaultA', {viewState: 'hint-to-asc', arrowDirection: 'asc'}); component.expectViewAndDirectionStates(expectedStates); // Mousing over another sort should set the view state to hint (desc) component.dispatchMouseEvent('overrideStart', 'mouseenter'); expectedStates.set('overrideStart', {viewState: 'desc-to-hint', arrowDirection: 'desc'}); component.expectViewAndDirectionStates(expectedStates); }); it('should be correct when mousing over header and then sorting', () => { // Mousing over the first sort should set the view state to hint component.dispatchMouseEvent('defaultA', 'mouseenter'); expectedStates.set('defaultA', {viewState: 'asc-to-hint', arrowDirection: 'asc'}); component.expectViewAndDirectionStates(expectedStates); // Clicking sort on the header should set it to be active immediately // (since it was already hinted) component.dispatchMouseEvent('defaultA', 'click'); expectedStates.set('defaultA', {viewState: 'active', arrowDirection: 'active-asc'}); component.expectViewAndDirectionStates(expectedStates); }); it('should be correct when cycling through a default sort header', () => { // Sort the header to set it to the active start state component.sort('defaultA'); expectedStates.set('defaultA', {viewState: 'asc-to-active', arrowDirection: 'active-asc'}); component.expectViewAndDirectionStates(expectedStates); // Sorting again will reverse its direction component.dispatchMouseEvent('defaultA', 'click'); expectedStates.set('defaultA', {viewState: 'active', arrowDirection: 'active-desc'}); component.expectViewAndDirectionStates(expectedStates); // Sorting again will remove the sort and animate away the view component.dispatchMouseEvent('defaultA', 'click'); expectedStates.set('defaultA', {viewState: 'active-to-desc', arrowDirection: 'desc'}); component.expectViewAndDirectionStates(expectedStates); }); it('should not enter sort with animations if an animations is disabled', () => { // Sort the header to set it to the active start state component.defaultA._disableViewStateAnimation = true; component.sort('defaultA'); expectedStates.set('defaultA', {viewState: 'active', arrowDirection: 'active-asc'}); component.expectViewAndDirectionStates(expectedStates); // Sorting again will reverse its direction component.defaultA._disableViewStateAnimation = true; component.dispatchMouseEvent('defaultA', 'click'); expectedStates.set('defaultA', {viewState: 'active', arrowDirection: 'active-desc'}); component.expectViewAndDirectionStates(expectedStates); }); it('should be correct when sort has changed while a header is active', () => { // Sort the first header to set up component.sort('defaultA'); expectedStates.set('defaultA', {viewState: 'asc-to-active', arrowDirection: 'active-asc'}); component.expectViewAndDirectionStates(expectedStates); // Sort the second header and verify that the first header animated away component.dispatchMouseEvent('defaultB', 'click'); expectedStates.set('defaultA', {viewState: 'active-to-asc', arrowDirection: 'asc'}); expectedStates.set('defaultB', {viewState: 'asc-to-active', arrowDirection: 'active-asc'}); component.expectViewAndDirectionStates(expectedStates); }); it('should be correct when sort has been disabled', () => { // Mousing over the first sort should set the view state to hint component.disabledColumnSort = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); component.dispatchMouseEvent('defaultA', 'mouseenter'); component.expectViewAndDirectionStates(expectedStates); }); it('should be correct when sorting programmatically', () => { component.active = 'defaultB'; component.direction = 'asc'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expectedStates.set('defaultB', {viewState: 'asc-to-active', arrowDirection: 'active-asc'}); component.expectViewAndDirectionStates(expectedStates); }); }); it('should be able to cycle from asc -> desc from either start point', () => { component.disableClear = true; component.start = 'asc'; fixture.changeDetectorRef.markForCheck(); testSingleColumnSortDirectionSequence(fixture, ['asc', 'desc']); // Reverse directions component.start = 'desc'; fixture.changeDetectorRef.markForCheck(); testSingleColumnSortDirectionSequence(fixture, ['desc', 'asc']); }); it('should be able to cycle asc -> desc -> [none]', () => { component.start = 'asc'; fixture.changeDetectorRef.markForCheck(); testSingleColumnSortDirectionSequence(fixture, ['asc', 'desc', '']); }); it('should be able to cycle desc -> asc -> [none]', () => { component.start = 'desc'; fixture.changeDetectorRef.markForCheck(); testSingleColumnSortDirectionSequence(fixture, ['desc', 'asc', '']); });
{ "end_byte": 10272, "start_byte": 969, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort.spec.ts" }
components/src/material/sort/sort.spec.ts_10278_20837
it('should allow for the cycling the sort direction to be disabled per column', () => { const container = fixture.nativeElement.querySelector('#defaultA .mat-sort-header-container'); component.sort('defaultA'); expect(component.matSort.direction).toBe('asc'); expect(container.getAttribute('tabindex')).toBe('0'); expect(container.getAttribute('role')).toBe('button'); component.disabledColumnSort = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); component.sort('defaultA'); expect(component.matSort.direction).toBe('asc'); expect(container.hasAttribute('tabindex')).toBe(false); expect(container.hasAttribute('role')).toBe(false); }); it('should allow for the cycling the sort direction to be disabled for all columns', () => { const container = fixture.nativeElement.querySelector('#defaultA .mat-sort-header-container'); component.sort('defaultA'); expect(component.matSort.active).toBe('defaultA'); expect(component.matSort.direction).toBe('asc'); expect(container.getAttribute('tabindex')).toBe('0'); component.disableAllSort = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); component.sort('defaultA'); expect(component.matSort.active).toBe('defaultA'); expect(component.matSort.direction).toBe('asc'); expect(container.getAttribute('tabindex')).toBeFalsy(); component.sort('defaultB'); expect(component.matSort.active).toBe('defaultA'); expect(component.matSort.direction).toBe('asc'); expect(container.getAttribute('tabindex')).toBeFalsy(); }); it('should reset sort direction when a different column is sorted', () => { component.sort('defaultA'); expect(component.matSort.active).toBe('defaultA'); expect(component.matSort.direction).toBe('asc'); component.sort('defaultA'); expect(component.matSort.active).toBe('defaultA'); expect(component.matSort.direction).toBe('desc'); component.sort('defaultB'); expect(component.matSort.active).toBe('defaultB'); expect(component.matSort.direction).toBe('asc'); }); it( 'should throw an error if an MatSortable is not contained within an MatSort ' + 'directive', () => { expect(() => TestBed.createComponent(MatSortHeaderMissingMatSortApp).detectChanges(), ).toThrowError(wrappedErrorMessage(getSortHeaderNotContainedWithinSortError())); }, ); it('should throw an error if two MatSortables have the same id', () => { expect(() => TestBed.createComponent(MatSortDuplicateMatSortableIdsApp).detectChanges(), ).toThrowError(wrappedErrorMessage(getSortDuplicateSortableIdError('duplicateId'))); }); it('should throw an error if an MatSortable is missing an id', () => { expect(() => TestBed.createComponent(MatSortableMissingIdApp).detectChanges()).toThrowError( wrappedErrorMessage(getSortHeaderMissingIdError()), ); }); it('should throw an error if the provided direction is invalid', () => { expect(() => TestBed.createComponent(MatSortableInvalidDirection).detectChanges(), ).toThrowError(wrappedErrorMessage(getSortInvalidDirectionError('ascending'))); }); it('should allow let MatSortable override the default sort parameters', () => { testSingleColumnSortDirectionSequence(fixture, ['asc', 'desc', '']); testSingleColumnSortDirectionSequence(fixture, ['desc', 'asc', ''], 'overrideStart'); testSingleColumnSortDirectionSequence(fixture, ['asc', 'desc'], 'overrideDisableClear'); }); it('should toggle indicator hint on button focus/blur and hide on click', () => { const header = fixture.componentInstance.defaultA; const container = fixture.nativeElement.querySelector('#defaultA .mat-sort-header-container'); const focusEvent = createFakeEvent('focus'); const blurEvent = createFakeEvent('blur'); // Should start without a displayed hint expect(header._showIndicatorHint).toBeFalsy(); // Focusing the button should show the hint, blurring should hide it container.dispatchEvent(focusEvent); expect(header._showIndicatorHint).toBeTruthy(); container.dispatchEvent(blurEvent); expect(header._showIndicatorHint).toBeFalsy(); // Show the indicator hint. On click the hint should be hidden container.dispatchEvent(focusEvent); expect(header._showIndicatorHint).toBeTruthy(); header._handleClick(); expect(header._showIndicatorHint).toBeFalsy(); }); it('should toggle indicator hint on mouseenter/mouseleave and hide on click', () => { const header = fixture.componentInstance.defaultA; const headerElement = fixture.nativeElement.querySelector('#defaultA'); const mouseenterEvent = createMouseEvent('mouseenter'); const mouseleaveEvent = createMouseEvent('mouseleave'); // Should start without a displayed hint expect(header._showIndicatorHint).toBeFalsy(); // Mouse enter should show the hint, blurring should hide it headerElement.dispatchEvent(mouseenterEvent); expect(header._showIndicatorHint).toBeTruthy(); headerElement.dispatchEvent(mouseleaveEvent); expect(header._showIndicatorHint).toBeFalsy(); // Show the indicator hint. On click the hint should be hidden headerElement.dispatchEvent(mouseenterEvent); expect(header._showIndicatorHint).toBeTruthy(); header._handleClick(); expect(header._showIndicatorHint).toBeFalsy(); }); it('should apply the aria-sort label to the header when sorted', () => { const sortHeaderElement = fixture.nativeElement.querySelector('#defaultA'); expect(sortHeaderElement.getAttribute('aria-sort')).toBe('none'); component.sort('defaultA'); fixture.detectChanges(); expect(sortHeaderElement.getAttribute('aria-sort')).toBe('ascending'); component.sort('defaultA'); fixture.detectChanges(); expect(sortHeaderElement.getAttribute('aria-sort')).toBe('descending'); component.sort('defaultA'); fixture.detectChanges(); expect(sortHeaderElement.getAttribute('aria-sort')).toBe('none'); }); it('should not render the arrow if sorting is disabled for that column', fakeAsync(() => { const sortHeaderElement = fixture.nativeElement.querySelector('#defaultA'); // Switch sorting to a different column before asserting. component.sort('defaultB'); fixture.componentInstance.disabledColumnSort = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(sortHeaderElement.querySelector('.mat-sort-header-arrow')).toBeFalsy(); })); it('should render the arrow if a disabled column is being sorted by', fakeAsync(() => { const sortHeaderElement = fixture.nativeElement.querySelector('#defaultA'); component.sort('defaultA'); fixture.componentInstance.disabledColumnSort = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(sortHeaderElement.querySelector('.mat-sort-header-arrow')).toBeTruthy(); })); it('should have a focus indicator', () => { const headerNativeElement = fixture.debugElement.query( By.directive(MatSortHeader), )!.nativeElement; const container = headerNativeElement.querySelector('.mat-sort-header-container'); expect(container.classList.contains('mat-focus-indicator')).toBe(true); }); it('should add a default aria description to sort buttons', () => { const sortButton = fixture.nativeElement.querySelector('.mat-sort-header-container'); const descriptionId = sortButton.getAttribute('aria-describedby'); expect(descriptionId).toBeDefined(); const descriptionElement = document.getElementById(descriptionId); expect(descriptionElement?.textContent).toBe('Sort'); }); it('should add a custom aria description to sort buttons', () => { const sortButton = fixture.nativeElement.querySelector( '#defaultB .mat-sort-header-container', ); let descriptionId = sortButton.getAttribute('aria-describedby'); expect(descriptionId).toBeDefined(); let descriptionElement = document.getElementById(descriptionId); expect(descriptionElement?.textContent).toBe('Sort second column'); fixture.componentInstance.secondColumnDescription = 'Sort 2nd column'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); descriptionId = sortButton.getAttribute('aria-describedby'); descriptionElement = document.getElementById(descriptionId); expect(descriptionElement?.textContent).toBe('Sort 2nd column'); }); it('should render arrows after sort header by default', () => { const matSortWithArrowPositionFixture = TestBed.createComponent(MatSortWithArrowPosition); matSortWithArrowPositionFixture.detectChanges(); const containerA = matSortWithArrowPositionFixture.nativeElement.querySelector( '#defaultA .mat-sort-header-container', ); const containerB = matSortWithArrowPositionFixture.nativeElement.querySelector( '#defaultB .mat-sort-header-container', ); expect(containerA.classList.contains('mat-sort-header-position-before')).toBe(false); expect(containerB.classList.contains('mat-sort-header-position-before')).toBe(false); }); it('should render arrows before if appropriate parameter passed', () => { const matSortWithArrowPositionFixture = TestBed.createComponent(MatSortWithArrowPosition); const matSortWithArrowPositionComponent = matSortWithArrowPositionFixture.componentInstance; matSortWithArrowPositionComponent.arrowPosition = 'before'; matSortWithArrowPositionFixture.detectChanges(); const containerA = matSortWithArrowPositionFixture.nativeElement.querySelector( '#defaultA .mat-sort-header-container', ); const containerB = matSortWithArrowPositionFixture.nativeElement.querySelector( '#defaultB .mat-sort-header-container', ); expect(containerA.classList.contains('mat-sort-header-position-before')).toBe(true); expect(containerB.classList.contains('mat-sort-header-position-before')).toBe(true); });
{ "end_byte": 20837, "start_byte": 10278, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort.spec.ts" }
components/src/material/sort/sort.spec.ts_20843_28994
it('should render arrows in proper position based on arrowPosition parameter', () => { const matSortWithArrowPositionFixture = TestBed.createComponent(MatSortWithArrowPosition); const matSortWithArrowPositionComponent = matSortWithArrowPositionFixture.componentInstance; matSortWithArrowPositionFixture.detectChanges(); const containerA = matSortWithArrowPositionFixture.nativeElement.querySelector( '#defaultA .mat-sort-header-container', ); const containerB = matSortWithArrowPositionFixture.nativeElement.querySelector( '#defaultB .mat-sort-header-container', ); expect(containerA.classList.contains('mat-sort-header-position-before')).toBe(false); expect(containerB.classList.contains('mat-sort-header-position-before')).toBe(false); matSortWithArrowPositionComponent.arrowPosition = 'before'; matSortWithArrowPositionFixture.changeDetectorRef.markForCheck(); matSortWithArrowPositionFixture.detectChanges(); expect(containerA.classList.contains('mat-sort-header-position-before')).toBe(true); expect(containerB.classList.contains('mat-sort-header-position-before')).toBe(true); }); }); describe('with default options', () => { let fixture: ComponentFixture<MatSortWithoutExplicitInputs>; let component: MatSortWithoutExplicitInputs; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ MatSortModule, MatTableModule, CdkTableModule, NoopAnimationsModule, MatSortWithoutExplicitInputs, ], providers: [ { provide: MAT_SORT_DEFAULT_OPTIONS, useValue: { disableClear: true, }, }, ], }); })); beforeEach(() => { fixture = TestBed.createComponent(MatSortWithoutExplicitInputs); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be able to cycle from asc -> desc from either start point', () => { component.start = 'asc'; testSingleColumnSortDirectionSequence(fixture, ['asc', 'desc']); // Reverse directions component.start = 'desc'; testSingleColumnSortDirectionSequence(fixture, ['desc', 'asc']); }); }); describe('with default arrowPosition', () => { let fixture: ComponentFixture<MatSortWithoutInputs>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ MatSortModule, MatTableModule, CdkTableModule, NoopAnimationsModule, MatSortWithoutInputs, ], providers: [ { provide: MAT_SORT_DEFAULT_OPTIONS, useValue: { disableClear: true, arrowPosition: 'before', }, }, ], }); })); beforeEach(() => { fixture = TestBed.createComponent(MatSortWithoutInputs); fixture.detectChanges(); }); it('should render arrows in proper position', () => { const containerA = fixture.nativeElement.querySelector( '#defaultA .mat-sort-header-container', ); const containerB = fixture.nativeElement.querySelector( '#defaultB .mat-sort-header-container', ); expect(containerA.classList.contains('mat-sort-header-position-before')).toBe(true); expect(containerB.classList.contains('mat-sort-header-position-before')).toBe(true); }); }); }); /** * Performs a sequence of sorting on a single column to see if the sort directions are * consistent with expectations. Detects any changes in the fixture to reflect any changes in * the inputs and resets the MatSort to remove any side effects from previous tests. */ function testSingleColumnSortDirectionSequence( fixture: ComponentFixture<SimpleMatSortApp | MatSortWithoutExplicitInputs>, expectedSequence: SortDirection[], id: SimpleMatSortAppColumnIds = 'defaultA', ) { // Detect any changes that were made in preparation for this sort sequence fixture.detectChanges(); // Reset the sort to make sure there are no side affects from previous tests const component = fixture.componentInstance; component.matSort.active = ''; component.matSort.direction = ''; // Run through the sequence to confirm the order const actualSequence = expectedSequence.map(() => { component.sort(id); // Check that the sort event's active sort is consistent with the MatSort expect(component.matSort.active).toBe(id); expect(component.latestSortEvent.active).toBe(id); // Check that the sort event's direction is consistent with the MatSort expect(component.matSort.direction).toBe(component.latestSortEvent.direction); return component.matSort.direction; }); expect(actualSequence).toEqual(expectedSequence); // Expect that performing one more sort will loop it back to the beginning. component.sort(id); expect(component.matSort.direction).toBe(expectedSequence[0]); } /** Column IDs of the SimpleMatSortApp for typing of function params in the component (e.g. sort) */ type SimpleMatSortAppColumnIds = 'defaultA' | 'defaultB' | 'overrideStart' | 'overrideDisableClear'; @Component({ template: ` <div matSort [matSortActive]="active" [matSortDisabled]="disableAllSort" [matSortStart]="start" [matSortDirection]="direction" [matSortDisableClear]="disableClear" (matSortChange)="latestSortEvent = $event"> <div id="defaultA" #defaultA mat-sort-header="defaultA" [disabled]="disabledColumnSort"> A </div> <div id="defaultB" #defaultB mat-sort-header="defaultB" [sortActionDescription]="secondColumnDescription"> B </div> <div id="overrideStart" #overrideStart mat-sort-header="overrideStart" start="desc"> D </div> <div id="overrideDisableClear" #overrideDisableClear mat-sort-header="overrideDisableClear" disableClear> E </div> </div> `, standalone: true, imports: [MatSortModule, MatTableModule, CdkTableModule], }) class SimpleMatSortApp { elementRef = inject<ElementRef<HTMLElement>>(ElementRef); latestSortEvent: Sort; active: string; start: SortDirection = 'asc'; direction: SortDirection = ''; disableClear: boolean; disabledColumnSort = false; disableAllSort = false; secondColumnDescription = 'Sort second column'; @ViewChild(MatSort) matSort: MatSort; @ViewChild('defaultA') defaultA: MatSortHeader; @ViewChild('defaultB') defaultB: MatSortHeader; @ViewChild('overrideStart') overrideStart: MatSortHeader; @ViewChild('overrideDisableClear') overrideDisableClear: MatSortHeader; sort(id: SimpleMatSortAppColumnIds) { this.dispatchMouseEvent(id, 'click'); } dispatchMouseEvent(id: SimpleMatSortAppColumnIds, event: string) { const sortElement = this.elementRef.nativeElement.querySelector(`#${id}`)!; dispatchMouseEvent(sortElement, event); } /** * Checks expectations for each sort header's view state and arrow direction states. Receives a * map that is keyed by each sort header's ID and contains the expectation for that header's * states. */ expectViewAndDirectionStates( viewStates: Map<string, {viewState: string; arrowDirection: string}>, ) { const sortHeaders = new Map([ ['defaultA', this.defaultA], ['defaultB', this.defaultB], ['overrideStart', this.overrideStart], ['overrideDisableClear', this.overrideDisableClear], ]); viewStates.forEach((viewState, id) => { expect(sortHeaders.get(id)!._getArrowViewState()).toEqual(viewState.viewState); expect(sortHeaders.get(id)!._getArrowDirectionState()).toEqual(viewState.arrowDirection); }); } } class FakeDataSource extends DataSource<any> { connect(collectionViewer: CollectionViewer): Observable<any[]> { return collectionViewer.viewChange.pipe(map(() => [])); } disconnect() {} }
{ "end_byte": 28994, "start_byte": 20843, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort.spec.ts" }
components/src/material/sort/sort.spec.ts_28996_34303
@Component({ template: ` <cdk-table [dataSource]="dataSource" matSort> <ng-container cdkColumnDef="column_a"> <cdk-header-cell *cdkHeaderCellDef #sortHeaderA mat-sort-header> Column A </cdk-header-cell> <cdk-cell *cdkCellDef="let row"> {{row.a}} </cdk-cell> </ng-container> <ng-container cdkColumnDef="column_b"> <cdk-header-cell *cdkHeaderCellDef #sortHeaderB mat-sort-header> Column B </cdk-header-cell> <cdk-cell *cdkCellDef="let row"> {{row.b}} </cdk-cell> </ng-container> <ng-container cdkColumnDef="column_c"> <cdk-header-cell *cdkHeaderCellDef #sortHeaderC mat-sort-header> Column C </cdk-header-cell> <cdk-cell *cdkCellDef="let row"> {{row.c}} </cdk-cell> </ng-container> <cdk-header-row *cdkHeaderRowDef="columnsToRender"></cdk-header-row> <cdk-row *cdkRowDef="let row; columns: columnsToRender"></cdk-row> </cdk-table> `, standalone: true, imports: [MatSortModule, MatTableModule, CdkTableModule], }) class CdkTableMatSortApp { @ViewChild(MatSort) matSort: MatSort; dataSource = new FakeDataSource(); columnsToRender = ['column_a', 'column_b', 'column_c']; } @Component({ template: ` <mat-table [dataSource]="dataSource" matSort> <ng-container matColumnDef="column_a"> <mat-header-cell *matHeaderCellDef #sortHeaderA mat-sort-header> Column A </mat-header-cell> <mat-cell *matCellDef="let row"> {{row.a}} </mat-cell> </ng-container> <ng-container matColumnDef="column_b"> <mat-header-cell *matHeaderCellDef #sortHeaderB mat-sort-header> Column B </mat-header-cell> <mat-cell *matCellDef="let row"> {{row.b}} </mat-cell> </ng-container> <ng-container matColumnDef="column_c"> <mat-header-cell *matHeaderCellDef #sortHeaderC mat-sort-header> Column C </mat-header-cell> <mat-cell *matCellDef="let row"> {{row.c}} </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="columnsToRender"></mat-header-row> <mat-row *matRowDef="let row; columns: columnsToRender"></mat-row> </mat-table> `, standalone: true, imports: [MatSortModule, MatTableModule, CdkTableModule], }) class MatTableMatSortApp { @ViewChild(MatSort) matSort: MatSort; dataSource = new FakeDataSource(); columnsToRender = ['column_a', 'column_b', 'column_c']; } @Component({ template: `<div mat-sort-header="a"> A </div>`, standalone: true, imports: [MatSortModule, MatTableModule, CdkTableModule], }) class MatSortHeaderMissingMatSortApp {} @Component({ template: ` <div matSort> <div mat-sort-header="duplicateId"> A </div> <div mat-sort-header="duplicateId"> A </div> </div> `, standalone: true, imports: [MatSortModule, MatTableModule, CdkTableModule], }) class MatSortDuplicateMatSortableIdsApp {} @Component({ template: ` <div matSort> <div mat-sort-header> A </div> </div> `, standalone: true, imports: [MatSortModule, MatTableModule, CdkTableModule], }) class MatSortableMissingIdApp {} @Component({ template: ` <div matSort matSortDirection="ascending"> <div mat-sort-header="a"> A </div> </div> `, standalone: true, imports: [MatSortModule, MatTableModule, CdkTableModule], }) class MatSortableInvalidDirection {} @Component({ template: ` <div matSort [matSortActive]="active" [matSortStart]="start" (matSortChange)="latestSortEvent = $event"> <div id="defaultA" #defaultA mat-sort-header="defaultA"> A </div> </div> `, standalone: true, imports: [MatSortModule, MatTableModule, CdkTableModule], }) class MatSortWithoutExplicitInputs { elementRef = inject<ElementRef<HTMLElement>>(ElementRef); latestSortEvent: Sort; active: string; start: SortDirection = 'asc'; @ViewChild(MatSort) matSort: MatSort; @ViewChild('defaultA') defaultA: MatSortHeader; sort(id: SimpleMatSortAppColumnIds) { this.dispatchMouseEvent(id, 'click'); } dispatchMouseEvent(id: SimpleMatSortAppColumnIds, event: string) { const sortElement = this.elementRef.nativeElement.querySelector(`#${id}`)!; dispatchMouseEvent(sortElement, event); } } @Component({ template: ` <div matSort> <div id="defaultA" #defaultA mat-sort-header="defaultA" [arrowPosition]="arrowPosition"> A </div> <div id="defaultB" #defaultB mat-sort-header="defaultB" [arrowPosition]="arrowPosition"> B </div> </div> `, standalone: true, imports: [MatSortModule, MatTableModule, CdkTableModule], }) class MatSortWithArrowPosition { arrowPosition?: 'before' | 'after'; @ViewChild(MatSort) matSort: MatSort; @ViewChild('defaultA') defaultA: MatSortHeader; @ViewChild('defaultB') defaultB: MatSortHeader; } @Component({ template: ` <div matSort> <div id="defaultA" #defaultA mat-sort-header="defaultA"> A </div> <div id="defaultB" #defaultB mat-sort-header="defaultB"> B </div> </div> `, standalone: true, imports: [MatSortModule, MatTableModule, CdkTableModule], }) class MatSortWithoutInputs { @ViewChild(MatSort) matSort: MatSort; @ViewChild('defaultA') defaultA: MatSortHeader; @ViewChild('defaultB') defaultB: MatSortHeader; }
{ "end_byte": 34303, "start_byte": 28996, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort.spec.ts" }
components/src/material/sort/_sort-theme.scss_0_2834
@use 'sass:map'; @use '../core/tokens/m2/mat/sort' as tokens-mat-sort; @use '../core/style/sass-utils'; @use '../core/typography/typography'; @use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @use '../core/tokens/token-utils'; @mixin base($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, base)); } @else { } } @mixin color($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, color)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mat-sort.$prefix, tokens-mat-sort.get-color-tokens($theme) ); } } } @mixin typography($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, typography)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mat-sort.$prefix, tokens-mat-sort.get-typography-tokens($theme) ); } } } @mixin density($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, density)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mat-sort.$prefix, tokens-mat-sort.get-density-tokens($theme) ); } } } /// Defines the tokens that will be available in the `overrides` mixin and for docs extraction. @function _define-overrides() { @return ( ( namespace: tokens-mat-sort.$prefix, tokens: tokens-mat-sort.get-token-slots(), ), ); } @mixin overrides($tokens: ()) { @include token-utils.batch-create-token-values($tokens, _define-overrides()...); } @mixin theme($theme) { @include theming.private-check-duplicate-theme-styles($theme, 'mat-sort') { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme)); } @else { @include base($theme); @if inspection.theme-has($theme, color) { @include color($theme); } @if inspection.theme-has($theme, density) { @include density($theme); } @if inspection.theme-has($theme, typography) { @include typography($theme); } } } } @mixin _theme-from-tokens($tokens) { @include validation.selector-defined( 'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector' ); @if ($tokens != ()) { @include token-utils.create-token-values( tokens-mat-sort.$prefix, map.get($tokens, tokens-mat-sort.$prefix) ); } }
{ "end_byte": 2834, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sort/_sort-theme.scss" }
components/src/material/sort/sort-header.ts_0_3133
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {AriaDescriber, FocusMonitor} from '@angular/cdk/a11y'; import {ENTER, SPACE} from '@angular/cdk/keycodes'; import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, Input, OnDestroy, OnInit, ViewEncapsulation, booleanAttribute, inject, } from '@angular/core'; import {merge, Subscription} from 'rxjs'; import { MAT_SORT_DEFAULT_OPTIONS, MatSort, MatSortable, MatSortDefaultOptions, SortHeaderArrowPosition, } from './sort'; import {matSortAnimations} from './sort-animations'; import {SortDirection} from './sort-direction'; import {getSortHeaderNotContainedWithinSortError} from './sort-errors'; import {MatSortHeaderIntl} from './sort-header-intl'; import {_CdkPrivateStyleLoader} from '@angular/cdk/private'; import {_StructuralStylesLoader} from '@angular/material/core'; /** * Valid positions for the arrow to be in for its opacity and translation. If the state is a * sort direction, the position of the arrow will be above/below and opacity 0. If the state is * hint, the arrow will be in the center with a slight opacity. Active state means the arrow will * be fully opaque in the center. * * @docs-private */ export type ArrowViewState = SortDirection | 'hint' | 'active'; /** * States describing the arrow's animated position (animating fromState to toState). * If the fromState is not defined, there will be no animated transition to the toState. * @docs-private */ export interface ArrowViewStateTransition { fromState?: ArrowViewState; toState?: ArrowViewState; } /** Column definition associated with a `MatSortHeader`. */ interface MatSortHeaderColumnDef { name: string; } /** * Applies sorting behavior (click to change sort) and styles to an element, including an * arrow to display the current sort direction. * * Must be provided with an id and contained within a parent MatSort directive. * * If used on header cells in a CdkTable, it will automatically default its id from its containing * column definition. */ @Component({ selector: '[mat-sort-header]', exportAs: 'matSortHeader', templateUrl: 'sort-header.html', styleUrl: 'sort-header.css', host: { 'class': 'mat-sort-header', '(click)': '_handleClick()', '(keydown)': '_handleKeydown($event)', '(mouseenter)': '_setIndicatorHintVisible(true)', '(mouseleave)': '_setIndicatorHintVisible(false)', '[attr.aria-sort]': '_getAriaSortAttribute()', '[class.mat-sort-header-disabled]': '_isDisabled()', }, encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, animations: [ matSortAnimations.indicator, matSortAnimations.leftPointer, matSortAnimations.rightPointer, matSortAnimations.arrowOpacity, matSortAnimations.arrowPosition, matSortAnimations.allowChildren, ], }) export class MatSortHeader implements MatSortable, OnDestroy, OnInit, AfterViewInit
{ "end_byte": 3133, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort-header.ts" }
components/src/material/sort/sort-header.ts_3134_11670
{ _intl = inject(MatSortHeaderIntl); private _changeDetectorRef = inject(ChangeDetectorRef); _sort = inject(MatSort, {optional: true})!; _columnDef = inject<MatSortHeaderColumnDef>('MAT_SORT_HEADER_COLUMN_DEF' as any, { optional: true, }); private _focusMonitor = inject(FocusMonitor); private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef); private _ariaDescriber = inject(AriaDescriber, {optional: true}); private _rerenderSubscription: Subscription; /** * The element with role="button" inside this component's view. We need this * in order to apply a description with AriaDescriber. */ private _sortButton: HTMLElement; /** * Flag set to true when the indicator should be displayed while the sort is not active. Used to * provide an affordance that the header is sortable by showing on focus and hover. */ _showIndicatorHint: boolean = false; /** * The view transition state of the arrow (translation/ opacity) - indicates its `from` and `to` * position through the animation. If animations are currently disabled, the fromState is removed * so that there is no animation displayed. */ _viewState: ArrowViewStateTransition = {}; /** The direction the arrow should be facing according to the current state. */ _arrowDirection: SortDirection = ''; /** * Whether the view state animation should show the transition between the `from` and `to` states. */ _disableViewStateAnimation = false; /** * ID of this sort header. If used within the context of a CdkColumnDef, this will default to * the column's name. */ @Input('mat-sort-header') id: string; /** Sets the position of the arrow that displays when sorted. */ @Input() arrowPosition: SortHeaderArrowPosition = 'after'; /** Overrides the sort start value of the containing MatSort for this MatSortable. */ @Input() start: SortDirection; /** whether the sort header is disabled. */ @Input({transform: booleanAttribute}) disabled: boolean = false; /** * Description applied to MatSortHeader's button element with aria-describedby. This text should * describe the action that will occur when the user clicks the sort header. */ @Input() get sortActionDescription(): string { return this._sortActionDescription; } set sortActionDescription(value: string) { this._updateSortActionDescription(value); } // Default the action description to "Sort" because it's better than nothing. // Without a description, the button's label comes from the sort header text content, // which doesn't give any indication that it performs a sorting operation. private _sortActionDescription: string = 'Sort'; /** Overrides the disable clear value of the containing MatSort for this MatSortable. */ @Input({transform: booleanAttribute}) disableClear: boolean; constructor(...args: unknown[]); constructor() { inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader); const defaultOptions = inject<MatSortDefaultOptions>(MAT_SORT_DEFAULT_OPTIONS, { optional: true, }); // Note that we use a string token for the `_columnDef`, because the value is provided both by // `material/table` and `cdk/table` and we can't have the CDK depending on Material, // and we want to avoid having the sort header depending on the CDK table because // of this single reference. if (!this._sort && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw getSortHeaderNotContainedWithinSortError(); } if (defaultOptions?.arrowPosition) { this.arrowPosition = defaultOptions?.arrowPosition; } this._handleStateChanges(); } ngOnInit() { if (!this.id && this._columnDef) { this.id = this._columnDef.name; } // Initialize the direction of the arrow and set the view state to be immediately that state. this._updateArrowDirection(); this._setAnimationTransitionState({ toState: this._isSorted() ? 'active' : this._arrowDirection, }); this._sort.register(this); this._sortButton = this._elementRef.nativeElement.querySelector('.mat-sort-header-container')!; this._updateSortActionDescription(this._sortActionDescription); } ngAfterViewInit() { // We use the focus monitor because we also want to style // things differently based on the focus origin. this._focusMonitor.monitor(this._elementRef, true).subscribe(origin => { const newState = !!origin; if (newState !== this._showIndicatorHint) { this._setIndicatorHintVisible(newState); this._changeDetectorRef.markForCheck(); } }); } ngOnDestroy() { this._focusMonitor.stopMonitoring(this._elementRef); this._sort.deregister(this); this._rerenderSubscription.unsubscribe(); if (this._sortButton) { this._ariaDescriber?.removeDescription(this._sortButton, this._sortActionDescription); } } /** * Sets the "hint" state such that the arrow will be semi-transparently displayed as a hint to the * user showing what the active sort will become. If set to false, the arrow will fade away. */ _setIndicatorHintVisible(visible: boolean) { // No-op if the sort header is disabled - should not make the hint visible. if (this._isDisabled() && visible) { return; } this._showIndicatorHint = visible; if (!this._isSorted()) { this._updateArrowDirection(); if (this._showIndicatorHint) { this._setAnimationTransitionState({fromState: this._arrowDirection, toState: 'hint'}); } else { this._setAnimationTransitionState({fromState: 'hint', toState: this._arrowDirection}); } } } /** * Sets the animation transition view state for the arrow's position and opacity. If the * `disableViewStateAnimation` flag is set to true, the `fromState` will be ignored so that * no animation appears. */ _setAnimationTransitionState(viewState: ArrowViewStateTransition) { this._viewState = viewState || {}; // If the animation for arrow position state (opacity/translation) should be disabled, // remove the fromState so that it jumps right to the toState. if (this._disableViewStateAnimation) { this._viewState = {toState: viewState.toState}; } } /** Triggers the sort on this sort header and removes the indicator hint. */ _toggleOnInteraction() { this._sort.sort(this); // Do not show the animation if the header was already shown in the right position. if (this._viewState.toState === 'hint' || this._viewState.toState === 'active') { this._disableViewStateAnimation = true; } } _handleClick() { if (!this._isDisabled()) { this._sort.sort(this); } } _handleKeydown(event: KeyboardEvent) { if (!this._isDisabled() && (event.keyCode === SPACE || event.keyCode === ENTER)) { event.preventDefault(); this._toggleOnInteraction(); } } /** Whether this MatSortHeader is currently sorted in either ascending or descending order. */ _isSorted() { return ( this._sort.active == this.id && (this._sort.direction === 'asc' || this._sort.direction === 'desc') ); } /** Returns the animation state for the arrow direction (indicator and pointers). */ _getArrowDirectionState() { return `${this._isSorted() ? 'active-' : ''}${this._arrowDirection}`; } /** Returns the arrow position state (opacity, translation). */ _getArrowViewState() { const fromState = this._viewState.fromState; return (fromState ? `${fromState}-to-` : '') + this._viewState.toState; } /** * Updates the direction the arrow should be pointing. If it is not sorted, the arrow should be * facing the start direction. Otherwise if it is sorted, the arrow should point in the currently * active sorted direction. The reason this is updated through a function is because the direction * should only be changed at specific times - when deactivated but the hint is displayed and when * the sort is active and the direction changes. Otherwise the arrow's direction should linger * in cases such as the sort becoming deactivated but we want to animate the arrow away while * preserving its direction, even though the next sort direction is actually different and should * only be changed once the arrow displays again (hint or activation). */ _updateArrowDirection() { this._arrowDirection = this._isSorted() ? this._sort.direction : this.start || this._sort.start; }
{ "end_byte": 11670, "start_byte": 3134, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort-header.ts" }
components/src/material/sort/sort-header.ts_11674_14339
_isDisabled() { return this._sort.disabled || this.disabled; } /** * Gets the aria-sort attribute that should be applied to this sort header. If this header * is not sorted, returns null so that the attribute is removed from the host element. Aria spec * says that the aria-sort property should only be present on one header at a time, so removing * ensures this is true. */ _getAriaSortAttribute() { if (!this._isSorted()) { return 'none'; } return this._sort.direction == 'asc' ? 'ascending' : 'descending'; } /** Whether the arrow inside the sort header should be rendered. */ _renderArrow() { return !this._isDisabled() || this._isSorted(); } private _updateSortActionDescription(newDescription: string) { // We use AriaDescriber for the sort button instead of setting an `aria-label` because some // screen readers (notably VoiceOver) will read both the column header *and* the button's label // for every *cell* in the table, creating a lot of unnecessary noise. // If _sortButton is undefined, the component hasn't been initialized yet so there's // nothing to update in the DOM. if (this._sortButton) { // removeDescription will no-op if there is no existing message. // TODO(jelbourn): remove optional chaining when AriaDescriber is required. this._ariaDescriber?.removeDescription(this._sortButton, this._sortActionDescription); this._ariaDescriber?.describe(this._sortButton, newDescription); } this._sortActionDescription = newDescription; } /** Handles changes in the sorting state. */ private _handleStateChanges() { this._rerenderSubscription = merge( this._sort.sortChange, this._sort._stateChanges, this._intl.changes, ).subscribe(() => { if (this._isSorted()) { this._updateArrowDirection(); // Do not show the animation if the header was already shown in the right position. if (this._viewState.toState === 'hint' || this._viewState.toState === 'active') { this._disableViewStateAnimation = true; } this._setAnimationTransitionState({fromState: this._arrowDirection, toState: 'active'}); this._showIndicatorHint = false; } // If this header was recently active and now no longer sorted, animate away the arrow. if (!this._isSorted() && this._viewState && this._viewState.toState === 'active') { this._disableViewStateAnimation = false; this._setAnimationTransitionState({fromState: 'active', toState: this._arrowDirection}); } this._changeDetectorRef.markForCheck(); }); } }
{ "end_byte": 14339, "start_byte": 11674, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort-header.ts" }
components/src/material/sort/sort.ts_0_6383
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Directive, EventEmitter, Inject, InjectionToken, Input, OnChanges, OnDestroy, OnInit, Optional, Output, booleanAttribute, } from '@angular/core'; import {Observable, ReplaySubject, Subject} from 'rxjs'; import {SortDirection} from './sort-direction'; import { getSortDuplicateSortableIdError, getSortHeaderMissingIdError, getSortInvalidDirectionError, } from './sort-errors'; /** Position of the arrow that displays when sorted. */ export type SortHeaderArrowPosition = 'before' | 'after'; /** Interface for a directive that holds sorting state consumed by `MatSortHeader`. */ export interface MatSortable { /** The id of the column being sorted. */ id: string; /** Starting sort direction. */ start: SortDirection; /** Whether to disable clearing the sorting state. */ disableClear: boolean; } /** The current sort state. */ export interface Sort { /** The id of the column being sorted. */ active: string; /** The sort direction. */ direction: SortDirection; } /** Default options for `mat-sort`. */ export interface MatSortDefaultOptions { /** Whether to disable clearing the sorting state. */ disableClear?: boolean; /** Position of the arrow that displays when sorted. */ arrowPosition?: SortHeaderArrowPosition; } /** Injection token to be used to override the default options for `mat-sort`. */ export const MAT_SORT_DEFAULT_OPTIONS = new InjectionToken<MatSortDefaultOptions>( 'MAT_SORT_DEFAULT_OPTIONS', ); /** Container for MatSortables to manage the sort state and provide default sort parameters. */ @Directive({ selector: '[matSort]', exportAs: 'matSort', host: { 'class': 'mat-sort', }, }) export class MatSort implements OnChanges, OnDestroy, OnInit { private _initializedStream = new ReplaySubject<void>(1); /** Collection of all registered sortables that this directive manages. */ sortables = new Map<string, MatSortable>(); /** Used to notify any child components listening to state changes. */ readonly _stateChanges = new Subject<void>(); /** The id of the most recently sorted MatSortable. */ @Input('matSortActive') active: string; /** * The direction to set when an MatSortable is initially sorted. * May be overridden by the MatSortable's sort start. */ @Input('matSortStart') start: SortDirection = 'asc'; /** The sort direction of the currently active MatSortable. */ @Input('matSortDirection') get direction(): SortDirection { return this._direction; } set direction(direction: SortDirection) { if ( direction && direction !== 'asc' && direction !== 'desc' && (typeof ngDevMode === 'undefined' || ngDevMode) ) { throw getSortInvalidDirectionError(direction); } this._direction = direction; } private _direction: SortDirection = ''; /** * Whether to disable the user from clearing the sort by finishing the sort direction cycle. * May be overridden by the MatSortable's disable clear input. */ @Input({alias: 'matSortDisableClear', transform: booleanAttribute}) disableClear: boolean; /** Whether the sortable is disabled. */ @Input({alias: 'matSortDisabled', transform: booleanAttribute}) disabled: boolean = false; /** Event emitted when the user changes either the active sort or sort direction. */ @Output('matSortChange') readonly sortChange: EventEmitter<Sort> = new EventEmitter<Sort>(); /** Emits when the paginator is initialized. */ initialized: Observable<void> = this._initializedStream; constructor( @Optional() @Inject(MAT_SORT_DEFAULT_OPTIONS) private _defaultOptions?: MatSortDefaultOptions, ) {} /** * Register function to be used by the contained MatSortables. Adds the MatSortable to the * collection of MatSortables. */ register(sortable: MatSortable): void { if (typeof ngDevMode === 'undefined' || ngDevMode) { if (!sortable.id) { throw getSortHeaderMissingIdError(); } if (this.sortables.has(sortable.id)) { throw getSortDuplicateSortableIdError(sortable.id); } } this.sortables.set(sortable.id, sortable); } /** * Unregister function to be used by the contained MatSortables. Removes the MatSortable from the * collection of contained MatSortables. */ deregister(sortable: MatSortable): void { this.sortables.delete(sortable.id); } /** Sets the active sort id and determines the new sort direction. */ sort(sortable: MatSortable): void { if (this.active != sortable.id) { this.active = sortable.id; this.direction = sortable.start ? sortable.start : this.start; } else { this.direction = this.getNextSortDirection(sortable); } this.sortChange.emit({active: this.active, direction: this.direction}); } /** Returns the next sort direction of the active sortable, checking for potential overrides. */ getNextSortDirection(sortable: MatSortable): SortDirection { if (!sortable) { return ''; } // Get the sort direction cycle with the potential sortable overrides. const disableClear = sortable?.disableClear ?? this.disableClear ?? !!this._defaultOptions?.disableClear; let sortDirectionCycle = getSortDirectionCycle(sortable.start || this.start, disableClear); // Get and return the next direction in the cycle let nextDirectionIndex = sortDirectionCycle.indexOf(this.direction) + 1; if (nextDirectionIndex >= sortDirectionCycle.length) { nextDirectionIndex = 0; } return sortDirectionCycle[nextDirectionIndex]; } ngOnInit() { this._initializedStream.next(); } ngOnChanges() { this._stateChanges.next(); } ngOnDestroy() { this._stateChanges.complete(); this._initializedStream.complete(); } } /** Returns the sort direction cycle to use given the provided parameters of order and clear. */ function getSortDirectionCycle(start: SortDirection, disableClear: boolean): SortDirection[] { let sortOrder: SortDirection[] = ['asc', 'desc']; if (start == 'desc') { sortOrder.reverse(); } if (!disableClear) { sortOrder.push(''); } return sortOrder; }
{ "end_byte": 6383, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sort/sort.ts" }
components/src/material/sort/BUILD.bazel_0_1622
load( "//tools:defaults.bzl", "extract_tokens", "markdown_to_html", "ng_module", "ng_test_library", "ng_web_test_suite", "sass_binary", "sass_library", ) package(default_visibility = ["//visibility:public"]) ng_module( name = "sort", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), assets = [":sort-header.css"] + glob(["**/*.html"]), deps = [ "//src:dev_mode_types", "//src/cdk/a11y", "//src/cdk/keycodes", "//src/material/core", "@npm//@angular/animations", "@npm//@angular/core", "@npm//rxjs", ], ) sass_library( name = "sort_scss_lib", srcs = glob(["**/_*.scss"]), deps = [ "//src/material/core:core_scss_lib", ], ) sass_binary( name = "sort_header_scss", src = "sort-header.scss", deps = [ "//src/cdk:sass_lib", "//src/material/core:core_scss_lib", ], ) ng_test_library( name = "unit_test_sources", srcs = glob( ["**/*.spec.ts"], exclude = ["**/*.e2e.spec.ts"], ), deps = [ ":sort", "//src/cdk/collections", "//src/cdk/table", "//src/cdk/testing/private", "//src/material/table", "@npm//@angular/platform-browser", "@npm//rxjs", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_test_sources"], ) markdown_to_html( name = "overview", srcs = [":sort.md"], ) extract_tokens( name = "tokens", srcs = [":sort_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "end_byte": 1622, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sort/BUILD.bazel" }