_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
components/src/material/button-toggle/testing/public-api.ts_0_396
/** * @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 './button-toggle-harness'; export * from './button-toggle-harness-filters'; export * from './button-toggle-group-harness'; export * from './button-toggle-group-harness-filters';
{ "end_byte": 396, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button-toggle/testing/public-api.ts" }
components/src/material/button-toggle/testing/button-toggle-harness-filters.ts_0_765
/** * @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'; /** Criteria that can be used to filter a list of `MatButtonToggleHarness` instances. */ export interface ButtonToggleHarnessFilters extends BaseHarnessFilters { /** Only find instances whose text matches the given value. */ text?: string | RegExp; /** Only find instances whose name matches the given value. */ name?: string | RegExp; /** Only find instances that are checked. */ checked?: boolean; /** Only find instances which match the given disabled state. */ disabled?: boolean; }
{ "end_byte": 765, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button-toggle/testing/button-toggle-harness-filters.ts" }
components/src/material/button-toggle/testing/button-toggle-group.spec.ts_0_3559
import {HarnessLoader} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {Component} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {MatButtonToggleAppearance, MatButtonToggleModule} from '@angular/material/button-toggle'; import {MatButtonToggleGroupHarness} from './button-toggle-group-harness'; describe('MatButtonToggleGroupHarness', () => { let fixture: ComponentFixture<ButtonToggleGroupHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ imports: [MatButtonToggleModule, ButtonToggleGroupHarnessTest], }); fixture = TestBed.createComponent(ButtonToggleGroupHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); it('should load all button toggle group harnesses', async () => { const groups = await loader.getAllHarnesses(MatButtonToggleGroupHarness); expect(groups.length).toBe(1); }); it('should load the toggles inside the group', async () => { const group = await loader.getHarness(MatButtonToggleGroupHarness); const toggles = await group.getToggles(); expect(toggles.length).toBe(2); }); it('should get whether the group is disabled', async () => { const group = await loader.getHarness(MatButtonToggleGroupHarness); expect(await group.isDisabled()).toBe(false); fixture.componentInstance.disabled = true; fixture.changeDetectorRef.markForCheck(); expect(await group.isDisabled()).toBe(true); }); it('should filter by whether the group is disabled', async () => { let enabledGroups = await loader.getAllHarnesses( MatButtonToggleGroupHarness.with({disabled: false}), ); let disabledGroups = await loader.getAllHarnesses( MatButtonToggleGroupHarness.with({disabled: true}), ); expect(enabledGroups.length).toBe(1); expect(disabledGroups.length).toBe(0); fixture.componentInstance.disabled = true; fixture.changeDetectorRef.markForCheck(); enabledGroups = await loader.getAllHarnesses( MatButtonToggleGroupHarness.with({disabled: false}), ); disabledGroups = await loader.getAllHarnesses( MatButtonToggleGroupHarness.with({disabled: true}), ); expect(enabledGroups.length).toBe(0); expect(disabledGroups.length).toBe(1); }); it('should get whether the group is vertical', async () => { const group = await loader.getHarness(MatButtonToggleGroupHarness); expect(await group.isVertical()).toBe(false); fixture.componentInstance.vertical = true; fixture.changeDetectorRef.markForCheck(); expect(await group.isVertical()).toBe(true); }); it('should get the group appearance', async () => { const group = await loader.getHarness(MatButtonToggleGroupHarness); expect(await group.getAppearance()).toBe('standard'); fixture.componentInstance.appearance = 'legacy'; fixture.changeDetectorRef.markForCheck(); expect(await group.getAppearance()).toBe('legacy'); }); }); @Component({ template: ` <mat-button-toggle-group [disabled]="disabled" [vertical]="vertical" [appearance]="appearance"> <mat-button-toggle value="1">One</mat-button-toggle> <mat-button-toggle value="2">Two</mat-button-toggle> </mat-button-toggle-group> `, standalone: true, imports: [MatButtonToggleModule], }) class ButtonToggleGroupHarnessTest { disabled = false; vertical = false; appearance: MatButtonToggleAppearance = 'standard'; }
{ "end_byte": 3559, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button-toggle/testing/button-toggle-group.spec.ts" }
components/src/material/button-toggle/testing/button-toggle-harness.spec.ts_0_6457
import {HarnessLoader} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {Component} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {MatButtonToggleModule} from '@angular/material/button-toggle'; import {MatButtonToggleHarness} from './button-toggle-harness'; describe('MatButtonToggleHarness', () => { let fixture: ComponentFixture<ButtonToggleHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ imports: [MatButtonToggleModule, ButtonToggleHarnessTest], }); fixture = TestBed.createComponent(ButtonToggleHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); it('should load all button toggle harnesses', async () => { const toggles = await loader.getAllHarnesses(MatButtonToggleHarness); expect(toggles.length).toBe(2); }); it('should load a button toggle with exact label', async () => { const toggles = await loader.getAllHarnesses(MatButtonToggleHarness.with({text: 'First'})); expect(toggles.length).toBe(1); expect(await toggles[0].getText()).toBe('First'); }); it('should load a button toggle with regex label match', async () => { const toggles = await loader.getAllHarnesses(MatButtonToggleHarness.with({text: /^s/i})); expect(toggles.length).toBe(1); expect(await toggles[0].getText()).toBe('Second'); }); it('should get the toggle checked state', async () => { const [checkedToggle, uncheckedToggle] = await loader.getAllHarnesses(MatButtonToggleHarness); expect(await checkedToggle.isChecked()).toBe(true); expect(await uncheckedToggle.isChecked()).toBe(false); }); it('should filter by whether the group is disabled', async () => { const enabledToggles = await loader.getAllHarnesses( MatButtonToggleHarness.with({disabled: false}), ); const disabledToggles = await loader.getAllHarnesses( MatButtonToggleHarness.with({disabled: true}), ); expect(enabledToggles.length).toBe(1); expect(disabledToggles.length).toBe(1); }); it('should get the toggle disabled state', async () => { const [enabledToggle, disabledToggle] = await loader.getAllHarnesses(MatButtonToggleHarness); expect(await enabledToggle.isDisabled()).toBe(false); expect(await disabledToggle.isDisabled()).toBe(true); }); it('should get the disabled state for an interactive disabled button', async () => { fixture.componentInstance.disabledInteractive = true; fixture.changeDetectorRef.markForCheck(); const disabledToggle = (await loader.getAllHarnesses(MatButtonToggleHarness))[1]; expect(await disabledToggle.isDisabled()).toBe(true); }); it('should get the toggle name', async () => { const toggle = await loader.getHarness(MatButtonToggleHarness.with({text: 'First'})); expect(await toggle.getName()).toBe('first-name'); }); it('should get the toggle aria-label', async () => { const toggle = await loader.getHarness(MatButtonToggleHarness.with({text: 'First'})); expect(await toggle.getAriaLabel()).toBe('First toggle'); }); it('should get the toggle aria-labelledby', async () => { const toggle = await loader.getHarness(MatButtonToggleHarness.with({text: 'Second'})); expect(await toggle.getAriaLabelledby()).toBe('second-label'); }); it('should get the toggle label text', async () => { const [firstToggle, secondToggle] = await loader.getAllHarnesses(MatButtonToggleHarness); expect(await firstToggle.getText()).toBe('First'); expect(await secondToggle.getText()).toBe('Second'); }); it('should get the toggle appearance', async () => { const [firstToggle, secondToggle] = await loader.getAllHarnesses(MatButtonToggleHarness); expect(await firstToggle.getAppearance()).toBe('standard'); expect(await secondToggle.getAppearance()).toBe('legacy'); }); it('should focus the button toggle', async () => { const toggle = await loader.getHarness(MatButtonToggleHarness.with({text: 'First'})); expect(await toggle.isFocused()).toBe(false); await toggle.focus(); expect(await toggle.isFocused()).toBe(true); }); it('should blur the button toggle', async () => { const toggle = await loader.getHarness(MatButtonToggleHarness.with({text: 'First'})); await toggle.focus(); expect(await toggle.isFocused()).toBe(true); await toggle.blur(); expect(await toggle.isFocused()).toBe(false); }); it('should toggle the button value', async () => { fixture.componentInstance.disabled = false; fixture.changeDetectorRef.markForCheck(); const [checkedToggle, uncheckedToggle] = await loader.getAllHarnesses(MatButtonToggleHarness); await checkedToggle.toggle(); await uncheckedToggle.toggle(); expect(await checkedToggle.isChecked()).toBe(false); expect(await uncheckedToggle.isChecked()).toBe(true); }); it('should check the button toggle', async () => { fixture.componentInstance.disabled = false; fixture.changeDetectorRef.markForCheck(); const [checkedToggle, uncheckedToggle] = await loader.getAllHarnesses(MatButtonToggleHarness); await checkedToggle.check(); await uncheckedToggle.check(); expect(await checkedToggle.isChecked()).toBe(true); expect(await uncheckedToggle.isChecked()).toBe(true); }); it('should uncheck the button toggle', async () => { fixture.componentInstance.disabled = false; fixture.changeDetectorRef.markForCheck(); const [checkedToggle, uncheckedToggle] = await loader.getAllHarnesses(MatButtonToggleHarness); await checkedToggle.uncheck(); await uncheckedToggle.uncheck(); expect(await checkedToggle.isChecked()).toBe(false); expect(await uncheckedToggle.isChecked()).toBe(false); }); }); @Component({ template: ` <mat-button-toggle name="first-name" value="first-value" aria-label="First toggle" checked>First</mat-button-toggle> <mat-button-toggle [disabled]="disabled" [disabledInteractive]="disabledInteractive" aria-labelledby="second-label" appearance="legacy">Second</mat-button-toggle> <span id="second-label">Second toggle</span> `, standalone: true, imports: [MatButtonToggleModule], }) class ButtonToggleHarnessTest { disabled = true; disabledInteractive = false; }
{ "end_byte": 6457, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button-toggle/testing/button-toggle-harness.spec.ts" }
components/src/material/button-toggle/testing/BUILD.bazel_0_755
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/button-toggle", ], ) 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/button-toggle", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_tests_lib"], )
{ "end_byte": 755, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button-toggle/testing/BUILD.bazel" }
components/src/material/button-toggle/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/button-toggle/testing/index.ts" }
components/src/material/button/icon-button.scss_0_3286
@use '../core/tokens/m2/mdc/icon-button' as tokens-mdc-icon-button; @use '../core/tokens/m2/mat/icon-button' as tokens-mat-icon-button; @use './button-base'; @use '../core/style/private'; @use '../core/style/vendor-prefixes'; @use '../core/tokens/token-utils'; .mat-mdc-icon-button { @include vendor-prefixes.user-select(none); display: inline-block; position: relative; box-sizing: border-box; border: none; outline: none; background-color: transparent; fill: currentColor; color: inherit; text-decoration: none; cursor: pointer; z-index: 0; overflow: visible; // Border radius is inherited by ripple to know its shape. Set to 50% so the ripple is round. border-radius: 50%; // Prevent the button from shrinking since it's always supposed to be a circle. flex-shrink: 0; // Ensure the icons are centered. text-align: center; @include token-utils.use-tokens( tokens-mdc-icon-button.$prefix, tokens-mdc-icon-button.get-token-slots()) { $button-size: token-utils.get-token-variable(state-layer-size, $fallback: 48px); $icon-size: token-utils.get-token-variable(icon-size, $fallback: 24px); // We emit these tokens ourselves here so we can provide a default value. // This avoids a lot internal breakages in apps that didn't include the icon button theme. width: $button-size; height: $button-size; // Note: this is wrapped in an interpolation, because of an internal lint rule that bans // interpolations in `calc`, even though this is the only way to achieve what we're looking for. padding: #{calc(#{calc(#{$button-size} - #{$icon-size})} / 2)}; // Icon size used to be placed on the host element. Now, in `theme-styles` it is placed on // the unused `.mdc-button__icon` class. Explicitly set the font-size here. @include token-utils.create-token-slot(font-size, icon-size); @include token-utils.create-token-slot(color, icon-color); } @include button-base.mat-private-button-interactive(); @include button-base.mat-private-button-ripple(tokens-mat-icon-button.$prefix, tokens-mat-icon-button.get-token-slots()); @include button-base.mat-private-button-touch-target(true, tokens-mat-icon-button.$prefix, tokens-mat-icon-button.get-token-slots()); @include private.private-animation-noop(); @include token-utils.use-tokens( tokens-mdc-icon-button.$prefix, tokens-mdc-icon-button.get-token-slots()) { @include button-base.mat-private-button-disabled { @include token-utils.create-token-slot(color, disabled-icon-color); }; img, svg { @include token-utils.create-token-slot(width, icon-size); @include token-utils.create-token-slot(height, icon-size); vertical-align: baseline; } } .mat-mdc-button-persistent-ripple { border-radius: 50%; } // MDC used to include this and it seems like a lot of apps depend on it. &[hidden] { display: none; } // MDC adds some styles to icon buttons that conflict with some of our focus indicator styles // and don't actually do anything. This undoes those conflicting styles. &.mat-unthemed, &.mat-primary, &.mat-accent, &.mat-warn { &:not(.mdc-ripple-upgraded):focus::before { background: transparent; opacity: 1; } } }
{ "end_byte": 3286, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/icon-button.scss" }
components/src/material/button/_icon-button-theme.scss_0_6265
@use 'sass:map'; @use 'sass:math'; @use '../core/tokens/m2/mdc/icon-button' as tokens-mdc-icon-button; @use '../core/tokens/m2/mat/icon-button' as tokens-mat-icon-button; @use '../core/style/sass-utils'; @use '../core/tokens/token-utils'; @use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @mixin base($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, base)); } @else { // Add default values for tokens not related to color, typography, or density. @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-icon-button.$prefix, tokens-mdc-icon-button.get-unthemable-tokens() ); } } } @mixin _icon-button-variant($theme, $palette) { $mdc-tokens: if( $palette, tokens-mdc-icon-button.private-get-color-palette-color-tokens($theme, $palette), tokens-mdc-icon-button.get-color-tokens($theme) ); $mat-tokens: if( $palette, tokens-mat-icon-button.private-get-color-palette-color-tokens($theme, $palette), tokens-mat-icon-button.get-color-tokens($theme) ); @include token-utils.create-token-values(tokens-mdc-icon-button.$prefix, $mdc-tokens); @include token-utils.create-token-values(tokens-mat-icon-button.$prefix, $mat-tokens); } /// Outputs color theme styles for the mat-icon-button. /// @param {Map} $theme The theme to generate color styles for. /// @param {ArgList} Additional optional arguments (only supported for M3 themes): /// $color-variant: The color variant to use for the button: primary, secondary, tertiary, or error. @mixin color($theme, $options...) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, color), $options...); } @else { @include sass-utils.current-selector-or-root() { @include _icon-button-variant($theme, null); .mat-mdc-icon-button { &.mat-primary { @include _icon-button-variant($theme, primary); } &.mat-accent { @include _icon-button-variant($theme, accent); } &.mat-warn { @include _icon-button-variant($theme, warn); } } } } } @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-icon-button.$prefix, tokens-mat-icon-button.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 { $icon-size: 24px; $density-scale: inspection.get-theme-density($theme); $size-map: ( 0: 48px, -1: 44px, -2: 40px, -3: 36px, -4: 32px, -5: 28px, ); $calculated-size: map.get($size-map, $density-scale); @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mat-icon-button.$prefix, tokens-mat-icon-button.get-density-tokens($theme) ); } // Use `mat-mdc-button-base` to increase the specificity over the button's structural styles. .mat-mdc-icon-button.mat-mdc-button-base { // Match the styles that used to be present. This is necessary for backwards // compat to match the previous implementations selector count (two classes). --mdc-icon-button-state-layer-size: #{$calculated-size}; // TODO: Switch calculated-size to "var(--mdc-icon-button-state-layer-size)" // Currently fails validation because the variable is "undefined" // in the sass stack. // TODO: Switch icon-size to "var(--mdc-icon-button-icon-size)". Currently // fails validation because the variable is "undefined" in the sass stack. width: var(--mdc-icon-button-state-layer-size); height: var(--mdc-icon-button-state-layer-size); padding: math.div($calculated-size - $icon-size, 2); } } } /// Defines the tokens that will be available in the `overrides` mixin and for docs extraction. @function _define-overrides() { @return ( ( namespace: tokens-mdc-icon-button.$prefix, tokens: tokens-mdc-icon-button.get-token-slots(), ), ( namespace: tokens-mat-icon-button.$prefix, tokens: tokens-mat-icon-button.get-token-slots(), ), ); } @mixin overrides($tokens: ()) { @include token-utils.batch-create-token-values($tokens, _define-overrides()...); } /// Outputs all (base, color, typography, and density) theme styles for the mat-icon-button. /// @param {Map} $theme The theme to generate styles for. /// @param {ArgList} Additional optional arguments (only supported for M3 themes): /// $color-variant: The color variant to use for the button: primary, secondary, tertiary, or error. @mixin theme($theme, $options...) { @include theming.private-check-duplicate-theme-styles($theme, 'mat-icon-button') { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme), $options...); } @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, $options...) { @include validation.selector-defined( 'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector' ); @if ($tokens != ()) { $mdc-tokens: token-utils.get-tokens-for($tokens, tokens-mdc-icon-button.$prefix, $options...); $mat-tokens: token-utils.get-tokens-for($tokens, tokens-mat-icon-button.$prefix, $options...); @include token-utils.create-token-values(tokens-mdc-icon-button.$prefix, $mdc-tokens); @include token-utils.create-token-values(tokens-mat-icon-button.$prefix, $mat-tokens); } }
{ "end_byte": 6265, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/_icon-button-theme.scss" }
components/src/material/button/icon-button.html_0_399
<span class="mat-mdc-button-persistent-ripple mdc-icon-button__ripple"></span> <ng-content></ng-content> <!-- The indicator can't be directly on the button, because MDC uses ::before for high contrast indication and it can't be on the ripple, because it has a border radius and overflow: hidden. --> <span class="mat-focus-indicator"></span> <span class="mat-mdc-button-touch-target"></span>
{ "end_byte": 399, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/icon-button.html" }
components/src/material/button/module.ts_0_953
/** * @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, MatRippleModule} from '@angular/material/core'; import {MatAnchor, MatButton} from './button'; import {MatFabAnchor, MatFabButton, MatMiniFabAnchor, MatMiniFabButton} from './fab'; import {MatIconAnchor, MatIconButton} from './icon-button'; @NgModule({ imports: [ MatCommonModule, MatRippleModule, MatAnchor, MatButton, MatIconAnchor, MatMiniFabAnchor, MatMiniFabButton, MatIconButton, MatFabAnchor, MatFabButton, ], exports: [ MatAnchor, MatButton, MatIconAnchor, MatIconButton, MatMiniFabAnchor, MatMiniFabButton, MatFabAnchor, MatFabButton, MatCommonModule, ], }) export class MatButtonModule {}
{ "end_byte": 953, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/module.ts" }
components/src/material/button/button.md_0_4378
Angular Material buttons are native `<button>` or `<a>` elements enhanced with Material Design styling and ink ripples. <!-- example(button-overview) --> Native `<button>` and `<a>` elements are always used in order to provide the most straightforward and accessible experience for users. A `<button>` element should be used whenever some _action_ is performed. An `<a>` element should be used whenever the user will _navigate_ to another view. There are several button variants, each applied as an attribute: | Attribute | Description | |----------------------|--------------------------------------------------------------------------| | `mat-button` | Rectangular text button w/ no elevation and rounded corners | | `mat-raised-button` | Rectangular contained button w/ elevation and rounded corners | | `mat-flat-button` | Rectangular contained button w/ no elevation and rounded corners | | `mat-stroked-button` | Rectangular outlined button w/ no elevation and rounded corners | | `mat-icon-button` | Circular button with a transparent background, meant to contain an icon | | `mat-fab` | Square button w/ elevation and rounded corners, meant to contain an icon. Can be [extended](https://material.angular.io/components/button/overview#extended-fab-buttons) to a rectangle to also fit a label | | `mat-mini-fab` | Same as `mat-fab` but smaller | ### Extended fab buttons Traditional fab buttons are circular and only have space for a single icon. However, you can add the `extended` attribute to allow the fab to expand into a rounded rectangle shape with space for a text label in addition to the icon. Only full sized fabs support the `extended` attribute, mini fabs do not. ```html <button mat-fab extended> <mat-icon>home</mat-icon> Home </button> ``` ### Interactive disabled buttons Native disabled `<button>` elements cannot receive focus and do not dispatch any events. This can be problematic in some cases because it can prevent the app from telling the user why the button is disabled. You can use the `disabledInteractive` input to style the button as disabled but allow for it to receive focus and dispatch events. The button will have `aria-disabled="true"` for assistive technology. The behavior can be configured globally through the `MAT_BUTTON_CONFIG` injection token. **Note:** Using the `disabledInteractive` input can result in buttons that previously prevented actions to no longer do so, for example a submit button in a form. When using this input, you should guard against such cases in your component. <!-- example(button-disabled-interactive) --> ### Accessibility Angular Material uses native `<button>` and `<a>` elements to ensure an accessible experience by default. A `<button>` element should be used for any interaction that _performs an action on the current page_. An `<a>` element should be used for any interaction that _navigates to another URL_. All standard accessibility best practices for buttons and anchors apply to `MatButton`. #### Capitalization Using ALL CAPS in the button text itself causes issues for screen-readers, which will read the text character-by-character. It can also cause issues for localization. We recommend not changing the default capitalization for the button text. #### Disabling anchors `MatAnchor` supports disabling an anchor in addition to the features provided by the native `<a>` element. When you disable an anchor, the component sets `aria-disabled="true"` and `tabindex="-1"`. Always test disabled anchors in your application to ensure compatibility with any assistive technology your application supports. #### Buttons with icons Buttons or links containing only icons (such as `mat-fab`, `mat-mini-fab`, and `mat-icon-button`) should be given a meaningful label via `aria-label` or `aria-labelledby`. [See the documentation for `MatIcon`](https://material.angular.io/components/icon) for more information on using icons in buttons. #### Toggle buttons [See the documentation for `MatButtonToggle`](https://material.angular.io/components/button-toggle) for information on stateful toggle buttons.
{ "end_byte": 4378, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/button.md" }
components/src/material/button/fab.ts_0_5312
/** * @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, InjectionToken, Input, ViewEncapsulation, booleanAttribute, inject, } from '@angular/core'; import {MatAnchor} from './button'; import {MAT_ANCHOR_HOST, MAT_BUTTON_HOST, MatButtonBase} from './button-base'; import {ThemePalette} from '@angular/material/core'; /** Default FAB options that can be overridden. */ export interface MatFabDefaultOptions { /** * Default theme color of the button. This API is supported in M2 themes * only, it has no effect in M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants */ color?: ThemePalette; } /** Injection token to be used to override the default options for FAB. */ export const MAT_FAB_DEFAULT_OPTIONS = new InjectionToken<MatFabDefaultOptions>( 'mat-mdc-fab-default-options', { providedIn: 'root', factory: MAT_FAB_DEFAULT_OPTIONS_FACTORY, }, ); /** @docs-private */ export function MAT_FAB_DEFAULT_OPTIONS_FACTORY(): MatFabDefaultOptions { return { // The FAB by default has its color set to accent. color: 'accent', }; } // Default FAB configuration. const defaults = MAT_FAB_DEFAULT_OPTIONS_FACTORY(); /** * Material Design floating action button (FAB) component. These buttons represent the primary * or most common action for users to interact with. * See https://material.io/components/buttons-floating-action-button/ * * The `MatFabButton` class has two appearances: normal and extended. */ @Component({ selector: `button[mat-fab]`, templateUrl: 'button.html', styleUrl: 'fab.css', host: { ...MAT_BUTTON_HOST, '[class.mdc-fab--extended]': 'extended', '[class.mat-mdc-extended-fab]': 'extended', }, exportAs: 'matButton', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) export class MatFabButton extends MatButtonBase { private _options = inject<MatFabDefaultOptions>(MAT_FAB_DEFAULT_OPTIONS, {optional: true}); override _isFab = true; @Input({transform: booleanAttribute}) extended: boolean; constructor(...args: unknown[]); constructor() { super(); this._options = this._options || defaults; this.color = this._options!.color || defaults.color; } } /** * Material Design mini floating action button (FAB) component. These buttons represent the primary * or most common action for users to interact with. * See https://material.io/components/buttons-floating-action-button/ */ @Component({ selector: `button[mat-mini-fab]`, templateUrl: 'button.html', styleUrl: 'fab.css', host: MAT_BUTTON_HOST, exportAs: 'matButton', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) export class MatMiniFabButton extends MatButtonBase { private _options = inject<MatFabDefaultOptions>(MAT_FAB_DEFAULT_OPTIONS, {optional: true}); override _isFab = true; constructor(...args: unknown[]); constructor() { super(); this._options = this._options || defaults; this.color = this._options!.color || defaults.color; } } /** * Material Design floating action button (FAB) component for anchor elements. Anchor elements * are used to provide links for the user to navigate across different routes or pages. * See https://material.io/components/buttons-floating-action-button/ * * The `MatFabAnchor` class has two appearances: normal and extended. */ @Component({ selector: `a[mat-fab]`, templateUrl: 'button.html', styleUrl: 'fab.css', host: { ...MAT_ANCHOR_HOST, '[class.mdc-fab--extended]': 'extended', '[class.mat-mdc-extended-fab]': 'extended', }, exportAs: 'matButton, matAnchor', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) export class MatFabAnchor extends MatAnchor { private _options = inject<MatFabDefaultOptions>(MAT_FAB_DEFAULT_OPTIONS, {optional: true}); override _isFab = true; @Input({transform: booleanAttribute}) extended: boolean; constructor(...args: unknown[]); constructor() { super(); this._options = this._options || defaults; this.color = this._options!.color || defaults.color; } } /** * Material Design mini floating action button (FAB) component for anchor elements. Anchor elements * are used to provide links for the user to navigate across different routes or pages. * See https://material.io/components/buttons-floating-action-button/ */ @Component({ selector: `a[mat-mini-fab]`, templateUrl: 'button.html', styleUrl: 'fab.css', host: MAT_ANCHOR_HOST, exportAs: 'matButton, matAnchor', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) export class MatMiniFabAnchor extends MatAnchor { private _options = inject<MatFabDefaultOptions>(MAT_FAB_DEFAULT_OPTIONS, {optional: true}); override _isFab = true; constructor(...args: unknown[]); constructor() { super(); this._options = this._options || defaults; this.color = this._options!.color || defaults.color; } }
{ "end_byte": 5312, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/fab.ts" }
components/src/material/button/button-high-contrast.scss_0_515
@use '@angular/cdk'; // Add an outline to make buttons more visible in high contrast mode. Stroked buttons and FABs // don't need a special look in high-contrast mode, because those already have an outline. .mat-mdc-button:not(.mdc-button--outlined), .mat-mdc-unelevated-button:not(.mdc-button--outlined), .mat-mdc-raised-button:not(.mdc-button--outlined), .mat-mdc-outlined-button:not(.mdc-button--outlined), .mat-mdc-icon-button.mat-mdc-icon-button { @include cdk.high-contrast { outline: solid 1px; } }
{ "end_byte": 515, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/button-high-contrast.scss" }
components/src/material/button/button.spec.ts_0_6588
import {createMouseEvent, dispatchEvent} from '@angular/cdk/testing/private'; import {ApplicationRef, Component} from '@angular/core'; import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {ThemePalette} from '@angular/material/core'; import {By} from '@angular/platform-browser'; import { MAT_BUTTON_CONFIG, MAT_FAB_DEFAULT_OPTIONS, MatButtonModule, MatFabDefaultOptions, } from './index'; describe('MatButton', () => { beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [MatButtonModule, TestApp], }); })); // General button tests it('should apply class based on color attribute', () => { let fixture = TestBed.createComponent(TestApp); let testComponent = fixture.debugElement.componentInstance; let buttonDebugElement = fixture.debugElement.query(By.css('button'))!; let aDebugElement = fixture.debugElement.query(By.css('a'))!; testComponent.buttonColor = 'primary'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(buttonDebugElement.nativeElement.classList.contains('mat-primary')).toBe(true); expect(aDebugElement.nativeElement.classList.contains('mat-primary')).toBe(true); testComponent.buttonColor = 'accent'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(buttonDebugElement.nativeElement.classList.contains('mat-accent')).toBe(true); expect(aDebugElement.nativeElement.classList.contains('mat-accent')).toBe(true); testComponent.buttonColor = null; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(buttonDebugElement.nativeElement.classList).not.toContain('mat-accent'); expect(aDebugElement.nativeElement.classList).not.toContain('mat-accent'); }); it('should apply class based on the disabled state', () => { const fixture = TestBed.createComponent(TestApp); const button = fixture.debugElement.query(By.css('button'))!.nativeElement; const anchor = fixture.debugElement.query(By.css('a'))!.nativeElement; expect(button.classList).not.toContain('mat-mdc-button-disabled'); expect(anchor.classList).not.toContain('mat-mdc-button-disabled'); fixture.componentInstance.isDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(button.classList).toContain('mat-mdc-button-disabled'); expect(anchor.classList).toContain('mat-mdc-button-disabled'); }); it('should not clear previous defined classes', () => { let fixture = TestBed.createComponent(TestApp); let testComponent = fixture.debugElement.componentInstance; let buttonDebugElement = fixture.debugElement.query(By.css('button'))!; buttonDebugElement.nativeElement.classList.add('custom-class'); testComponent.buttonColor = 'primary'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(buttonDebugElement.nativeElement.classList.contains('mat-primary')).toBe(true); expect(buttonDebugElement.nativeElement.classList.contains('custom-class')).toBe(true); testComponent.buttonColor = 'accent'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(buttonDebugElement.nativeElement.classList.contains('mat-primary')).toBe(false); expect(buttonDebugElement.nativeElement.classList.contains('mat-accent')).toBe(true); expect(buttonDebugElement.nativeElement.classList.contains('custom-class')).toBe(true); }); describe('button[mat-fab]', () => { it('should have accent palette by default', () => { const fixture = TestBed.createComponent(TestApp); const fabButtonDebugEl = fixture.debugElement.query(By.css('button[mat-fab]'))!; fixture.detectChanges(); expect(fabButtonDebugEl.nativeElement.classList) .withContext('Expected fab buttons to use accent palette by default') .toContain('mat-accent'); }); }); describe('button[mat-mini-fab]', () => { it('should have accent palette by default', () => { const fixture = TestBed.createComponent(TestApp); const miniFabButtonDebugEl = fixture.debugElement.query(By.css('button[mat-mini-fab]'))!; fixture.detectChanges(); expect(miniFabButtonDebugEl.nativeElement.classList) .withContext('Expected mini-fab buttons to use accent palette by default') .toContain('mat-accent'); }); }); describe('button[mat-fab] extended', () => { it('should be extended', () => { const fixture = TestBed.createComponent(TestApp); fixture.detectChanges(); const extendedFabButtonDebugEl = fixture.debugElement.query(By.css('.extended-fab-test'))!; expect( extendedFabButtonDebugEl.nativeElement.classList.contains('mat-mdc-extended-fab'), ).toBeFalse(); fixture.componentInstance.extended = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(extendedFabButtonDebugEl.nativeElement.classList).toContain('mat-mdc-extended-fab'); }); }); // Regular button tests describe('button[mat-button]', () => { it('should handle a click on the button', () => { let fixture = TestBed.createComponent(TestApp); let testComponent = fixture.debugElement.componentInstance; let buttonDebugElement = fixture.debugElement.query(By.css('button'))!; buttonDebugElement.nativeElement.click(); expect(testComponent.clickCount).toBe(1); }); it('should not increment if disabled', () => { let fixture = TestBed.createComponent(TestApp); let testComponent = fixture.debugElement.componentInstance; let buttonDebugElement = fixture.debugElement.query(By.css('button'))!; testComponent.isDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); buttonDebugElement.nativeElement.click(); expect(testComponent.clickCount).toBe(0); }); it('should disable the native button element', () => { let fixture = TestBed.createComponent(TestApp); let buttonNativeElement = fixture.nativeElement.querySelector('button'); expect(buttonNativeElement.disabled) .withContext('Expected button not to be disabled') .toBeFalsy(); fixture.componentInstance.isDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(buttonNativeElement.disabled) .withContext('Expected button to be disabled') .toBeTruthy(); }); }); // Anchor button tests
{ "end_byte": 6588, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/button.spec.ts" }
components/src/material/button/button.spec.ts_6591_15648
describe('a[mat-button]', () => { it('should not redirect if disabled', () => { let fixture = TestBed.createComponent(TestApp); let testComponent = fixture.debugElement.componentInstance; let buttonDebugElement = fixture.debugElement.query(By.css('a'))!; testComponent.isDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); buttonDebugElement.nativeElement.click(); }); it('should remove tabindex if disabled', () => { let fixture = TestBed.createComponent(TestApp); let testComponent = fixture.debugElement.componentInstance; let buttonDebugElement = fixture.debugElement.query(By.css('a'))!; fixture.detectChanges(); expect(buttonDebugElement.nativeElement.hasAttribute('tabindex')).toBe(false); testComponent.isDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(buttonDebugElement.nativeElement.getAttribute('tabindex')).toBe('-1'); }); it('should add aria-disabled attribute if disabled', () => { let fixture = TestBed.createComponent(TestApp); let testComponent = fixture.debugElement.componentInstance; let buttonDebugElement = fixture.debugElement.query(By.css('a'))!; fixture.detectChanges(); expect(buttonDebugElement.nativeElement.hasAttribute('aria-disabled')).toBe(false); testComponent.isDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(buttonDebugElement.nativeElement.getAttribute('aria-disabled')).toBe('true'); }); it('should not add aria-disabled attribute if disabled is false', () => { let fixture = TestBed.createComponent(TestApp); let testComponent = fixture.debugElement.componentInstance; let buttonDebugElement = fixture.debugElement.query(By.css('a'))!; fixture.detectChanges(); expect(buttonDebugElement.nativeElement.hasAttribute('aria-disabled')).toBe(false); expect(buttonDebugElement.nativeElement.getAttribute('disabled')).toBeNull(); testComponent.isDisabled = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(buttonDebugElement.nativeElement.hasAttribute('aria-disabled')).toBe(false); expect(buttonDebugElement.nativeElement.getAttribute('disabled')).toBeNull(); }); it('should be able to set a custom tabindex', () => { let fixture = TestBed.createComponent(TestApp); let testComponent = fixture.debugElement.componentInstance; let buttonElement = fixture.debugElement.query(By.css('a'))!.nativeElement; fixture.componentInstance.tabIndex = 3; fixture.detectChanges(); expect(buttonElement.getAttribute('tabindex')) .withContext('Expected custom tabindex to be set') .toBe('3'); testComponent.isDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(buttonElement.getAttribute('tabindex')) .withContext('Expected custom tabindex to be overwritten when disabled.') .toBe('-1'); }); it('should not set a default tabindex on enabled links', () => { const fixture = TestBed.createComponent(TestApp); const buttonElement = fixture.debugElement.query(By.css('a'))!.nativeElement; fixture.detectChanges(); expect(buttonElement.hasAttribute('tabindex')).toBe(false); }); describe('change detection behavior', () => { it('should not run change detection for disabled anchor but should prevent the default behavior and stop event propagation', () => { const appRef = TestBed.inject(ApplicationRef); const fixture = TestBed.createComponent(TestApp); fixture.componentInstance.isDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const anchorElement = fixture.debugElement.query(By.css('a'))!.nativeElement; spyOn(appRef, 'tick'); const event = createMouseEvent('click'); spyOn(event, 'preventDefault').and.callThrough(); spyOn(event, 'stopImmediatePropagation').and.callThrough(); dispatchEvent(anchorElement, event); expect(appRef.tick).not.toHaveBeenCalled(); expect(event.preventDefault).toHaveBeenCalled(); expect(event.stopImmediatePropagation).toHaveBeenCalled(); }); }); }); it('should have a focus indicator', () => { const fixture = TestBed.createComponent(TestApp); const buttonNativeElements = [ ...fixture.debugElement.nativeElement.querySelectorAll('a, button'), ]; expect( buttonNativeElements.every(element => !!element.querySelector('.mat-focus-indicator')), ).toBe(true); }); it('should be able to configure the default color of buttons', () => { @Component({ template: `<button mat-button>Click me</button>`, standalone: true, imports: [MatButtonModule], }) class ConfigTestApp {} TestBed.resetTestingModule(); TestBed.configureTestingModule({ imports: [MatButtonModule, ConfigTestApp], providers: [ { provide: MAT_BUTTON_CONFIG, useValue: {color: 'warn'}, }, ], }); const fixture = TestBed.createComponent(ConfigTestApp); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); expect(button.classList).toContain('mat-warn'); }); describe('interactive disabled buttons', () => { let fixture: ComponentFixture<TestApp>; let button: HTMLButtonElement; beforeEach(() => { fixture = TestBed.createComponent(TestApp); fixture.componentInstance.isDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); button = fixture.debugElement.query(By.css('button'))!.nativeElement; }); it('should set a class when allowing disabled interactivity', () => { expect(button.classList).not.toContain('mat-mdc-button-disabled-interactive'); fixture.componentInstance.disabledInteractive = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(button.classList).toContain('mat-mdc-button-disabled-interactive'); }); it('should set aria-disabled when allowing disabled interactivity', () => { expect(button.hasAttribute('aria-disabled')).toBe(false); fixture.componentInstance.disabledInteractive = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(button.getAttribute('aria-disabled')).toBe('true'); }); it('should not set the disabled attribute when allowing disabled interactivity', () => { expect(button.getAttribute('disabled')).toBe('true'); fixture.componentInstance.disabledInteractive = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(button.hasAttribute('disabled')).toBe(false); }); }); }); describe('MatFabDefaultOptions', () => { function configure(defaults: MatFabDefaultOptions) { TestBed.configureTestingModule({ imports: [MatButtonModule, TestApp], providers: [{provide: MAT_FAB_DEFAULT_OPTIONS, useValue: defaults}], }); } it('should override default color in component', () => { configure({color: 'primary'}); const fixture: ComponentFixture<TestApp> = TestBed.createComponent(TestApp); fixture.detectChanges(); const fabButtonDebugEl = fixture.debugElement.query(By.css('button[mat-fab]'))!; expect(fabButtonDebugEl.nativeElement.classList).toContain('mat-primary'); }); it('should default to accent if config does not specify color', () => { configure({}); const fixture: ComponentFixture<TestApp> = TestBed.createComponent(TestApp); fixture.detectChanges(); const fabButtonDebugEl = fixture.debugElement.query(By.css('button[mat-fab]'))!; expect(fabButtonDebugEl.nativeElement.classList).toContain('mat-accent'); }); }); /** Test component that contains an MatButton. */ @Component({ selector: 'test-app', template: ` <button [tabIndex]="tabIndex" mat-button type="button" (click)="increment()" [disabled]="isDisabled" [color]="buttonColor" [disableRipple]="rippleDisabled" [disabledInteractive]="disabledInteractive"> Go </button> <a [tabIndex]="tabIndex" href="https://www.google.com" mat-button [disabled]="isDisabled" [color]="buttonColor" [disabledInteractive]="disabledInteractive"> Link </a> <button mat-fab>Fab Button</button> <button mat-fab [extended]="extended" class="extended-fab-test">Extended</button> <button mat-mini-fab>Mini Fab Button</button> `, standalone: true, imports: [MatButtonModule], }) class TestApp { clickCount = 0; isDisabled = false; rippleDisabled = false; buttonColor: ThemePalette; tabIndex: number; extended = false; disabledInteractive = false; increment() { this.clickCount++; } }
{ "end_byte": 15648, "start_byte": 6591, "url": "https://github.com/angular/components/blob/main/src/material/button/button.spec.ts" }
components/src/material/button/button.scss_0_7935
@use './button-base'; @use '../core/style/private' as style-private; @use '../core/style/vendor-prefixes'; @use '../core/tokens/token-utils'; @use '../core/focus-indicators/private' as focus-indicators-private; @use '../core/tokens/m2/mdc/filled-button' as tokens-mdc-filled-button; @use '../core/tokens/m2/mat/filled-button' as tokens-mat-filled-button; @use '../core/tokens/m2/mdc/outlined-button' as tokens-mdc-outlined-button; @use '../core/tokens/m2/mat/outlined-button' as tokens-mat-outlined-button; @use '../core/tokens/m2/mdc/protected-button' as tokens-mdc-protected-button; @use '../core/tokens/m2/mat/protected-button' as tokens-mat-protected-button; @use '../core/tokens/m2/mdc/text-button' as tokens-mdc-text-button; @use '../core/tokens/m2/mat/text-button' as tokens-mat-text-button; .mat-mdc-button-base { text-decoration: none; } .mdc-button { @include vendor-prefixes.user-select(none); position: relative; display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box; min-width: 64px; border: none; outline: none; line-height: inherit; -webkit-appearance: none; overflow: visible; vertical-align: middle; background: transparent; padding: 0 8px; &::-moz-focus-inner { padding: 0; border: 0; } &:active { outline: none; } &:hover { cursor: pointer; } &:disabled { cursor: default; pointer-events: none; } &[hidden] { display: none; } .mdc-button__label { position: relative; } } .mat-mdc-button { $mat-text-button-slots: tokens-mat-text-button.get-token-slots(); @include token-utils.use-tokens(tokens-mat-text-button.$prefix, $mat-text-button-slots) { padding: 0 #{token-utils.get-token-variable(horizontal-padding, true)}; } @include token-utils.use-tokens( tokens-mdc-text-button.$prefix, tokens-mdc-text-button.get-token-slots() ) { @include token-utils.create-token-slot(height, container-height); @include token-utils.create-token-slot(font-family, label-text-font); @include token-utils.create-token-slot(font-size, label-text-size); @include token-utils.create-token-slot(letter-spacing, label-text-tracking); @include token-utils.create-token-slot(text-transform, label-text-transform); @include token-utils.create-token-slot(font-weight, label-text-weight); &, .mdc-button__ripple { @include token-utils.create-token-slot(border-radius, container-shape); } &:not(:disabled) { @include token-utils.create-token-slot(color, label-text-color); } // We need to re-apply the disabled tokens since MDC uses // `:disabled` which doesn't apply to anchors. @include button-base.mat-private-button-disabled { @include token-utils.create-token-slot(color, disabled-label-text-color); } } @include button-base.mat-private-button-horizontal-layout(tokens-mat-text-button.$prefix, $mat-text-button-slots, true); @include button-base.mat-private-button-ripple(tokens-mat-text-button.$prefix, $mat-text-button-slots); @include button-base.mat-private-button-touch-target(false, tokens-mat-text-button.$prefix, $mat-text-button-slots); } .mat-mdc-unelevated-button { $mat-filled-button-slots: tokens-mat-filled-button.get-token-slots(); transition: box-shadow 280ms cubic-bezier(0.4, 0, 0.2, 1); @include token-utils.use-tokens( tokens-mdc-filled-button.$prefix, tokens-mdc-filled-button.get-token-slots() ) { @include token-utils.create-token-slot(height, container-height); @include token-utils.create-token-slot(font-family, label-text-font); @include token-utils.create-token-slot(font-size, label-text-size); @include token-utils.create-token-slot(letter-spacing, label-text-tracking); @include token-utils.create-token-slot(text-transform, label-text-transform); @include token-utils.create-token-slot(font-weight, label-text-weight); } @include token-utils.use-tokens(tokens-mat-filled-button.$prefix, $mat-filled-button-slots) { padding: 0 #{token-utils.get-token-variable(horizontal-padding, true)}; } @include button-base.mat-private-button-horizontal-layout(tokens-mat-filled-button.$prefix, $mat-filled-button-slots, false); @include button-base.mat-private-button-ripple(tokens-mat-filled-button.$prefix, $mat-filled-button-slots); @include button-base.mat-private-button-touch-target(false, tokens-mat-filled-button.$prefix, $mat-filled-button-slots); @include token-utils.use-tokens( tokens-mdc-filled-button.$prefix, tokens-mdc-filled-button.get-token-slots() ) { &:not(:disabled) { @include token-utils.create-token-slot(color, label-text-color); @include token-utils.create-token-slot(background-color, container-color); } &, .mdc-button__ripple { @include token-utils.create-token-slot(border-radius, container-shape); } // We need to re-apply the disabled tokens since MDC uses // `:disabled` which doesn't apply to anchors. @include button-base.mat-private-button-disabled { @include token-utils.create-token-slot(color, disabled-label-text-color); @include token-utils.create-token-slot(background-color, disabled-container-color); } } } .mat-mdc-raised-button { $mat-protected-button-slots: tokens-mat-protected-button.get-token-slots(); transition: box-shadow 280ms cubic-bezier(0.4, 0, 0.2, 1); @include token-utils.use-tokens( tokens-mdc-protected-button.$prefix, tokens-mdc-protected-button.get-token-slots() ) { @include button-base.mat-private-button-elevation(container-elevation); @include token-utils.create-token-slot(height, container-height); @include token-utils.create-token-slot(font-family, label-text-font); @include token-utils.create-token-slot(font-size, label-text-size); @include token-utils.create-token-slot(letter-spacing, label-text-tracking); @include token-utils.create-token-slot(text-transform, label-text-transform); @include token-utils.create-token-slot(font-weight, label-text-weight); } @include token-utils.use-tokens( tokens-mat-protected-button.$prefix, $mat-protected-button-slots ) { padding: 0 #{token-utils.get-token-variable(horizontal-padding, true)}; } @include button-base.mat-private-button-horizontal-layout(tokens-mat-protected-button.$prefix, $mat-protected-button-slots, false); @include button-base.mat-private-button-ripple(tokens-mat-protected-button.$prefix, $mat-protected-button-slots); @include button-base.mat-private-button-touch-target(false, tokens-mat-protected-button.$prefix, $mat-protected-button-slots); @include token-utils.use-tokens( tokens-mdc-protected-button.$prefix, tokens-mdc-protected-button.get-token-slots() ) { &:not(:disabled) { @include token-utils.create-token-slot(color, label-text-color); @include token-utils.create-token-slot(background-color, container-color); } &, .mdc-button__ripple { @include token-utils.create-token-slot(border-radius, container-shape); } &:hover { @include button-base.mat-private-button-elevation(hover-container-elevation); } &:focus { @include button-base.mat-private-button-elevation(focus-container-elevation); } &:active, &:focus:active { @include button-base.mat-private-button-elevation(pressed-container-elevation); } // We need to re-apply the disabled tokens since MDC uses // `:disabled` which doesn't apply to anchors. @include button-base.mat-private-button-disabled { @include token-utils.create-token-slot(color, disabled-label-text-color); @include token-utils.create-token-slot(background-color, disabled-container-color); &.mat-mdc-button-disabled { @include button-base.mat-private-button-elevation(disabled-container-elevation); } } } }
{ "end_byte": 7935, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/button.scss" }
components/src/material/button/button.scss_7937_12525
.mat-mdc-outlined-button { $mat-outlined-button-slots: tokens-mat-outlined-button.get-token-slots(); border-style: solid; transition: border 280ms cubic-bezier(0.4, 0, 0.2, 1); @include token-utils.use-tokens( tokens-mdc-outlined-button.$prefix, tokens-mdc-outlined-button.get-token-slots() ) { @include token-utils.create-token-slot(height, container-height); @include token-utils.create-token-slot(font-family, label-text-font); @include token-utils.create-token-slot(font-size, label-text-size); @include token-utils.create-token-slot(letter-spacing, label-text-tracking); @include token-utils.create-token-slot(text-transform, label-text-transform); @include token-utils.create-token-slot(font-weight, label-text-weight); @include token-utils.create-token-slot(border-radius, container-shape); @include token-utils.create-token-slot(border-width, outline-width); } @include token-utils.use-tokens(tokens-mat-outlined-button.$prefix, $mat-outlined-button-slots) { padding: 0 #{token-utils.get-token-variable(horizontal-padding, true)}; } @include button-base.mat-private-button-horizontal-layout(tokens-mat-outlined-button.$prefix, $mat-outlined-button-slots, false); @include button-base.mat-private-button-ripple(tokens-mat-outlined-button.$prefix, $mat-outlined-button-slots); @include button-base.mat-private-button-touch-target(false, tokens-mat-outlined-button.$prefix, $mat-outlined-button-slots); @include token-utils.use-tokens( tokens-mdc-outlined-button.$prefix, tokens-mdc-outlined-button.get-token-slots() ) { &:not(:disabled) { @include token-utils.create-token-slot(color, label-text-color); @include token-utils.create-token-slot(border-color, outline-color); } // We need to re-apply the disabled tokens since MDC uses // `:disabled` which doesn't apply to anchors. @include button-base.mat-private-button-disabled { @include token-utils.create-token-slot(color, disabled-label-text-color); @include token-utils.create-token-slot(border-color, disabled-outline-color); } // TODO(crisbeto): this causes a weird gap between the ripple and the // outline. We should remove it and update the screenshot tests. .mdc-button__ripple { @include token-utils.create-token-slot(border-width, outline-width); border-style: solid; border-color: transparent; } } } .mat-mdc-button, .mat-mdc-unelevated-button, .mat-mdc-raised-button, .mat-mdc-outlined-button { @include button-base.mat-private-button-interactive(); @include style-private.private-animation-noop(); // Similar to MDC's `_icon-structure`, apart from the margin which we // handle via custom tokens in `mat-private-button-horizontal-layout`. & > .mat-icon { $icon-size: 1.125rem; display: inline-block; position: relative; vertical-align: top; font-size: $icon-size; height: $icon-size; width: $icon-size; } } // Since the stroked button has has an actual border that reduces the available space for // child elements such as the ripple container or focus overlay, an inherited border radius // for the absolute-positioned child elements does not work properly. This is because the // child element cannot expand to the same boundaries as the parent element with a border. // In order to work around this issue by *not* hiding overflow, we adjust the child elements // to fully cover the actual button element. This means that the border-radius would be correct // then. See: https://github.com/angular/components/issues/13738 .mat-mdc-outlined-button .mat-mdc-button-ripple, .mat-mdc-outlined-button .mdc-button__ripple { $offset: -1px; top: $offset; left: $offset; bottom: $offset; right: $offset; } // For the button element, default inset/offset values are necessary to ensure that // the focus indicator is sufficiently contrastive and renders appropriately. .mat-mdc-unelevated-button, .mat-mdc-raised-button { .mat-focus-indicator::before { $default-border-width: focus-indicators-private.$default-border-width; $border-width: var(--mat-focus-indicator-border-width, #{$default-border-width}); $offset: calc(#{$border-width} + 2px); margin: calc(#{$offset} * -1); } } .mat-mdc-outlined-button .mat-focus-indicator::before { $default-border-width: focus-indicators-private.$default-border-width; $border-width: var(--mat-focus-indicator-border-width, #{$default-border-width}); $offset: calc(#{$border-width} + 3px); margin: calc(#{$offset} * -1); }
{ "end_byte": 12525, "start_byte": 7937, "url": "https://github.com/angular/components/blob/main/src/material/button/button.scss" }
components/src/material/button/public-api.ts_0_376
/** * @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 './button'; export * from './fab'; export * from './icon-button'; export * from './module'; export {MAT_BUTTON_CONFIG, MatButtonConfig} from './button-base';
{ "end_byte": 376, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/public-api.ts" }
components/src/material/button/button.html_0_776
<span class="mat-mdc-button-persistent-ripple" [class.mdc-button__ripple]="!_isFab" [class.mdc-fab__ripple]="_isFab"></span> <ng-content select=".material-icons:not([iconPositionEnd]), mat-icon:not([iconPositionEnd]), [matButtonIcon]:not([iconPositionEnd])"> </ng-content> <span class="mdc-button__label"><ng-content></ng-content></span> <ng-content select=".material-icons[iconPositionEnd], mat-icon[iconPositionEnd], [matButtonIcon][iconPositionEnd]"> </ng-content> <!-- The indicator can't be directly on the button, because MDC uses ::before for high contrast indication and it can't be on the ripple, because it has a border radius and overflow: hidden. --> <span class="mat-focus-indicator"></span> <span class="mat-mdc-button-touch-target"></span>
{ "end_byte": 776, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/button.html" }
components/src/material/button/button.ts_0_2191
/** * @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, ViewEncapsulation} from '@angular/core'; import {MAT_ANCHOR_HOST, MAT_BUTTON_HOST, MatAnchorBase, MatButtonBase} from './button-base'; /** * Material Design button component. Users interact with a button to perform an action. * See https://material.io/components/buttons * * The `MatButton` class applies to native button elements and captures the appearances for * "text button", "outlined button", and "contained button" per the Material Design * specification. `MatButton` additionally captures an additional "flat" appearance, which matches * "contained" but without elevation. */ @Component({ selector: ` button[mat-button], button[mat-raised-button], button[mat-flat-button], button[mat-stroked-button] `, templateUrl: 'button.html', styleUrls: ['button.css', 'button-high-contrast.css'], host: MAT_BUTTON_HOST, exportAs: 'matButton', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) export class MatButton extends MatButtonBase {} /** * Material Design button component for anchor elements. Anchor elements are used to provide * links for the user to navigate across different routes or pages. * See https://material.io/components/buttons * * The `MatAnchor` class applies to native anchor elements and captures the appearances for * "text button", "outlined button", and "contained button" per the Material Design * specification. `MatAnchor` additionally captures an additional "flat" appearance, which matches * "contained" but without elevation. */ @Component({ selector: `a[mat-button], a[mat-raised-button], a[mat-flat-button], a[mat-stroked-button]`, exportAs: 'matButton, matAnchor', host: MAT_ANCHOR_HOST, templateUrl: 'button.html', styleUrls: ['button.css', 'button-high-contrast.css'], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) export class MatAnchor extends MatAnchorBase {}
{ "end_byte": 2191, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/button.ts" }
components/src/material/button/button-base.ts_0_7238
/** * @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 {FocusMonitor, FocusOrigin} from '@angular/cdk/a11y'; import {Platform} from '@angular/cdk/platform'; import { AfterViewInit, ANIMATION_MODULE_TYPE, booleanAttribute, Directive, ElementRef, inject, InjectionToken, Input, NgZone, numberAttribute, OnDestroy, OnInit, } from '@angular/core'; import {_StructuralStylesLoader, MatRippleLoader, ThemePalette} from '@angular/material/core'; import {_CdkPrivateStyleLoader} from '@angular/cdk/private'; /** Object that can be used to configure the default options for the button component. */ export interface MatButtonConfig { /** Whether disabled buttons should be interactive. */ disabledInteractive?: boolean; /** Default palette color to apply to buttons. */ color?: ThemePalette; } /** Injection token that can be used to provide the default options the button component. */ export const MAT_BUTTON_CONFIG = new InjectionToken<MatButtonConfig>('MAT_BUTTON_CONFIG'); /** Shared host configuration for all buttons */ export const MAT_BUTTON_HOST = { '[attr.disabled]': '_getDisabledAttribute()', '[attr.aria-disabled]': '_getAriaDisabled()', '[class.mat-mdc-button-disabled]': 'disabled', '[class.mat-mdc-button-disabled-interactive]': 'disabledInteractive', '[class._mat-animation-noopable]': '_animationMode === "NoopAnimations"', // MDC automatically applies the primary theme color to the button, but we want to support // an unthemed version. If color is undefined, apply a CSS class that makes it easy to // select and style this "theme". '[class.mat-unthemed]': '!color', // Add a class that applies to all buttons. This makes it easier to target if somebody // wants to target all Material buttons. '[class.mat-mdc-button-base]': 'true', '[class]': 'color ? "mat-" + color : ""', }; /** List of classes to add to buttons instances based on host attribute selector. */ const HOST_SELECTOR_MDC_CLASS_PAIR: {attribute: string; mdcClasses: string[]}[] = [ { attribute: 'mat-button', mdcClasses: ['mdc-button', 'mat-mdc-button'], }, { attribute: 'mat-flat-button', mdcClasses: ['mdc-button', 'mdc-button--unelevated', 'mat-mdc-unelevated-button'], }, { attribute: 'mat-raised-button', mdcClasses: ['mdc-button', 'mdc-button--raised', 'mat-mdc-raised-button'], }, { attribute: 'mat-stroked-button', mdcClasses: ['mdc-button', 'mdc-button--outlined', 'mat-mdc-outlined-button'], }, { attribute: 'mat-fab', mdcClasses: ['mdc-fab', 'mat-mdc-fab-base', 'mat-mdc-fab'], }, { attribute: 'mat-mini-fab', mdcClasses: ['mdc-fab', 'mat-mdc-fab-base', 'mdc-fab--mini', 'mat-mdc-mini-fab'], }, { attribute: 'mat-icon-button', mdcClasses: ['mdc-icon-button', 'mat-mdc-icon-button'], }, ]; /** Base class for all buttons. */ @Directive() export class MatButtonBase implements AfterViewInit, OnDestroy { _elementRef = inject(ElementRef); _platform = inject(Platform); _ngZone = inject(NgZone); _animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true}); private readonly _focusMonitor = inject(FocusMonitor); /** * Handles the lazy creation of the MatButton ripple. * Used to improve initial load time of large applications. */ protected _rippleLoader: MatRippleLoader = inject(MatRippleLoader); /** Whether this button is a FAB. Used to apply the correct class on the ripple. */ protected _isFab = false; /** * Theme color of the button. This API is supported in M2 themes only, it has * no effect in M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants. */ @Input() color?: string | null; /** Whether the ripple effect is disabled or not. */ @Input({transform: booleanAttribute}) get disableRipple(): boolean { return this._disableRipple; } set disableRipple(value: any) { this._disableRipple = value; this._updateRippleDisabled(); } private _disableRipple: boolean = false; /** Whether the button is disabled. */ @Input({transform: booleanAttribute}) get disabled(): boolean { return this._disabled; } set disabled(value: any) { this._disabled = value; this._updateRippleDisabled(); } private _disabled: boolean = false; /** `aria-disabled` value of the button. */ @Input({transform: booleanAttribute, alias: 'aria-disabled'}) ariaDisabled: boolean | undefined; /** * Natively disabled buttons prevent focus and any pointer events from reaching the button. * In some scenarios this might not be desirable, because it can prevent users from finding out * why the button is disabled (e.g. via tooltip). * * Enabling this input will change the button so that it is styled to be disabled and will be * marked as `aria-disabled`, but it will allow the button to receive events and focus. * * Note that by enabling this, you need to set the `tabindex` yourself if the button isn't * meant to be tabbable and you have to prevent the button action (e.g. form submissions). */ @Input({transform: booleanAttribute}) disabledInteractive: boolean; constructor(...args: unknown[]); constructor() { inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader); const config = inject(MAT_BUTTON_CONFIG, {optional: true}); const element = this._elementRef.nativeElement; const classList = (element as HTMLElement).classList; this.disabledInteractive = config?.disabledInteractive ?? false; this.color = config?.color ?? null; this._rippleLoader?.configureRipple(element, {className: 'mat-mdc-button-ripple'}); // For each of the variant selectors that is present in the button's host // attributes, add the correct corresponding MDC classes. for (const {attribute, mdcClasses} of HOST_SELECTOR_MDC_CLASS_PAIR) { if (element.hasAttribute(attribute)) { classList.add(...mdcClasses); } } } ngAfterViewInit() { this._focusMonitor.monitor(this._elementRef, true); } ngOnDestroy() { this._focusMonitor.stopMonitoring(this._elementRef); this._rippleLoader?.destroyRipple(this._elementRef.nativeElement); } /** Focuses the button. */ focus(origin: FocusOrigin = 'program', options?: FocusOptions): void { if (origin) { this._focusMonitor.focusVia(this._elementRef.nativeElement, origin, options); } else { this._elementRef.nativeElement.focus(options); } } protected _getAriaDisabled() { if (this.ariaDisabled != null) { return this.ariaDisabled; } return this.disabled && this.disabledInteractive ? true : null; } protected _getDisabledAttribute() { return this.disabledInteractive || !this.disabled ? null : true; } private _updateRippleDisabled(): void { this._rippleLoader?.setDisabled( this._elementRef.nativeElement, this.disableRipple || this.disabled, ); } } /** Shared host configuration for buttons using the `<a>` tag. */
{ "end_byte": 7238, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/button-base.ts" }
components/src/material/button/button-base.ts_7239_9247
export const MAT_ANCHOR_HOST = { '[attr.disabled]': '_getDisabledAttribute()', '[class.mat-mdc-button-disabled]': 'disabled', '[class.mat-mdc-button-disabled-interactive]': 'disabledInteractive', '[class._mat-animation-noopable]': '_animationMode === "NoopAnimations"', // Note that we ignore the user-specified tabindex when it's disabled for // consistency with the `mat-button` applied on native buttons where even // though they have an index, they're not tabbable. '[attr.tabindex]': 'disabled && !disabledInteractive ? -1 : tabIndex', '[attr.aria-disabled]': '_getDisabledAttribute()', // MDC automatically applies the primary theme color to the button, but we want to support // an unthemed version. If color is undefined, apply a CSS class that makes it easy to // select and style this "theme". '[class.mat-unthemed]': '!color', // Add a class that applies to all buttons. This makes it easier to target if somebody // wants to target all Material buttons. '[class.mat-mdc-button-base]': 'true', '[class]': 'color ? "mat-" + color : ""', }; /** * Anchor button base. */ @Directive() export class MatAnchorBase extends MatButtonBase implements OnInit, OnDestroy { @Input({ transform: (value: unknown) => { return value == null ? undefined : numberAttribute(value); }, }) tabIndex: number; ngOnInit(): void { this._ngZone.runOutsideAngular(() => { this._elementRef.nativeElement.addEventListener('click', this._haltDisabledEvents); }); } override ngOnDestroy(): void { super.ngOnDestroy(); this._elementRef.nativeElement.removeEventListener('click', this._haltDisabledEvents); } _haltDisabledEvents = (event: Event): void => { // A disabled button shouldn't apply any actions if (this.disabled) { event.preventDefault(); event.stopImmediatePropagation(); } }; protected override _getAriaDisabled() { return this.ariaDisabled == null ? this.disabled : this.ariaDisabled; } }
{ "end_byte": 9247, "start_byte": 7239, "url": "https://github.com/angular/components/blob/main/src/material/button/button-base.ts" }
components/src/material/button/fab.scss_0_6533
@use './button-base'; @use '../core/tokens/token-utils'; @use '../core/style/private' as style-private; @use '../core/style/vendor-prefixes'; @use '../core/focus-indicators/private' as focus-indicators-private; @use '../core/tokens/m2/mdc/extended-fab' as tokens-mdc-extended-fab; @use '../core/tokens/m2/mdc/fab' as tokens-mdc-fab; @use '../core/tokens/m2/mat/fab' as tokens-mat-fab; @use '../core/tokens/m2/mdc/fab-small' as tokens-mdc-fab-small; @use '../core/tokens/m2/mat/fab-small' as tokens-mat-fab-small; .mat-mdc-fab-base { @include vendor-prefixes.user-select(none); position: relative; display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box; width: 56px; height: 56px; padding: 0; border: none; fill: currentColor; text-decoration: none; cursor: pointer; -moz-appearance: none; -webkit-appearance: none; overflow: visible; transition: box-shadow 280ms cubic-bezier(0.4, 0, 0.2, 1), opacity 15ms linear 30ms, transform 270ms 0ms cubic-bezier(0, 0, 0.2, 1); flex-shrink: 0; // Prevent the button from shrinking since it's always supposed to be a circle. @include button-base.mat-private-button-interactive(); @include style-private.private-animation-noop(); &::before { position: absolute; box-sizing: border-box; width: 100%; height: 100%; top: 0; left: 0; border: 1px solid transparent; border-radius: inherit; content: ''; pointer-events: none; } // MDC used to include this and it seems like a lot of apps depend on it. &[hidden] { display: none; } &::-moz-focus-inner { padding: 0; border: 0; } &:active, &:focus { outline: none; } &:hover { cursor: pointer; } & > svg { width: 100%; } // MDC expects the fab icon to contain this HTML content: // ```html // <span class="mdc-fab__icon material-icons">favorite</span> // ``` // However, Angular Material expects a `mat-icon` instead. The following // mixin will style the icons appropriately. // stylelint-disable-next-line selector-class-pattern .mat-icon, .material-icons { transition: transform 180ms 90ms cubic-bezier(0, 0, 0.2, 1); fill: currentColor; will-change: transform; } .mat-focus-indicator::before { $default-border-width: focus-indicators-private.$default-border-width; $border-width: var(--mat-focus-indicator-border-width, #{$default-border-width}); $offset: calc(#{$border-width} + 2px); margin: calc(#{$offset} * -1); } @include button-base.mat-private-button-disabled { // Necessary for interactive disabled buttons. &, &:focus { box-shadow: none; } } } @mixin _fab-elevation($mdc-tokens) { @include token-utils.use-tokens($mdc-tokens...) { @include token-utils.create-token-slot(box-shadow, container-elevation-shadow); &:hover { @include token-utils.create-token-slot(box-shadow, hover-container-elevation-shadow); } &:focus { @include token-utils.create-token-slot(box-shadow, focus-container-elevation-shadow); } &:active, &:focus:active { @include token-utils.create-token-slot(box-shadow, pressed-container-elevation-shadow); } } } @mixin _fab-structure($mdc-tokens, $mat-tokens) { @include token-utils.use-tokens($mdc-tokens...) { @include token-utils.create-token-slot(background-color, container-color); @include token-utils.create-token-slot(border-radius, container-shape); } @include token-utils.use-tokens($mat-tokens...) { @include token-utils.create-token-slot(color, foreground-color, inherit); } @include _fab-elevation($mdc-tokens); @include button-base.mat-private-button-disabled { @include token-utils.use-tokens($mat-tokens...) { @include token-utils.create-token-slot(color, disabled-state-foreground-color); @include token-utils.create-token-slot(background-color, disabled-state-container-color); } } @include button-base.mat-private-button-touch-target(true, $mat-tokens...); @include button-base.mat-private-button-ripple($mat-tokens...); } .mat-mdc-fab { @include _fab-structure( (tokens-mdc-fab.$prefix, tokens-mdc-fab.get-token-slots()), (tokens-mat-fab.$prefix, tokens-mat-fab.get-token-slots()), ); } .mat-mdc-mini-fab { width: 40px; height: 40px; @include _fab-structure( (tokens-mdc-fab-small.$prefix, tokens-mdc-fab-small.get-token-slots()), (tokens-mat-fab-small.$prefix, tokens-mat-fab-small.get-token-slots()), ); } .mat-mdc-extended-fab { $mdc-tokens: (tokens-mdc-extended-fab.$prefix, tokens-mdc-extended-fab.get-token-slots()); // Before tokens MDC included the font smoothing automatically, but with // tokens it doesn't. We add it since it can cause tiny differences in // screenshot tests and it generally looks better. @include vendor-prefixes.smooth-font(); border-radius: 24px; padding-left: 20px; padding-right: 20px; width: auto; max-width: 100%; line-height: normal; @include token-utils.use-tokens($mdc-tokens...) { @include token-utils.create-token-slot(height, container-height); @include token-utils.create-token-slot(border-radius, container-shape); @include token-utils.create-token-slot(font-family, label-text-font); @include token-utils.create-token-slot(font-size, label-text-size); @include token-utils.create-token-slot(font-weight, label-text-weight); @include token-utils.create-token-slot(letter-spacing, label-text-tracking); } @include _fab-elevation($mdc-tokens); @include button-base.mat-private-button-disabled { // Necessary for interactive disabled buttons. &, &:focus { box-shadow: none; } } // stylelint-disable selector-class-pattern // For Extended FAB with text label followed by icon. // We are checking for the a button class because white this is a FAB it // uses the same template as button. [dir='rtl'] & .mdc-button__label + .mat-icon, [dir='rtl'] & .mdc-button__label + .material-icons, > .mat-icon, > .material-icons { margin-left: -8px; margin-right: 12px; } .mdc-button__label + .mat-icon, .mdc-button__label + .material-icons, [dir='rtl'] & > .mat-icon, [dir='rtl'] & > .material-icons { margin-left: 12px; margin-right: -8px; } // stylelint-enable selector-class-pattern // All FABs are square except the extended ones so we // need to set the touch target back to full-width. .mat-mdc-button-touch-target { width: 100%; } }
{ "end_byte": 6533, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/fab.scss" }
components/src/material/button/_button-theme.scss_0_7394
@use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @use '../core/tokens/token-utils'; @use '../core/typography/typography'; @use '../core/tokens/m2/mdc/filled-button' as tokens-mdc-filled-button; @use '../core/tokens/m2/mat/filled-button' as tokens-mat-filled-button; @use '../core/tokens/m2/mdc/outlined-button' as tokens-mdc-outlined-button; @use '../core/tokens/m2/mat/outlined-button' as tokens-mat-outlined-button; @use '../core/tokens/m2/mdc/protected-button' as tokens-mdc-protected-button; @use '../core/tokens/m2/mat/protected-button' as tokens-mat-protected-button; @use '../core/tokens/m2/mdc/text-button' as tokens-mdc-text-button; @use '../core/tokens/m2/mat/text-button' as tokens-mat-text-button; @use '../core/style/sass-utils'; @mixin _text-button-variant($theme, $palette) { $mdc-tokens: if( $palette, tokens-mdc-text-button.private-get-color-palette-color-tokens($theme, $palette), tokens-mdc-text-button.get-color-tokens($theme) ); $mat-tokens: if( $palette, tokens-mat-text-button.private-get-color-palette-color-tokens($theme, $palette), tokens-mat-text-button.get-color-tokens($theme) ); @include token-utils.create-token-values(tokens-mdc-text-button.$prefix, $mdc-tokens); @include token-utils.create-token-values(tokens-mat-text-button.$prefix, $mat-tokens); } @mixin _filled-button-variant($theme, $palette) { $mdc-tokens: if( $palette, tokens-mdc-filled-button.private-get-color-palette-color-tokens($theme, $palette), tokens-mdc-filled-button.get-color-tokens($theme) ); $mat-tokens: if( $palette, tokens-mat-filled-button.private-get-color-palette-color-tokens($theme, $palette), tokens-mat-filled-button.get-color-tokens($theme) ); @include token-utils.create-token-values(tokens-mdc-filled-button.$prefix, $mdc-tokens); @include token-utils.create-token-values(tokens-mat-filled-button.$prefix, $mat-tokens); } @mixin _protected-button-variant($theme, $palette) { $mdc-tokens: if( $palette, tokens-mdc-protected-button.private-get-color-palette-color-tokens($theme, $palette), tokens-mdc-protected-button.get-color-tokens($theme) ); $mat-tokens: if( $palette, tokens-mat-protected-button.private-get-color-palette-color-tokens($theme, $palette), tokens-mat-protected-button.get-color-tokens($theme) ); @include token-utils.create-token-values(tokens-mdc-protected-button.$prefix, $mdc-tokens); @include token-utils.create-token-values(tokens-mat-protected-button.$prefix, $mat-tokens); } @mixin _outlined-button-variant($theme, $palette) { $mdc-tokens: if( $palette, tokens-mdc-outlined-button.private-get-color-palette-color-tokens($theme, $palette), tokens-mdc-outlined-button.get-color-tokens($theme) ); $mat-tokens: if( $palette, tokens-mat-outlined-button.private-get-color-palette-color-tokens($theme, $palette), tokens-mat-outlined-button.get-color-tokens($theme) ); @include token-utils.create-token-values(tokens-mdc-outlined-button.$prefix, $mdc-tokens); @include token-utils.create-token-values(tokens-mat-outlined-button.$prefix, $mat-tokens); } @mixin _theme-from-tokens($tokens, $options...) { @include validation.selector-defined( 'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector' ); $mdc-text-button-tokens: token-utils.get-tokens-for( $tokens, tokens-mdc-text-button.$prefix, $options... ); $mdc-protected-button-tokens: token-utils.get-tokens-for( $tokens, tokens-mdc-protected-button.$prefix, $options... ); $mdc-filled-button-tokens: token-utils.get-tokens-for( $tokens, tokens-mdc-filled-button.$prefix, $options... ); $mdc-outlined-button-tokens: token-utils.get-tokens-for( $tokens, tokens-mdc-outlined-button.$prefix, $options... ); $mat-text-button-tokens: token-utils.get-tokens-for( $tokens, tokens-mat-text-button.$prefix, $options... ); $mat-protected-button-tokens: token-utils.get-tokens-for( $tokens, tokens-mat-protected-button.$prefix, $options... ); $mat-filled-button-tokens: token-utils.get-tokens-for( $tokens, tokens-mat-filled-button.$prefix, $options... ); $mat-outlined-button-tokens: token-utils.get-tokens-for( $tokens, tokens-mat-outlined-button.$prefix, $options... ); @include token-utils.create-token-values(tokens-mdc-text-button.$prefix, $mdc-text-button-tokens); @include token-utils.create-token-values( tokens-mdc-protected-button.$prefix, $mdc-protected-button-tokens ); @include token-utils.create-token-values( tokens-mdc-filled-button.$prefix, $mdc-filled-button-tokens ); @include token-utils.create-token-values( tokens-mdc-outlined-button.$prefix, $mdc-outlined-button-tokens ); @include token-utils.create-token-values(tokens-mat-text-button.$prefix, $mat-text-button-tokens); @include token-utils.create-token-values( tokens-mat-protected-button.$prefix, $mat-protected-button-tokens ); @include token-utils.create-token-values( tokens-mat-filled-button.$prefix, $mat-filled-button-tokens ); @include token-utils.create-token-values( tokens-mat-outlined-button.$prefix, $mat-outlined-button-tokens ); } /// Outputs base theme styles (styles not dependent on the color, typography, or density settings) /// for the mat-button. /// @param {Map} $theme The theme to generate base styles for. @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-mdc-text-button.$prefix, tokens-mdc-text-button.get-unthemable-tokens() ); @include token-utils.create-token-values( tokens-mdc-filled-button.$prefix, tokens-mdc-filled-button.get-unthemable-tokens() ); @include token-utils.create-token-values( tokens-mdc-protected-button.$prefix, tokens-mdc-protected-button.get-unthemable-tokens() ); @include token-utils.create-token-values( tokens-mdc-outlined-button.$prefix, tokens-mdc-outlined-button.get-unthemable-tokens() ); @include token-utils.create-token-values( tokens-mat-text-button.$prefix, tokens-mat-text-button.get-unthemable-tokens() ); @include token-utils.create-token-values( tokens-mat-filled-button.$prefix, tokens-mat-filled-button.get-unthemable-tokens() ); @include token-utils.create-token-values( tokens-mat-protected-button.$prefix, tokens-mat-protected-button.get-unthemable-tokens() ); @include token-utils.create-token-values( tokens-mat-outlined-button.$prefix, tokens-mat-outlined-button.get-unthemable-tokens() ); } } } /// Outputs color theme styles for the mat-button. /// @param {Map} $theme The theme to generate color styles for. /// @param {ArgList} Additional optional arguments (only supported for M3 themes): /// $color-variant: The color variant to use for the button: primary, secondary, tertiary, /// or error (If not specified, default primary color will be used).
{ "end_byte": 7394, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/_button-theme.scss" }
components/src/material/button/_button-theme.scss_7395_15367
@mixin color($theme, $options...) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, color), $options...); } @else { @include sass-utils.current-selector-or-root() { @include _text-button-variant($theme, null); @include _filled-button-variant($theme, null); @include _protected-button-variant($theme, null); @include _outlined-button-variant($theme, null); } .mat-mdc-button { &.mat-primary { @include _text-button-variant($theme, primary); } &.mat-accent { @include _text-button-variant($theme, accent); } &.mat-warn { @include _text-button-variant($theme, warn); } } .mat-mdc-unelevated-button { &.mat-primary { @include _filled-button-variant($theme, primary); } &.mat-accent { @include _filled-button-variant($theme, accent); } &.mat-warn { @include _filled-button-variant($theme, warn); } } .mat-mdc-raised-button { &.mat-primary { @include _protected-button-variant($theme, primary); } &.mat-accent { @include _protected-button-variant($theme, accent); } &.mat-warn { @include _protected-button-variant($theme, warn); } } .mat-mdc-outlined-button { &.mat-primary { @include _outlined-button-variant($theme, primary); } &.mat-accent { @include _outlined-button-variant($theme, accent); } &.mat-warn { @include _outlined-button-variant($theme, warn); } } } } /// Outputs typography theme styles for the mat-button. /// @param {Map} $theme The theme to generate typography styles for. @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-mdc-text-button.$prefix, tokens-mdc-text-button.get-typography-tokens($theme) ); @include token-utils.create-token-values( tokens-mdc-filled-button.$prefix, tokens-mdc-filled-button.get-typography-tokens($theme) ); @include token-utils.create-token-values( tokens-mdc-protected-button.$prefix, tokens-mdc-protected-button.get-typography-tokens($theme) ); @include token-utils.create-token-values( tokens-mdc-outlined-button.$prefix, tokens-mdc-outlined-button.get-typography-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-text-button.$prefix, tokens-mat-text-button.get-typography-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-filled-button.$prefix, tokens-mat-filled-button.get-typography-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-protected-button.$prefix, tokens-mat-protected-button.get-typography-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-outlined-button.$prefix, tokens-mat-outlined-button.get-typography-tokens($theme) ); } } } /// Outputs density theme styles for the mat-button. /// @param {Map} $theme The theme to generate density styles for. @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-mdc-text-button.$prefix, tokens-mdc-text-button.get-density-tokens($theme) ); @include token-utils.create-token-values( tokens-mdc-filled-button.$prefix, tokens-mdc-filled-button.get-density-tokens($theme) ); @include token-utils.create-token-values( tokens-mdc-protected-button.$prefix, tokens-mdc-protected-button.get-density-tokens($theme) ); @include token-utils.create-token-values( tokens-mdc-outlined-button.$prefix, tokens-mdc-outlined-button.get-density-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-text-button.$prefix, tokens-mat-text-button.get-density-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-filled-button.$prefix, tokens-mat-filled-button.get-density-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-protected-button.$prefix, tokens-mat-protected-button.get-density-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-outlined-button.$prefix, tokens-mat-outlined-button.get-density-tokens($theme) ); } } } /// Defines the tokens that will be available in the `overrides` mixin and for docs extraction. @function _define-overrides() { $mdc-filled-button-tokens: tokens-mdc-filled-button.get-token-slots(); $mat-filled-button-tokens: tokens-mat-filled-button.get-token-slots(); $mdc-outlined-button-tokens: tokens-mdc-outlined-button.get-token-slots(); $mat-outlined-button-tokens: tokens-mat-outlined-button.get-token-slots(); $mdc-protected-button-tokens: tokens-mdc-protected-button.get-token-slots(); $mat-protected-button-tokens: tokens-mat-protected-button.get-token-slots(); $mdc-text-button-tokens: tokens-mdc-text-button.get-token-slots(); $mat-text-button-tokens: tokens-mat-text-button.get-token-slots(); @return ( ( namespace: tokens-mdc-filled-button.$prefix, tokens: $mdc-filled-button-tokens, prefix: 'filled-', ), ( namespace: tokens-mat-filled-button.$prefix, tokens: $mat-filled-button-tokens, prefix: 'filled-', ), ( namespace: tokens-mdc-outlined-button.$prefix, tokens: $mdc-outlined-button-tokens, prefix: 'outlined-', ), ( namespace: tokens-mat-outlined-button.$prefix, tokens: $mat-outlined-button-tokens, prefix: 'outlined-', ), ( namespace: tokens-mdc-protected-button.$prefix, tokens: $mdc-protected-button-tokens, prefix: 'protected-', ), ( namespace: tokens-mat-protected-button.$prefix, tokens: $mat-protected-button-tokens, prefix: 'protected-', ), ( namespace: tokens-mdc-text-button.$prefix, tokens: $mdc-text-button-tokens, prefix: 'text-', ), ( namespace: tokens-mat-text-button.$prefix, tokens: $mat-text-button-tokens, prefix: 'text-', ), ); } /// Outputs the CSS variable values for the given tokens. /// @param {Map} $tokens The token values to emit. @mixin overrides($tokens: ()) { @include token-utils.batch-create-token-values($tokens, _define-overrides()...); } /// Outputs all (base, color, typography, and density) theme styles for the mat-button. /// @param {Map} $theme The theme to generate styles for. /// @param {ArgList} Additional optional arguments (only supported for M3 themes): /// $color-variant: The color variant to use for the button: primary, secondary, tertiary, /// or error (If not specified, default primary color will be used). @mixin theme($theme, $options...) { @include theming.private-check-duplicate-theme-styles($theme, 'mat-button') { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme), $options...); } @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); } } } }
{ "end_byte": 15367, "start_byte": 7395, "url": "https://github.com/angular/components/blob/main/src/material/button/_button-theme.scss" }
components/src/material/button/icon-button.ts_0_1713
/** * @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, ViewEncapsulation} from '@angular/core'; import {MAT_ANCHOR_HOST, MAT_BUTTON_HOST, MatAnchorBase, MatButtonBase} from './button-base'; /** * Material Design icon button component. This type of button displays a single interactive icon for * users to perform an action. * See https://material.io/develop/web/components/buttons/icon-buttons/ */ @Component({ selector: `button[mat-icon-button]`, templateUrl: 'icon-button.html', styleUrls: ['icon-button.css', 'button-high-contrast.css'], host: MAT_BUTTON_HOST, exportAs: 'matButton', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) export class MatIconButton extends MatButtonBase { constructor(...args: unknown[]); constructor() { super(); this._rippleLoader.configureRipple(this._elementRef.nativeElement, {centered: true}); } } /** * Material Design icon button component for anchor elements. This button displays a single * interaction icon that allows users to navigate across different routes or pages. * See https://material.io/develop/web/components/buttons/icon-buttons/ */ @Component({ selector: `a[mat-icon-button]`, templateUrl: 'icon-button.html', styleUrls: ['icon-button.css', 'button-high-contrast.css'], host: MAT_ANCHOR_HOST, exportAs: 'matButton, matAnchor', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) export class MatIconAnchor extends MatAnchorBase {}
{ "end_byte": 1713, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/icon-button.ts" }
components/src/material/button/BUILD.bazel_0_2189
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 = "button", srcs = glob( ["**/*.ts"], exclude = [ "**/*.spec.ts", ], ), assets = [ ":button_high_contrast_scss", ":button_scss", ":fab_scss", ":icon-button_scss", ] + glob(["**/*.html"]), deps = [ "//src/cdk/platform", "//src/material/core", ], ) sass_library( name = "button_scss_lib", srcs = glob(["**/_*.scss"]), deps = [ "//src/material/core:core_scss_lib", ], ) sass_library( name = "button_base_scss_lib", srcs = ["_button-base.scss"], ) sass_binary( name = "button_scss", src = "button.scss", deps = [ ":button_base_scss_lib", "//src/material:sass_lib", "//src/material/core:core_scss_lib", ], ) sass_binary( name = "button_high_contrast_scss", src = "button-high-contrast.scss", deps = [ "//src/cdk:sass_lib", ], ) sass_binary( name = "fab_scss", src = "fab.scss", deps = [ ":button_base_scss_lib", "//src/material:sass_lib", "//src/material/core:core_scss_lib", ], ) sass_binary( name = "icon-button_scss", src = "icon-button.scss", deps = [ ":button_base_scss_lib", "//src/material:sass_lib", "//src/material/core:core_scss_lib", ], ) ng_test_library( name = "button_tests_lib", srcs = glob( ["**/*.spec.ts"], ), deps = [ ":button", "//src/cdk/platform", "//src/cdk/testing/private", "//src/material/core", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":button_tests_lib", ], ) markdown_to_html( name = "overview", srcs = [":button.md"], ) extract_tokens( name = "tokens", srcs = [":button_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "end_byte": 2189, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/BUILD.bazel" }
components/src/material/button/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/button/index.ts" }
components/src/material/button/_fab-theme.scss_0_7302
@use '../core/style/sass-utils'; @use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @use '../core/tokens/m2/mdc/fab' as tokens-mdc-fab; @use '../core/tokens/m2/mdc/fab-small' as tokens-mdc-fab-small; @use '../core/tokens/m2/mdc/extended-fab' as tokens-mdc-extended-fab; @use '../core/tokens/m2/mat/fab' as tokens-mat-fab; @use '../core/tokens/m2/mat/fab-small' as tokens-mat-fab-small; @use '../core/tokens/token-utils'; @use '../core/typography/typography'; /// Outputs base theme styles (styles not dependent on the color, typography, or density settings) /// for the mat-fab. /// @param {Map} $theme The theme to generate base styles for. @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-mdc-fab.$prefix, tokens-mdc-fab.get-unthemable-tokens() ); @include token-utils.create-token-values( tokens-mdc-fab-small.$prefix, tokens-mdc-fab-small.get-unthemable-tokens() ); @include token-utils.create-token-values( tokens-mdc-extended-fab.$prefix, tokens-mdc-extended-fab.get-unthemable-tokens() ); } } } @mixin _fab-variant($theme, $palette) { $mdc-tokens: if( $palette, tokens-mdc-fab.private-get-color-palette-color-tokens($theme, $palette), tokens-mdc-fab.get-color-tokens($theme) ); $mat-tokens: if( $palette, tokens-mat-fab.private-get-color-palette-color-tokens($theme, $palette), tokens-mat-fab.get-color-tokens($theme) ); @include token-utils.create-token-values(tokens-mdc-fab.$prefix, $mdc-tokens); @include token-utils.create-token-values(tokens-mat-fab.$prefix, $mat-tokens); } @mixin _fab-small-variant($theme, $palette) { $mdc-tokens: if( $palette, tokens-mdc-fab-small.private-get-color-palette-color-tokens($theme, $palette), tokens-mdc-fab-small.get-color-tokens($theme) ); $mat-tokens: if( $palette, tokens-mat-fab-small.private-get-color-palette-color-tokens($theme, $palette), tokens-mat-fab-small.get-color-tokens($theme) ); @include token-utils.create-token-values(tokens-mdc-fab-small.$prefix, $mdc-tokens); @include token-utils.create-token-values(tokens-mat-fab-small.$prefix, $mat-tokens); } /// Outputs color theme styles for the mat-fab. /// @param {Map} $theme The theme to generate color styles for. /// @param {ArgList} Additional optional arguments (only supported for M3 themes): /// $color-variant: The color variant to use for the fab: primary, secondary, or tertiary /// (If not specified, default primary color will be used). @mixin color($theme, $options...) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, color), $options...); } @else { @include sass-utils.current-selector-or-root() { @include _fab-variant($theme, null); @include _fab-small-variant($theme, null); @include token-utils.create-token-values( tokens-mdc-extended-fab.$prefix, tokens-mdc-extended-fab.get-color-tokens($theme) ); .mat-mdc-fab { &.mat-primary { @include _fab-variant($theme, primary); } &.mat-accent { @include _fab-variant($theme, accent); } &.mat-warn { @include _fab-variant($theme, warn); } } .mat-mdc-mini-fab { &.mat-primary { @include _fab-small-variant($theme, primary); } &.mat-accent { @include _fab-small-variant($theme, accent); } &.mat-warn { @include _fab-small-variant($theme, warn); } } } } } /// Outputs typography theme styles for the mat-fab. /// @param {Map} $theme The theme to generate typography styles for. @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-mdc-extended-fab.$prefix, tokens-mdc-extended-fab.get-typography-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-fab.$prefix, tokens-mat-fab.get-typography-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-fab-small.$prefix, tokens-mat-fab-small.get-typography-tokens($theme) ); } } } /// Outputs density theme styles for the mat-fab. /// @param {Map} $theme The theme to generate density styles for. @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-fab.$prefix, tokens-mat-fab.get-density-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-fab-small.$prefix, tokens-mat-fab-small.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-mdc-fab.$prefix, tokens: tokens-mdc-fab.get-token-slots(), ), ( namespace: tokens-mdc-fab-small.$prefix, tokens: tokens-mdc-fab-small.get-token-slots(), prefix: 'small-', ), ( namespace: tokens-mdc-extended-fab.$prefix, tokens: tokens-mdc-extended-fab.get-token-slots(), prefix: 'extended-', ), ( namespace: tokens-mat-fab.$prefix, tokens: tokens-mat-fab.get-token-slots(), ), ( namespace: tokens-mat-fab-small.$prefix, tokens: tokens-mat-fab-small.get-token-slots(), prefix: 'small-', ), ); } /// Outputs the CSS variable values for the given tokens. /// @param {Map} $tokens The token values to emit. @mixin overrides($tokens: ()) { @include token-utils.batch-create-token-values($tokens, _define-overrides()...); } /// Outputs all (base, color, typography, and density) theme styles for the mat-checkbox. /// @param {Map} $theme The theme to generate styles for. /// @param {ArgList} Additional optional arguments (only supported for M3 themes): /// $color-variant: The color variant to use for the fab: primary, secondary, or tertiary /// (If not specified, default primary color will be used). @mixin theme($theme, $options...) { @include theming.private-check-duplicate-theme-styles($theme, 'mat-fab') { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme), $options...); } @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); } } } }
{ "end_byte": 7302, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/_fab-theme.scss" }
components/src/material/button/_fab-theme.scss_7304_8526
@mixin _theme-from-tokens($tokens, $options...) { @include validation.selector-defined( 'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector' ); $mdc-extended-fab-tokens: token-utils.get-tokens-for( $tokens, tokens-mdc-extended-fab.$prefix, $options... ); $mdc-fab-tokens: token-utils.get-tokens-for($tokens, tokens-mdc-fab.$prefix, $options...); $mdc-fab-small-tokens: token-utils.get-tokens-for( $tokens, tokens-mdc-fab-small.$prefix, $options... ); $mat-fab-tokens: token-utils.get-tokens-for($tokens, tokens-mat-fab.$prefix, $options...); $mat-fab-small-tokens: token-utils.get-tokens-for( $tokens, tokens-mat-fab-small.$prefix, $options... ); @include token-utils.create-token-values( tokens-mdc-extended-fab.$prefix, $mdc-extended-fab-tokens ); @include token-utils.create-token-values(tokens-mdc-fab.$prefix, $mdc-fab-tokens); @include token-utils.create-token-values(tokens-mdc-fab-small.$prefix, $mdc-fab-small-tokens); @include token-utils.create-token-values(tokens-mat-fab.$prefix, $mat-fab-tokens); @include token-utils.create-token-values(tokens-mat-fab-small.$prefix, $mat-fab-small-tokens); }
{ "end_byte": 8526, "start_byte": 7304, "url": "https://github.com/angular/components/blob/main/src/material/button/_fab-theme.scss" }
components/src/material/button/_button-base.scss_0_6153
@use '../core/tokens/token-utils'; @use '../core/style/layout-common'; // Adds styles necessary to provide stateful interactions with the button. This includes providing // content for the state container's ::before and ::after so that they can be given a background // color and opacity for states like hover, active, and focus. Additionally, adds styles to the // ripple and state container so that they fill the button, match the border radius, and avoid // pointer events. @mixin mat-private-button-interactive() { -webkit-tap-highlight-color: transparent; // The ripple container should match the bounds of the entire button. .mat-mdc-button-ripple, .mat-mdc-button-persistent-ripple, .mat-mdc-button-persistent-ripple::before { @include layout-common.fill; // Disable pointer events for the ripple container and state overlay because the container // will overlay the user content and we don't want to disable mouse events on the user content. // Pointer events can be safely disabled because the ripple trigger element is the host element. pointer-events: none; // Inherit the border radius from the parent so that state overlay and ripples don't exceed the // parent button boundaries. Note that an inherited border radius does not work properly if // the actual button element does have a border because it causes the inner content to be // smaller. We have special logic for stroked buttons to handle this scenario. border-radius: inherit; } // This style used to be applied by the MatRipple // directive, which is no longer attached to this element. .mat-mdc-button-ripple { overflow: hidden; } // We use ::before so that we can reuse some of MDC's theming. .mat-mdc-button-persistent-ripple::before { content: ''; opacity: 0; } // The content should appear over the state and ripple layers, otherwise they may adversely affect // the accessibility of the text content. .mdc-button__label, .mat-icon { z-index: 1; position: relative; } // The focus indicator should match the bounds of the entire button. .mat-focus-indicator { @include layout-common.fill(); } &:focus .mat-focus-indicator::before { content: ''; } } @mixin mat-private-button-ripple($prefix, $slots) { @include token-utils.use-tokens($prefix, $slots) { .mat-ripple-element { @include token-utils.create-token-slot(background-color, ripple-color); } .mat-mdc-button-persistent-ripple::before { @include token-utils.create-token-slot(background-color, state-layer-color); } &.mat-mdc-button-disabled .mat-mdc-button-persistent-ripple::before { @include token-utils.create-token-slot(background-color, disabled-state-layer-color); } &:hover .mat-mdc-button-persistent-ripple::before { @include token-utils.create-token-slot(opacity, hover-state-layer-opacity); } &.cdk-program-focused, &.cdk-keyboard-focused, &.mat-mdc-button-disabled-interactive:focus { .mat-mdc-button-persistent-ripple::before { @include token-utils.create-token-slot(opacity, focus-state-layer-opacity); } } &:active .mat-mdc-button-persistent-ripple::before { @include token-utils.create-token-slot(opacity, pressed-state-layer-opacity); } } } // MDC's disabled buttons define a default cursor with pointer-events none. However, they select // :disabled for this, which does not affect anchor tags. // TODO(andrewseguin): Discuss with the MDC team about a mixin we can call for applying this style, // and note that having pointer-events may have unintended side-effects, e.g. allowing the user // to click the target underneath the button. @mixin mat-private-button-disabled() { // `[disabled]` shouldn't be necessary, but we keep it to maintain // compatibility with apps setting it through host bindings. &[disabled], &.mat-mdc-button-disabled { cursor: default; pointer-events: none; @content; } &.mat-mdc-button-disabled-interactive { pointer-events: auto; } } // Adds an elevation shadow to a button. @mixin mat-private-button-elevation($token-name) { // MDC outputs a variable that is the same as the token name, but suffixed with `-shadow`. box-shadow: token-utils.get-token-variable($token-name + '-shadow'); } @mixin mat-private-button-touch-target($is-square, $prefix, $slots) { .mat-mdc-button-touch-target { position: absolute; top: 50%; height: 48px; @if $is-square { left: 50%; width: 48px; transform: translate(-50%, -50%); } @else { left: 0; right: 0; transform: translateY(-50%); } @include token-utils.use-tokens($prefix, $slots) { @include token-utils.create-token-slot(display, touch-target-display); } } } @mixin mat-private-button-horizontal-layout($prefix, $slots, $has-with-icon-padding) { @include token-utils.use-tokens($prefix, $slots) { $icon-spacing: token-utils.get-token-variable(icon-spacing, true); $icon-offset: token-utils.get-token-variable(icon-offset, true); @if ($has-with-icon-padding) { $with-icon-horizontal-padding: token-utils.get-token-variable(with-icon-horizontal-padding, true); // stylelint-disable-next-line selector-class-pattern &:has(.material-icons, mat-icon, [matButtonIcon]) { padding: 0 $with-icon-horizontal-padding; } } // MDC expects button icons to contain this HTML content: // ```html // <span class="mdc-button__icon material-icons">favorite</span> // ``` // However, Angular Material expects a `mat-icon` instead. The following // styles will lay out the icons appropriately. & > .mat-icon { margin-right: $icon-spacing; margin-left: $icon-offset; [dir='rtl'] & { margin-right: $icon-offset; margin-left: $icon-spacing; } } .mdc-button__label + .mat-icon { margin-right: $icon-offset; margin-left: $icon-spacing; [dir='rtl'] & { margin-right: $icon-spacing; margin-left: $icon-offset; } } } }
{ "end_byte": 6153, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/_button-base.scss" }
components/src/material/button/testing/public-api.ts_0_280
/** * @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 './button-harness'; export * from './button-harness-filters';
{ "end_byte": 280, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/testing/public-api.ts" }
components/src/material/button/testing/button-harness-filters.ts_0_809
/** * @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'; /** Possible button appearances. */ export type ButtonVariant = 'basic' | 'raised' | 'flat' | 'icon' | 'stroked' | 'fab' | 'mini-fab'; /** A set of criteria that can be used to filter a list of button harness instances. */ export interface ButtonHarnessFilters extends BaseHarnessFilters { /** Only find instances whose text matches the given value. */ text?: string | RegExp; /** Only find instances with a variant. */ variant?: ButtonVariant; /** Only find instances which match the given disabled state. */ disabled?: boolean; }
{ "end_byte": 809, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/testing/button-harness-filters.ts" }
components/src/material/button/testing/BUILD.bazel_0_899
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/testing", "@npm//@angular/core", ], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), ) ng_test_library( name = "unit_tests_lib", srcs = glob(["**/*.spec.ts"]), deps = [ ":testing", "//src/cdk/platform", "//src/cdk/testing", "//src/cdk/testing/testbed", "//src/material/button", "//src/material/icon", "//src/material/icon/testing", "@npm//@angular/forms", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":unit_tests_lib", ], )
{ "end_byte": 899, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/testing/BUILD.bazel" }
components/src/material/button/testing/button-harness.ts_0_4039
/** * @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 {booleanAttribute} from '@angular/core'; import { ComponentHarnessConstructor, ContentContainerComponentHarness, HarnessPredicate, } from '@angular/cdk/testing'; import {ButtonHarnessFilters, ButtonVariant} from './button-harness-filters'; /** Harness for interacting with a mat-button in tests. */ export class MatButtonHarness extends ContentContainerComponentHarness { // TODO(jelbourn) use a single class, like `.mat-button-base` static hostSelector = `[mat-button], [mat-raised-button], [mat-flat-button], [mat-icon-button], [mat-stroked-button], [mat-fab], [mat-mini-fab]`; /** * Gets a `HarnessPredicate` that can be used to search for a button with specific attributes. * @param options Options for narrowing the search: * - `selector` finds a button whose host element matches the given selector. * - `text` finds a button with specific text content. * - `variant` finds buttons matching a specific variant. * @return a `HarnessPredicate` configured with the given options. */ static with<T extends MatButtonHarness>( this: ComponentHarnessConstructor<T>, options: ButtonHarnessFilters = {}, ): HarnessPredicate<T> { return new HarnessPredicate(this, options) .addOption('text', options.text, (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text), ) .addOption('variant', options.variant, (harness, variant) => HarnessPredicate.stringMatches(harness.getVariant(), variant), ) .addOption('disabled', options.disabled, async (harness, disabled) => { return (await harness.isDisabled()) === disabled; }); } /** * Clicks the button at the given position relative to its top-left. * @param relativeX The relative x position of the click. * @param relativeY The relative y position of the click. */ click(relativeX: number, relativeY: number): Promise<void>; /** Clicks the button at its center. */ click(location: 'center'): Promise<void>; /** Clicks the button. */ click(): Promise<void>; async click(...args: [] | ['center'] | [number, number]): Promise<void> { return (await this.host()).click(...(args as [])); } /** Gets a boolean promise indicating if the button is disabled. */ async isDisabled(): Promise<boolean> { const host = await this.host(); return ( booleanAttribute(await host.getAttribute('disabled')) || (await host.hasClass('mat-mdc-button-disabled')) ); } /** Gets a promise for the button's label text. */ async getText(): Promise<string> { return (await this.host()).text(); } /** Focuses the button and returns a void promise that indicates when the action is complete. */ async focus(): Promise<void> { return (await this.host()).focus(); } /** Blurs the button and returns a void promise that indicates when the action is complete. */ async blur(): Promise<void> { return (await this.host()).blur(); } /** Whether the button is focused. */ async isFocused(): Promise<boolean> { return (await this.host()).isFocused(); } /** Gets the variant of the button. */ async getVariant(): Promise<ButtonVariant> { const host = await this.host(); if ((await host.getAttribute('mat-raised-button')) != null) { return 'raised'; } else if ((await host.getAttribute('mat-flat-button')) != null) { return 'flat'; } else if ((await host.getAttribute('mat-icon-button')) != null) { return 'icon'; } else if ((await host.getAttribute('mat-stroked-button')) != null) { return 'stroked'; } else if ((await host.getAttribute('mat-fab')) != null) { return 'fab'; } else if ((await host.getAttribute('mat-mini-fab')) != null) { return 'mini-fab'; } return 'basic'; } }
{ "end_byte": 4039, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/testing/button-harness.ts" }
components/src/material/button/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/button/testing/index.ts" }
components/src/material/button/testing/button-harness.spec.ts_0_7059
import {Component} from '@angular/core'; import {ComponentFixture, inject, TestBed} from '@angular/core/testing'; import {Platform, PlatformModule} from '@angular/cdk/platform'; import {HarnessLoader, parallel} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {MatButtonModule} from '@angular/material/button'; import {MatIconModule} from '@angular/material/icon'; import {MatIconHarness} from '@angular/material/icon/testing'; import {MatButtonHarness} from './button-harness'; describe('MatButtonHarness', () => { let fixture: ComponentFixture<ButtonHarnessTest>; let loader: HarnessLoader; let platform: Platform; beforeEach(() => { TestBed.configureTestingModule({ imports: [MatButtonModule, MatIconModule, PlatformModule, ButtonHarnessTest], }); fixture = TestBed.createComponent(ButtonHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); beforeEach(inject([Platform], (p: Platform) => { platform = p; })); it('should load all button harnesses', async () => { const buttons = await loader.getAllHarnesses(MatButtonHarness); expect(buttons.length).toBe(15); }); it('should load button with exact text', async () => { const buttons = await loader.getAllHarnesses(MatButtonHarness.with({text: 'Basic button'})); expect(buttons.length).toBe(1); expect(await buttons[0].getText()).toBe('Basic button'); }); it('should load button with regex label match', async () => { const buttons = await loader.getAllHarnesses(MatButtonHarness.with({text: /basic/i})); expect(buttons.length).toBe(2); expect(await buttons[0].getText()).toBe('Basic button'); expect(await buttons[1].getText()).toBe('Basic anchor'); }); it('should filter by whether a button is disabled', async () => { const enabledButtons = await loader.getAllHarnesses(MatButtonHarness.with({disabled: false})); const disabledButtons = await loader.getAllHarnesses(MatButtonHarness.with({disabled: true})); expect(enabledButtons.length).toBe(13); expect(disabledButtons.length).toBe(2); }); it('should get disabled state', async () => { // Grab each combination of [enabled, disabled] ⨯ [button, anchor] const [disabledFlatButton, enabledFlatAnchor] = await loader.getAllHarnesses( MatButtonHarness.with({text: /flat/i}), ); const [enabledRaisedButton, disabledRaisedAnchor] = await loader.getAllHarnesses( MatButtonHarness.with({text: /raised/i}), ); expect(await enabledFlatAnchor.isDisabled()).toBe(false); expect(await disabledFlatButton.isDisabled()).toBe(true); expect(await enabledRaisedButton.isDisabled()).toBe(false); expect(await disabledRaisedAnchor.isDisabled()).toBe(true); }); it('should get button text', async () => { const [firstButton, secondButton] = await loader.getAllHarnesses(MatButtonHarness); expect(await firstButton.getText()).toBe('Basic button'); expect(await secondButton.getText()).toBe('Flat button'); }); it('should focus and blur a button', async () => { const button = await loader.getHarness(MatButtonHarness.with({text: 'Basic button'})); expect(await button.isFocused()).toBe(false); await button.focus(); expect(await button.isFocused()).toBe(true); await button.blur(); expect(await button.isFocused()).toBe(false); }); it('should click a button', async () => { const button = await loader.getHarness(MatButtonHarness.with({text: 'Basic button'})); await button.click(); expect(fixture.componentInstance.clicked).toBe(true); }); it('should not click a disabled button', async () => { // Older versions of Edge have a bug where `disabled` buttons are still clickable if // they contain child elements. Also new versions of Firefox (starting v65) do not // cancel dispatched click events on disabled buttons. We skip this check on Edge and Firefox. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1582570 and: // https://stackoverflow.com/questions/32377026/disabled-button-is-clickable-on-edge-browser if (platform.FIREFOX) { return; } const button = await loader.getHarness(MatButtonHarness.with({text: 'Flat button'})); await button.click(); expect(fixture.componentInstance.clicked).toBe(false); }); it('should be able to handle nested harnesses', async () => { const homeBtn = await loader.getHarness(MatButtonHarness.with({selector: '#home-icon'})); const favBtn = await loader.getHarness(MatButtonHarness.with({selector: '#favorite-icon'})); const homeIcon = await homeBtn.getHarness(MatIconHarness); const favIcon = await favBtn.getHarness(MatIconHarness); expect(await homeIcon.getName()).toBe('home'); expect(await favIcon.getName()).toBe('favorite'); }); it('should load all button harnesses', async () => { const buttons = await loader.getAllHarnesses(MatButtonHarness); const variants = await parallel(() => buttons.map(button => button.getVariant())); expect(variants).toEqual([ 'basic', 'flat', 'raised', 'stroked', 'icon', 'icon', 'fab', 'mini-fab', 'basic', 'flat', 'raised', 'stroked', 'icon', 'fab', 'mini-fab', ]); }); it('should be able to filter buttons based on their variant', async () => { const button = await loader.getHarness(MatButtonHarness.with({variant: 'flat'})); expect(await button.getText()).toBe('Flat button'); }); }); @Component({ // Include one of each type of button selector to ensure that they're all captured by // the harness's selector. template: ` <button id="basic" type="button" mat-button (click)="clicked = true"> Basic button </button> <button id="flat" type="button" mat-flat-button disabled (click)="clicked = true"> Flat button </button> <button id="raised" type="button" mat-raised-button>Raised button</button> <button id="stroked" type="button" mat-stroked-button>Stroked button</button> <button id="home-icon" type="button" mat-icon-button> <mat-icon>home</mat-icon> </button> <button id="favorite-icon" type="button" mat-icon-button> <mat-icon>favorite</mat-icon> </button> <button id="fab" type="button" mat-fab>Fab button</button> <button id="mini-fab" type="button" mat-mini-fab>Mini Fab button</button> <a id="anchor-basic" mat-button>Basic anchor</a> <a id="anchor-flat" mat-flat-button>Flat anchor</a> <a id="anchor-raised" mat-raised-button disabled>Raised anchor</a> <a id="anchor-stroked" mat-stroked-button>Stroked anchor</a> <a id="anchor-icon" mat-icon-button>Icon anchor</a> <a id="anchor-fab" mat-fab>Fab anchor</a> <a id="anchor-mini-fab" mat-mini-fab>Mini Fab anchor</a> `, standalone: true, imports: [MatButtonModule, MatIconModule, PlatformModule], }) class ButtonHarnessTest { disabled = true; clicked = false; }
{ "end_byte": 7059, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/button/testing/button-harness.spec.ts" }
components/src/material/table/table.spec.ts_0_8537
import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core'; import { waitForAsync, ComponentFixture, fakeAsync, flushMicrotasks, TestBed, tick, } from '@angular/core/testing'; import {MatTable, MatTableDataSource, MatTableModule} from './index'; import {DataSource} from '@angular/cdk/table'; import {BehaviorSubject, Observable} from 'rxjs'; import {MatSort, MatSortHeader, MatSortModule} from '@angular/material/sort'; import {MatPaginator, MatPaginatorModule} from '@angular/material/paginator'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; describe('MatTable', () => { beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ MatTableModule, MatPaginatorModule, MatSortModule, NoopAnimationsModule, MatTableApp, MatTableWithWhenRowApp, ArrayDataSourceMatTableApp, NativeHtmlTableApp, MatTableWithSortApp, MatTableWithPaginatorApp, StickyTableApp, TableWithNgContainerRow, NestedTableApp, MatFlexTableApp, ], }); })); describe('with basic data source', () => { it('should be able to create a table with the right content and without when row', () => { let fixture = TestBed.createComponent(MatTableApp); fixture.detectChanges(); const tableElement = fixture.nativeElement.querySelector('table')!; const data = fixture.componentInstance.dataSource!.data; expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], [data[0].a, data[0].b, data[0].c], [data[1].a, data[1].b, data[1].c], [data[2].a, data[2].b, data[2].c], ['fourth_row'], ['Footer A', 'Footer B', 'Footer C'], ]); }); it('should create a table with special when row', () => { let fixture = TestBed.createComponent(MatTableWithWhenRowApp); fixture.detectChanges(); const tableElement = fixture.nativeElement.querySelector('table'); expectTableToMatchContent(tableElement, [ ['Column A'], ['a_1'], ['a_2'], ['a_3'], ['fourth_row'], ['Footer A'], ]); }); it('should create a table with multiTemplateDataRows true', () => { let fixture = TestBed.createComponent(MatTableWithWhenRowApp); fixture.componentInstance.multiTemplateDataRows = true; fixture.detectChanges(); const tableElement = fixture.nativeElement.querySelector('table'); expectTableToMatchContent(tableElement, [ ['Column A'], ['a_1'], ['a_2'], ['a_3'], ['a_4'], // With multiple rows, this row shows up along with the special 'when' fourth_row ['fourth_row'], ['Footer A'], ]); }); it('should be able to render a table correctly with native elements', () => { let fixture = TestBed.createComponent(NativeHtmlTableApp); fixture.detectChanges(); const tableElement = fixture.nativeElement.querySelector('table'); const data = fixture.componentInstance.dataSource!.data; expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], [data[0].a, data[0].b, data[0].c], [data[1].a, data[1].b, data[1].c], [data[2].a, data[2].b, data[2].c], [data[3].a, data[3].b, data[3].c], ]); }); it('should be able to nest tables', () => { const fixture = TestBed.createComponent(NestedTableApp); fixture.detectChanges(); const outerTable = fixture.nativeElement.querySelector('table'); const innerTable = outerTable.querySelector('table'); const outerRows = Array.from<HTMLTableRowElement>(outerTable.querySelector('tbody').rows); const innerRows = Array.from<HTMLTableRowElement>(innerTable.querySelector('tbody').rows); expect(outerTable).toBeTruthy(); expect(outerRows.map(row => row.cells.length)).toEqual([3, 3, 3, 3]); expect(innerTable).toBeTruthy(); expect(innerRows.map(row => row.cells.length)).toEqual([3, 3, 3, 3]); }); it('should be able to show a message when no data is being displayed in a native table', () => { const fixture = TestBed.createComponent(NativeHtmlTableApp); fixture.detectChanges(); // Assert that the data is inside the tbody specifically. const tbody = fixture.nativeElement.querySelector('tbody')!; const dataSource = fixture.componentInstance.dataSource!; const initialData = dataSource.data; expect(tbody.querySelector('.mat-mdc-no-data-row')).toBeFalsy(); dataSource.data = []; fixture.detectChanges(); const noDataRow: HTMLElement = tbody.querySelector('.mat-mdc-no-data-row'); expect(noDataRow).toBeTruthy(); expect(noDataRow.getAttribute('role')).toBe('row'); dataSource.data = initialData; fixture.detectChanges(); expect(tbody.querySelector('.mat-mdc-no-data-row')).toBeFalsy(); }); it('should be able to show a message when no data is being displayed', () => { const fixture = TestBed.createComponent(MatTableApp); fixture.detectChanges(); // Assert that the data is inside the tbody specifically. const tbody = fixture.nativeElement.querySelector('tbody')!; const initialData = fixture.componentInstance.dataSource!.data; expect(tbody.querySelector('.mat-mdc-no-data-row')).toBeFalsy(); fixture.componentInstance.dataSource!.data = []; fixture.detectChanges(); const noDataRow: HTMLElement = tbody.querySelector('.mat-mdc-no-data-row'); expect(noDataRow).toBeTruthy(); expect(noDataRow.getAttribute('role')).toBe('row'); fixture.componentInstance.dataSource!.data = initialData; fixture.detectChanges(); expect(tbody.querySelector('.mat-mdc-no-data-row')).toBeFalsy(); }); it('should show the no data row if there is no data on init', () => { const fixture = TestBed.createComponent(MatTableApp); fixture.componentInstance.dataSource!.data = []; fixture.detectChanges(); const tbody = fixture.nativeElement.querySelector('tbody')!; expect(tbody.querySelector('.mat-mdc-no-data-row')).toBeTruthy(); }); it('should set the content styling class on the tbody', () => { let fixture = TestBed.createComponent(NativeHtmlTableApp); fixture.detectChanges(); const tbodyElement = fixture.nativeElement.querySelector('tbody'); expect(tbodyElement.classList).toContain('mdc-data-table__content'); }); }); it('should render with MatTableDataSource and sort', () => { let fixture = TestBed.createComponent(MatTableWithSortApp); fixture.detectChanges(); const tableElement = fixture.nativeElement.querySelector('table')!; const data = fixture.componentInstance.dataSource!.data; expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], [data[0].a, data[0].b, data[0].c], [data[1].a, data[1].b, data[1].c], [data[2].a, data[2].b, data[2].c], ]); }); it('should render with MatTableDataSource and pagination', () => { let fixture = TestBed.createComponent(MatTableWithPaginatorApp); fixture.detectChanges(); const tableElement = fixture.nativeElement.querySelector('table')!; const data = fixture.componentInstance.dataSource!.data; expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], [data[0].a, data[0].b, data[0].c], [data[1].a, data[1].b, data[1].c], [data[2].a, data[2].b, data[2].c], ]); }); it('should apply custom sticky CSS class to sticky cells', fakeAsync(() => { let fixture = TestBed.createComponent(StickyTableApp); fixture.detectChanges(); flushMicrotasks(); const stuckCellElement = fixture.nativeElement.querySelector('table th')!; expect(stuckCellElement.classList).toContain('mat-mdc-table-sticky'); })); // Note: needs to be fakeAsync so it catches the error. it('should not throw when a row definition is on an ng-container', fakeAsync(() => { const fixture = TestBed.createComponent(TableWithNgContainerRow); expect(() => { fixture.detectChanges(); tick(); }).not.toThrow(); })); it('should be able to render a flexbox-based table', () => { expect(() => { const fixture = TestBed.createComponent(MatFlexTableApp); fixture.detectChanges(); }).not.toThrow(); });
{ "end_byte": 8537, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/table.spec.ts" }
components/src/material/table/table.spec.ts_8541_16062
describe('with MatTableDataSource and sort/pagination/filter', () => { let tableElement: HTMLElement; let fixture: ComponentFixture<ArrayDataSourceMatTableApp>; let dataSource: MatTableDataSource<TestData>; let component: ArrayDataSourceMatTableApp; beforeEach(() => { fixture = TestBed.createComponent(ArrayDataSourceMatTableApp); fixture.detectChanges(); tableElement = fixture.nativeElement.querySelector('table'); component = fixture.componentInstance; dataSource = fixture.componentInstance.dataSource; }); it('should create table and display data source contents', () => { expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_1', 'b_1', 'c_1'], ['a_2', 'b_2', 'c_2'], ['a_3', 'b_3', 'c_3'], ['Footer A', 'Footer B', 'Footer C'], ]); }); it('changing data should update the table contents', () => { // Add data component.underlyingDataSource.addData(); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_1', 'b_1', 'c_1'], ['a_2', 'b_2', 'c_2'], ['a_3', 'b_3', 'c_3'], ['a_4', 'b_4', 'c_4'], ['Footer A', 'Footer B', 'Footer C'], ]); // Remove data const modifiedData = dataSource.data.slice(); modifiedData.shift(); dataSource.data = modifiedData; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_2', 'b_2', 'c_2'], ['a_3', 'b_3', 'c_3'], ['a_4', 'b_4', 'c_4'], ['Footer A', 'Footer B', 'Footer C'], ]); }); it('should update the page index when switching to a smaller data set from a page', fakeAsync(() => { // Add 20 rows so we can switch pages. for (let i = 0; i < 20; i++) { component.underlyingDataSource.addData(); fixture.detectChanges(); tick(); fixture.detectChanges(); } // Go to the last page. fixture.componentInstance.paginator.lastPage(); fixture.detectChanges(); // Switch to a smaller data set. dataSource.data = [{a: 'a_0', b: 'b_0', c: 'c_0'}]; fixture.detectChanges(); tick(); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_0', 'b_0', 'c_0'], ['Footer A', 'Footer B', 'Footer C'], ]); })); it('should be able to filter the table contents', fakeAsync(() => { // Change filter to a_1, should match one row dataSource.filter = 'a_1'; flushMicrotasks(); // Resolve promise that updates paginator's length fixture.detectChanges(); expect(dataSource.filteredData.length).toBe(1); expect(dataSource.filteredData[0]).toBe(dataSource.data[0]); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_1', 'b_1', 'c_1'], ['Footer A', 'Footer B', 'Footer C'], ]); expect(dataSource.paginator!.length).toBe(1); // Change filter to ' A_2 ', should match one row (ignores case and whitespace) dataSource.filter = ' A_2 '; flushMicrotasks(); fixture.detectChanges(); expect(dataSource.filteredData.length).toBe(1); expect(dataSource.filteredData[0]).toBe(dataSource.data[1]); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_2', 'b_2', 'c_2'], ['Footer A', 'Footer B', 'Footer C'], ]); // Change filter to empty string, should match all rows dataSource.filter = ''; flushMicrotasks(); fixture.detectChanges(); expect(dataSource.filteredData.length).toBe(3); expect(dataSource.filteredData[0]).toBe(dataSource.data[0]); expect(dataSource.filteredData[1]).toBe(dataSource.data[1]); expect(dataSource.filteredData[2]).toBe(dataSource.data[2]); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_1', 'b_1', 'c_1'], ['a_2', 'b_2', 'c_2'], ['a_3', 'b_3', 'c_3'], ['Footer A', 'Footer B', 'Footer C'], ]); // Change filter function and filter, should match to rows with zebra. dataSource.filterPredicate = (data, filter) => { let dataStr; switch (data.a) { case 'a_1': dataStr = 'elephant'; break; case 'a_2': dataStr = 'zebra'; break; case 'a_3': dataStr = 'monkey'; break; default: dataStr = ''; } return dataStr.indexOf(filter) != -1; }; dataSource.filter = 'zebra'; flushMicrotasks(); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_2', 'b_2', 'c_2'], ['Footer A', 'Footer B', 'Footer C'], ]); // Change the filter to a falsy value that might come in from the view. dataSource.filter = 0 as any; flushMicrotasks(); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['Footer A', 'Footer B', 'Footer C'], ]); })); it('should not match concatenated words', fakeAsync(() => { // Set the value to the last character of the first // column plus the first character of the second column. dataSource.filter = '1b'; flushMicrotasks(); fixture.detectChanges(); expect(dataSource.filteredData.length).toBe(0); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['Footer A', 'Footer B', 'Footer C'], ]); })); it('should be able to sort the table contents', () => { // Activate column A sort component.sort.sort(component.sortHeader); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_1', 'b_1', 'c_1'], ['a_2', 'b_2', 'c_2'], ['a_3', 'b_3', 'c_3'], ['Footer A', 'Footer B', 'Footer C'], ]); // Activate column A sort again (reverse direction) component.sort.sort(component.sortHeader); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_3', 'b_3', 'c_3'], ['a_2', 'b_2', 'c_2'], ['a_1', 'b_1', 'c_1'], ['Footer A', 'Footer B', 'Footer C'], ]); // Change sort function to customize how it sorts - first column 1, then 3, then 2 dataSource.sortingDataAccessor = data => { switch (data.a) { case 'a_1': return 'elephant'; case 'a_2': return 'zebra'; case 'a_3': return 'monkey'; default: return ''; } }; component.sort.direction = ''; component.sort.sort(component.sortHeader); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_1', 'b_1', 'c_1'], ['a_3', 'b_3', 'c_3'], ['a_2', 'b_2', 'c_2'], ['Footer A', 'Footer B', 'Footer C'], ]); });
{ "end_byte": 16062, "start_byte": 8541, "url": "https://github.com/angular/components/blob/main/src/material/table/table.spec.ts" }
components/src/material/table/table.spec.ts_16068_22546
it('should by default correctly sort an empty string', () => { // Activate column A sort dataSource.data[0].a = ' '; component.sort.sort(component.sortHeader); fixture.detectChanges(); // Expect that empty string row comes before the other values expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['', 'b_1', 'c_1'], ['a_2', 'b_2', 'c_2'], ['a_3', 'b_3', 'c_3'], ['Footer A', 'Footer B', 'Footer C'], ]); // Expect that empty string row comes before the other values component.sort.sort(component.sortHeader); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_3', 'b_3', 'c_3'], ['a_2', 'b_2', 'c_2'], ['', 'b_1', 'c_1'], ['Footer A', 'Footer B', 'Footer C'], ]); }); it('should by default correctly sort undefined values', () => { // Activate column A sort dataSource.data[0].a = undefined; // Expect that undefined row comes before the other values component.sort.sort(component.sortHeader); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['', 'b_1', 'c_1'], ['a_2', 'b_2', 'c_2'], ['a_3', 'b_3', 'c_3'], ['Footer A', 'Footer B', 'Footer C'], ]); // Expect that undefined row comes after the other values component.sort.sort(component.sortHeader); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_3', 'b_3', 'c_3'], ['a_2', 'b_2', 'c_2'], ['', 'b_1', 'c_1'], ['Footer A', 'Footer B', 'Footer C'], ]); }); it('should sort zero correctly', () => { // Activate column A sort dataSource.data[0].a = 1; dataSource.data[1].a = 0; dataSource.data[2].a = -1; // Expect that zero comes after the negative numbers and before the positive ones. component.sort.sort(component.sortHeader); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['-1', 'b_3', 'c_3'], ['0', 'b_2', 'c_2'], ['1', 'b_1', 'c_1'], ['Footer A', 'Footer B', 'Footer C'], ]); // Expect that zero comes after the negative numbers and before // the positive ones when switching the sorting direction. component.sort.sort(component.sortHeader); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['1', 'b_1', 'c_1'], ['0', 'b_2', 'c_2'], ['-1', 'b_3', 'c_3'], ['Footer A', 'Footer B', 'Footer C'], ]); }); it('should be able to page the table contents', fakeAsync(() => { // Add 100 rows, should only display first 5 since page length is 5 for (let i = 0; i < 100; i++) { component.underlyingDataSource.addData(); } fixture.detectChanges(); flushMicrotasks(); // Resolve promise that updates paginator's length expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_1', 'b_1', 'c_1'], ['a_2', 'b_2', 'c_2'], ['a_3', 'b_3', 'c_3'], ['a_4', 'b_4', 'c_4'], ['a_5', 'b_5', 'c_5'], ['Footer A', 'Footer B', 'Footer C'], ]); // Navigate to the next page component.paginator.nextPage(); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_6', 'b_6', 'c_6'], ['a_7', 'b_7', 'c_7'], ['a_8', 'b_8', 'c_8'], ['a_9', 'b_9', 'c_9'], ['a_10', 'b_10', 'c_10'], ['Footer A', 'Footer B', 'Footer C'], ]); })); it('should sort strings with numbers larger than MAX_SAFE_INTEGER correctly', () => { const large = '9563256840123535'; const larger = '9563256840123536'; const largest = '9563256840123537'; dataSource.data[0].a = largest; dataSource.data[1].a = larger; dataSource.data[2].a = large; component.sort.sort(component.sortHeader); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], [large, 'b_3', 'c_3'], [larger, 'b_2', 'c_2'], [largest, 'b_1', 'c_1'], ['Footer A', 'Footer B', 'Footer C'], ]); component.sort.sort(component.sortHeader); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], [largest, 'b_1', 'c_1'], [larger, 'b_2', 'c_2'], [large, 'b_3', 'c_3'], ['Footer A', 'Footer B', 'Footer C'], ]); }); it('should fall back to empty table if invalid data is passed in', () => { component.underlyingDataSource.addData(); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_1', 'b_1', 'c_1'], ['a_2', 'b_2', 'c_2'], ['a_3', 'b_3', 'c_3'], ['a_4', 'b_4', 'c_4'], ['Footer A', 'Footer B', 'Footer C'], ]); dataSource.data = null!; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['Footer A', 'Footer B', 'Footer C'], ]); component.underlyingDataSource.addData(); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_1', 'b_1', 'c_1'], ['a_2', 'b_2', 'c_2'], ['a_3', 'b_3', 'c_3'], ['a_4', 'b_4', 'c_4'], ['a_5', 'b_5', 'c_5'], ['Footer A', 'Footer B', 'Footer C'], ]); dataSource.data = {} as any; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['Footer A', 'Footer B', 'Footer C'], ]); }); }); }); interface TestData { a: string | number | undefined; b: string | number | undefined; c: string | number | undefined; }
{ "end_byte": 22546, "start_byte": 16068, "url": "https://github.com/angular/components/blob/main/src/material/table/table.spec.ts" }
components/src/material/table/table.spec.ts_22548_29910
class FakeDataSource extends DataSource<TestData> { _dataChange = new BehaviorSubject<TestData[]>([]); get data() { return this._dataChange.getValue(); } set data(data: TestData[]) { this._dataChange.next(data); } constructor() { super(); for (let i = 0; i < 4; i++) { this.addData(); } } connect(): Observable<TestData[]> { return this._dataChange; } disconnect() {} addData() { const nextIndex = this.data.length + 1; let copiedData = this.data.slice(); copiedData.push({ a: `a_${nextIndex}`, b: `b_${nextIndex}`, c: `c_${nextIndex}`, }); this.data = copiedData; } } @Component({ template: ` <table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="column_a"> <th mat-header-cell *matHeaderCellDef> Column A</th> <td mat-cell *matCellDef="let row"> {{row.a}}</td> <td mat-footer-cell *matFooterCellDef> Footer A</td> </ng-container> <ng-container matColumnDef="column_b"> <th mat-header-cell *matHeaderCellDef> Column B</th> <td mat-cell *matCellDef="let row"> {{row.b}}</td> <td mat-footer-cell *matFooterCellDef> Footer B</td> </ng-container> <ng-container matColumnDef="column_c"> <th mat-header-cell *matHeaderCellDef> Column C</th> <td mat-cell *matCellDef="let row"> {{row.c}}</td> <td mat-footer-cell *matFooterCellDef> Footer C</td> </ng-container> <ng-container matColumnDef="special_column"> <td mat-cell *matCellDef="let row"> fourth_row </td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToRender"></tr> <tr mat-row *matRowDef="let row; columns: columnsToRender"></tr> <tr mat-row *matRowDef="let row; columns: ['special_column']; when: isFourthRow"></tr> <tr *matNoDataRow> <td>No data</td> </tr> <tr mat-footer-row *matFooterRowDef="columnsToRender"></tr> </table> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class MatTableApp { dataSource: FakeDataSource | null = new FakeDataSource(); columnsToRender = ['column_a', 'column_b', 'column_c']; isFourthRow = (i: number, _rowData: TestData) => i == 3; @ViewChild(MatTable) table: MatTable<TestData>; } @Component({ template: ` <table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="column_a"> <th mat-header-cell *matHeaderCellDef> Column A</th> <td mat-cell *matCellDef="let row"> {{row.a}}</td> </ng-container> <ng-container matColumnDef="column_b"> <th mat-header-cell *matHeaderCellDef> Column B</th> <td mat-cell *matCellDef="let row"> {{row.b}}</td> </ng-container> <ng-container matColumnDef="column_c"> <th mat-header-cell *matHeaderCellDef> Column C</th> <td mat-cell *matCellDef="let row"> {{row.c}}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToRender"></tr> <tr mat-row *matRowDef="let row; columns: columnsToRender"></tr> <tr *matNoDataRow> <td>No data</td> </tr> </table> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class NativeHtmlTableApp { dataSource: FakeDataSource | null = new FakeDataSource(); columnsToRender = ['column_a', 'column_b', 'column_c']; @ViewChild(MatTable) table: MatTable<TestData>; } @Component({ template: ` <table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="column_a"> <th mat-header-cell *matHeaderCellDef>Column A</th> <td mat-cell *matCellDef="let row">{{row.a}}</td> </ng-container> <ng-container matColumnDef="column_b"> <th mat-header-cell *matHeaderCellDef>Column B</th> <td mat-cell *matCellDef="let row"> <table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="column_a"> <th mat-header-cell *matHeaderCellDef> Column A</th> <td mat-cell *matCellDef="let row"> {{row.a}}</td> <td mat-footer-cell *matFooterCellDef> Footer A</td> </ng-container> <ng-container matColumnDef="column_b"> <th mat-header-cell *matHeaderCellDef> Column B</th> <td mat-cell *matCellDef="let row"> {{row.b}}</td> <td mat-footer-cell *matFooterCellDef> Footer B</td> </ng-container> <ng-container matColumnDef="column_c"> <th mat-header-cell *matHeaderCellDef> Column C</th> <td mat-cell *matCellDef="let row"> {{row.c}}</td> <td mat-footer-cell *matFooterCellDef> Footer C</td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToRender"></tr> <tr mat-row *matRowDef="let row; columns: columnsToRender"></tr> </table> </td> </ng-container> <ng-container matColumnDef="column_c"> <th mat-header-cell *matHeaderCellDef>Column C</th> <td mat-cell *matCellDef="let row">{{row.c}}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToRender"></tr> <tr mat-row *matRowDef="let row; columns: columnsToRender"></tr> </table> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class NestedTableApp { dataSource: FakeDataSource | null = new FakeDataSource(); columnsToRender = ['column_a', 'column_b', 'column_c']; } @Component({ template: ` <table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="column_a"> <th mat-header-cell *matHeaderCellDef> Column A </th> <td mat-cell *matCellDef="let row"> {{row.a}} </td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToRender; sticky: true"></tr> <tr mat-row *matRowDef="let row; columns: columnsToRender"></tr> </table> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class StickyTableApp { dataSource = new FakeDataSource(); columnsToRender = ['column_a']; @ViewChild(MatTable) table: MatTable<TestData>; } @Component({ template: ` <table mat-table [dataSource]="dataSource" [multiTemplateDataRows]="multiTemplateDataRows"> <ng-container matColumnDef="column_a"> <th mat-header-cell *matHeaderCellDef> Column A</th> <td mat-cell *matCellDef="let row"> {{row.a}}</td> <td mat-footer-cell *matFooterCellDef> Footer A</td> </ng-container> <ng-container matColumnDef="special_column"> <td mat-cell *matCellDef="let row"> fourth_row </td> </ng-container> <tr mat-header-row *matHeaderRowDef="['column_a']"></tr> <tr mat-row *matRowDef="let row; columns: ['column_a']"></tr> <tr mat-row *matRowDef="let row; columns: ['special_column']; when: isFourthRow"></tr> <tr mat-footer-row *matFooterRowDef="['column_a']"></tr> </table> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class MatTableWithWhenRowApp { multiTemplateDataRows = false; dataSource: FakeDataSource | null = new FakeDataSource(); isFourthRow = (i: number, _rowData: TestData) => i == 3; @ViewChild(MatTable) table: MatTable<TestData>; }
{ "end_byte": 29910, "start_byte": 22548, "url": "https://github.com/angular/components/blob/main/src/material/table/table.spec.ts" }
components/src/material/table/table.spec.ts_29912_37864
@Component({ template: ` <table mat-table [dataSource]="dataSource" matSort> <ng-container matColumnDef="column_a"> <th mat-header-cell *matHeaderCellDef mat-sort-header="a"> Column A</th> <td mat-cell *matCellDef="let row"> {{row.a}}</td> <td mat-footer-cell *matFooterCellDef> Footer A</td> </ng-container> <ng-container matColumnDef="column_b"> <th mat-header-cell *matHeaderCellDef> Column B</th> <td mat-cell *matCellDef="let row"> {{row.b}}</td> <td mat-footer-cell *matFooterCellDef> Footer B</td> </ng-container> <ng-container matColumnDef="column_c"> <th mat-header-cell *matHeaderCellDef> Column C</th> <td mat-cell *matCellDef="let row"> {{row.c}}</td> <td mat-footer-cell *matFooterCellDef> Footer C</td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToRender"></tr> <tr mat-row *matRowDef="let row; columns: columnsToRender"></tr> <tr mat-footer-row *matFooterRowDef="columnsToRender"></tr> </table> <mat-paginator [pageSize]="5"></mat-paginator> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class ArrayDataSourceMatTableApp implements AfterViewInit { underlyingDataSource = new FakeDataSource(); dataSource = new MatTableDataSource<TestData>(); columnsToRender = ['column_a', 'column_b', 'column_c']; @ViewChild(MatTable) table: MatTable<TestData>; @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatSort) sort: MatSort; @ViewChild(MatSortHeader) sortHeader: MatSortHeader; constructor() { this.underlyingDataSource.data = []; // Add three rows of data this.underlyingDataSource.addData(); this.underlyingDataSource.addData(); this.underlyingDataSource.addData(); this.underlyingDataSource.connect().subscribe(data => { this.dataSource.data = data; }); } ngAfterViewInit() { this.dataSource.sort = this.sort; this.dataSource.paginator = this.paginator; } } @Component({ template: ` <table mat-table [dataSource]="dataSource" matSort> <ng-container matColumnDef="column_a"> <th mat-header-cell *matHeaderCellDef mat-sort-header="a"> Column A</th> <td mat-cell *matCellDef="let row"> {{row.a}}</td> </ng-container> <ng-container matColumnDef="column_b"> <th mat-header-cell *matHeaderCellDef> Column B</th> <td mat-cell *matCellDef="let row"> {{row.b}}</td> </ng-container> <ng-container matColumnDef="column_c"> <th mat-header-cell *matHeaderCellDef> Column C</th> <td mat-cell *matCellDef="let row"> {{row.c}}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToRender"></tr> <tr mat-row *matRowDef="let row; columns: columnsToRender"></tr> </table> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class MatTableWithSortApp implements OnInit { underlyingDataSource = new FakeDataSource(); dataSource = new MatTableDataSource<TestData>(); columnsToRender = ['column_a', 'column_b', 'column_c']; @ViewChild(MatTable) table: MatTable<TestData>; @ViewChild(MatSort) sort: MatSort; constructor() { this.underlyingDataSource.data = []; // Add three rows of data this.underlyingDataSource.addData(); this.underlyingDataSource.addData(); this.underlyingDataSource.addData(); this.underlyingDataSource.connect().subscribe(data => { this.dataSource.data = data; }); } ngOnInit() { this.dataSource!.sort = this.sort; } } @Component({ template: ` <table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="column_a"> <th mat-header-cell *matHeaderCellDef> Column A</th> <td mat-cell *matCellDef="let row"> {{row.a}}</td> </ng-container> <ng-container matColumnDef="column_b"> <th mat-header-cell *matHeaderCellDef> Column B</th> <td mat-cell *matCellDef="let row"> {{row.b}}</td> </ng-container> <ng-container matColumnDef="column_c"> <th mat-header-cell *matHeaderCellDef> Column C</th> <td mat-cell *matCellDef="let row"> {{row.c}}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToRender"></tr> <tr mat-row *matRowDef="let row; columns: columnsToRender"></tr> </table> <mat-paginator [pageSize]="5"></mat-paginator> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class MatTableWithPaginatorApp implements OnInit { underlyingDataSource = new FakeDataSource(); dataSource = new MatTableDataSource<TestData>(); columnsToRender = ['column_a', 'column_b', 'column_c']; @ViewChild(MatTable) table: MatTable<TestData>; @ViewChild(MatPaginator) paginator: MatPaginator; constructor() { this.underlyingDataSource.data = []; // Add three rows of data this.underlyingDataSource.addData(); this.underlyingDataSource.addData(); this.underlyingDataSource.addData(); this.underlyingDataSource.connect().subscribe(data => { this.dataSource.data = data; }); } ngOnInit() { this.dataSource!.paginator = this.paginator; } } @Component({ template: ` <table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="column_a"> <th mat-header-cell *matHeaderCellDef>Column A</th> <td mat-cell *matCellDef="let row">{{row.a}}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToRender"></tr> <ng-container *matRowDef="let row; columns: columnsToRender"> <tr mat-row></tr> </ng-container> </table> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class TableWithNgContainerRow { dataSource: FakeDataSource | null = new FakeDataSource(); columnsToRender = ['column_a']; } @Component({ template: ` <mat-table [dataSource]="dataSource"> <ng-container matColumnDef="column_a"> <mat-header-cell *matHeaderCellDef> Column A</mat-header-cell> <mat-cell *matCellDef="let row"> {{row.a}}</mat-cell> <mat-footer-cell *matFooterCellDef> Footer A</mat-footer-cell> </ng-container> <ng-container matColumnDef="column_b"> <mat-header-cell *matHeaderCellDef> Column B</mat-header-cell> <mat-cell *matCellDef="let row"> {{row.b}}</mat-cell> <mat-footer-cell *matFooterCellDef> Footer B</mat-footer-cell> </ng-container> <ng-container matColumnDef="column_c"> <mat-header-cell *matHeaderCellDef> Column C</mat-header-cell> <mat-cell *matCellDef="let row"> {{row.c}}</mat-cell> <mat-footer-cell *matFooterCellDef> Footer C</mat-footer-cell> </ng-container> <ng-container matColumnDef="special_column"> <mat-cell *matCellDef="let row"> fourth_row </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="columnsToRender"></mat-header-row> <mat-row *matRowDef="let row; columns: columnsToRender"></mat-row> <div *matNoDataRow>No data</div> <mat-footer-row *matFooterRowDef="columnsToRender"></mat-footer-row> </mat-table> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class MatFlexTableApp { dataSource: FakeDataSource | null = new FakeDataSource(); columnsToRender = ['column_a', 'column_b', 'column_c']; @ViewChild(MatTable) table: MatTable<TestData>; } function getElements(element: Element, query: string): Element[] { return [].slice.call(element.querySelectorAll(query)); } function getHeaderRows(tableElement: Element): Element[] { return [].slice.call(tableElement.querySelectorAll('.mat-mdc-header-row'))!; } function getFooterRows(tableElement: Element): Element[] { return [].slice.call(tableElement.querySelectorAll('.mat-mdc-footer-row'))!; }
{ "end_byte": 37864, "start_byte": 29912, "url": "https://github.com/angular/components/blob/main/src/material/table/table.spec.ts" }
components/src/material/table/table.spec.ts_37866_40102
function getRows(tableElement: Element): Element[] { return getElements(tableElement, '.mat-mdc-row'); } function getCells(row: Element): Element[] { if (!row) { return []; } return getElements(row, 'td'); } function getHeaderCells(headerRow: Element): Element[] { return getElements(headerRow, 'th'); } function getFooterCells(footerRow: Element): Element[] { return getElements(footerRow, 'td'); } function getActualTableContent(tableElement: Element): string[][] { let actualTableContent: Element[][] = []; getHeaderRows(tableElement).forEach(row => { actualTableContent.push(getHeaderCells(row)); }); // Check data row cells const rows = getRows(tableElement).map(row => getCells(row)); actualTableContent = actualTableContent.concat(rows); getFooterRows(tableElement).forEach(row => { actualTableContent.push(getFooterCells(row)); }); // Convert the nodes into their text content; return actualTableContent.map(row => row.map(cell => cell.textContent!.trim())); } export function expectTableToMatchContent(tableElement: Element, expected: any[]) { const missedExpectations: string[] = []; function checkCellContent(actualCell: string, expectedCell: string) { if (actualCell !== expectedCell) { missedExpectations.push(`Expected cell contents to be ${expectedCell} but was ${actualCell}`); } } const actual = getActualTableContent(tableElement); // Make sure the number of rows match if (actual.length !== expected.length) { missedExpectations.push(`Expected ${expected.length} total rows but got ${actual.length}`); fail(missedExpectations.join('\n')); } actual.forEach((row, rowIndex) => { const expectedRow = expected[rowIndex]; // Make sure the number of cells match if (row.length !== expectedRow.length) { missedExpectations.push(`Expected ${expectedRow.length} cells in row but got ${row.length}`); fail(missedExpectations.join('\n')); } row.forEach((actualCell, cellIndex) => { const expectedCell = expectedRow ? expectedRow[cellIndex] : null; checkCellContent(actualCell, expectedCell); }); }); if (missedExpectations.length) { fail(missedExpectations.join('\n')); } }
{ "end_byte": 40102, "start_byte": 37866, "url": "https://github.com/angular/components/blob/main/src/material/table/table.spec.ts" }
components/src/material/table/_table-flex-styles.scss_0_1507
// Flex-based table structure $header-row-height: 56px; $row-height: 48px; $row-horizontal-padding: 24px; // Only use tag name selectors here since the styles are shared between MDC and non-MDC @mixin private-table-flex-styles { mat-table { display: block; } mat-header-row { min-height: $header-row-height; } mat-row, mat-footer-row { min-height: $row-height; } mat-row, mat-header-row, mat-footer-row { display: flex; // Define a border style, but then widths default to 3px. Reset them to 0px except the bottom // which should be 1px; border-width: 0; border-bottom-width: 1px; border-style: solid; align-items: center; box-sizing: border-box; } mat-cell, mat-header-cell, mat-footer-cell { // Note: we use `first-of-type`/`last-of-type` here in order to prevent extra // elements like ripples or badges from throwing off the layout (see #11165). &:first-of-type { padding-left: $row-horizontal-padding; [dir='rtl'] &:not(:only-of-type) { padding-left: 0; padding-right: $row-horizontal-padding; } } &:last-of-type { padding-right: $row-horizontal-padding; [dir='rtl'] &:not(:only-of-type) { padding-right: 0; padding-left: $row-horizontal-padding; } } } mat-cell, mat-header-cell, mat-footer-cell { flex: 1; display: flex; align-items: center; overflow: hidden; word-wrap: break-word; min-height: inherit; } }
{ "end_byte": 1507, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/_table-flex-styles.scss" }
components/src/material/table/row.ts_0_4431
/** * @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 { CdkFooterRow, CdkFooterRowDef, CdkHeaderRow, CdkHeaderRowDef, CdkRow, CdkRowDef, CdkNoDataRow, CdkCellOutlet, } from '@angular/cdk/table'; import { ChangeDetectionStrategy, Component, Directive, ViewEncapsulation, booleanAttribute, } from '@angular/core'; // We can't reuse `CDK_ROW_TEMPLATE` because it's incompatible with local compilation mode. const ROW_TEMPLATE = `<ng-container cdkCellOutlet></ng-container>`; /** * Header row definition for the mat-table. * Captures the header row's template and other header properties such as the columns to display. */ @Directive({ selector: '[matHeaderRowDef]', providers: [{provide: CdkHeaderRowDef, useExisting: MatHeaderRowDef}], inputs: [ {name: 'columns', alias: 'matHeaderRowDef'}, {name: 'sticky', alias: 'matHeaderRowDefSticky', transform: booleanAttribute}, ], }) export class MatHeaderRowDef extends CdkHeaderRowDef {} /** * Footer row definition for the mat-table. * Captures the footer row's template and other footer properties such as the columns to display. */ @Directive({ selector: '[matFooterRowDef]', providers: [{provide: CdkFooterRowDef, useExisting: MatFooterRowDef}], inputs: [ {name: 'columns', alias: 'matFooterRowDef'}, {name: 'sticky', alias: 'matFooterRowDefSticky', transform: booleanAttribute}, ], }) export class MatFooterRowDef extends CdkFooterRowDef {} /** * Data row definition for the mat-table. * Captures the data row's template and other properties such as the columns to display and * a when predicate that describes when this row should be used. */ @Directive({ selector: '[matRowDef]', providers: [{provide: CdkRowDef, useExisting: MatRowDef}], inputs: [ {name: 'columns', alias: 'matRowDefColumns'}, {name: 'when', alias: 'matRowDefWhen'}, ], }) export class MatRowDef<T> extends CdkRowDef<T> {} /** Header template container that contains the cell outlet. Adds the right class and role. */ @Component({ selector: 'mat-header-row, tr[mat-header-row]', template: ROW_TEMPLATE, host: { 'class': 'mat-mdc-header-row mdc-data-table__header-row', 'role': 'row', }, // See note on CdkTable for explanation on why this uses the default change detection strategy. // tslint:disable-next-line:validate-decorators changeDetection: ChangeDetectionStrategy.Default, encapsulation: ViewEncapsulation.None, exportAs: 'matHeaderRow', providers: [{provide: CdkHeaderRow, useExisting: MatHeaderRow}], imports: [CdkCellOutlet], }) export class MatHeaderRow extends CdkHeaderRow {} /** Footer template container that contains the cell outlet. Adds the right class and role. */ @Component({ selector: 'mat-footer-row, tr[mat-footer-row]', template: ROW_TEMPLATE, host: { 'class': 'mat-mdc-footer-row mdc-data-table__row', 'role': 'row', }, // See note on CdkTable for explanation on why this uses the default change detection strategy. // tslint:disable-next-line:validate-decorators changeDetection: ChangeDetectionStrategy.Default, encapsulation: ViewEncapsulation.None, exportAs: 'matFooterRow', providers: [{provide: CdkFooterRow, useExisting: MatFooterRow}], imports: [CdkCellOutlet], }) export class MatFooterRow extends CdkFooterRow {} /** Data row template container that contains the cell outlet. Adds the right class and role. */ @Component({ selector: 'mat-row, tr[mat-row]', template: ROW_TEMPLATE, host: { 'class': 'mat-mdc-row mdc-data-table__row', 'role': 'row', }, // See note on CdkTable for explanation on why this uses the default change detection strategy. // tslint:disable-next-line:validate-decorators changeDetection: ChangeDetectionStrategy.Default, encapsulation: ViewEncapsulation.None, exportAs: 'matRow', providers: [{provide: CdkRow, useExisting: MatRow}], imports: [CdkCellOutlet], }) export class MatRow extends CdkRow {} /** Row that can be used to display a message when no data is shown in the table. */ @Directive({ selector: 'ng-template[matNoDataRow]', providers: [{provide: CdkNoDataRow, useExisting: MatNoDataRow}], }) export class MatNoDataRow extends CdkNoDataRow { override _contentClassName = 'mat-mdc-no-data-row'; }
{ "end_byte": 4431, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/row.ts" }
components/src/material/table/table.ts_0_3566
/** * @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, Directive, ViewEncapsulation} from '@angular/core'; import { CdkTable, _CoalescedStyleScheduler, _COALESCED_STYLE_SCHEDULER, CDK_TABLE, STICKY_POSITIONING_LISTENER, HeaderRowOutlet, DataRowOutlet, NoDataRowOutlet, FooterRowOutlet, } from '@angular/cdk/table'; import { _DisposeViewRepeaterStrategy, _RecycleViewRepeaterStrategy, _VIEW_REPEATER_STRATEGY, } from '@angular/cdk/collections'; /** * Enables the recycle view repeater strategy, which reduces rendering latency. Not compatible with * tables that animate rows. */ @Directive({ selector: 'mat-table[recycleRows], table[mat-table][recycleRows]', providers: [{provide: _VIEW_REPEATER_STRATEGY, useClass: _RecycleViewRepeaterStrategy}], }) export class MatRecycleRows {} @Component({ selector: 'mat-table, table[mat-table]', exportAs: 'matTable', // Note that according to MDN, the `caption` element has to be projected as the **first** // element in the table. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption // We can't reuse `CDK_TABLE_TEMPLATE` because it's incompatible with local compilation mode. template: ` <ng-content select="caption"/> <ng-content select="colgroup, col"/> <!-- Unprojected content throws a hydration error so we need this to capture it. It gets removed on the client so it doesn't affect the layout. --> @if (_isServer) { <ng-content/> } @if (_isNativeHtmlTable) { <thead role="rowgroup"> <ng-container headerRowOutlet/> </thead> <tbody class="mdc-data-table__content" role="rowgroup"> <ng-container rowOutlet/> <ng-container noDataRowOutlet/> </tbody> <tfoot role="rowgroup"> <ng-container footerRowOutlet/> </tfoot> } @else { <ng-container headerRowOutlet/> <ng-container rowOutlet/> <ng-container noDataRowOutlet/> <ng-container footerRowOutlet/> } `, styleUrl: 'table.css', host: { 'class': 'mat-mdc-table mdc-data-table__table', '[class.mdc-table-fixed-layout]': 'fixedLayout', }, providers: [ {provide: CdkTable, useExisting: MatTable}, {provide: CDK_TABLE, useExisting: MatTable}, {provide: _COALESCED_STYLE_SCHEDULER, useClass: _CoalescedStyleScheduler}, // TODO(michaeljamesparsons) Abstract the view repeater strategy to a directive API so this code // is only included in the build if used. {provide: _VIEW_REPEATER_STRATEGY, useClass: _DisposeViewRepeaterStrategy}, // Prevent nested tables from seeing this table's StickyPositioningListener. {provide: STICKY_POSITIONING_LISTENER, useValue: null}, ], encapsulation: ViewEncapsulation.None, // See note on CdkTable for explanation on why this uses the default change detection strategy. // tslint:disable-next-line:validate-decorators changeDetection: ChangeDetectionStrategy.Default, imports: [HeaderRowOutlet, DataRowOutlet, NoDataRowOutlet, FooterRowOutlet], }) export class MatTable<T> extends CdkTable<T> { /** Overrides the sticky CSS class set by the `CdkTable`. */ protected override stickyCssClass = 'mat-mdc-table-sticky'; /** Overrides the need to add position: sticky on every sticky cell element in `CdkTable`. */ protected override needsPositionStickyOnElement = false; }
{ "end_byte": 3566, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/table.ts" }
components/src/material/table/module.ts_0_1275
/** * @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} from '@angular/material/core'; import {MatRecycleRows, MatTable} from './table'; import {CdkTableModule} from '@angular/cdk/table'; import { MatCell, MatCellDef, MatColumnDef, MatFooterCell, MatFooterCellDef, MatHeaderCell, MatHeaderCellDef, } from './cell'; import { MatFooterRow, MatFooterRowDef, MatHeaderRow, MatHeaderRowDef, MatRow, MatRowDef, MatNoDataRow, } from './row'; import {MatTextColumn} from './text-column'; const EXPORTED_DECLARATIONS = [ // Table MatTable, MatRecycleRows, // Template defs MatHeaderCellDef, MatHeaderRowDef, MatColumnDef, MatCellDef, MatRowDef, MatFooterCellDef, MatFooterRowDef, // Cell directives MatHeaderCell, MatCell, MatFooterCell, // Row directives MatHeaderRow, MatRow, MatFooterRow, MatNoDataRow, MatTextColumn, ]; @NgModule({ imports: [MatCommonModule, CdkTableModule, ...EXPORTED_DECLARATIONS], exports: [MatCommonModule, EXPORTED_DECLARATIONS], }) export class MatTableModule {}
{ "end_byte": 1275, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/module.ts" }
components/src/material/table/public-api.ts_0_370
/** * @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 './table'; export * from './module'; export * from './cell'; export * from './row'; export * from './table-data-source'; export * from './text-column';
{ "end_byte": 370, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/public-api.ts" }
components/src/material/table/text-column.ts_0_1979
/** * @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 {CdkTextColumn} from '@angular/cdk/table'; import {ChangeDetectionStrategy, Component, ViewEncapsulation} from '@angular/core'; import {MatColumnDef, MatHeaderCellDef, MatHeaderCell, MatCellDef, MatCell} from './cell'; /** * Column that simply shows text content for the header and row cells. Assumes that the table * is using the native table implementation (`<table>`). * * By default, the name of this column will be the header text and data property accessor. * The header text can be overridden with the `headerText` input. Cell values can be overridden with * the `dataAccessor` input. Change the text justification to the start or end using the `justify` * input. */ @Component({ selector: 'mat-text-column', template: ` <ng-container matColumnDef> <th mat-header-cell *matHeaderCellDef [style.text-align]="justify"> {{headerText}} </th> <td mat-cell *matCellDef="let data" [style.text-align]="justify"> {{dataAccessor(data, name)}} </td> </ng-container> `, encapsulation: ViewEncapsulation.None, // Change detection is intentionally not set to OnPush. This component's template will be provided // to the table to be inserted into its view. This is problematic when change detection runs since // the bindings in this template will be evaluated _after_ the table's view is evaluated, which // mean's the template in the table's view will not have the updated value (and in fact will cause // an ExpressionChangedAfterItHasBeenCheckedError). // tslint:disable-next-line:validate-decorators changeDetection: ChangeDetectionStrategy.Default, imports: [MatColumnDef, MatHeaderCellDef, MatHeaderCell, MatCellDef, MatCell], }) export class MatTextColumn<T> extends CdkTextColumn<T> {}
{ "end_byte": 1979, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/text-column.ts" }
components/src/material/table/table.scss_0_5916
@use '../core/tokens/token-utils'; @use '../core/tokens/m2/mat/table' as tokens-mat-table; @use '../core/style/vendor-prefixes'; @use './table-flex-styles'; .mat-mdc-table-sticky { // Note that the table can either set this class or an inline style to make something sticky. // We set the style as `!important` so that we get an identical specificity in both cases // and to avoid cases where user styles have a higher specificity. position: sticky !important; } @mixin _cell-border { @include token-utils.create-token-slot(border-bottom-color, row-item-outline-color, true); @include token-utils.create-token-slot(border-bottom-width, row-item-outline-width, true); border-bottom-style: solid; } @include table-flex-styles.private-table-flex-styles(); .mat-mdc-table { min-width: 100%; border: 0; border-spacing: 0; table-layout: auto; white-space: normal; @include token-utils.use-tokens(tokens-mat-table.$prefix, tokens-mat-table.get-token-slots()) { @include token-utils.create-token-slot(background-color, background-color); } } .mdc-data-table__cell { box-sizing: border-box; overflow: hidden; text-align: left; text-overflow: ellipsis; [dir='rtl'] & { text-align: right; } } .mdc-data-table__cell, .mdc-data-table__header-cell { padding: 0 16px; } @include token-utils.use-tokens(tokens-mat-table.$prefix, tokens-mat-table.get-token-slots()) { // TODO(crisbeto): these tokens have default values in order to make the initial token // work easier to land in g3. Eventually we should remove them. .mat-mdc-header-row { @include vendor-prefixes.smooth-font; @include token-utils.create-token-slot(height, header-container-height, 56px); @include token-utils.create-token-slot(color, header-headline-color, true); @include token-utils.create-token-slot(font-family, header-headline-font, true); @include token-utils.create-token-slot(line-height, header-headline-line-height); @include token-utils.create-token-slot(font-size, header-headline-size, 14px); @include token-utils.create-token-slot(font-weight, header-headline-weight, 500); } .mat-mdc-row { @include token-utils.create-token-slot(height, row-item-container-height, 52px); @include token-utils.create-token-slot(color, row-item-label-text-color, true); } // Note that while it's redundant to apply the typography both to the row // and the content element since the cell inherit from both of them, // applying it only to one results in sub-pixel differences in the // letter spacing which leads to a lot of internal screenshot diffs. .mat-mdc-row, .mdc-data-table__content { @include vendor-prefixes.smooth-font; @include token-utils.create-token-slot(font-family, row-item-label-text-font, true); @include token-utils.create-token-slot(line-height, row-item-label-text-line-height); @include token-utils.create-token-slot(font-size, row-item-label-text-size, 14px); @include token-utils.create-token-slot(font-weight, row-item-label-text-weight); } .mat-mdc-footer-row { @include vendor-prefixes.smooth-font; @include token-utils.create-token-slot(height, footer-container-height, 52px); @include token-utils.create-token-slot(color, row-item-label-text-color, true); @include token-utils.create-token-slot(font-family, footer-supporting-text-font, true); @include token-utils.create-token-slot(line-height, footer-supporting-text-line-height); @include token-utils.create-token-slot(font-size, footer-supporting-text-size, 14px); @include token-utils.create-token-slot(font-weight, footer-supporting-text-weight); @include token-utils.create-token-slot(letter-spacing, footer-supporting-text-tracking); } .mat-mdc-header-cell { @include _cell-border; @include token-utils.create-token-slot(letter-spacing, header-headline-tracking); font-weight: inherit; line-height: inherit; box-sizing: border-box; text-overflow: ellipsis; overflow: hidden; outline: none; text-align: left; [dir='rtl'] & { text-align: right; } } .mat-mdc-cell { @include _cell-border; @include token-utils.create-token-slot(letter-spacing, row-item-label-text-tracking); line-height: inherit; .mdc-data-table__row:last-child & { border-bottom: none; } } .mat-mdc-footer-cell { @include token-utils.create-token-slot(letter-spacing, row-item-label-text-tracking); } } // MDC table rows are styled with a top border, whereas our legacy flex table styles rows with // a bottom border. Remove the bottom border style from the rows and let MDC display its top // border. mat-row.mat-mdc-row, mat-header-row.mat-mdc-header-row, mat-footer-row.mat-mdc-footer-row { border-bottom: none; } // Cells need to inherit their background in order to overlap each other when sticky. // The background needs to be inherited from the table, tbody/tfoot, row, and cell. .mat-mdc-table tbody, .mat-mdc-table tfoot, .mat-mdc-table thead, .mat-mdc-cell, .mat-mdc-footer-cell, .mat-mdc-header-row, .mat-mdc-row, .mat-mdc-footer-row, .mat-mdc-table .mat-mdc-header-cell { background: inherit; } // Flex rows should not set a definite height, but instead stretch to the height of their // children. Otherwise, the cells grow larger than the row and the layout breaks. .mat-mdc-table mat-header-row.mat-mdc-header-row, .mat-mdc-table mat-row.mat-mdc-row, .mat-mdc-table mat-footer-row.mat-mdc-footer-cell { height: unset; } // Flex cells should stretch to the height of their parent. This was okay for the legacy // table since the cells were centered and the borders displayed on the rows, but the MDC // version displays borders on the cells and do not correctly line up with the row bottom. mat-header-cell.mat-mdc-header-cell, mat-cell.mat-mdc-cell, mat-footer-cell.mat-mdc-footer-cell { align-self: stretch; }
{ "end_byte": 5916, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/table.scss" }
components/src/material/table/table.md_0_6289
The `mat-table` provides a Material Design styled data-table that can be used to display rows of data. This table builds on the foundation of the CDK data-table and uses a similar interface for its data input and template, except that its element and attribute selectors will be prefixed with `mat-` instead of `cdk-`. For more information on the interface and a detailed look at how the table is implemented, see the [guide covering the CDK data-table](https://material.angular.io/guide/cdk-table). ### Getting Started <!-- example(table-basic) --> #### 1. Write your mat-table and provide data Begin by adding the `<table mat-table>` component to your template and passing in data. The simplest way to provide data to the table is by passing a data array to the table's `dataSource` input. The table will take the array and render a row for each object in the data array. ```html <table mat-table [dataSource]="myDataArray"> ... </table> ``` Since the table optimizes for performance, it will not automatically check for changes to the data array. Instead, when objects are added, removed, or moved on the data array, you can trigger an update to the table's rendered rows by calling its `renderRows()` method. While an array is the _simplest_ way to bind data into the data source, it is also the most limited. For more complex applications, using a `DataSource` instance is recommended. See the section "Advanced data sources" below for more information. #### 2. Define the column templates Next, write your table's column templates. Each column definition should be given a unique name and contain the content for its header and row cells. Here's a simple column definition with the name `'score'`. The header cell contains the text "Score" and each row cell will render the `score` property of each row's data. ```html <ng-container matColumnDef="score"> <th mat-header-cell *matHeaderCellDef> Score </th> <td mat-cell *matCellDef="let user"> {{user.score}} </td> </ng-container> ``` Note that the cell templates are not restricted to only showing simple string values, but are flexible and allow you to provide any template. If your column is only responsible for rendering a single string value for the header and cells, you can instead define your column using the `mat-text-column`. The following column definition is equivalent to the one above. ```html <mat-text-column name="score"></mat-text-column> ``` Check out the API docs and examples of the `mat-text-column` to see how you can customize the header text, text alignment, and cell data accessor. Note that this is not compatible with the flex-layout table. Also, a data accessor should be provided if your data may have its properties minified since the string name will no longer match after minification. #### 3. Define the row templates Finally, once you have defined your columns, you need to tell the table which columns will be rendered in the header and data rows. To start, create a variable in your component that contains the list of the columns you want to render. ```ts columnsToDisplay = ['userName', 'age']; ``` Then add `mat-header-row` and `mat-row` to the content of your `mat-table` and provide your column list as inputs. ```html <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr> <tr mat-row *matRowDef="let myRowData; columns: columnsToDisplay"></tr> ``` Note that this list of columns provided to the rows can be in any order, not necessarily the order in which you wrote the column definitions. Also, you do not necessarily have to include every column that was defined in your template. This means that by changing your column list provided to the rows, you can easily re-order and include/exclude columns dynamically. ### Advanced data sources The simplest way to provide data to your table is by passing a data array. More complex use-cases may benefit from a more flexible approach involving an Observable stream or by encapsulating your data source logic into a `DataSource` class. #### Observable stream of data arrays An alternative approach to providing data to the table is by passing an Observable stream that emits the data array to be rendered each time it is changed. The table will listen to this stream and automatically trigger an update to the rows each time a new data array is emitted. #### DataSource For most real-world applications, providing the table a `DataSource` instance will be the best way to manage data. The `DataSource` is meant to serve as a place to encapsulate any sorting, filtering, pagination, and data retrieval logic specific to the application. A `DataSource` is simply a class that has at a minimum the following methods: `connect` and `disconnect`. The `connect` method will be called by the table to provide an `Observable` that emits the data array that should be rendered. The table will call `disconnect` when the table is destroyed, which may be the right time to clean up any subscriptions that may have been registered in the `connect` method. Although Angular Material provides a ready-made table `DataSource` class, `MatTableDataSource`, you may want to create your own custom `DataSource` class for more complex use cases. This can be done by extending the abstract `DataSource` class with a custom `DataSource` class that then implements the `connect` and `disconnect` methods. For use cases where the custom `DataSource` must also inherit functionality by extending a different base class, the `DataSource` base class can be implemented instead (`MyCustomDataSource extends SomeOtherBaseClass implements DataSource`) to respect Typescript's restriction to only implement one base class. ### Styling Columns Each table cell has an automatically generated class based on which column it appears in. The format for this generated class is `mat-column-NAME`. For example, cells in a column named "symbol" can be targeted with the selector `.mat-column-symbol`. <!-- example(table-column-styling) --> ### Row Templates Event handlers and property binding on the row templates will be applied to each row rendered by the table. For example, adding a `(click)` handler to the row template will cause each individual row to call the handler when clicked. <!-- example(table-row-binding) -->
{ "end_byte": 6289, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/table.md" }
components/src/material/table/table.md_6289_14799
### Features The `MatTable` is focused on a single responsibility: efficiently render rows of data in a performant and accessible way. You'll notice that the table itself doesn't come out of the box with a lot of features, but expects that the table will be included in a composition of components that fills out its features. For example, you can add sorting and pagination to the table by using MatSort and MatPaginator and mutating the data provided to the table according to their outputs. To simplify the use case of having a table that can sort, paginate, and filter an array of data, the Angular Material library comes with a `MatTableDataSource` that has already implemented the logic of determining what rows should be rendered according to the current table state. To add these feature to the table, check out their respective sections below. #### Pagination To paginate the table's data, add a `<mat-paginator>` after the table. If you are using the `MatTableDataSource` for your table's data source, simply provide the `MatPaginator` to your data source. It will automatically listen for page changes made by the user and send the right paged data to the table. Otherwise if you are implementing the logic to paginate your data, you will want to listen to the paginator's `(page)` output and pass the right slice of data to your table. For more information on using and configuring the `<mat-paginator>`, check out the [mat-paginator docs](https://material.angular.io/components/paginator/overview). The `MatPaginator` is one provided solution to paginating your table's data, but it is not the only option. In fact, the table can work with any custom pagination UI or strategy since the `MatTable` and its interface is not tied to any one specific implementation. <!-- example(table-pagination) --> #### Sorting To add sorting behavior to the table, add the `matSort` directive to the table and add `mat-sort-header` to each column header cell that should trigger sorting. Note that you have to import `MatSortModule` in order to initialize the `matSort` directive (see [API docs](https://material.angular.io/components/sort/api)). ```html <!-- Name Column --> <ng-container matColumnDef="position"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th> <td mat-cell *matCellDef="let element"> {{element.position}} </td> </ng-container> ``` If you are using the `MatTableDataSource` for your table's data source, provide the `MatSort` directive to the data source and it will automatically listen for sorting changes and change the order of data rendered by the table. By default, the `MatTableDataSource` sorts with the assumption that the sorted column's name matches the data property name that the column displays. For example, the following column definition is named `position`, which matches the name of the property displayed in the row cell. Note that if the data properties do not match the column names, or if a more complex data property accessor is required, then a custom `sortingDataAccessor` function can be set to override the default data accessor on the `MatTableDataSource`. When updating the data soure asynchronously avoid doing so by recreating the entire `MatTableDataSource` as this could break sorting. Rather update it through the `MatTableDataSource.data` property. If you are not using the `MatTableDataSource`, but instead implementing custom logic to sort your data, listen to the sort's `(matSortChange)` event and re-order your data according to the sort state. If you are providing a data array directly to the table, don't forget to call `renderRows()` on the table, since it will not automatically check the array for changes. <!-- example(table-sorting) --> For more information on using and configuring the sorting behavior, check out the [matSort docs](https://material.angular.io/components/sort/overview). The `MatSort` is one provided solution to sorting your table's data, but it is not the only option. In fact, the table can work with any custom sorting UI or strategy since the `MatTable` and its interface is not tied to any one specific implementation. #### Filtering Angular Material does not provide a specific component to be used for filtering the `MatTable` since there is no single common approach to adding a filter UI to table data. A general strategy is to add an input where users can type in a filter string and listen to this input to change what data is offered from the data source to the table. If you are using the `MatTableDataSource`, simply provide the filter string to the `MatTableDataSource`. The data source will reduce each row data to a serialized form and will filter out the row if it does not contain the filter string. By default, the row data reducing function will concatenate all the object values and convert them to lowercase. For example, the data object `{id: 123, name: 'Mr. Smith', favoriteColor: 'blue'}` will be reduced to `123mr. smithblue`. If your filter string was `blue` then it would be considered a match because it is contained in the reduced string, and the row would be displayed in the table. To override the default filtering behavior, a custom `filterPredicate` function can be set which takes a data object and filter string and returns true if the data object is considered a match. If you want to show a message when not data matches the filter, you can use the `*matNoDataRow` directive. <!--- example(table-filtering) --> #### Selection Right now there is no formal support for adding a selection UI to the table, but Angular Material does offer the right components and pieces to set this up. The following steps are one solution but it is not the only way to incorporate row selection in your table. ##### 1. Add a selection model Get started by setting up a `SelectionModel` from `@angular/cdk/collections` that will maintain the selection state. ```js const initialSelection = []; const allowMultiSelect = true; this.selection = new SelectionModel<MyDataType>(allowMultiSelect, initialSelection); ``` ##### 2. Define a selection column Add a column definition for displaying the row checkboxes, including a main toggle checkbox for the header. The column name should be added to the list of displayed columns provided to the header and data row. ```html <ng-container matColumnDef="select"> <th mat-header-cell *matHeaderCellDef> <mat-checkbox (change)="$event ? toggleAllRows() : null" [checked]="selection.hasValue() && isAllSelected()" [indeterminate]="selection.hasValue() && !isAllSelected()"> </mat-checkbox> </th> <td mat-cell *matCellDef="let row"> <mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selection.toggle(row) : null" [checked]="selection.isSelected(row)"> </mat-checkbox> </td> </ng-container> ``` ##### 3. Add event handling logic Implement the behavior in your component's logic to handle the header's main toggle and checking if all rows are selected. ```js /** Whether the number of selected elements matches the total number of rows. */ isAllSelected() { const numSelected = this.selection.selected.length; const numRows = this.dataSource.data.length; return numSelected == numRows; } /** Selects all rows if they are not all selected; otherwise clear selection. */ toggleAllRows() { this.isAllSelected() ? this.selection.clear() : this.dataSource.data.forEach(row => this.selection.select(row)); } ``` ##### 4. Include overflow styling Finally, adjust the styling for the select column so that its overflow is not hidden. This allows the ripple effect to extend beyond the cell. ```css .mat-column-select { overflow: initial; } ``` <!--- example(table-selection) --> #### Footer row A footer row can be added to the table by adding a footer row definition to the table and adding footer cell templates to column definitions. The footer row will be rendered after the rendered data rows. ```html <ng-container matColumnDef="cost"> <th mat-header-cell *matHeaderCellDef> Cost </th> <td mat-cell *matCellDef="let data"> {{data.cost}} </td> <td mat-footer-cell *matFooterCellDef> {{totalCost}} </td> </ng-container> ... <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr> <tr mat-row *matRowDef="let myRowData; columns: columnsToDisplay"></tr> <tr mat-footer-row *matFooterRowDef="columnsToDisplay"></tr> ``` <!--- example(table-footer-row) -->
{ "end_byte": 14799, "start_byte": 6289, "url": "https://github.com/angular/components/blob/main/src/material/table/table.md" }
components/src/material/table/table.md_14799_19419
#### Sticky Rows and Columns By using `position: sticky` styling, the table's rows and columns can be fixed so that they do not leave the viewport even when scrolled. The table provides inputs that will automatically apply the correct CSS styling so that the rows and columns become sticky. In order to fix the header row to the top of the scrolling viewport containing the table, you can add a `sticky` input to the `matHeaderRowDef`. <!--- example(table-sticky-header) --> Similarly, this can also be applied to the table's footer row. Note that if you are using the native `<table>` and using Safari, then the footer will only stick if `sticky` is applied to all the rendered footer rows. <!--- example(table-sticky-footer) --> It is also possible to fix cell columns to the start or end of the horizontally scrolling viewport. To do this, add the `sticky` or `stickyEnd` directive to the `ng-container` column definition. <!--- example(table-sticky-columns) --> Note that on Safari mobile when using the flex-based table, a cell stuck in more than one direction will struggle to stay in the correct position as you scroll. For example, if a header row is stuck to the top and the first column is stuck, then the top-left-most cell will appear jittery as you scroll. Also, sticky positioning in Edge will appear shaky for special cases. For example, if the scrolling container has a complex box shadow and has sibling elements, the stuck cells will appear jittery. There is currently an [open issue with Edge](https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/17514118/) to resolve this. #### Multiple row templates When using the `multiTemplateDataRows` directive to support multiple rows for each data object, the context of `*matRowDef` is the same except that the `index` value is replaced by `dataIndex` and `renderIndex`. <!--- example(table-multiple-row-template) --> ### Accessibility By default, `MatTable` applies `role="table"`, assuming the table's contains primarily static content. You can change the role by explicitly setting `role="grid"` or `role="treegrid"` on the table element. While changing the role will update child element roles, such as changing `role="cell"` to `role="gridcell"`, this does _not_ apply additional keyboard input handling or focus management to the table. Always provide an accessible label for your tables via `aria-label` or `aria-labelledby` on the table element. ### Tables with `display: flex` The `MatTable` does not require that you use a native HTML table. Instead, you can use an alternative approach that uses `display: flex` for the table's styles. This alternative approach replaces the native table element tags with the `MatTable` directive selectors. For example, `<table mat-table>` becomes `<mat-table>`; `<tr mat-row>` becomes `<mat-row>`. The following shows a previous example using this alternative template: ```html <mat-table [dataSource]="dataSource"> <!-- User name Definition --> <ng-container matColumnDef="username"> <mat-header-cell *matHeaderCellDef> User name </mat-header-cell> <mat-cell *matCellDef="let row"> {{row.username}} </mat-cell> </ng-container> <!-- Age Definition --> <ng-container matColumnDef="age"> <mat-header-cell *matHeaderCellDef> Age </mat-header-cell> <mat-cell *matCellDef="let row"> {{row.age}} </mat-cell> </ng-container> <!-- Title Definition --> <ng-container matColumnDef="title"> <mat-header-cell *matHeaderCellDef> Title </mat-header-cell> <mat-cell *matCellDef="let row"> {{row.title}} </mat-cell> </ng-container> <!-- Header and Row Declarations --> <mat-header-row *matHeaderRowDef="['username', 'age', 'title']"></mat-header-row> <mat-row *matRowDef="let row; columns: ['username', 'age', 'title']"></mat-row> </mat-table> ``` Note that this approach means you cannot include certain native-table features such colspan/rowspan or have columns that resize themselves based on their content. ### Tables with `MatRipple` By default, `MatTable` does not set up Material Design ripples for rows. A ripple effect can be added to table rows by using the `MatRipple` directive from `@angular/material/core`. Due to limitations in browsers, ripples cannot be applied native `th` or `tr` elements. The recommended approach for setting up ripples is using the non-native `display: flex` variant of `MatTable`. <!--- example(table-with-ripples) --> More details about ripples on native table rows and their limitations can be found [in this issue](https://github.com/angular/components/issues/11883#issuecomment-634942981).
{ "end_byte": 19419, "start_byte": 14799, "url": "https://github.com/angular/components/blob/main/src/material/table/table.md" }
components/src/material/table/README.md_0_96
Please see the official documentation at https://material.angular.io/components/component/table
{ "end_byte": 96, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/README.md" }
components/src/material/table/table-data-source.ts_0_1561
/** * @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 {MatPaginator, PageEvent} from '@angular/material/paginator'; import { BehaviorSubject, combineLatest, merge, Observable, of as observableOf, Subject, Subscription, } from 'rxjs'; import {DataSource} from '@angular/cdk/collections'; import {MatSort, Sort} from '@angular/material/sort'; import {_isNumberValue} from '@angular/cdk/coercion'; import {map} from 'rxjs/operators'; /** * Corresponds to `Number.MAX_SAFE_INTEGER`. Moved out into a variable here due to * flaky browser support and the value not being defined in Closure's typings. */ const MAX_SAFE_INTEGER = 9007199254740991; /** * Data source that accepts a client-side data array and includes native support of filtering, * sorting (using MatSort), and pagination (using MatPaginator). * * Allows for sort customization by overriding sortingDataAccessor, which defines how data * properties are accessed. Also allows for filter customization by overriding filterPredicate, * which defines how row data is converted to a string for filter matching. * * **Note:** This class is meant to be a simple data source to help you get started. As such * it isn't equipped to handle some more advanced cases like robust i18n support or server-side * interactions. If your app needs to support more advanced use cases, consider implementing your * own `DataSource`. */
{ "end_byte": 1561, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/table-data-source.ts" }
components/src/material/table/table-data-source.ts_1562_10056
export class MatTableDataSource<T, P extends MatPaginator = MatPaginator> extends DataSource<T> { /** Stream that emits when a new data array is set on the data source. */ private readonly _data: BehaviorSubject<T[]>; /** Stream emitting render data to the table (depends on ordered data changes). */ private readonly _renderData = new BehaviorSubject<T[]>([]); /** Stream that emits when a new filter string is set on the data source. */ private readonly _filter = new BehaviorSubject<string>(''); /** Used to react to internal changes of the paginator that are made by the data source itself. */ private readonly _internalPageChanges = new Subject<void>(); /** * Subscription to the changes that should trigger an update to the table's rendered rows, such * as filtering, sorting, pagination, or base data changes. */ _renderChangesSubscription: Subscription | null = null; /** * The filtered set of data that has been matched by the filter string, or all the data if there * is no filter. Useful for knowing the set of data the table represents. * For example, a 'selectAll()' function would likely want to select the set of filtered data * shown to the user rather than all the data. */ filteredData: T[]; /** Array of data that should be rendered by the table, where each object represents one row. */ get data() { return this._data.value; } set data(data: T[]) { data = Array.isArray(data) ? data : []; this._data.next(data); // Normally the `filteredData` is updated by the re-render // subscription, but that won't happen if it's inactive. if (!this._renderChangesSubscription) { this._filterData(data); } } /** * Filter term that should be used to filter out objects from the data array. To override how * data objects match to this filter string, provide a custom function for filterPredicate. */ get filter(): string { return this._filter.value; } set filter(filter: string) { this._filter.next(filter); // Normally the `filteredData` is updated by the re-render // subscription, but that won't happen if it's inactive. if (!this._renderChangesSubscription) { this._filterData(this.data); } } /** * Instance of the MatSort directive used by the table to control its sorting. Sort changes * emitted by the MatSort will trigger an update to the table's rendered data. */ get sort(): MatSort | null { return this._sort; } set sort(sort: MatSort | null) { this._sort = sort; this._updateChangeSubscription(); } private _sort: MatSort | null; /** * Instance of the paginator component used by the table to control what page of the data is * displayed. Page changes emitted by the paginator will trigger an update to the * table's rendered data. * * Note that the data source uses the paginator's properties to calculate which page of data * should be displayed. If the paginator receives its properties as template inputs, * e.g. `[pageLength]=100` or `[pageIndex]=1`, then be sure that the paginator's view has been * initialized before assigning it to this data source. */ get paginator(): P | null { return this._paginator; } set paginator(paginator: P | null) { this._paginator = paginator; this._updateChangeSubscription(); } private _paginator: P | null; /** * Data accessor function that is used for accessing data properties for sorting through * the default sortData function. * This default function assumes that the sort header IDs (which defaults to the column name) * matches the data's properties (e.g. column Xyz represents data['Xyz']). * May be set to a custom function for different behavior. * @param data Data object that is being accessed. * @param sortHeaderId The name of the column that represents the data. */ sortingDataAccessor: (data: T, sortHeaderId: string) => string | number = ( data: T, sortHeaderId: string, ): string | number => { const value = (data as unknown as Record<string, any>)[sortHeaderId]; if (_isNumberValue(value)) { const numberValue = Number(value); // Numbers beyond `MAX_SAFE_INTEGER` can't be compared reliably so we leave them as strings. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER return numberValue < MAX_SAFE_INTEGER ? numberValue : value; } return value; }; /** * Gets a sorted copy of the data array based on the state of the MatSort. Called * after changes are made to the filtered data or when sort changes are emitted from MatSort. * By default, the function retrieves the active sort and its direction and compares data * by retrieving data using the sortingDataAccessor. May be overridden for a custom implementation * of data ordering. * @param data The array of data that should be sorted. * @param sort The connected MatSort that holds the current sort state. */ sortData: (data: T[], sort: MatSort) => T[] = (data: T[], sort: MatSort): T[] => { const active = sort.active; const direction = sort.direction; if (!active || direction == '') { return data; } return data.sort((a, b) => { let valueA = this.sortingDataAccessor(a, active); let valueB = this.sortingDataAccessor(b, active); // If there are data in the column that can be converted to a number, // it must be ensured that the rest of the data // is of the same type so as not to order incorrectly. const valueAType = typeof valueA; const valueBType = typeof valueB; if (valueAType !== valueBType) { if (valueAType === 'number') { valueA += ''; } if (valueBType === 'number') { valueB += ''; } } // If both valueA and valueB exist (truthy), then compare the two. Otherwise, check if // one value exists while the other doesn't. In this case, existing value should come last. // This avoids inconsistent results when comparing values to undefined/null. // If neither value exists, return 0 (equal). let comparatorResult = 0; if (valueA != null && valueB != null) { // Check if one value is greater than the other; if equal, comparatorResult should remain 0. if (valueA > valueB) { comparatorResult = 1; } else if (valueA < valueB) { comparatorResult = -1; } } else if (valueA != null) { comparatorResult = 1; } else if (valueB != null) { comparatorResult = -1; } return comparatorResult * (direction == 'asc' ? 1 : -1); }); }; /** * Checks if a data object matches the data source's filter string. By default, each data object * is converted to a string of its properties and returns true if the filter has * at least one occurrence in that string. By default, the filter string has its whitespace * trimmed and the match is case-insensitive. May be overridden for a custom implementation of * filter matching. * @param data Data object used to check against the filter. * @param filter Filter string that has been set on the data source. * @returns Whether the filter matches against the data */ filterPredicate: (data: T, filter: string) => boolean = (data: T, filter: string): boolean => { // Transform the data into a lowercase string of all property values. const dataStr = Object.keys(data as unknown as Record<string, any>) .reduce((currentTerm: string, key: string) => { // Use an obscure Unicode character to delimit the words in the concatenated string. // This avoids matches where the values of two columns combined will match the user's query // (e.g. `Flute` and `Stop` will match `Test`). The character is intended to be something // that has a very low chance of being typed in by somebody in a text field. This one in // particular is "White up-pointing triangle with dot" from // https://en.wikipedia.org/wiki/List_of_Unicode_characters return currentTerm + (data as unknown as Record<string, any>)[key] + '◬'; }, '') .toLowerCase(); // Transform the filter by converting it to lowercase and removing whitespace. const transformedFilter = filter.trim().toLowerCase(); return dataStr.indexOf(transformedFilter) != -1; };
{ "end_byte": 10056, "start_byte": 1562, "url": "https://github.com/angular/components/blob/main/src/material/table/table-data-source.ts" }
components/src/material/table/table-data-source.ts_10060_15606
nstructor(initialData: T[] = []) { super(); this._data = new BehaviorSubject<T[]>(initialData); this._updateChangeSubscription(); } /** * Subscribe to changes that should trigger an update to the table's rendered rows. When the * changes occur, process the current state of the filter, sort, and pagination along with * the provided base data and send it to the table for rendering. */ _updateChangeSubscription() { // Sorting and/or pagination should be watched if sort and/or paginator are provided. // The events should emit whenever the component emits a change or initializes, or if no // component is provided, a stream with just a null event should be provided. // The `sortChange` and `pageChange` acts as a signal to the combineLatests below so that the // pipeline can progress to the next step. Note that the value from these streams are not used, // they purely act as a signal to progress in the pipeline. const sortChange: Observable<Sort | null | void> = this._sort ? (merge(this._sort.sortChange, this._sort.initialized) as Observable<Sort | void>) : observableOf(null); const pageChange: Observable<PageEvent | null | void> = this._paginator ? (merge( this._paginator.page, this._internalPageChanges, this._paginator.initialized, ) as Observable<PageEvent | void>) : observableOf(null); const dataStream = this._data; // Watch for base data or filter changes to provide a filtered set of data. const filteredData = combineLatest([dataStream, this._filter]).pipe( map(([data]) => this._filterData(data)), ); // Watch for filtered data or sort changes to provide an ordered set of data. const orderedData = combineLatest([filteredData, sortChange]).pipe( map(([data]) => this._orderData(data)), ); // Watch for ordered data or page changes to provide a paged set of data. const paginatedData = combineLatest([orderedData, pageChange]).pipe( map(([data]) => this._pageData(data)), ); // Watched for paged data changes and send the result to the table to render. this._renderChangesSubscription?.unsubscribe(); this._renderChangesSubscription = paginatedData.subscribe(data => this._renderData.next(data)); } /** * Returns a filtered data array where each filter object contains the filter string within * the result of the filterPredicate function. If no filter is set, returns the data array * as provided. */ _filterData(data: T[]) { // If there is a filter string, filter out data that does not contain it. // Each data object is converted to a string using the function defined by filterPredicate. // May be overridden for customization. this.filteredData = this.filter == null || this.filter === '' ? data : data.filter(obj => this.filterPredicate(obj, this.filter)); if (this.paginator) { this._updatePaginator(this.filteredData.length); } return this.filteredData; } /** * Returns a sorted copy of the data if MatSort has a sort applied, otherwise just returns the * data array as provided. Uses the default data accessor for data lookup, unless a * sortDataAccessor function is defined. */ _orderData(data: T[]): T[] { // If there is no active sort or direction, return the data without trying to sort. if (!this.sort) { return data; } return this.sortData(data.slice(), this.sort); } /** * Returns a paged slice of the provided data array according to the provided paginator's page * index and length. If there is no paginator provided, returns the data array as provided. */ _pageData(data: T[]): T[] { if (!this.paginator) { return data; } const startIndex = this.paginator.pageIndex * this.paginator.pageSize; return data.slice(startIndex, startIndex + this.paginator.pageSize); } /** * Updates the paginator to reflect the length of the filtered data, and makes sure that the page * index does not exceed the paginator's last page. Values are changed in a resolved promise to * guard against making property changes within a round of change detection. */ _updatePaginator(filteredDataLength: number) { Promise.resolve().then(() => { const paginator = this.paginator; if (!paginator) { return; } paginator.length = filteredDataLength; // If the page index is set beyond the page, reduce it to the last page. if (paginator.pageIndex > 0) { const lastPageIndex = Math.ceil(paginator.length / paginator.pageSize) - 1 || 0; const newPageIndex = Math.min(paginator.pageIndex, lastPageIndex); if (newPageIndex !== paginator.pageIndex) { paginator.pageIndex = newPageIndex; // Since the paginator only emits after user-generated changes, // we need our own stream so we know to should re-render the data. this._internalPageChanges.next(); } } }); } /** * Used by the MatTable. Called when it connects to the data source. * @docs-private */ connect() { if (!this._renderChangesSubscription) { this._updateChangeSubscription(); } return this._renderData; } /** * Used by the MatTable. Called when it disconnects from the data source. * @docs-private */ disconnect() { this._renderChangesSubscription?.unsubscribe(); this._renderChangesSubscription = null; } }
{ "end_byte": 15606, "start_byte": 10060, "url": "https://github.com/angular/components/blob/main/src/material/table/table-data-source.ts" }
components/src/material/table/cell.ts_0_3092
/** * @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, Input} from '@angular/core'; import { CdkCell, CdkCellDef, CdkColumnDef, CdkFooterCell, CdkFooterCellDef, CdkHeaderCell, CdkHeaderCellDef, } from '@angular/cdk/table'; /** * Cell definition for the mat-table. * Captures the template of a column's data row cell as well as cell-specific properties. */ @Directive({ selector: '[matCellDef]', providers: [{provide: CdkCellDef, useExisting: MatCellDef}], }) export class MatCellDef extends CdkCellDef {} /** * Header cell definition for the mat-table. * Captures the template of a column's header cell and as well as cell-specific properties. */ @Directive({ selector: '[matHeaderCellDef]', providers: [{provide: CdkHeaderCellDef, useExisting: MatHeaderCellDef}], }) export class MatHeaderCellDef extends CdkHeaderCellDef {} /** * Footer cell definition for the mat-table. * Captures the template of a column's footer cell and as well as cell-specific properties. */ @Directive({ selector: '[matFooterCellDef]', providers: [{provide: CdkFooterCellDef, useExisting: MatFooterCellDef}], }) export class MatFooterCellDef extends CdkFooterCellDef {} /** * Column definition for the mat-table. * Defines a set of cells available for a table column. */ @Directive({ selector: '[matColumnDef]', providers: [ {provide: CdkColumnDef, useExisting: MatColumnDef}, {provide: 'MAT_SORT_HEADER_COLUMN_DEF', useExisting: MatColumnDef}, ], }) export class MatColumnDef extends CdkColumnDef { /** Unique name for this column. */ @Input('matColumnDef') override get name(): string { return this._name; } override set name(name: string) { this._setNameInput(name); } /** * Add "mat-column-" prefix in addition to "cdk-column-" prefix. * In the future, this will only add "mat-column-" and columnCssClassName * will change from type string[] to string. * @docs-private */ protected override _updateColumnCssClassName() { super._updateColumnCssClassName(); this._columnCssClassName!.push(`mat-column-${this.cssClassFriendlyName}`); } } /** Header cell template container that adds the right classes and role. */ @Directive({ selector: 'mat-header-cell, th[mat-header-cell]', host: { 'class': 'mat-mdc-header-cell mdc-data-table__header-cell', 'role': 'columnheader', }, }) export class MatHeaderCell extends CdkHeaderCell {} /** Footer cell template container that adds the right classes and role. */ @Directive({ selector: 'mat-footer-cell, td[mat-footer-cell]', host: { 'class': 'mat-mdc-footer-cell mdc-data-table__cell', }, }) export class MatFooterCell extends CdkFooterCell {} /** Cell template container that adds the right classes and role. */ @Directive({ selector: 'mat-cell, td[mat-cell]', host: { 'class': 'mat-mdc-cell mdc-data-table__cell', }, }) export class MatCell extends CdkCell {}
{ "end_byte": 3092, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/cell.ts" }
components/src/material/table/BUILD.bazel_0_1686
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 = "table", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), assets = [":table_scss"] + glob(["**/*.html"]), deps = [ "//src/cdk/table", "//src/material/core", "//src/material/paginator", "//src/material/sort", "@npm//@angular/core", ], ) sass_library( name = "table_scss_lib", srcs = glob(["**/_*.scss"]), deps = [ "//src/material/core:core_scss_lib", ], ) sass_binary( name = "table_scss", src = "table.scss", deps = [ ":table_flex_scss_lib", "//src/material/core:core_scss_lib", ], ) sass_library( name = "table_flex_scss_lib", srcs = [ "_table-flex-styles.scss", ], deps = ["//src/material/core:core_scss_lib"], ) ########### # Testing ########### ng_test_library( name = "table_tests_lib", srcs = glob( ["**/*.spec.ts"], ), deps = [ ":table", "//src/cdk/table", "//src/material/paginator", "//src/material/sort", "@npm//@angular/platform-browser", "@npm//rxjs", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":table_tests_lib", ], ) markdown_to_html( name = "overview", srcs = [":table.md"], ) extract_tokens( name = "tokens", srcs = [":table_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "end_byte": 1686, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/BUILD.bazel" }
components/src/material/table/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/table/index.ts" }
components/src/material/table/_table-theme.scss_0_3046
@use 'sass:map'; @use '../core/tokens/m2/mat/table' as tokens-mat-table; @use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @use '../core/typography/typography'; @use '../core/tokens/token-utils'; @use '../core/style/sass-utils'; @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-table.$prefix, tokens-mat-table.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-table.$prefix, tokens-mat-table.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-table.$prefix, tokens-mat-table.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-table.$prefix, tokens-mat-table.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-table.$prefix, tokens: tokens-mat-table.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-table') { @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-table.$prefix, map.get($tokens, tokens-mat-table.$prefix) ); } }
{ "end_byte": 3046, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/_table-theme.scss" }
components/src/material/table/testing/table-harness.ts_0_3934
/** * @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 { ComponentHarnessConstructor, ContentContainerComponentHarness, HarnessPredicate, parallel, } from '@angular/cdk/testing'; import { MatFooterRowHarness, MatHeaderRowHarness, MatRowHarness, MatRowHarnessColumnsText, } from './row-harness'; import {RowHarnessFilters, TableHarnessFilters} from './table-harness-filters'; /** Text extracted from a table organized by columns. */ export interface MatTableHarnessColumnsText { [columnName: string]: { text: string[]; headerText: string[]; footerText: string[]; }; } /** Harness for interacting with a mat-table in tests. */ export class MatTableHarness extends ContentContainerComponentHarness<string> { /** The selector for the host element of a `MatTableHarness` instance. */ static hostSelector = '.mat-mdc-table'; _headerRowHarness = MatHeaderRowHarness; _rowHarness = MatRowHarness; private _footerRowHarness = MatFooterRowHarness; /** * Gets a `HarnessPredicate` that can be used to search for a table with specific attributes. * @param options Options for narrowing the search * @return a `HarnessPredicate` configured with the given options. */ static with<T extends MatTableHarness>( this: ComponentHarnessConstructor<T>, options: TableHarnessFilters = {}, ): HarnessPredicate<T> { return new HarnessPredicate(this, options); } /** Gets all the header rows in a table. */ async getHeaderRows(filter: RowHarnessFilters = {}): Promise<MatHeaderRowHarness[]> { return this.locatorForAll(this._headerRowHarness.with(filter))(); } /** Gets all the regular data rows in a table. */ async getRows(filter: RowHarnessFilters = {}): Promise<MatRowHarness[]> { return this.locatorForAll(this._rowHarness.with(filter))(); } /** Gets all the footer rows in a table. */ async getFooterRows(filter: RowHarnessFilters = {}): Promise<MatFooterRowHarness[]> { return this.locatorForAll(this._footerRowHarness.with(filter))(); } /** Gets the text inside the entire table organized by rows. */ async getCellTextByIndex(): Promise<string[][]> { const rows = await this.getRows(); return parallel(() => rows.map(row => row.getCellTextByIndex())); } /** Gets the text inside the entire table organized by columns. */ async getCellTextByColumnName(): Promise<MatTableHarnessColumnsText> { const [headerRows, footerRows, dataRows] = await parallel(() => [ this.getHeaderRows(), this.getFooterRows(), this.getRows(), ]); const text: MatTableHarnessColumnsText = {}; const [headerData, footerData, rowsData] = await parallel(() => [ parallel(() => headerRows.map(row => row.getCellTextByColumnName())), parallel(() => footerRows.map(row => row.getCellTextByColumnName())), parallel(() => dataRows.map(row => row.getCellTextByColumnName())), ]); rowsData.forEach(data => { Object.keys(data).forEach(columnName => { const cellText = data[columnName]; if (!text[columnName]) { text[columnName] = { headerText: getCellTextsByColumn(headerData, columnName), footerText: getCellTextsByColumn(footerData, columnName), text: [], }; } text[columnName].text.push(cellText); }); }); return text; } } /** Extracts the text of cells only under a particular column. */ function getCellTextsByColumn(rowsData: MatRowHarnessColumnsText[], column: string): string[] { const columnTexts: string[] = []; rowsData.forEach(data => { Object.keys(data).forEach(columnName => { if (columnName === column) { columnTexts.push(data[columnName]); } }); }); return columnTexts; }
{ "end_byte": 3934, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/testing/table-harness.ts" }
components/src/material/table/testing/public-api.ts_0_341
/** * @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 './table-harness'; export * from './row-harness'; export * from './cell-harness'; export * from './table-harness-filters';
{ "end_byte": 341, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/testing/public-api.ts" }
components/src/material/table/testing/table-harness.spec.ts_0_6485
import {Component} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {HarnessLoader, parallel} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {MatTableModule} from '../module'; import {MatTableHarness} from './table-harness'; describe('MatTableHarness', () => { let fixture: ComponentFixture<TableHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ imports: [MatTableModule, TableHarnessTest], }); fixture = TestBed.createComponent(TableHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); it('should load harness for a table', async () => { const tables = await loader.getAllHarnesses(MatTableHarness); expect(tables.length).toBe(1); }); it('should get the different kinds of rows in the table', async () => { const table = await loader.getHarness(MatTableHarness); const headerRows = await table.getHeaderRows(); const footerRows = await table.getFooterRows(); const rows = await table.getRows(); expect(headerRows.length).toBe(1); expect(footerRows.length).toBe(1); expect(rows.length).toBe(10); }); it('should get cells inside a row', async () => { const table = await loader.getHarness(MatTableHarness); const headerRows = await table.getHeaderRows(); const footerRows = await table.getFooterRows(); const rows = await table.getRows(); const headerCells = (await parallel(() => headerRows.map(row => row.getCells()))).map( row => row.length, ); const footerCells = (await parallel(() => footerRows.map(row => row.getCells()))).map( row => row.length, ); const cells = (await parallel(() => rows.map(row => row.getCells()))).map(row => row.length); expect(headerCells).toEqual([4]); expect(cells).toEqual([4, 4, 4, 4, 4, 4, 4, 4, 4, 4]); expect(footerCells).toEqual([4]); }); it('should be able to get the text of a cell', async () => { const table = await loader.getHarness(MatTableHarness); const secondRow = (await table.getRows())[1]; const cells = await secondRow.getCells(); const cellTexts = await parallel(() => cells.map(cell => cell.getText())); expect(cellTexts).toEqual(['2', 'Helium', '4.0026', 'He']); }); it('should be able to get the column name of a cell', async () => { const table = await loader.getHarness(MatTableHarness); const fifthRow = (await table.getRows())[1]; const cells = await fifthRow.getCells(); const cellColumnNames = await parallel(() => cells.map(cell => cell.getColumnName())); expect(cellColumnNames).toEqual(['position', 'name', 'weight', 'symbol']); }); it('should be able to filter cells by text', async () => { const table = await loader.getHarness(MatTableHarness); const firstRow = (await table.getRows())[0]; const cells = await firstRow.getCells({text: '1.0079'}); const cellTexts = await parallel(() => cells.map(cell => cell.getText())); expect(cellTexts).toEqual(['1.0079']); }); it('should be able to filter cells by column name', async () => { const table = await loader.getHarness(MatTableHarness); const firstRow = (await table.getRows())[0]; const cells = await firstRow.getCells({columnName: 'symbol'}); const cellTexts = await parallel(() => cells.map(cell => cell.getText())); expect(cellTexts).toEqual(['H']); }); it('should be able to filter cells by regex', async () => { const table = await loader.getHarness(MatTableHarness); const firstRow = (await table.getRows())[0]; const cells = await firstRow.getCells({text: /^H/}); const cellTexts = await parallel(() => cells.map(cell => cell.getText())); expect(cellTexts).toEqual(['Hydrogen', 'H']); }); it('should be able to get the table text organized by columns', async () => { const table = await loader.getHarness(MatTableHarness); const text = await table.getCellTextByColumnName(); expect(text).toEqual({ position: { headerText: ['No.'], footerText: ['Number of the element'], text: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'], }, name: { headerText: ['Name'], footerText: ['Name of the element'], text: [ 'Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron', 'Carbon', 'Nitrogen', 'Oxygen', 'Fluorine', 'Neon', ], }, weight: { headerText: ['Weight'], footerText: ['Weight of the element'], text: [ '1.0079', '4.0026', '6.941', '9.0122', '10.811', '12.0107', '14.0067', '15.9994', '18.9984', '20.1797', ], }, symbol: { headerText: ['Symbol'], footerText: ['Symbol of the element'], text: ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne'], }, }); }); it('should be able to get the table text organized by rows', async () => { const table = await loader.getHarness(MatTableHarness); const text = await table.getCellTextByIndex(); expect(text).toEqual([ ['1', 'Hydrogen', '1.0079', 'H'], ['2', 'Helium', '4.0026', 'He'], ['3', 'Lithium', '6.941', 'Li'], ['4', 'Beryllium', '9.0122', 'Be'], ['5', 'Boron', '10.811', 'B'], ['6', 'Carbon', '12.0107', 'C'], ['7', 'Nitrogen', '14.0067', 'N'], ['8', 'Oxygen', '15.9994', 'O'], ['9', 'Fluorine', '18.9984', 'F'], ['10', 'Neon', '20.1797', 'Ne'], ]); }); it('should be able to get the cell text in a row organized by index', async () => { const table = await loader.getHarness(MatTableHarness); const rows = await table.getRows(); expect(rows.length).toBeGreaterThan(0); expect(await rows[0].getCellTextByIndex()).toEqual(['1', 'Hydrogen', '1.0079', 'H']); }); it('should be able to get the cell text in a row organized by columns', async () => { const table = await loader.getHarness(MatTableHarness); const rows = await table.getRows(); expect(rows.length).toBeGreaterThan(0); expect(await rows[0].getCellTextByColumnName()).toEqual({ position: '1', name: 'Hydrogen', weight: '1.0079', symbol: 'H', }); }); });
{ "end_byte": 6485, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/testing/table-harness.spec.ts" }
components/src/material/table/testing/table-harness.spec.ts_6487_8681
@Component({ template: ` <table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="position"> <th mat-header-cell *matHeaderCellDef>No.</th> <td mat-cell *matCellDef="let element">{{element.position}}</td> <td mat-footer-cell *matFooterCellDef>Number of the element</td> </ng-container> <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef>Name</th> <td mat-cell *matCellDef="let element">{{element.name}}</td> <td mat-footer-cell *matFooterCellDef>Name of the element</td> </ng-container> <ng-container matColumnDef="weight"> <th mat-header-cell *matHeaderCellDef>Weight</th> <td mat-cell *matCellDef="let element">{{element.weight}}</td> <td mat-footer-cell *matFooterCellDef>Weight of the element</td> </ng-container> <ng-container matColumnDef="symbol"> <th mat-header-cell *matHeaderCellDef>Symbol</th> <td mat-cell *matCellDef="let element">{{element.symbol}}</td> <td mat-footer-cell *matFooterCellDef>Symbol of the element</td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-footer-row *matFooterRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> `, standalone: true, imports: [MatTableModule], }) class TableHarnessTest { displayedColumns: string[] = ['position', 'name', 'weight', 'symbol']; dataSource = [ {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'}, {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}, {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'}, {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'}, {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'}, {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'}, {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'}, {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'}, {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'}, {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'}, ]; }
{ "end_byte": 8681, "start_byte": 6487, "url": "https://github.com/angular/components/blob/main/src/material/table/testing/table-harness.spec.ts" }
components/src/material/table/testing/table-harness-filters.ts_0_916
/** * @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 cell harness instances. */ export interface CellHarnessFilters extends BaseHarnessFilters { /** Only find instances whose text matches the given value. */ text?: string | RegExp; /** Only find instances whose column name matches the given value. */ columnName?: string | RegExp; } /** A set of criteria that can be used to filter a list of row harness instances. */ export interface RowHarnessFilters extends BaseHarnessFilters {} /** A set of criteria that can be used to filter a list of table harness instances. */ export interface TableHarnessFilters extends BaseHarnessFilters {}
{ "end_byte": 916, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/testing/table-harness-filters.ts" }
components/src/material/table/testing/row-harness.ts_0_4287
/** * @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 { ComponentHarness, ComponentHarnessConstructor, HarnessPredicate, parallel, } from '@angular/cdk/testing'; import { _MatCellHarnessBase, MatCellHarness, MatFooterCellHarness, MatHeaderCellHarness, } from './cell-harness'; import {CellHarnessFilters, RowHarnessFilters} from './table-harness-filters'; /** Text extracted from a table row organized by columns. */ export interface MatRowHarnessColumnsText { [columnName: string]: string; } export abstract class _MatRowHarnessBase< CellType extends ComponentHarnessConstructor<Cell> & { with: (options?: CellHarnessFilters) => HarnessPredicate<Cell>; }, Cell extends _MatCellHarnessBase, > extends ComponentHarness { protected abstract _cellHarness: CellType; /** Gets a list of `MatCellHarness` for all cells in the row. */ async getCells(filter: CellHarnessFilters = {}): Promise<Cell[]> { return this.locatorForAll(this._cellHarness.with(filter))(); } /** Gets the text of the cells in the row. */ async getCellTextByIndex(filter: CellHarnessFilters = {}): Promise<string[]> { const cells = await this.getCells(filter); return parallel(() => cells.map(cell => cell.getText())); } /** Gets the text inside the row organized by columns. */ async getCellTextByColumnName(): Promise<MatRowHarnessColumnsText> { const output: MatRowHarnessColumnsText = {}; const cells = await this.getCells(); const cellsData = await parallel(() => cells.map(cell => { return parallel(() => [cell.getColumnName(), cell.getText()]); }), ); cellsData.forEach(([columnName, text]) => (output[columnName] = text)); return output; } } /** Harness for interacting with an Angular Material table row. */ export class MatRowHarness extends _MatRowHarnessBase<typeof MatCellHarness, MatCellHarness> { /** The selector for the host element of a `MatRowHarness` instance. */ static hostSelector = '.mat-mdc-row'; protected _cellHarness = MatCellHarness; /** * Gets a `HarnessPredicate` that can be used to search for a table row with specific attributes. * @param options Options for narrowing the search * @return a `HarnessPredicate` configured with the given options. */ static with<T extends MatRowHarness>( this: ComponentHarnessConstructor<T>, options: RowHarnessFilters = {}, ): HarnessPredicate<T> { return new HarnessPredicate(this, options); } } /** Harness for interacting with an Angular Material table header row. */ export class MatHeaderRowHarness extends _MatRowHarnessBase< typeof MatHeaderCellHarness, MatHeaderCellHarness > { /** The selector for the host element of a `MatHeaderRowHarness` instance. */ static hostSelector = '.mat-mdc-header-row'; protected _cellHarness = MatHeaderCellHarness; /** * Gets a `HarnessPredicate` that can be used to search for a table header row with specific * attributes. * @param options Options for narrowing the search * @return a `HarnessPredicate` configured with the given options. */ static with<T extends MatHeaderRowHarness>( this: ComponentHarnessConstructor<T>, options: RowHarnessFilters = {}, ): HarnessPredicate<T> { return new HarnessPredicate(this, options); } } /** Harness for interacting with an Angular Material table footer row. */ export class MatFooterRowHarness extends _MatRowHarnessBase< typeof MatFooterCellHarness, MatFooterCellHarness > { /** The selector for the host element of a `MatFooterRowHarness` instance. */ static hostSelector = '.mat-mdc-footer-row'; protected _cellHarness = MatFooterCellHarness; /** * Gets a `HarnessPredicate` that can be used to search for a table footer row cell with specific * attributes. * @param options Options for narrowing the search * @return a `HarnessPredicate` configured with the given options. */ static with<T extends MatFooterRowHarness>( this: ComponentHarnessConstructor<T>, options: RowHarnessFilters = {}, ): HarnessPredicate<T> { return new HarnessPredicate(this, options); } }
{ "end_byte": 4287, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/testing/row-harness.ts" }
components/src/material/table/testing/BUILD.bazel_0_677
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/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/table", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_tests_lib"], )
{ "end_byte": 677, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/testing/BUILD.bazel" }
components/src/material/table/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/table/testing/index.ts" }
components/src/material/table/testing/cell-harness.ts_0_3607
/** * @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 { ComponentHarnessConstructor, ContentContainerComponentHarness, HarnessPredicate, } from '@angular/cdk/testing'; import {CellHarnessFilters} from './table-harness-filters'; export abstract class _MatCellHarnessBase extends ContentContainerComponentHarness { /** Gets the cell's text. */ async getText(): Promise<string> { return (await this.host()).text(); } /** Gets the name of the column that the cell belongs to. */ async getColumnName(): Promise<string> { const host = await this.host(); const classAttribute = await host.getAttribute('class'); if (classAttribute) { const prefix = 'mat-column-'; const name = classAttribute .split(' ') .map(c => c.trim()) .find(c => c.startsWith(prefix)); if (name) { return name.split(prefix)[1]; } } throw Error('Could not determine column name of cell.'); } protected static _getCellPredicate<T extends MatCellHarness>( type: ComponentHarnessConstructor<T>, options: CellHarnessFilters, ): HarnessPredicate<T> { return new HarnessPredicate(type, options) .addOption('text', options.text, (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text), ) .addOption('columnName', options.columnName, (harness, name) => HarnessPredicate.stringMatches(harness.getColumnName(), name), ); } } /** Harness for interacting with an Angular Material table cell. */ export class MatCellHarness extends _MatCellHarnessBase { /** The selector for the host element of a `MatCellHarness` instance. */ static hostSelector = '.mat-mdc-cell'; /** * Gets a `HarnessPredicate` that can be used to search for a table cell with specific attributes. * @param options Options for narrowing the search * @return a `HarnessPredicate` configured with the given options. */ static with(options: CellHarnessFilters = {}): HarnessPredicate<MatCellHarness> { return _MatCellHarnessBase._getCellPredicate(this, options); } } /** Harness for interacting with an Angular Material table header cell. */ export class MatHeaderCellHarness extends _MatCellHarnessBase { /** The selector for the host element of a `MatHeaderCellHarness` instance. */ static hostSelector = '.mat-mdc-header-cell'; /** * Gets a `HarnessPredicate` that can be used to search for a table header cell with specific * attributes. * @param options Options for narrowing the search * @return a `HarnessPredicate` configured with the given options. */ static with(options: CellHarnessFilters = {}): HarnessPredicate<MatHeaderCellHarness> { return _MatCellHarnessBase._getCellPredicate(this, options); } } /** Harness for interacting with an Angular Material table footer cell. */ export class MatFooterCellHarness extends _MatCellHarnessBase { /** The selector for the host element of a `MatFooterCellHarness` instance. */ static hostSelector = '.mat-mdc-footer-cell'; /** * Gets a `HarnessPredicate` that can be used to search for a table footer cell with specific * attributes. * @param options Options for narrowing the search * @return a `HarnessPredicate` configured with the given options. */ static with(options: CellHarnessFilters = {}): HarnessPredicate<MatFooterCellHarness> { return _MatCellHarnessBase._getCellPredicate(this, options); } }
{ "end_byte": 3607, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/table/testing/cell-harness.ts" }
components/src/material/list/nav-list.ts_0_1582
/** * @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, InjectionToken, ViewEncapsulation} from '@angular/core'; import {MatListBase} from './list-base'; /** * Injection token that can be used to inject instances of `MatNavList`. It serves as * alternative token to the actual `MatNavList` class which could cause unnecessary * retention of the class and its component metadata. */ export const MAT_NAV_LIST = new InjectionToken<MatNavList>('MatNavList'); @Component({ selector: 'mat-nav-list', exportAs: 'matNavList', template: '<ng-content></ng-content>', host: { 'class': 'mat-mdc-nav-list mat-mdc-list-base mdc-list', 'role': 'navigation', }, styleUrl: 'list.css', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, providers: [{provide: MatListBase, useExisting: MatNavList}], }) export class MatNavList extends MatListBase { // An navigation list is considered interactive, but does not extend the interactive list // base class. We do this because as per MDC, items of interactive lists are only reachable // through keyboard shortcuts. We want all items for the navigation list to be reachable // through tab key as we do not intend to provide any special accessibility treatment. The // accessibility treatment depends on how the end-user will interact with it. override _isNonInteractive = false; }
{ "end_byte": 1582, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/nav-list.ts" }
components/src/material/list/_list-item-hcm-indicator.scss_0_764
@use '@angular/cdk'; // Renders a circle indicator when Windows Hich Constrast mode (HCM) is enabled. In some // situations, such as a selected option, the list item communicates the selected state by changing // its background color. Since that doesn't work in HCM, this mixin provides an alternative by // rendering a circle. @mixin private-high-contrast-list-item-indicator() { @include cdk.high-contrast { &::after { $size: 10px; content: ''; position: absolute; top: 50%; right: 16px; transform: translateY(-50%); width: $size; height: 0; border-bottom: solid $size; border-radius: $size; } [dir='rtl'] { &::after { right: auto; left: 16px; } } } }
{ "end_byte": 764, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/_list-item-hcm-indicator.scss" }
components/src/material/list/list-option.ts_0_4144
/** * @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 {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; import {SelectionModel} from '@angular/cdk/collections'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, ElementRef, EventEmitter, InjectionToken, Input, OnDestroy, OnInit, Output, QueryList, ViewChild, ViewEncapsulation, inject, } from '@angular/core'; import {ThemePalette} from '@angular/material/core'; import {MatListBase, MatListItemBase} from './list-base'; import {LIST_OPTION, ListOption, MatListOptionTogglePosition} from './list-option-types'; import {MatListItemLine, MatListItemTitle} from './list-item-sections'; import {NgTemplateOutlet} from '@angular/common'; import {CdkObserveContent} from '@angular/cdk/observers'; /** * Injection token that can be used to reference instances of an `SelectionList`. It serves * as alternative token to an actual implementation which would result in circular references. * @docs-private */ export const SELECTION_LIST = new InjectionToken<SelectionList>('SelectionList'); /** * Interface describing the containing list of a list option. This is used to avoid * circular dependencies between the list-option and the selection list. * @docs-private */ export interface SelectionList extends MatListBase { multiple: boolean; color: ThemePalette; selectedOptions: SelectionModel<MatListOption>; hideSingleSelectionIndicator: boolean; compareWith: (o1: any, o2: any) => boolean; _value: string[] | null; _reportValueChange(): void; _emitChangeEvent(options: MatListOption[]): void; _onTouched(): void; } @Component({ selector: 'mat-list-option', exportAs: 'matListOption', styleUrl: 'list-option.css', host: { 'class': 'mat-mdc-list-item mat-mdc-list-option mdc-list-item', 'role': 'option', // As per MDC, only list items without checkbox or radio indicator should receive the // `--selected` class. '[class.mdc-list-item--selected]': 'selected && !_selectionList.multiple && _selectionList.hideSingleSelectionIndicator', // Based on the checkbox/radio position and whether there are icons or avatars, we apply MDC's // list-item `--leading` and `--trailing` classes. '[class.mdc-list-item--with-leading-avatar]': '_hasProjected("avatars", "before")', '[class.mdc-list-item--with-leading-icon]': '_hasProjected("icons", "before")', '[class.mdc-list-item--with-trailing-icon]': '_hasProjected("icons", "after")', '[class.mat-mdc-list-option-with-trailing-avatar]': '_hasProjected("avatars", "after")', // Based on the checkbox/radio position, we apply the `--leading` or `--trailing` MDC classes // which ensure that the checkbox/radio is positioned correctly within the list item. '[class.mdc-list-item--with-leading-checkbox]': '_hasCheckboxAt("before")', '[class.mdc-list-item--with-trailing-checkbox]': '_hasCheckboxAt("after")', '[class.mdc-list-item--with-leading-radio]': '_hasRadioAt("before")', '[class.mdc-list-item--with-trailing-radio]': '_hasRadioAt("after")', // Utility class that makes it easier to target the case where there's both a leading // and a trailing icon. Avoids having to write out all the combinations. '[class.mat-mdc-list-item-both-leading-and-trailing]': '_hasBothLeadingAndTrailing()', '[class.mat-accent]': 'color !== "primary" && color !== "warn"', '[class.mat-warn]': 'color === "warn"', '[class._mat-animation-noopable]': '_noopAnimations', '[attr.aria-selected]': 'selected', '(blur)': '_handleBlur()', '(click)': '_toggleOnInteraction()', }, templateUrl: 'list-option.html', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, providers: [ {provide: MatListItemBase, useExisting: MatListOption}, {provide: LIST_OPTION, useExisting: MatListOption}, ], imports: [NgTemplateOutlet, CdkObserveContent], }) export
{ "end_byte": 4144, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/list-option.ts" }
components/src/material/list/list-option.ts_4145_11872
class MatListOption extends MatListItemBase implements ListOption, OnInit, OnDestroy { private _selectionList = inject<SelectionList>(SELECTION_LIST); private _changeDetectorRef = inject(ChangeDetectorRef); @ContentChildren(MatListItemLine, {descendants: true}) _lines: QueryList<MatListItemLine>; @ContentChildren(MatListItemTitle, {descendants: true}) _titles: QueryList<MatListItemTitle>; @ViewChild('unscopedContent') _unscopedContent: ElementRef<HTMLSpanElement>; /** * Emits when the selected state of the option has changed. * Use to facilitate two-data binding to the `selected` property. * @docs-private */ @Output() readonly selectedChange: EventEmitter<boolean> = new EventEmitter<boolean>(); /** Whether the label should appear before or after the checkbox/radio. Defaults to 'after' */ @Input() togglePosition: MatListOptionTogglePosition = 'after'; /** * Whether the label should appear before or after the checkbox/radio. Defaults to 'after' * * @deprecated Use `togglePosition` instead. * @breaking-change 17.0.0 */ @Input() get checkboxPosition(): MatListOptionTogglePosition { return this.togglePosition; } set checkboxPosition(value: MatListOptionTogglePosition) { this.togglePosition = value; } /** * Theme color of the list option. This sets the color of the checkbox/radio. * This API is supported in M2 themes only, it has no effect in M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants. */ @Input() get color(): ThemePalette { return this._color || this._selectionList.color; } set color(newValue: ThemePalette) { this._color = newValue; } private _color: ThemePalette; /** Value of the option */ @Input() get value(): any { return this._value; } set value(newValue: any) { if (this.selected && newValue !== this.value && this._inputsInitialized) { this.selected = false; } this._value = newValue; } private _value: any; /** Whether the option is selected. */ @Input() get selected(): boolean { return this._selectionList.selectedOptions.isSelected(this); } set selected(value: BooleanInput) { const isSelected = coerceBooleanProperty(value); if (isSelected !== this._selected) { this._setSelected(isSelected); if (isSelected || this._selectionList.multiple) { this._selectionList._reportValueChange(); } } } private _selected = false; /** * This is set to true after the first OnChanges cycle so we don't * clear the value of `selected` in the first cycle. */ private _inputsInitialized = false; ngOnInit() { const list = this._selectionList; if (list._value && list._value.some(value => list.compareWith(this._value, value))) { this._setSelected(true); } const wasSelected = this._selected; // List options that are selected at initialization can't be reported properly to the form // control. This is because it takes some time until the selection-list knows about all // available options. Also it can happen that the ControlValueAccessor has an initial value // that should be used instead. Deferring the value change report to the next tick ensures // that the form control value is not being overwritten. Promise.resolve().then(() => { if (this._selected || wasSelected) { this.selected = true; this._changeDetectorRef.markForCheck(); } }); this._inputsInitialized = true; } override ngOnDestroy(): void { super.ngOnDestroy(); if (this.selected) { // We have to delay this until the next tick in order // to avoid changed after checked errors. Promise.resolve().then(() => { this.selected = false; }); } } /** Toggles the selection state of the option. */ toggle(): void { this.selected = !this.selected; } /** Allows for programmatic focusing of the option. */ focus(): void { this._hostElement.focus(); } /** Gets the text label of the list option. Used for the typeahead functionality in the list. */ getLabel() { const titleElement = this._titles?.get(0)?._elementRef.nativeElement; // If there is no explicit title element, the unscoped text content // is treated as the list item title. const labelEl = titleElement || this._unscopedContent?.nativeElement; return labelEl?.textContent || ''; } /** Whether a checkbox is shown at the given position. */ _hasCheckboxAt(position: MatListOptionTogglePosition): boolean { return this._selectionList.multiple && this._getTogglePosition() === position; } /** Where a radio indicator is shown at the given position. */ _hasRadioAt(position: MatListOptionTogglePosition): boolean { return ( !this._selectionList.multiple && this._getTogglePosition() === position && !this._selectionList.hideSingleSelectionIndicator ); } /** Whether icons or avatars are shown at the given position. */ _hasIconsOrAvatarsAt(position: 'before' | 'after'): boolean { return this._hasProjected('icons', position) || this._hasProjected('avatars', position); } /** Gets whether the given type of element is projected at the specified position. */ _hasProjected(type: 'icons' | 'avatars', position: 'before' | 'after'): boolean { // If the checkbox/radio is shown at the specified position, neither icons or // avatars can be shown at the position. return ( this._getTogglePosition() !== position && (type === 'avatars' ? this._avatars.length !== 0 : this._icons.length !== 0) ); } _handleBlur() { this._selectionList._onTouched(); } /** Gets the current position of the checkbox/radio. */ _getTogglePosition() { return this.togglePosition || 'after'; } /** * Sets the selected state of the option. * @returns Whether the value has changed. */ _setSelected(selected: boolean): boolean { if (selected === this._selected) { return false; } this._selected = selected; if (selected) { this._selectionList.selectedOptions.select(this); } else { this._selectionList.selectedOptions.deselect(this); } this.selectedChange.emit(selected); this._changeDetectorRef.markForCheck(); return true; } /** * Notifies Angular that the option needs to be checked in the next change detection run. * Mainly used to trigger an update of the list option if the disabled state of the selection * list changed. */ _markForCheck() { this._changeDetectorRef.markForCheck(); } /** Toggles the option's value based on a user interaction. */ _toggleOnInteraction() { if (!this.disabled) { if (this._selectionList.multiple) { this.selected = !this.selected; this._selectionList._emitChangeEvent([this]); } else if (!this.selected) { this.selected = true; this._selectionList._emitChangeEvent([this]); } } } /** Sets the tabindex of the list option. */ _setTabindex(value: number) { this._hostElement.setAttribute('tabindex', value + ''); } protected _hasBothLeadingAndTrailing(): boolean { const hasLeading = this._hasProjected('avatars', 'before') || this._hasProjected('icons', 'before') || this._hasCheckboxAt('before') || this._hasRadioAt('before'); const hasTrailing = this._hasProjected('icons', 'after') || this._hasProjected('avatars', 'after') || this._hasCheckboxAt('after') || this._hasRadioAt('after'); return hasLeading && hasTrailing; } }
{ "end_byte": 11872, "start_byte": 4145, "url": "https://github.com/angular/components/blob/main/src/material/list/list-option.ts" }
components/src/material/list/list-option-types.ts_0_1037
/** * @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 {InjectionToken} from '@angular/core'; /** * Type describing possible positions of a checkbox or radio in a list option * with respect to the list item's text. */ export type MatListOptionTogglePosition = 'before' | 'after'; /** * Interface describing a list option. This is used to avoid circular * dependencies between the list-option and the styler directives. * @docs-private */ export interface ListOption { _getTogglePosition(): MatListOptionTogglePosition; } /** * Injection token that can be used to reference instances of an `ListOption`. It serves * as alternative token to an actual implementation which could result in undesired * retention of the class or circular references breaking runtime execution. * @docs-private */ export const LIST_OPTION = new InjectionToken<ListOption>('ListOption');
{ "end_byte": 1037, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/list-option-types.ts" }
components/src/material/list/public-api.ts_0_758
/** * @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 './action-list'; export * from './list'; export * from './list-module'; export * from './nav-list'; export * from './selection-list'; export * from './list-option'; export * from './subheader'; export * from './list-item-sections'; export * from './tokens'; export {MatListOption} from './list-option'; export { MatListOptionTogglePosition, /** * @deprecated Use `MatListOptionTogglePosition` instead. * @breaking-change 17.0.0 */ MatListOptionTogglePosition as MatListOptionCheckboxPosition, } from './list-option-types';
{ "end_byte": 758, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/public-api.ts" }
components/src/material/list/list-item.html_0_695
<ng-content select="[matListItemAvatar],[matListItemIcon]"></ng-content> <span class="mdc-list-item__content"> <ng-content select="[matListItemTitle]"></ng-content> <ng-content select="[matListItemLine]"></ng-content> <span #unscopedContent class="mat-mdc-list-item-unscoped-content" (cdkObserveContent)="_updateItemLines(true)"> <ng-content></ng-content> </span> </span> <ng-content select="[matListItemMeta]"></ng-content> <ng-content select="mat-divider"></ng-content> <!-- Strong focus indicator element. MDC uses the `::before` pseudo element for the default focus/hover/selected state, so we need a separate element. --> <div class="mat-focus-indicator"></div>
{ "end_byte": 695, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/list-item.html" }
components/src/material/list/_list-theme.scss_0_7819
@use 'sass:map'; @use '../core/style/sass-utils'; @use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @use '../core/tokens/m2/mat/list' as tokens-mat-list; @use '../core/tokens/m2/mdc/checkbox' as tokens-mdc-checkbox; @use '../core/tokens/m2/mdc/radio' as tokens-mdc-radio; @use '../core/tokens/m2/mdc/list' as tokens-mdc-list; @use '../core/tokens/token-utils'; @use '../core/typography/typography'; @mixin base($theme) { // Add default values for tokens not related to color, typography, or density. @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-mdc-list.$prefix, tokens-mdc-list.get-unthemable-tokens() ); @include token-utils.create-token-values( tokens-mat-list.$prefix, tokens-mat-list.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-mdc-list.$prefix, tokens-mdc-list.get-color-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-list.$prefix, tokens-mat-list.get-color-tokens($theme) ); } .mdc-list-item__start, .mdc-list-item__end { @include token-utils.create-token-values( tokens-mdc-radio.$prefix, tokens-mdc-radio.get-color-tokens($theme, primary) ); } .mat-accent { .mdc-list-item__start, .mdc-list-item__end { @include token-utils.create-token-values( tokens-mdc-radio.$prefix, tokens-mdc-radio.get-color-tokens($theme, accent) ); } } .mat-warn { .mdc-list-item__start, .mdc-list-item__end { @include token-utils.create-token-values( tokens-mdc-radio.$prefix, tokens-mdc-radio.get-color-tokens($theme, warn) ); } } .mat-mdc-list-option { @include token-utils.create-token-values( tokens-mdc-checkbox.$prefix, tokens-mdc-checkbox.get-color-tokens($theme, primary) ); } .mat-mdc-list-option.mat-accent { @include token-utils.create-token-values( tokens-mdc-checkbox.$prefix, tokens-mdc-checkbox.get-color-tokens($theme, accent) ); } .mat-mdc-list-option.mat-warn { @include token-utils.create-token-values( tokens-mdc-checkbox.$prefix, tokens-mdc-checkbox.get-color-tokens($theme, warn) ); } // There is no token for activated color on nav list. // TODO(mmalerba): Add a token to MDC or make a custom one. .mat-mdc-list-base.mat-mdc-list-base { .mdc-list-item--selected, .mdc-list-item--activated { .mdc-list-item__primary-text, .mdc-list-item__start { color: inspection.get-theme-color($theme, primary); } } } // TODO(mmalerba): Leaking styles from the old MDC list mixins used in other components can // cause opacity issues, so we need this override for now. We can remove it when all // Angular Material components stop using the old MDC mixins. .mat-mdc-list-base .mdc-list-item--disabled { .mdc-list-item__start, .mdc-list-item__content, .mdc-list-item__end { opacity: 1; } } } } @mixin density($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, density)); } @else { $density-scale: inspection.get-theme-density($theme); @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-list.$prefix, tokens-mdc-list.get-density-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-list.$prefix, tokens-mat-list.get-density-tokens($theme) ); } .mdc-list-item__start, .mdc-list-item__end { @include token-utils.create-token-values( tokens-mdc-radio.$prefix, tokens-mdc-radio.get-density-tokens($theme) ); } // TODO(mmalerba): This is added to maintain the same style MDC used prior to the token-based // API, to avoid screenshot diffs. We should remove it in favor of following MDC's current // style, or add custom tokens for it. .mat-mdc-list-item { &.mdc-list-item--with-leading-avatar, &.mdc-list-item--with-leading-checkbox, &.mdc-list-item--with-leading-icon { &.mdc-list-item--with-one-line { height: map.get( ( 0: 56px, -1: 52px, -2: 48px, -3: 44px, -4: 40px, -5: 40px, ), $density-scale ); } &.mdc-list-item--with-two-lines { height: map.get( ( 0: 72px, -1: 68px, -2: 64px, -3: 60px, -4: 56px, -5: 56px, ), $density-scale ); } } } } } @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-mdc-list.$prefix, tokens-mdc-list.get-typography-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-list.$prefix, tokens-mat-list.get-typography-tokens($theme) ); } // MDC does not have tokens for the subheader. // TODO(mmalerba): Discuss with MDC about adding them, or create custom tokens. .mdc-list-group__subheader { font: inspection.get-theme-typography($theme, subtitle-1, font); letter-spacing: inspection.get-theme-typography($theme, subtitle-1, letter-spacing); } } } /// Defines the tokens that will be available in the `overrides` mixin and for docs extraction. @function _define-overrides() { @return ( ( namespace: tokens-mat-list.$prefix, tokens: tokens-mat-list.get-token-slots(), ), ( namespace: tokens-mdc-list.$prefix, tokens: tokens-mdc-list.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-list') { @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' ); $mdc-list-tokens: token-utils.get-tokens-for($tokens, tokens-mdc-list.$prefix); $mat-list-tokens: token-utils.get-tokens-for($tokens, tokens-mat-list.$prefix); @include token-utils.create-token-values(tokens-mdc-list.$prefix, $mdc-list-tokens); @include token-utils.create-token-values(tokens-mat-list.$prefix, $mat-list-tokens); }
{ "end_byte": 7819, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/_list-theme.scss" }
components/src/material/list/list.scss_0_7205
@use '../core/style/layout-common'; @use '../core/tokens/m2/mat/list' as tokens-mat-list; @use '../core/tokens/m2/mdc/list' as tokens-mdc-list; @use '../core/tokens/token-utils'; @use './list-item-hcm-indicator'; @use './list-inherited-structure'; @include list-inherited-structure.private-list-inherited-structural-styles; // Add additional slots for the MDC list tokens, needed in Angular Material. @include token-utils.use-tokens(tokens-mdc-list.$prefix, tokens-mdc-list.get-token-slots()) { // MDC allows focus and hover colors to take precedence over disabled color. We add the disabled // color here with higher specificity so that the disabled color takes precedence. // TODO(mmalerba): Dicuss with MDC whether to change this in their code. .mdc-list-item.mdc-list-item--disabled .mdc-list-item__primary-text { @include token-utils.create-token-slot(color, list-item-disabled-label-text-color); } // We don't use MDC's state layer since it's tied in with their ripple. Instead we emit slots // for our own state layer. // TODO(mmalerba): Consider using MDC's ripple & state layer. .mdc-list-item:hover::before { @include token-utils.create-token-slot(background-color, list-item-hover-state-layer-color); @include token-utils.create-token-slot(opacity, list-item-hover-state-layer-opacity); } .mdc-list-item.mdc-list-item--disabled::before { @include token-utils.create-token-slot(background-color, list-item-disabled-state-layer-color); @include token-utils.create-token-slot(opacity, list-item-disabled-state-layer-opacity); } .mdc-list-item:focus::before { @include token-utils.create-token-slot(background-color, list-item-focus-state-layer-color); @include token-utils.create-token-slot(opacity, list-item-focus-state-layer-opacity); } // Apply the disabled opacity to the checkbox/radio indicators. // TODO(mmalerba): We should probably stop doing this and allow the checkbox/radio to decide // what their disabled state looks like. This is done for now to avoid screenshot diffs. .mdc-list-item--disabled { .mdc-radio, .mdc-checkbox { @include token-utils.create-token-slot(opacity, list-item-disabled-label-text-opacity); } } // In Angular Material we put the avatar class directly on the .mdc-list-item__start element, // rather than nested inside it, so we need to emit avatar slots ourselves. // TODO(mmalerba): We should try to change MDC's recommended DOM or change ours to match their // recommendation. .mdc-list-item--with-leading-avatar .mat-mdc-list-item-avatar { @include token-utils.create-token-slot(border-radius, list-item-leading-avatar-shape); @include token-utils.create-token-slot(background-color, list-item-leading-avatar-color); } // Set font-size of leading icon to same value as its width and height. Ensure icon scales to // "list-item-leading-icon-size" token. In Angular Material, the icon is on the same element as // ".mdc-list-item__start", rather than a child of ".mdc-list-item__start". .mat-mdc-list-item-icon { @include token-utils.create-token-slot(font-size, list-item-leading-icon-size); } } a.mdc-list-item--activated { // Improve accessibility for Window High Contrast Mode (HCM) by adding an idicator on active // links. @include list-item-hcm-indicator.private-high-contrast-list-item-indicator(); } // MDC expects the list element to be a `<ul>`, since we use `<mat-list>` instead we need to // explicitly set `display: block` .mat-mdc-list-base { display: block; // MDC sets `pointer-events: none` on these elements, // even though we allowed interactive content in them. .mdc-list-item__start, .mdc-list-item__end, .mdc-list-item__content { pointer-events: auto; } } .mat-mdc-list-item, .mat-mdc-list-option { // MDC expects that the list items are always `<li>`, since we actually use `<button>` in some // cases, we need to make sure it expands to fill the available width. width: 100%; box-sizing: border-box; -webkit-tap-highlight-color: transparent; &:not(.mat-mdc-list-item-interactive) { cursor: default; } // MDC doesn't have list dividers, so we use mat-divider and style appropriately. // TODO(devversion): check if we can use the MDC dividers. .mat-divider-inset { position: absolute; left: 0; right: 0; bottom: 0; } .mat-mdc-list-item-avatar ~ .mat-divider-inset { margin-left: 72px; [dir='rtl'] & { margin-right: 72px; } } } // MDC's hover and focus state styles are included with their ripple which we don't use. // Instead we add the focus, hover and selected styles ourselves using this pseudo-element .mat-mdc-list-item-interactive::before { @include layout-common.fill(); content: ''; opacity: 0; pointer-events: none; // This comes up in some internal implementations. border-radius: inherit; } // The MDC-based list items already use the `::before` pseudo element for the standard // focus/selected/hover state. Hence, we need to have a separate list-item spanning // element that can be used for strong focus indicators. .mat-mdc-list-item { > .mat-focus-indicator { @include layout-common.fill(); pointer-events: none; } // For list items, render the focus indicator when the parent // listem item is focused. &:focus > .mat-focus-indicator::before { content: ''; } } .mat-mdc-list-item.mdc-list-item--with-three-lines { .mat-mdc-list-item-line.mdc-list-item__secondary-text { white-space: nowrap; line-height: normal; } // Unscoped content can wrap if the list item has acquired three lines. MDC implements // this functionality for secondary text but there is no proper text ellipsis when // text overflows the third line. These styles ensure the overflow is handled properly. // TODO: Move this to the MDC list once it drops IE11 support. .mat-mdc-list-item-unscoped-content.mdc-list-item__secondary-text { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; } } // MDC doesn't account for button being used as a list item. We override some of // the default button styles here so that they look right when used as a list // item. mat-action-list button { background: none; color: inherit; border: none; font: inherit; outline: inherit; -webkit-tap-highlight-color: transparent; text-align: start; &::-moz-focus-inner { border: 0; } } @include token-utils.use-tokens(tokens-mat-list.$prefix, tokens-mat-list.get-token-slots()) { .mdc-list-item--with-leading-icon .mdc-list-item__start { @include token-utils.create-token-slot(margin-inline-start, list-item-leading-icon-start-space); @include token-utils.create-token-slot(margin-inline-end, list-item-leading-icon-end-space); } .mat-mdc-nav-list .mat-mdc-list-item { @include token-utils.create-token-slot(border-radius, active-indicator-shape); @include token-utils.create-token-slot( --mat-focus-indicator-border-radius, active-indicator-shape ); &.mdc-list-item--activated { @include token-utils.create-token-slot(background-color, active-indicator-color); } } }
{ "end_byte": 7205, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/list.scss" }
components/src/material/list/selection-list.ts_0_2396
/** * @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 {FocusKeyManager} from '@angular/cdk/a11y'; import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; import {SelectionModel} from '@angular/cdk/collections'; import {A, ENTER, SPACE, hasModifierKey} from '@angular/cdk/keycodes'; import {_getFocusedElementPierceShadowDom} from '@angular/cdk/platform'; import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, ElementRef, EventEmitter, Input, NgZone, OnChanges, OnDestroy, Output, QueryList, SimpleChanges, ViewEncapsulation, forwardRef, inject, } from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import {ThemePalette} from '@angular/material/core'; import {Subject} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {MatListBase} from './list-base'; import {MatListOption, SELECTION_LIST, SelectionList} from './list-option'; export const MAT_SELECTION_LIST_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MatSelectionList), multi: true, }; /** Change event that is being fired whenever the selected state of an option changes. */ export class MatSelectionListChange { constructor( /** Reference to the selection list that emitted the event. */ public source: MatSelectionList, /** Reference to the options that have been changed. */ public options: MatListOption[], ) {} } @Component({ selector: 'mat-selection-list', exportAs: 'matSelectionList', host: { 'class': 'mat-mdc-selection-list mat-mdc-list-base mdc-list', 'role': 'listbox', '[attr.aria-multiselectable]': 'multiple', '(keydown)': '_handleKeydown($event)', }, template: '<ng-content></ng-content>', styleUrl: 'list.css', encapsulation: ViewEncapsulation.None, providers: [ MAT_SELECTION_LIST_VALUE_ACCESSOR, {provide: MatListBase, useExisting: MatSelectionList}, {provide: SELECTION_LIST, useExisting: MatSelectionList}, ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class MatSelectionList extends MatListBase implements SelectionList, ControlValueAccessor, AfterViewInit, OnChanges, OnDestroy
{ "end_byte": 2396, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/selection-list.ts" }
components/src/material/list/selection-list.ts_2397_11128
{ _element = inject<ElementRef<HTMLElement>>(ElementRef); private _ngZone = inject(NgZone); private _initialized = false; private _keyManager: FocusKeyManager<MatListOption>; /** Emits when the list has been destroyed. */ private _destroyed = new Subject<void>(); /** Whether the list has been destroyed. */ private _isDestroyed: boolean; /** View to model callback that should be called whenever the selected options change. */ private _onChange: (value: any) => void = (_: any) => {}; @ContentChildren(MatListOption, {descendants: true}) _items: QueryList<MatListOption>; /** Emits a change event whenever the selected state of an option changes. */ @Output() readonly selectionChange: EventEmitter<MatSelectionListChange> = new EventEmitter<MatSelectionListChange>(); /** * Theme color of the selection list. This sets the checkbox color for all * list options. This API is supported in M2 themes only, it has no effect in * M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants. */ @Input() color: ThemePalette = 'accent'; /** * Function used for comparing an option against the selected value when determining which * options should appear as selected. The first argument is the value of an options. The second * one is a value from the selected value. A boolean must be returned. */ @Input() compareWith: (o1: any, o2: any) => boolean = (a1, a2) => a1 === a2; /** Whether selection is limited to one or multiple items (default multiple). */ @Input() get multiple(): boolean { return this._multiple; } set multiple(value: BooleanInput) { const newValue = coerceBooleanProperty(value); if (newValue !== this._multiple) { if ((typeof ngDevMode === 'undefined' || ngDevMode) && this._initialized) { throw new Error( 'Cannot change `multiple` mode of mat-selection-list after initialization.', ); } this._multiple = newValue; this.selectedOptions = new SelectionModel(this._multiple, this.selectedOptions.selected); } } private _multiple = true; /** Whether radio indicator for all list items is hidden. */ @Input() get hideSingleSelectionIndicator(): boolean { return this._hideSingleSelectionIndicator; } set hideSingleSelectionIndicator(value: BooleanInput) { this._hideSingleSelectionIndicator = coerceBooleanProperty(value); } private _hideSingleSelectionIndicator: boolean = this._defaultOptions?.hideSingleSelectionIndicator ?? false; /** The currently selected options. */ selectedOptions = new SelectionModel<MatListOption>(this._multiple); /** Keeps track of the currently-selected value. */ _value: string[] | null; /** View to model callback that should be called if the list or its options lost focus. */ _onTouched: () => void = () => {}; private readonly _changeDetectorRef = inject(ChangeDetectorRef); constructor(...args: unknown[]); constructor() { super(); this._isNonInteractive = false; } ngAfterViewInit() { // Mark the selection list as initialized so that the `multiple` // binding can no longer be changed. this._initialized = true; this._setupRovingTabindex(); // These events are bound outside the zone, because they don't change // any change-detected properties and they can trigger timeouts. this._ngZone.runOutsideAngular(() => { this._element.nativeElement.addEventListener('focusin', this._handleFocusin); this._element.nativeElement.addEventListener('focusout', this._handleFocusout); }); if (this._value) { this._setOptionsFromValues(this._value); } this._watchForSelectionChange(); } ngOnChanges(changes: SimpleChanges) { const disabledChanges = changes['disabled']; const disableRippleChanges = changes['disableRipple']; const hideSingleSelectionIndicatorChanges = changes['hideSingleSelectionIndicator']; if ( (disableRippleChanges && !disableRippleChanges.firstChange) || (disabledChanges && !disabledChanges.firstChange) || (hideSingleSelectionIndicatorChanges && !hideSingleSelectionIndicatorChanges.firstChange) ) { this._markOptionsForCheck(); } } ngOnDestroy() { this._keyManager?.destroy(); this._element.nativeElement.removeEventListener('focusin', this._handleFocusin); this._element.nativeElement.removeEventListener('focusout', this._handleFocusout); this._destroyed.next(); this._destroyed.complete(); this._isDestroyed = true; } /** Focuses the selection list. */ focus(options?: FocusOptions) { this._element.nativeElement.focus(options); } /** Selects all of the options. Returns the options that changed as a result. */ selectAll(): MatListOption[] { return this._setAllOptionsSelected(true); } /** Deselects all of the options. Returns the options that changed as a result. */ deselectAll(): MatListOption[] { return this._setAllOptionsSelected(false); } /** Reports a value change to the ControlValueAccessor */ _reportValueChange() { // Stop reporting value changes after the list has been destroyed. This avoids // cases where the list might wrongly reset its value once it is removed, but // the form control is still live. if (this.options && !this._isDestroyed) { const value = this._getSelectedOptionValues(); this._onChange(value); this._value = value; } } /** Emits a change event if the selected state of an option changed. */ _emitChangeEvent(options: MatListOption[]) { this.selectionChange.emit(new MatSelectionListChange(this, options)); } /** Implemented as part of ControlValueAccessor. */ writeValue(values: string[]): void { this._value = values; if (this.options) { this._setOptionsFromValues(values || []); } } /** Implemented as a part of ControlValueAccessor. */ setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; this._changeDetectorRef.markForCheck(); } /** * Whether the *entire* selection list is disabled. When true, each list item is also disabled * and each list item is removed from the tab order (has tabindex="-1"). */ @Input() override get disabled(): boolean { return this._selectionListDisabled; } override set disabled(value: BooleanInput) { // Update the disabled state of this list. Write to `this._selectionListDisabled` instead of // `super.disabled`. That is to avoid closure compiler compatibility issues with assigning to // a super property. this._selectionListDisabled = coerceBooleanProperty(value); if (this._selectionListDisabled) { this._keyManager?.setActiveItem(-1); } } private _selectionListDisabled = false; /** Implemented as part of ControlValueAccessor. */ registerOnChange(fn: (value: any) => void): void { this._onChange = fn; } /** Implemented as part of ControlValueAccessor. */ registerOnTouched(fn: () => void): void { this._onTouched = fn; } /** Watches for changes in the selected state of the options and updates the list accordingly. */ private _watchForSelectionChange() { this.selectedOptions.changed.pipe(takeUntil(this._destroyed)).subscribe(event => { // Sync external changes to the model back to the options. for (let item of event.added) { item.selected = true; } for (let item of event.removed) { item.selected = false; } if (!this._containsFocus()) { this._resetActiveOption(); } }); } /** Sets the selected options based on the specified values. */ private _setOptionsFromValues(values: string[]) { this.options.forEach(option => option._setSelected(false)); values.forEach(value => { const correspondingOption = this.options.find(option => { // Skip options that are already in the model. This allows us to handle cases // where the same primitive value is selected multiple times. return option.selected ? false : this.compareWith(option.value, value); }); if (correspondingOption) { correspondingOption._setSelected(true); } }); } /** Returns the values of the selected options. */ private _getSelectedOptionValues(): string[] { return this.options.filter(option => option.selected).map(option => option.value); } /** Marks all the options to be checked in the next change detection run. */ private _markOptionsForCheck() { if (this.options) { this.options.forEach(option => option._markForCheck()); } }
{ "end_byte": 11128, "start_byte": 2397, "url": "https://github.com/angular/components/blob/main/src/material/list/selection-list.ts" }
components/src/material/list/selection-list.ts_11132_16067
/** * Sets the selected state on all of the options * and emits an event if anything changed. */ private _setAllOptionsSelected(isSelected: boolean, skipDisabled?: boolean): MatListOption[] { // Keep track of whether anything changed, because we only want to // emit the changed event when something actually changed. const changedOptions: MatListOption[] = []; this.options.forEach(option => { if ((!skipDisabled || !option.disabled) && option._setSelected(isSelected)) { changedOptions.push(option); } }); if (changedOptions.length) { this._reportValueChange(); } return changedOptions; } // Note: This getter exists for backwards compatibility. The `_items` query list // cannot be named `options` as it will be picked up by the interactive list base. /** The option components contained within this selection-list. */ get options(): QueryList<MatListOption> { return this._items; } /** Handles keydown events within the list. */ _handleKeydown(event: KeyboardEvent) { const activeItem = this._keyManager.activeItem; if ( (event.keyCode === ENTER || event.keyCode === SPACE) && !this._keyManager.isTyping() && activeItem && !activeItem.disabled ) { event.preventDefault(); activeItem._toggleOnInteraction(); } else if ( event.keyCode === A && this.multiple && !this._keyManager.isTyping() && hasModifierKey(event, 'ctrlKey') ) { const shouldSelect = this.options.some(option => !option.disabled && !option.selected); event.preventDefault(); this._emitChangeEvent(this._setAllOptionsSelected(shouldSelect, true)); } else { this._keyManager.onKeydown(event); } } /** Handles focusout events within the list. */ private _handleFocusout = () => { // Focus takes a while to update so we have to wrap our call in a timeout. setTimeout(() => { if (!this._containsFocus()) { this._resetActiveOption(); } }); }; /** Handles focusin events within the list. */ private _handleFocusin = (event: FocusEvent) => { if (this.disabled) { return; } const activeIndex = this._items .toArray() .findIndex(item => item._elementRef.nativeElement.contains(event.target as HTMLElement)); if (activeIndex > -1) { this._setActiveOption(activeIndex); } else { this._resetActiveOption(); } }; /** * Sets up the logic for maintaining the roving tabindex. * * `skipPredicate` determines if key manager should avoid putting a given list item in the tab * index. Allow disabled list items to receive focus 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..." */ private _setupRovingTabindex() { this._keyManager = new FocusKeyManager(this._items) .withHomeAndEnd() .withTypeAhead() .withWrap() .skipPredicate(() => this.disabled); // Set the initial focus. this._resetActiveOption(); // Move the tabindex to the currently-focused list item. this._keyManager.change.subscribe(activeItemIndex => this._setActiveOption(activeItemIndex)); // If the active item is removed from the list, reset back to the first one. this._items.changes.pipe(takeUntil(this._destroyed)).subscribe(() => { const activeItem = this._keyManager.activeItem; if (!activeItem || this._items.toArray().indexOf(activeItem) === -1) { this._resetActiveOption(); } }); } /** * Sets an option as active. * @param index Index of the active option. If set to -1, no option will be active. */ private _setActiveOption(index: number) { this._items.forEach((item, itemIndex) => item._setTabindex(itemIndex === index ? 0 : -1)); this._keyManager.updateActiveItem(index); } /** * Resets the active option. When the list is disabled, remove all options from to the tab order. * Otherwise, focus the first selected option. */ private _resetActiveOption() { if (this.disabled) { this._setActiveOption(-1); return; } const activeItem = this._items.find(item => item.selected && !item.disabled) || this._items.first; this._setActiveOption(activeItem ? this._items.toArray().indexOf(activeItem) : -1); } /** Returns whether the focus is currently within the list. */ private _containsFocus() { const activeElement = _getFocusedElementPierceShadowDom(); return activeElement && this._element.nativeElement.contains(activeElement); } }
{ "end_byte": 16067, "start_byte": 11132, "url": "https://github.com/angular/components/blob/main/src/material/list/selection-list.ts" }
components/src/material/list/list.md_0_8345
`<mat-list>` is a container component that wraps and formats a series of `<mat-list-item>`. As the base list component, it provides Material Design styling, but no behavior of its own. <!-- example(list-overview) --> List items can be constructed in two ways depending the content they need to show: ### Simple lists If a list item needs to show a single line of textual information, the text can be inserted directly into the `<mat-list-item>` element. ```html <mat-list> <mat-list-item>Pepper</mat-list-item> <mat-list-item>Salt</mat-list-item> <mat-list-item>Paprika</mat-list-item> </mat-list> ``` ### Multi-line lists List items that have more than one line of text have to use the `matListItemTitle` directive to indicate their title text for accessibility purposes, in addition to the `matListItemLine` directive for each subsequent line of text. ```html <mat-list> <mat-list-item> <span matListItemTitle>Pepper</span> <span matListItemLine>Produced by a plant</span> </mat-list-item> <mat-list-item> <span matListItemTitle>Salt</span> <span matListItemLine>Extracted from sea water</span> </mat-list-item> <mat-list-item> <span matListItemTitle>Paprika</span> <span matListItemLine>Produced by dried and ground red peppers</span> </mat-list-item> </mat-list> ``` To activate text wrapping, the `lines` input has to be set on the `<mat-list-item>` indicating the number of lines of text. The following directives can be used to style the content of a list item: | Directive | Description | |---------------------|----------------------------------------------------------------------------| | `matListItemTitle` | Indicates the title of the list item. Required for multi-line list items. | | `matListItemLine` | Wraps a line of text within a list item. | | `matListItemIcon` | Icon typically placed at the beginning of a list item. | | `matListItemAvatar` | Image typically placed at the beginning of a list item. | | `matListItemMeta` | Inserts content in the meta section at the end of a list item. | ### Navigation lists Use `mat-nav-list` tags for navigation lists (i.e. lists that have anchor tags). Simple navigation lists can use the `mat-list-item` attribute on anchor tag elements directly: ```html <mat-nav-list> @for (link of list; track link) { <a mat-list-item href="..." [activated]="link.isActive">{{ link }}</a> } </mat-nav-list> ``` For more complex navigation lists (e.g. with more than one target per item), wrap the anchor element in an `<mat-list-item>`. ```html <mat-nav-list> @for (link of links; track link) { <mat-list-item [activated]="link.isActive"> <a matListItemTitle href="...">{{ link }}</a> <button mat-icon-button (click)="showInfo(link)" matListItemMeta> <mat-icon>info</mat-icon> </button> </mat-list-item> } </mat-nav-list> ``` ### Action lists Use the `<mat-action-list>` element when each item in the list performs some _action_. Each item in an action list is a `<button>` element. Simple action lists can use the `mat-list-item` attribute on button tag elements directly: ```html <mat-action-list> <button mat-list-item (click)="save()">Save</button> <button mat-list-item (click)="undo()">Undo</button> </mat-action-list> ``` ### Selection lists A selection list provides an interface for selecting values, where each list item is an option. <!-- example(list-selection) --> The options within a selection-list should not contain further interactive controls, such as buttons and anchors. ### Multi-line lists For lists that require multiple lines per item, annotate each line with an `matListItemLine` attribute. Whichever heading tag is appropriate for your DOM hierarchy should be used (not necessarily `<h3>` as shown in the example). ```html <!-- two line list --> <mat-list> @for (message of messages; track message) { <mat-list-item> <h3 matListItemTitle>{{message.from}}</h3> <p matListItemLine> <span>{{message.subject}}</span> <span class="demo-2"> -- {{message.content}}</span> </p> </mat-list-item> } </mat-list> <!-- three line list --> <mat-list> @for (message of messages; track message) { <mat-list-item> <h3 matListItemTitle>{{message.from}}</h3> <p matListItemLine>{{message.subject}}</p> <p matListItemLine class="demo-2">{{message.content}}</p> </mat-list-item> } </mat-list> ``` ### Lists with icons To add an icon to your list item, use the `matListItemIcon` attribute. ```html <mat-list> @for (message of messages; track message) { <mat-list-item> <mat-icon matListItemIcon>folder</mat-icon> <h3 matListItemTitle>{{message.from}}</h3> <p matListItemLine> <span>{{message.subject}}</span> <span class="demo-2"> -- {{message.content}}</span> </p> </mat-list-item> } </mat-list> ``` ### Lists with avatars To include an avatar image, add an image tag with an `matListItemAvatar` attribute. ```html <mat-list> @for (message of messages; track message) { <mat-list-item> <img matListItemAvatar src="..." alt="..."> <h3 matListItemTitle>{{message.from}}</h3> <p matListItemLine> <span>{{message.subject}}</span> <span class="demo-2"> -- {{message.content}}</span> </p> </mat-list-item> } </mat-list> ``` ### Lists with multiple sections Subheaders can be added to a list by annotating a heading tag with an `matSubheader` attribute. To add a divider, use `<mat-divider>`. ```html <mat-list> <h3 matSubheader>Folders</h3> @for (folder of folders; track folder) { <mat-list-item> <mat-icon matListIcon>folder</mat-icon> <h4 matListItemTitle>{{folder.name}}</h4> <p matListItemLine class="demo-2"> {{folder.updated}} </p> </mat-list-item> } <mat-divider></mat-divider> <h3 matSubheader>Notes</h3> @for (note of notes; track note) { <mat-list-item> <mat-icon matListIcon>note</mat-icon> <h4 matListItemTitle>{{note.name}}</h4> <p matListItemLine class="demo-2"> {{note.updated}} </p> </mat-list-item> } </mat-list> ``` ### Accessibility Angular Material offers multiple varieties of list so that you can choose the type that best applies to your use-case. #### Navigation You should use `MatNavList` when every item in the list is an anchor that navigate to another URL. The root `<mat-nav-list>` element sets `role="navigation"` and should contain only anchor elements with the `mat-list-item` attribute. You should not nest any interactive elements inside these anchors, including buttons and checkboxes. Always provide an accessible label for the `<mat-nav-list>` element via `aria-label` or `aria-labelledby`. #### Selection You should use `MatSelectionList` and `MatListOption` for lists that allow the user to select one or more values. This list variant uses the `role="listbox"` interaction pattern, handling all associated keyboard input and focus management. You should not nest any interactive elements inside these options, including buttons and anchors. Always provide an accessible label for the `<mat-selection-list>` element via `aria-label` or `aria-labelledby` that describes the selection being made. By default, `MatSelectionList` displays radio or checkmark indicators to identify selected items. While you can hide the radio indicator for single-selection via `hideSingleSelectionIndicator`, this makes the component less accessible by making it harder or impossible for users to visually identify selected items. #### Custom scenarios By default, the list assumes that it will be used in a purely decorative fashion and thus it sets no roles, ARIA attributes, or keyboard shortcuts. This is equivalent to having a sequence of `<div>` elements on the page. Any interactive content within the list should be given an appropriate accessibility treatment based on the specific workflow of your application. If the list is used to present a list of non-interactive content items, then the list element should be given `role="list"` and each list item should be given `role="listitem"`.
{ "end_byte": 8345, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/list.md" }
components/src/material/list/README.md_0_95
Please see the official documentation at https://material.angular.io/components/component/list
{ "end_byte": 95, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/README.md" }
components/src/material/list/list-item-sections.ts_0_3673
/** * @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'; import {LIST_OPTION, ListOption} from './list-option-types'; /** * Directive capturing the title of a list item. A list item usually consists of a * title and optional secondary or tertiary lines. * * Text content for the title never wraps. There can only be a single title per list item. */ @Directive({ selector: '[matListItemTitle]', host: {'class': 'mat-mdc-list-item-title mdc-list-item__primary-text'}, }) export class MatListItemTitle { _elementRef = inject<ElementRef<HTMLElement>>(ElementRef); constructor(...args: unknown[]); constructor() {} } /** * Directive capturing a line in a list item. A list item usually consists of a * title and optional secondary or tertiary lines. * * Text content inside a line never wraps. There can be at maximum two lines per list item. */ @Directive({ selector: '[matListItemLine]', host: {'class': 'mat-mdc-list-item-line mdc-list-item__secondary-text'}, }) export class MatListItemLine { _elementRef = inject<ElementRef<HTMLElement>>(ElementRef); constructor(...args: unknown[]); constructor() {} } /** * Directive matching an optional meta section for list items. * * List items can reserve space at the end of an item to display a control, * button or additional text content. */ @Directive({ selector: '[matListItemMeta]', host: {'class': 'mat-mdc-list-item-meta mdc-list-item__end'}, }) export class MatListItemMeta {} /** * @docs-private * * MDC uses the very intuitively named classes `.mdc-list-item__start` and `.mat-list-item__end` to * position content such as icons or checkboxes/radios that comes either before or after the text * content respectively. This directive detects the placement of the checkbox/radio and applies the * correct MDC class to position the icon/avatar on the opposite side. */ @Directive({ host: { // MDC uses intuitively named classes `.mdc-list-item__start` and `.mat-list-item__end` to // position content such as icons or checkboxes/radios that comes either before or after the // text content respectively. This directive detects the placement of the checkbox/radio and // applies the correct MDC class to position the icon/avatar on the opposite side. '[class.mdc-list-item__start]': '_isAlignedAtStart()', '[class.mdc-list-item__end]': '!_isAlignedAtStart()', }, }) export class _MatListItemGraphicBase { _listOption = inject<ListOption>(LIST_OPTION, {optional: true}); constructor(...args: unknown[]); constructor() {} _isAlignedAtStart() { // By default, in all list items the graphic is aligned at start. In list options, // the graphic is only aligned at start if the checkbox/radio is at the end. return !this._listOption || this._listOption?._getTogglePosition() === 'after'; } } /** * Directive matching an optional avatar within a list item. * * List items can reserve space at the beginning of an item to display an avatar. */ @Directive({ selector: '[matListItemAvatar]', host: {'class': 'mat-mdc-list-item-avatar'}, }) export class MatListItemAvatar extends _MatListItemGraphicBase {} /** * Directive matching an optional icon within a list item. * * List items can reserve space at the beginning of an item to display an icon. */ @Directive({ selector: '[matListItemIcon]', host: {'class': 'mat-mdc-list-item-icon'}, }) export class MatListItemIcon extends _MatListItemGraphicBase {}
{ "end_byte": 3673, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/list-item-sections.ts" }
components/src/material/list/tokens.ts_0_662
/** * @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 {InjectionToken} from '@angular/core'; /** Object that can be used to configure the default options for the list module. */ export interface MatListConfig { /** Wheter icon indicators should be hidden for single-selection. */ hideSingleSelectionIndicator?: boolean; } /** Injection token that can be used to provide the default options for the list module. */ export const MAT_LIST_CONFIG = new InjectionToken<MatListConfig>('MAT_LIST_CONFIG');
{ "end_byte": 662, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/tokens.ts" }
components/src/material/list/_list-inherited-structure.scss_0_7711
@use '../core/style/vendor-prefixes'; @use '../core/tokens/m2/mdc/list' as tokens-mdc-list; @use '../core/tokens/token-utils'; // Includes the structural styles for the list that were inherited from MDC. @mixin private-list-inherited-structural-styles { $tokens: (tokens-mdc-list.$prefix, tokens-mdc-list.get-token-slots()); .mdc-list { margin: 0; padding: 8px 0; list-style-type: none; &:focus { outline: none; } } .mdc-list-item { display: flex; position: relative; justify-content: flex-start; overflow: hidden; padding: 0; align-items: stretch; cursor: pointer; padding-left: 16px; padding-right: 16px; @include token-utils.use-tokens($tokens...) { @include token-utils.create-token-slot(background-color, list-item-container-color); @include token-utils.create-token-slot(border-radius, list-item-container-shape); &.mdc-list-item--selected { @include token-utils.create-token-slot(background-color, list-item-selected-container-color); } } &:focus { outline: 0; } &.mdc-list-item--disabled { cursor: auto; } &.mdc-list-item--with-one-line { @include token-utils.use-tokens($tokens...) { @include token-utils.create-token-slot(height, list-item-one-line-container-height); } .mdc-list-item__start { align-self: center; margin-top: 0; } .mdc-list-item__end { align-self: center; margin-top: 0; } } &.mdc-list-item--with-two-lines { @include token-utils.use-tokens($tokens...) { @include token-utils.create-token-slot(height, list-item-two-line-container-height); } .mdc-list-item__start { align-self: flex-start; margin-top: 16px; } .mdc-list-item__end { align-self: center; margin-top: 0; } } &.mdc-list-item--with-three-lines { @include token-utils.use-tokens($tokens...) { @include token-utils.create-token-slot(height, list-item-three-line-container-height); } .mdc-list-item__start { align-self: flex-start; margin-top: 16px; } .mdc-list-item__end { align-self: flex-start; margin-top: 16px; } } // Not used in Material, but some internal tests seem to depend on it. &.mdc-list-item--selected::before, &.mdc-list-item--selected:focus::before, &:not(.mdc-list-item--selected):focus::before { position: absolute; box-sizing: border-box; width: 100%; height: 100%; top: 0; left: 0; content: ''; pointer-events: none; } } a.mdc-list-item { color: inherit; text-decoration: none; } .mdc-list-item__start { fill: currentColor; flex-shrink: 0; pointer-events: none; @include token-utils.use-tokens($tokens...) { .mdc-list-item--with-leading-icon & { @include token-utils.create-token-slot(color, list-item-leading-icon-color); @include token-utils.create-token-slot(width, list-item-leading-icon-size); @include token-utils.create-token-slot(height, list-item-leading-icon-size); margin-left: 16px; margin-right: 32px; } [dir='rtl'] .mdc-list-item--with-leading-icon & { margin-left: 32px; margin-right: 16px; } .mdc-list-item--with-leading-icon:hover & { @include token-utils.create-token-slot(color, list-item-hover-leading-icon-color); } // This is the same in RTL, but we need the specificity. .mdc-list-item--with-leading-avatar & { @include token-utils.create-token-slot(width, list-item-leading-avatar-size); @include token-utils.create-token-slot(height, list-item-leading-avatar-size); margin-left: 16px; margin-right: 16px; border-radius: 50%; } .mdc-list-item--with-leading-avatar &, [dir='rtl'] .mdc-list-item--with-leading-avatar & { margin-left: 16px; margin-right: 16px; border-radius: 50%; } } } .mdc-list-item__end { flex-shrink: 0; pointer-events: none; @include token-utils.use-tokens($tokens...) { .mdc-list-item--with-trailing-meta & { @include token-utils.create-token-slot(font-family, list-item-trailing-supporting-text-font); @include token-utils.create-token-slot(line-height, list-item-trailing-supporting-text-line-height); @include token-utils.create-token-slot(font-size, list-item-trailing-supporting-text-size); @include token-utils.create-token-slot(font-weight, list-item-trailing-supporting-text-weight); @include token-utils.create-token-slot(letter-spacing, list-item-trailing-supporting-text-tracking); } .mdc-list-item--with-trailing-icon & { @include token-utils.create-token-slot(color, list-item-trailing-icon-color); @include token-utils.create-token-slot(width, list-item-trailing-icon-size); @include token-utils.create-token-slot(height, list-item-trailing-icon-size); } .mdc-list-item--with-trailing-icon:hover & { @include token-utils.create-token-slot(color, list-item-hover-trailing-icon-color); } // For some reason this has an increased specificity just for the `color`. // Keeping it in place for now to reduce the amount of screenshot diffs. .mdc-list-item.mdc-list-item--with-trailing-meta & { @include token-utils.create-token-slot(color, list-item-trailing-supporting-text-color); } .mdc-list-item--selected.mdc-list-item--with-trailing-icon & { @include token-utils.create-token-slot(color, list-item-selected-trailing-icon-color); } } } .mdc-list-item__content { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; align-self: center; flex: 1; pointer-events: none; .mdc-list-item--with-two-lines &, .mdc-list-item--with-three-lines & { align-self: stretch; } } .mdc-list-item__primary-text { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; @include token-utils.use-tokens($tokens...) { @include token-utils.create-token-slot(color, list-item-label-text-color); @include token-utils.create-token-slot(font-family, list-item-label-text-font); @include token-utils.create-token-slot(line-height, list-item-label-text-line-height); @include token-utils.create-token-slot(font-size, list-item-label-text-size); @include token-utils.create-token-slot(font-weight, list-item-label-text-weight); @include token-utils.create-token-slot(letter-spacing, list-item-label-text-tracking); .mdc-list-item:hover & { @include token-utils.create-token-slot(color, list-item-hover-label-text-color); } .mdc-list-item:focus & { @include token-utils.create-token-slot(color, list-item-focus-label-text-color); } } .mdc-list-item--with-two-lines &, .mdc-list-item--with-three-lines & { display: block; margin-top: 0; line-height: normal; margin-bottom: -20px; } .mdc-list-item--with-two-lines &::before, .mdc-list-item--with-three-lines &::before { display: inline-block; width: 0; height: 28px; content: ''; vertical-align: 0; } .mdc-list-item--with-two-lines &::after, .mdc-list-item--with-three-lines &::after { display: inline-block; width: 0; height: 20px; content: ''; vertical-align: -20px; } }
{ "end_byte": 7711, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/_list-inherited-structure.scss" }
components/src/material/list/_list-inherited-structure.scss_7715_13634
.mdc-list-item__secondary-text { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; display: block; margin-top: 0; @include token-utils.use-tokens($tokens...) { @include token-utils.create-token-slot(color, list-item-supporting-text-color); @include token-utils.create-token-slot(font-family, list-item-supporting-text-font); @include token-utils.create-token-slot(line-height, list-item-supporting-text-line-height); @include token-utils.create-token-slot(font-size, list-item-supporting-text-size); @include token-utils.create-token-slot(font-weight, list-item-supporting-text-weight); @include token-utils.create-token-slot(letter-spacing, list-item-supporting-text-tracking); } &::before { display: inline-block; width: 0; height: 20px; content: ''; vertical-align: 0; } .mdc-list-item--with-three-lines & { white-space: normal; line-height: 20px; } .mdc-list-item--with-overline & { white-space: nowrap; line-height: auto; } } .mdc-list-item--with-leading-radio, .mdc-list-item--with-leading-checkbox, .mdc-list-item--with-leading-icon, .mdc-list-item--with-leading-avatar { &.mdc-list-item { padding-left: 0; padding-right: 16px; [dir='rtl'] & { padding-left: 16px; padding-right: 0; } } &.mdc-list-item--with-two-lines { .mdc-list-item__primary-text { display: block; margin-top: 0; line-height: normal; margin-bottom: -20px; // This was used by MDC to set the text baseline. We should figure out a way to // remove it, because it can introduce unnecessary whitespace at the beginning // of the element. &::before { display: inline-block; width: 0; height: 32px; content: ''; vertical-align: 0; } &::after { display: inline-block; width: 0; height: 20px; content: ''; vertical-align: -20px; } } &.mdc-list-item--with-trailing-meta { .mdc-list-item__end { display: block; margin-top: 0; line-height: normal; &::before { display: inline-block; width: 0; height: 32px; content: ''; vertical-align: 0; } } } } } .mdc-list-item--with-trailing-icon { &.mdc-list-item { // This is the same in RTL, but we need the specificity. &, [dir='rtl'] & { padding-left: 0; padding-right: 0; } } .mdc-list-item__end { margin-left: 16px; margin-right: 16px; } } .mdc-list-item--with-trailing-meta { &.mdc-list-item { padding-left: 16px; padding-right: 0; [dir='rtl'] & { padding-left: 0; padding-right: 16px; } } .mdc-list-item__end { @include vendor-prefixes.user-select(none); margin-left: 28px; margin-right: 16px; [dir='rtl'] & { margin-left: 16px; margin-right: 28px; } } &.mdc-list-item--with-three-lines .mdc-list-item__end, &.mdc-list-item--with-two-lines .mdc-list-item__end { display: block; line-height: normal; align-self: flex-start; margin-top: 0; &::before { display: inline-block; width: 0; height: 28px; content: ''; vertical-align: 0; } } } .mdc-list-item--with-leading-radio, .mdc-list-item--with-leading-checkbox { .mdc-list-item__start { margin-left: 8px; margin-right: 24px; [dir='rtl'] & { margin-left: 24px; margin-right: 8px; } } &.mdc-list-item--with-two-lines { .mdc-list-item__start { align-self: flex-start; margin-top: 8px; } } } .mdc-list-item--with-trailing-radio, .mdc-list-item--with-trailing-checkbox { &.mdc-list-item { padding-left: 16px; padding-right: 0; [dir='rtl'] & { padding-left: 0; padding-right: 16px; } } &.mdc-list-item--with-leading-icon, &.mdc-list-item--with-leading-avatar { padding-left: 0; [dir='rtl'] & { padding-right: 0; } } .mdc-list-item__end { margin-left: 24px; margin-right: 8px; [dir='rtl'] & { margin-left: 8px; margin-right: 24px; } } &.mdc-list-item--with-three-lines .mdc-list-item__end { align-self: flex-start; margin-top: 8px; } } .mdc-list-group__subheader { margin: 0.75rem 16px; } .mdc-list-item--disabled { .mdc-list-item__start, .mdc-list-item__content, .mdc-list-item__end { opacity: 1; } .mdc-list-item__primary-text, .mdc-list-item__secondary-text { @include token-utils.use-tokens($tokens...) { @include token-utils.create-token-slot(opacity, list-item-disabled-label-text-opacity); } } &.mdc-list-item--with-leading-icon .mdc-list-item__start { @include token-utils.use-tokens($tokens...) { @include token-utils.create-token-slot(color, list-item-disabled-leading-icon-color); @include token-utils.create-token-slot(opacity, list-item-disabled-leading-icon-opacity); } } &.mdc-list-item--with-trailing-icon .mdc-list-item__end { @include token-utils.use-tokens($tokens...) { @include token-utils.create-token-slot(color, list-item-disabled-trailing-icon-color); @include token-utils.create-token-slot(opacity, list-item-disabled-trailing-icon-opacity); } } } .mat-mdc-list-item.mat-mdc-list-item-both-leading-and-trailing { &, [dir='rtl'] & { padding-left: 0; padding-right: 0; } } }
{ "end_byte": 13634, "start_byte": 7715, "url": "https://github.com/angular/components/blob/main/src/material/list/_list-inherited-structure.scss" }
components/src/material/list/subheader.ts_0_686
/** * @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} from '@angular/core'; /** * Directive whose purpose is to add the mat- CSS styling to this selector. * @docs-private */ @Directive({ selector: '[mat-subheader], [matSubheader]', // TODO(mmalerba): MDC's subheader font looks identical to the list item font, figure out why and // make a change in one of the repos to visually distinguish. host: {'class': 'mat-mdc-subheader mdc-list-group__subheader'}, }) export class MatListSubheaderCssMatStyler {}
{ "end_byte": 686, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/subheader.ts" }
components/src/material/list/action-list.ts_0_1269
/** * @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, ViewEncapsulation} from '@angular/core'; import {MatListBase} from './list-base'; @Component({ selector: 'mat-action-list', exportAs: 'matActionList', template: '<ng-content></ng-content>', host: { 'class': 'mat-mdc-action-list mat-mdc-list-base mdc-list', 'role': 'group', }, styleUrl: 'list.css', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, providers: [{provide: MatListBase, useExisting: MatActionList}], }) export class MatActionList extends MatListBase { // An navigation list is considered interactive, but does not extend the interactive list // base class. We do this because as per MDC, items of interactive lists are only reachable // through keyboard shortcuts. We want all items for the navigation list to be reachable // through tab key as we do not intend to provide any special accessibility treatment. The // accessibility treatment depends on how the end-user will interact with it. override _isNonInteractive = false; }
{ "end_byte": 1269, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/action-list.ts" }
components/src/material/list/list-module.ts_0_1571
/** * @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 {MatPseudoCheckboxModule, MatRippleModule, MatCommonModule} from '@angular/material/core'; import {MatDividerModule} from '@angular/material/divider'; import {MatActionList} from './action-list'; import {MatList, MatListItem} from './list'; import {MatListOption} from './list-option'; import {MatListSubheaderCssMatStyler} from './subheader'; import { MatListItemLine, MatListItemTitle, MatListItemMeta, MatListItemAvatar, MatListItemIcon, } from './list-item-sections'; import {MatNavList} from './nav-list'; import {MatSelectionList} from './selection-list'; import {ObserversModule} from '@angular/cdk/observers'; @NgModule({ imports: [ ObserversModule, MatCommonModule, MatRippleModule, MatPseudoCheckboxModule, MatList, MatActionList, MatNavList, MatSelectionList, MatListItem, MatListOption, MatListSubheaderCssMatStyler, MatListItemAvatar, MatListItemIcon, MatListItemLine, MatListItemTitle, MatListItemMeta, ], exports: [ MatList, MatActionList, MatNavList, MatSelectionList, MatListItem, MatListOption, MatListItemAvatar, MatListItemIcon, MatListSubheaderCssMatStyler, MatDividerModule, MatListItemLine, MatListItemTitle, MatListItemMeta, ], }) export class MatListModule {}
{ "end_byte": 1571, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/list-module.ts" }
components/src/material/list/BUILD.bazel_0_2462
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 = "list", srcs = glob( ["**/*.ts"], exclude = [ "**/*.spec.ts", ], ), assets = [ ":list_scss", ":list_option_scss", ] + glob(["**/*.html"]), deps = [ "//src:dev_mode_types", "//src/cdk/coercion", "//src/cdk/collections", "//src/cdk/observers", "//src/cdk/private", "//src/material/core", "//src/material/divider", "@npm//@angular/core", "@npm//@angular/forms", ], ) sass_library( name = "hcm_indicator_scss_lib", srcs = ["_list-item-hcm-indicator.scss"], ) sass_library( name = "inherited_structure_scss_lib", srcs = ["_list-inherited-structure.scss"], deps = [ "//src/cdk:sass_lib", "//src/material/core:core_scss_lib", ], ) sass_library( name = "list_scss_lib", srcs = glob(["**/_*.scss"]), deps = [ ":hcm_indicator_scss_lib", "//src/material/checkbox:checkbox_scss_lib", "//src/material/core:core_scss_lib", "//src/material/radio:radio_scss_lib", ], ) sass_binary( name = "list_scss", src = "list.scss", deps = [ ":hcm_indicator_scss_lib", ":inherited_structure_scss_lib", "//src/material/core:core_scss_lib", ], ) sass_binary( name = "list_option_scss", src = "list-option.scss", deps = [ ":list_scss_lib", "//src/cdk:sass_lib", "//src/material/checkbox:checkbox_scss_lib", "//src/material/core:core_scss_lib", ], ) ng_test_library( name = "list_tests_lib", srcs = glob( ["**/*.spec.ts"], ), deps = [ ":list", "//src/cdk/keycodes", "//src/cdk/testing/private", "//src/cdk/testing/testbed", "//src/material/core", "@npm//@angular/forms", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":list_tests_lib", ], ) markdown_to_html( name = "overview", srcs = [":list.md"], ) extract_tokens( name = "tokens", srcs = [":list_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "end_byte": 2462, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/BUILD.bazel" }
components/src/material/list/list-base.ts_0_2037
/** * @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 {BooleanInput, coerceBooleanProperty, coerceNumberProperty} from '@angular/cdk/coercion'; import {Platform} from '@angular/cdk/platform'; import { AfterViewInit, ContentChildren, Directive, ElementRef, inject, Input, NgZone, OnDestroy, QueryList, ANIMATION_MODULE_TYPE, Injector, } from '@angular/core'; import { _StructuralStylesLoader, MAT_RIPPLE_GLOBAL_OPTIONS, RippleConfig, RippleGlobalOptions, RippleRenderer, RippleTarget, } from '@angular/material/core'; import {_CdkPrivateStyleLoader} from '@angular/cdk/private'; import {Subscription, merge} from 'rxjs'; import { MatListItemLine, MatListItemTitle, MatListItemIcon, MatListItemAvatar, } from './list-item-sections'; import {MAT_LIST_CONFIG} from './tokens'; @Directive({ host: { '[attr.aria-disabled]': 'disabled', }, }) /** @docs-private */ export abstract class MatListBase { _isNonInteractive: boolean = true; /** Whether ripples for all list items is disabled. */ @Input() get disableRipple(): boolean { return this._disableRipple; } set disableRipple(value: BooleanInput) { this._disableRipple = coerceBooleanProperty(value); } private _disableRipple: boolean = false; /** * Whether the entire list is disabled. When disabled, the list itself and each of its list items * are disabled. */ @Input() get disabled(): boolean { return this._disabled; } set disabled(value: BooleanInput) { this._disabled = coerceBooleanProperty(value); } private _disabled = false; protected _defaultOptions = inject(MAT_LIST_CONFIG, {optional: true}); } @Directive({ host: { '[class.mdc-list-item--disabled]': 'disabled', '[attr.aria-disabled]': 'disabled', '[attr.disabled]': '(_isButtonElement && disabled) || null', }, }) /** @docs-private */ export
{ "end_byte": 2037, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/list-base.ts" }
components/src/material/list/list-base.ts_2038_10422
abstract class MatListItemBase implements AfterViewInit, OnDestroy, RippleTarget { _elementRef = inject<ElementRef<HTMLElement>>(ElementRef); protected _ngZone = inject(NgZone); private _listBase = inject(MatListBase, {optional: true}); private _platform = inject(Platform); /** Query list matching list-item line elements. */ abstract _lines: QueryList<MatListItemLine> | undefined; /** Query list matching list-item title elements. */ abstract _titles: QueryList<MatListItemTitle> | undefined; /** * Element reference to the unscoped content in a list item. * * Unscoped content is user-projected text content in a list item that is * not part of an explicit line or title. */ abstract _unscopedContent: ElementRef<HTMLSpanElement> | undefined; /** Host element for the list item. */ _hostElement: HTMLElement; /** indicate whether the host element is a button or not */ _isButtonElement: boolean; /** Whether animations are disabled. */ _noopAnimations: boolean; @ContentChildren(MatListItemAvatar, {descendants: false}) _avatars: QueryList<never>; @ContentChildren(MatListItemIcon, {descendants: false}) _icons: QueryList<never>; /** * The number of lines this list item should reserve space for. If not specified, * lines are inferred based on the projected content. * * Explicitly specifying the number of lines is useful if you want to acquire additional * space and enable the wrapping of text. The unscoped text content of a list item will * always be able to take up the remaining space of the item, unless it represents the title. * * A maximum of three lines is supported as per the Material Design specification. */ @Input() set lines(lines: number | string | null) { this._explicitLines = coerceNumberProperty(lines, null); this._updateItemLines(false); } _explicitLines: number | null = null; /** Whether ripples for list items are disabled. */ @Input() get disableRipple(): boolean { return ( this.disabled || this._disableRipple || this._noopAnimations || !!this._listBase?.disableRipple ); } set disableRipple(value: BooleanInput) { this._disableRipple = coerceBooleanProperty(value); } private _disableRipple: boolean = false; /** Whether the list-item is disabled. */ @Input() get disabled(): boolean { return this._disabled || !!this._listBase?.disabled; } set disabled(value: BooleanInput) { this._disabled = coerceBooleanProperty(value); } private _disabled = false; private _subscriptions = new Subscription(); private _rippleRenderer: RippleRenderer | null = null; /** Whether the list item has unscoped text content. */ _hasUnscopedTextContent: boolean = false; /** * Implemented as part of `RippleTarget`. * @docs-private */ rippleConfig: RippleConfig & RippleGlobalOptions; /** * Implemented as part of `RippleTarget`. * @docs-private */ get rippleDisabled(): boolean { return this.disableRipple || !!this.rippleConfig.disabled; } constructor(...args: unknown[]); constructor() { inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader); const globalRippleOptions = inject<RippleGlobalOptions>(MAT_RIPPLE_GLOBAL_OPTIONS, { optional: true, }); const animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true}); this.rippleConfig = globalRippleOptions || {}; this._hostElement = this._elementRef.nativeElement; this._isButtonElement = this._hostElement.nodeName.toLowerCase() === 'button'; this._noopAnimations = animationMode === 'NoopAnimations'; if (this._listBase && !this._listBase._isNonInteractive) { this._initInteractiveListItem(); } // If no type attribute is specified for a host `<button>` element, set it to `button`. If a // type attribute is already specified, we do nothing. We do this for backwards compatibility. // TODO: Determine if we intend to continue doing this for the MDC-based list. if (this._isButtonElement && !this._hostElement.hasAttribute('type')) { this._hostElement.setAttribute('type', 'button'); } } ngAfterViewInit() { this._monitorProjectedLinesAndTitle(); this._updateItemLines(true); } ngOnDestroy() { this._subscriptions.unsubscribe(); if (this._rippleRenderer !== null) { this._rippleRenderer._removeTriggerEvents(); } } /** Whether the list item has icons or avatars. */ _hasIconOrAvatar() { return !!(this._avatars.length || this._icons.length); } private _initInteractiveListItem() { this._hostElement.classList.add('mat-mdc-list-item-interactive'); this._rippleRenderer = new RippleRenderer( this, this._ngZone, this._hostElement, this._platform, inject(Injector), ); this._rippleRenderer.setupTriggerEvents(this._hostElement); } /** * Subscribes to changes in the projected title and lines. Triggers a * item lines update whenever a change occurs. */ private _monitorProjectedLinesAndTitle() { this._ngZone.runOutsideAngular(() => { this._subscriptions.add( merge(this._lines!.changes, this._titles!.changes).subscribe(() => this._updateItemLines(false), ), ); }); } /** * Updates the lines of the list item. Based on the projected user content and optional * explicit lines setting, the visual appearance of the list item is determined. * * This method should be invoked whenever the projected user content changes, or * when the explicit lines have been updated. * * @param recheckUnscopedContent Whether the projected unscoped content should be re-checked. * The unscoped content is not re-checked for every update as it is a rather expensive check * for content that is expected to not change very often. */ _updateItemLines(recheckUnscopedContent: boolean) { // If the updated is triggered too early before the view and content is initialized, // we just skip the update. After view initialization the update is triggered again. if (!this._lines || !this._titles || !this._unscopedContent) { return; } // Re-check the DOM for unscoped text content if requested. This needs to // happen before any computation or sanity checks run as these rely on the // result of whether there is unscoped text content or not. if (recheckUnscopedContent) { this._checkDomForUnscopedTextContent(); } // Sanity check the list item lines and title in the content. This is a dev-mode only // check that can be dead-code eliminated by Terser in production. if (typeof ngDevMode === 'undefined' || ngDevMode) { sanityCheckListItemContent(this); } const numberOfLines = this._explicitLines ?? this._inferLinesFromContent(); const unscopedContentEl = this._unscopedContent.nativeElement; // Update the list item element to reflect the number of lines. this._hostElement.classList.toggle('mat-mdc-list-item-single-line', numberOfLines <= 1); this._hostElement.classList.toggle('mdc-list-item--with-one-line', numberOfLines <= 1); this._hostElement.classList.toggle('mdc-list-item--with-two-lines', numberOfLines === 2); this._hostElement.classList.toggle('mdc-list-item--with-three-lines', numberOfLines === 3); // If there is no title and the unscoped content is the is the only line, the // unscoped text content will be treated as the title of the list-item. if (this._hasUnscopedTextContent) { const treatAsTitle = this._titles.length === 0 && numberOfLines === 1; unscopedContentEl.classList.toggle('mdc-list-item__primary-text', treatAsTitle); unscopedContentEl.classList.toggle('mdc-list-item__secondary-text', !treatAsTitle); } else { unscopedContentEl.classList.remove('mdc-list-item__primary-text'); unscopedContentEl.classList.remove('mdc-list-item__secondary-text'); } } /** * Infers the number of lines based on the projected user content. This is useful * if no explicit number of lines has been specified on the list item. * * The number of lines is inferred based on whether there is a title, the number of * additional lines (secondary/tertiary). An additional line is acquired if there is * unscoped text content. */
{ "end_byte": 10422, "start_byte": 2038, "url": "https://github.com/angular/components/blob/main/src/material/list/list-base.ts" }
components/src/material/list/list-base.ts_10425_12023
private _inferLinesFromContent() { let numOfLines = this._titles!.length + this._lines!.length; if (this._hasUnscopedTextContent) { numOfLines += 1; } return numOfLines; } /** Checks whether the list item has unscoped text content. */ private _checkDomForUnscopedTextContent() { this._hasUnscopedTextContent = Array.from<ChildNode>( this._unscopedContent!.nativeElement.childNodes, ) .filter(node => node.nodeType !== node.COMMENT_NODE) .some(node => !!(node.textContent && node.textContent.trim())); } } /** * Sanity checks the configuration of the list item with respect to the amount * of lines, whether there is a title, or if there is unscoped text content. * * The checks are extracted into a top-level function that can be dead-code * eliminated by Terser or other optimizers in production mode. */ function sanityCheckListItemContent(item: MatListItemBase) { const numTitles = item._titles!.length; const numLines = item._lines!.length; if (numTitles > 1) { console.warn('A list item cannot have multiple titles.'); } if (numTitles === 0 && numLines > 0) { console.warn('A list item line can only be used if there is a list item title.'); } if ( numTitles === 0 && item._hasUnscopedTextContent && item._explicitLines !== null && item._explicitLines > 1 ) { console.warn('A list item cannot have wrapping content without a title.'); } if (numLines > 2 || (numLines === 2 && item._hasUnscopedTextContent)) { console.warn('A list item can have at maximum three lines.'); } }
{ "end_byte": 12023, "start_byte": 10425, "url": "https://github.com/angular/components/blob/main/src/material/list/list-base.ts" }
components/src/material/list/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/list/index.ts" }
components/src/material/list/list-option.scss_0_2905
@use '../checkbox/checkbox-common'; @use '../radio/radio-common'; @use './list-item-hcm-indicator'; // For compatibility with the non-MDC selection list, we support avatars that are // shown at the end of the list option. This is not supported by the MDC list as the // spec only defines avatars at the beginning of a list item. For selection list options, // we support changing the checkbox position to `before`. This results in the avatar from // the list start being moved to the end. Similar to MDC's `--trailing-icon` class, we // implement a `--trailing-avatar` class that is based on the original `--leading-avatar` // implementation. .mat-mdc-list-option-with-trailing-avatar { &.mdc-list-item, [dir='rtl'] &.mdc-list-item { padding-left: 0; padding-right: 0; } .mdc-list-item__end { margin-left: 16px; margin-right: 16px; width: 40px; height: 40px; } &.mdc-list-item--with-two-lines { $top: 32px; $bottom: 20px; .mdc-list-item__primary-text { display: block; margin-top: 0; line-height: normal; margin-bottom: $bottom * -1; // This was used by MDC to set the text baseline. We should figure out a way to // remove it, because it can introduce unnecessary whitespace at the beginning // of the element. &::before { display: inline-block; width: 0; height: $top; content: ''; vertical-align: 0; } &::after { display: inline-block; width: 0; height: $bottom; content: ''; vertical-align: $bottom * -1; } } } .mdc-list-item__end { border-radius: 50%; } } .mat-mdc-list-option { // We can't use the MDC checkbox here directly, because this checkbox is purely // decorative and including the MDC one will bring in unnecessary JS. @include checkbox-common.checkbox-structure(false); @include checkbox-common.checkbox-noop-animations; @include radio-common.radio-structure(false); @include radio-common.radio-noop-animations; // The internal checkbox/radio is purely decorative, but because it's an `input`, the user can // still focus it by tabbing or clicking. Furthermore, `mat-list-option` has the `option` role // which doesn't allow a nested `input`. We use `display: none` both to remove it from the tab // order and to prevent focus from reaching it through the screen reader's forms mode. Ideally // we'd remove the `input` completely, but we can't because MDC uses a `:checked` selector to // toggle the selected styles. .mdc-checkbox__native-control, .mdc-radio__native-control { display: none; } } .mat-mdc-list-option.mdc-list-item--selected { // Improve accessibility for Window High Contrast Mode (HCM) by adding an idicator on the selected // option. @include list-item-hcm-indicator.private-high-contrast-list-item-indicator(); }
{ "end_byte": 2905, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/list-option.scss" }
components/src/material/list/selection-list.spec.ts_0_965
import {A, D, DOWN_ARROW, END, ENTER, HOME, SPACE, UP_ARROW} from '@angular/cdk/keycodes'; import { createKeyboardEvent, dispatchEvent, dispatchFakeEvent, dispatchKeyboardEvent, dispatchMouseEvent, } from '@angular/cdk/testing/private'; import { ChangeDetectionStrategy, Component, DebugElement, QueryList, ViewChildren, } from '@angular/core'; import { ComponentFixture, TestBed, fakeAsync, flush, tick, waitForAsync, } from '@angular/core/testing'; import {FormControl, FormsModule, NgModel, ReactiveFormsModule} from '@angular/forms'; import {ThemePalette} from '@angular/material/core'; import {By} from '@angular/platform-browser'; import { MAT_LIST_CONFIG, MatListConfig, MatListModule, MatListOption, MatListOptionTogglePosition, MatSelectionList, MatSelectionListChange, } from './index'; describe('MatSelectionList without forms', () => { const typeaheadInterval = 200; describe('with list option', () =>
{ "end_byte": 965, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/list/selection-list.spec.ts" }
components/src/material/list/selection-list.spec.ts_966_10712
{ let fixture: ComponentFixture<SelectionListWithListOptions>; let listOptions: DebugElement[]; let selectionList: DebugElement; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ MatListModule, SelectionListWithListOptions, SelectionListWithCheckboxPositionAfter, SelectionListWithListDisabled, SelectionListWithOnlyOneOption, SelectionListWithIndirectChildOptions, SelectionListWithSelectedOptionAndValue, ], }); })); beforeEach(waitForAsync(() => { fixture = TestBed.createComponent(SelectionListWithListOptions); fixture.detectChanges(); listOptions = fixture.debugElement.queryAll(By.directive(MatListOption)); selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!; })); function getFocusIndex() { return listOptions.findIndex(o => document.activeElement === o.nativeElement); } it('should be able to set a value on a list option', () => { const optionValues = ['inbox', 'starred', 'sent-mail', 'archive', 'drafts']; optionValues.forEach((optionValue, index) => { expect(listOptions[index].componentInstance.value).toBe(optionValue); }); }); it('should not emit a selectionChange event if an option changed programmatically', () => { spyOn(fixture.componentInstance, 'onSelectionChange'); expect(fixture.componentInstance.onSelectionChange).toHaveBeenCalledTimes(0); listOptions[2].componentInstance.toggle(); fixture.detectChanges(); expect(fixture.componentInstance.onSelectionChange).toHaveBeenCalledTimes(0); }); it('should emit a selectionChange event if an option got clicked', () => { spyOn(fixture.componentInstance, 'onSelectionChange'); expect(fixture.componentInstance.onSelectionChange).toHaveBeenCalledTimes(0); dispatchMouseEvent(listOptions[2].nativeElement, 'click'); fixture.detectChanges(); expect(fixture.componentInstance.onSelectionChange).toHaveBeenCalledTimes(1); }); it('should be able to dispatch one selected item', () => { let testListItem = listOptions[2].injector.get<MatListOption>(MatListOption); let selectList = selectionList.injector.get<MatSelectionList>(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); expect(listOptions[2].nativeElement.getAttribute('aria-selected')).toBe('false'); testListItem.toggle(); fixture.detectChanges(); expect(listOptions[2].nativeElement.getAttribute('aria-selected')).toBe('true'); expect(listOptions[2].nativeElement.getAttribute('aria-disabled')).toBe('false'); expect(selectList.selected.length).toBe(1); }); it('should be able to dispatch multiple selected items', () => { let testListItem = listOptions[2].injector.get<MatListOption>(MatListOption); let testListItem2 = listOptions[1].injector.get<MatListOption>(MatListOption); let selectList = selectionList.injector.get<MatSelectionList>(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); expect(listOptions[2].nativeElement.getAttribute('aria-selected')).toBe('false'); expect(listOptions[1].nativeElement.getAttribute('aria-selected')).toBe('false'); testListItem.toggle(); fixture.detectChanges(); testListItem2.toggle(); fixture.detectChanges(); expect(selectList.selected.length).toBe(2); expect(listOptions[2].nativeElement.getAttribute('aria-selected')).toBe('true'); expect(listOptions[1].nativeElement.getAttribute('aria-selected')).toBe('true'); expect(listOptions[1].nativeElement.getAttribute('aria-disabled')).toBe('false'); expect(listOptions[2].nativeElement.getAttribute('aria-disabled')).toBe('false'); }); it('should be able to specify a color for list options', () => { const optionNativeElements = listOptions.map(option => option.nativeElement); expect(optionNativeElements.every(option => !option.classList.contains('mat-primary'))).toBe( true, ); expect(optionNativeElements.every(option => !option.classList.contains('mat-warn'))).toBe( true, ); // All options will be set to the "warn" color. fixture.componentInstance.selectionListColor = 'warn'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(optionNativeElements.every(option => !option.classList.contains('mat-primary'))).toBe( true, ); expect(optionNativeElements.every(option => option.classList.contains('mat-warn'))).toBe( true, ); // Color will be set explicitly for an option and should take precedence. fixture.componentInstance.firstOptionColor = 'primary'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(optionNativeElements[0].classList).not.toContain('mat-accent'); expect(optionNativeElements[0].classList).not.toContain('mat-warn'); expect( optionNativeElements.slice(1).every(option => option.classList.contains('mat-warn')), ).toBe(true); }); it('should explicitly set the `accent` color', () => { const classList = listOptions[0].nativeElement.classList; fixture.componentInstance.firstOptionColor = 'primary'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(classList).not.toContain('mat-accent'); expect(classList).not.toContain('mat-warn'); fixture.componentInstance.firstOptionColor = 'accent'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(classList).not.toContain('mat-primary'); expect(classList).toContain('mat-accent'); expect(classList).not.toContain('mat-warn'); }); it('should be able to deselect an option', () => { let testListItem = listOptions[2].injector.get<MatListOption>(MatListOption); let selectList = selectionList.injector.get<MatSelectionList>(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); testListItem.toggle(); fixture.detectChanges(); expect(selectList.selected.length).toBe(1); testListItem.toggle(); fixture.detectChanges(); expect(selectList.selected.length).toBe(0); }); it('should not add the mdc-list-item--selected class (in multiple mode)', () => { let testListItem = listOptions[2].injector.get<MatListOption>(MatListOption); dispatchMouseEvent(testListItem._hostElement, 'click'); fixture.detectChanges(); expect(listOptions[2].nativeElement.classList.contains('mdc-list-item--selected')).toBe( false, ); }); it('should not allow selection of disabled items', () => { let testListItem = listOptions[0].injector.get<MatListOption>(MatListOption); let selectList = selectionList.injector.get<MatSelectionList>(MatSelectionList).selectedOptions; expect(selectList.selected.length).withContext('before click').toBe(0); expect(listOptions[0].nativeElement.getAttribute('aria-disabled')).toBe('true'); dispatchMouseEvent(testListItem._hostElement, 'click'); fixture.detectChanges(); expect(selectList.selected.length).withContext('after click').toBe(0); }); it('should be able to un-disable disabled items', () => { let testListItem = listOptions[0].injector.get<MatListOption>(MatListOption); expect(listOptions[0].nativeElement.getAttribute('aria-disabled')).toBe('true'); testListItem.disabled = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(listOptions[0].nativeElement.getAttribute('aria-disabled')).toBe('false'); }); it('should be able to use keyboard select with SPACE', () => { const testListItem = listOptions[1].nativeElement as HTMLElement; const selectList = selectionList.injector.get<MatSelectionList>(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); testListItem.focus(); expect(getFocusIndex()).toBe(1); const event = dispatchKeyboardEvent(testListItem, 'keydown', SPACE); fixture.detectChanges(); expect(selectList.selected.length).toBe(1); expect(event.defaultPrevented).toBe(true); }); it('should be able to select an item using ENTER', () => { const testListItem = listOptions[1].nativeElement as HTMLElement; const selectList = selectionList.injector.get<MatSelectionList>(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); testListItem.focus(); expect(getFocusIndex()).toBe(1); const event = dispatchKeyboardEvent(testListItem, 'keydown', ENTER); fixture.detectChanges(); expect(selectList.selected.length).toBe(1); expect(event.defaultPrevented).toBe(true); }); it('should not be able to toggle a disabled option using SPACE', () => { const testListItem = listOptions[1].nativeElement as HTMLElement; const selectionModel = selectionList.componentInstance.selectedOptions; expect(selectionModel.selected.length).toBe(0); listOptions[1].componentInstance.disabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); testListItem.focus(); expect(getFocusIndex()).toBe(1); dispatchKeyboardEvent(testListItem, 'keydown', SPACE); fixture.detectChanges(); expect(selectionModel.selected.length).toBe(0); });
{ "end_byte": 10712, "start_byte": 966, "url": "https://github.com/angular/components/blob/main/src/material/list/selection-list.spec.ts" }
components/src/material/list/selection-list.spec.ts_10718_20238
it('should focus the first option when the list takes focus for the first time', () => { expect(listOptions[0].nativeElement.tabIndex).toBe(0); expect(listOptions.slice(1).every(o => o.nativeElement.tabIndex === -1)).toBe(true); }); it('should focus the first selected option when list receives focus', fakeAsync(() => { dispatchMouseEvent(listOptions[2].nativeElement, 'click'); fixture.detectChanges(); expect(listOptions.map(o => o.nativeElement.tabIndex)).toEqual([-1, -1, 0, -1, -1]); dispatchMouseEvent(listOptions[1].nativeElement, 'click'); fixture.detectChanges(); expect(listOptions.map(o => o.nativeElement.tabIndex)).toEqual([-1, 0, -1, -1, -1]); // De-select both options to ensure that the first item in the list-item // becomes the designated option for focus. dispatchMouseEvent(listOptions[1].nativeElement, 'click'); dispatchMouseEvent(listOptions[2].nativeElement, 'click'); fixture.detectChanges(); expect(listOptions.map(o => o.nativeElement.tabIndex)).toEqual([0, -1, -1, -1, -1]); })); it('should focus previous item when press UP ARROW', () => { listOptions[2].nativeElement.focus(); expect(getFocusIndex()).toEqual(2); dispatchKeyboardEvent(listOptions[2].nativeElement, 'keydown', UP_ARROW); fixture.detectChanges(); expect(getFocusIndex()).toEqual(1); }); it('should focus next item when press DOWN ARROW', () => { listOptions[2].nativeElement.focus(); expect(getFocusIndex()).toEqual(2); dispatchKeyboardEvent(listOptions[2].nativeElement, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(getFocusIndex()).toEqual(3); }); it('should be able to focus the first item when pressing HOME', () => { listOptions[2].nativeElement.focus(); expect(getFocusIndex()).toBe(2); const event = dispatchKeyboardEvent(listOptions[2].nativeElement, 'keydown', HOME); fixture.detectChanges(); expect(getFocusIndex()).toBe(0); expect(event.defaultPrevented).toBe(true); }); it('should focus the last item when pressing END', () => { listOptions[2].nativeElement.focus(); expect(getFocusIndex()).toBe(2); const event = dispatchKeyboardEvent(listOptions[2].nativeElement, 'keydown', END); fixture.detectChanges(); expect(getFocusIndex()).toBe(4); expect(event.defaultPrevented).toBe(true); }); it('should select all items using ctrl + a', () => { listOptions.forEach(option => (option.componentInstance.disabled = false)); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(listOptions.some(option => option.componentInstance.selected)).toBe(false); listOptions[2].nativeElement.focus(); dispatchKeyboardEvent(listOptions[2].nativeElement, 'keydown', A, 'A', {control: true}); fixture.detectChanges(); expect(listOptions.every(option => option.componentInstance.selected)).toBe(true); }); it('should not select disabled items when pressing ctrl + a', () => { listOptions.slice(0, 2).forEach(option => (option.componentInstance.disabled = true)); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(listOptions.map(option => option.componentInstance.selected)).toEqual([ false, false, false, false, false, ]); listOptions[3].nativeElement.focus(); dispatchKeyboardEvent(listOptions[3].nativeElement, 'keydown', A, 'A', {control: true}); fixture.detectChanges(); expect(listOptions.map(option => option.componentInstance.selected)).toEqual([ false, false, true, true, true, ]); }); it('should select all items using ctrl + a if some items are selected', () => { listOptions.slice(0, 2).forEach(option => (option.componentInstance.selected = true)); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(listOptions.some(option => option.componentInstance.selected)).toBe(true); listOptions[2].nativeElement.focus(); dispatchKeyboardEvent(listOptions[2].nativeElement, 'keydown', A, 'A', {control: true}); fixture.detectChanges(); expect(listOptions.every(option => option.componentInstance.selected)).toBe(true); }); it('should deselect all with ctrl + a if all options are selected', () => { listOptions.forEach(option => (option.componentInstance.selected = true)); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(listOptions.every(option => option.componentInstance.selected)).toBe(true); listOptions[2].nativeElement.focus(); dispatchKeyboardEvent(listOptions[2].nativeElement, 'keydown', A, 'A', {control: true}); fixture.detectChanges(); expect(listOptions.every(option => option.componentInstance.selected)).toBe(false); }); it('should dispatch the selectionChange event when selecting via ctrl + a', () => { const spy = spyOn(fixture.componentInstance, 'onSelectionChange'); listOptions.forEach(option => (option.componentInstance.disabled = false)); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); listOptions[2].nativeElement.focus(); dispatchKeyboardEvent(listOptions[2].nativeElement, 'keydown', A, 'A', {control: true}); fixture.detectChanges(); expect(spy).toHaveBeenCalledTimes(1); expect(spy).toHaveBeenCalledWith( jasmine.objectContaining({ options: listOptions.map(option => option.componentInstance), }), ); }); it('should be able to jump focus down to an item by typing', fakeAsync(() => { const firstOption = listOptions[0].nativeElement; firstOption.focus(); expect(getFocusIndex()).toBe(0); dispatchEvent(firstOption, createKeyboardEvent('keydown', 83, 's')); fixture.detectChanges(); tick(typeaheadInterval); expect(getFocusIndex()).toBe(1); dispatchEvent(firstOption, createKeyboardEvent('keydown', 68, 'd')); fixture.detectChanges(); tick(typeaheadInterval); expect(getFocusIndex()).toBe(4); })); it('should be able to skip to an item by typing', fakeAsync(() => { listOptions[0].nativeElement.focus(); expect(getFocusIndex()).toBe(0); dispatchKeyboardEvent(listOptions[0].nativeElement, 'keydown', D, 'd'); fixture.detectChanges(); tick(typeaheadInterval); expect(getFocusIndex()).toBe(4); })); // Test for "A" specifically, because it's a special case that can be used // to select all values. it('should be able to skip to an item by typing the letter "A"', fakeAsync(() => { listOptions[0].nativeElement.focus(); expect(getFocusIndex()).toBe(0); dispatchKeyboardEvent(listOptions[0].nativeElement, 'keydown', A, 'a'); fixture.detectChanges(); tick(typeaheadInterval); expect(getFocusIndex()).toBe(3); })); it('should not select items while using the typeahead', fakeAsync(() => { const testListItem = listOptions[1].nativeElement as HTMLElement; const model = selectionList.injector.get<MatSelectionList>(MatSelectionList).selectedOptions; testListItem.focus(); dispatchFakeEvent(testListItem, 'focus'); fixture.detectChanges(); expect(getFocusIndex()).toBe(1); expect(model.isEmpty()).toBe(true); dispatchKeyboardEvent(testListItem, 'keydown', D, 'd'); fixture.detectChanges(); tick(typeaheadInterval / 2); // Tick only half the typeahead timeout. dispatchKeyboardEvent(testListItem, 'keydown', SPACE); fixture.detectChanges(); // Tick the buffer timeout again as a new key has been pressed that resets // the buffer timeout. tick(typeaheadInterval); expect(getFocusIndex()).toBe(4); expect(model.isEmpty()).toBe(true); })); it('should be able to select all options', () => { const list: MatSelectionList = selectionList.componentInstance; expect(list.options.toArray().every(option => option.selected)).toBe(false); const result = list.selectAll(); fixture.detectChanges(); expect(list.options.toArray().every(option => option.selected)).toBe(true); expect(result).toEqual(list.options.toArray()); }); it('should be able to select all options, even if they are disabled', () => { const list: MatSelectionList = selectionList.componentInstance; list.options.forEach(option => (option.disabled = true)); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(list.options.toArray().every(option => option.selected)).toBe(false); list.selectAll(); fixture.detectChanges(); expect(list.options.toArray().every(option => option.selected)).toBe(true); }); it('should be able to deselect all options', () => { const list: MatSelectionList = selectionList.componentInstance; list.options.forEach(option => option.toggle()); expect(list.options.toArray().every(option => option.selected)).toBe(true); const result = list.deselectAll(); fixture.detectChanges(); expect(list.options.toArray().every(option => option.selected)).toBe(false); expect(result).toEqual(list.options.toArray()); });
{ "end_byte": 20238, "start_byte": 10718, "url": "https://github.com/angular/components/blob/main/src/material/list/selection-list.spec.ts" }