_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
components/src/material/toolbar/public-api.ts_0_265 | /**
* @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 './toolbar-module';
export * from './toolbar';
| {
"end_byte": 265,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/public-api.ts"
} |
components/src/material/toolbar/toolbar.ts_0_3261 | /**
* @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 {Platform} from '@angular/cdk/platform';
import {DOCUMENT} from '@angular/common';
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
ContentChildren,
Directive,
ElementRef,
Input,
QueryList,
ViewEncapsulation,
inject,
} from '@angular/core';
@Directive({
selector: 'mat-toolbar-row',
exportAs: 'matToolbarRow',
host: {'class': 'mat-toolbar-row'},
})
export class MatToolbarRow {}
@Component({
selector: 'mat-toolbar',
exportAs: 'matToolbar',
templateUrl: 'toolbar.html',
styleUrl: 'toolbar.css',
host: {
'class': 'mat-toolbar',
'[class]': 'color ? "mat-" + color : ""',
'[class.mat-toolbar-multiple-rows]': '_toolbarRows.length > 0',
'[class.mat-toolbar-single-row]': '_toolbarRows.length === 0',
},
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
})
export class MatToolbar implements AfterViewInit {
protected _elementRef = inject(ElementRef);
private _platform = inject(Platform);
private _document = inject(DOCUMENT);
// TODO: should be typed as `ThemePalette` but internal apps pass in arbitrary strings.
/**
* Theme color of the toolbar. 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;
/** Reference to all toolbar row elements that have been projected. */
@ContentChildren(MatToolbarRow, {descendants: true}) _toolbarRows: QueryList<MatToolbarRow>;
constructor(...args: unknown[]);
constructor() {}
ngAfterViewInit() {
if (this._platform.isBrowser) {
this._checkToolbarMixedModes();
this._toolbarRows.changes.subscribe(() => this._checkToolbarMixedModes());
}
}
/**
* Throws an exception when developers are attempting to combine the different toolbar row modes.
*/
private _checkToolbarMixedModes() {
if (this._toolbarRows.length && (typeof ngDevMode === 'undefined' || ngDevMode)) {
// Check if there are any other DOM nodes that can display content but aren't inside of
// a <mat-toolbar-row> element.
const isCombinedUsage = Array.from<HTMLElement>(this._elementRef.nativeElement.childNodes)
.filter(node => !(node.classList && node.classList.contains('mat-toolbar-row')))
.filter(node => node.nodeType !== (this._document ? this._document.COMMENT_NODE : 8))
.some(node => !!(node.textContent && node.textContent.trim()));
if (isCombinedUsage) {
throwToolbarMixedModesError();
}
}
}
}
/**
* Throws an exception when attempting to combine the different toolbar row modes.
* @docs-private
*/
export function throwToolbarMixedModesError() {
throw Error(
'MatToolbar: Attempting to combine different toolbar modes. ' +
'Either specify multiple `<mat-toolbar-row>` elements explicitly or just place content ' +
'inside of a `<mat-toolbar>` for a single row.',
);
}
| {
"end_byte": 3261,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/toolbar.ts"
} |
components/src/material/toolbar/README.md_0_97 | Please see the official documentation at https://material.angular.io/components/component/toolbar | {
"end_byte": 97,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/README.md"
} |
components/src/material/toolbar/toolbar.html_0_77 | <ng-content></ng-content>
<ng-content select="mat-toolbar-row"></ng-content>
| {
"end_byte": 77,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/toolbar.html"
} |
components/src/material/toolbar/toolbar.spec.ts_0_4693 | import {Component, signal} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {MatToolbarModule} from './index';
describe('MatToolbar', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
MatToolbarModule,
ToolbarSingleRow,
ToolbarMultipleRows,
ToolbarMixedRowModes,
ToolbarMultipleIndirectRows,
],
});
}));
describe('with single row', () => {
let fixture: ComponentFixture<ToolbarSingleRow>;
let testComponent: ToolbarSingleRow;
let toolbarElement: HTMLElement;
beforeEach(() => {
fixture = TestBed.createComponent(ToolbarSingleRow);
testComponent = fixture.debugElement.componentInstance;
toolbarElement = fixture.debugElement.query(By.css('.mat-toolbar'))!.nativeElement;
});
it('should apply class based on color attribute', () => {
testComponent.toolbarColor.set('primary');
fixture.detectChanges();
expect(toolbarElement.classList.contains('mat-primary')).toBe(true);
testComponent.toolbarColor.set('accent');
fixture.detectChanges();
expect(toolbarElement.classList.contains('mat-primary')).toBe(false);
expect(toolbarElement.classList.contains('mat-accent')).toBe(true);
testComponent.toolbarColor.set('warn');
fixture.detectChanges();
expect(toolbarElement.classList.contains('mat-accent')).toBe(false);
expect(toolbarElement.classList.contains('mat-warn')).toBe(true);
});
it('should not wrap the first row contents inside of a generated element', () => {
expect(toolbarElement.firstElementChild!.tagName)
.withContext(
'Expected the <span> element of the first row to be a direct child ' + 'of the toolbar',
)
.toBe('SPAN');
});
});
describe('with multiple rows', () => {
it('should project each toolbar-row element inside of the toolbar', () => {
const fixture = TestBed.createComponent(ToolbarMultipleRows);
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('.mat-toolbar > .mat-toolbar-row')).length)
.withContext('Expected one toolbar row to be present while no content is projected.')
.toBe(2);
});
it('should throw an error if different toolbar modes are mixed', () => {
expect(() => {
const fixture = TestBed.createComponent(ToolbarMixedRowModes);
fixture.detectChanges();
}).toThrowError(/attempting to combine different/i);
});
it('should throw an error if a toolbar-row is added later', async () => {
const fixture = TestBed.createComponent(ToolbarMixedRowModes);
await expectAsync(
(async () => {
fixture.componentInstance.showToolbarRow.set(false);
fixture.detectChanges();
await fixture.whenStable();
fixture.componentInstance.showToolbarRow.set(true);
fixture.detectChanges();
await fixture.whenStable();
})(),
).toBeRejectedWithError(/attempting to combine different/i);
});
it('should pick up indirect descendant rows', () => {
const fixture = TestBed.createComponent(ToolbarMultipleIndirectRows);
fixture.detectChanges();
const toolbar = fixture.nativeElement.querySelector('.mat-toolbar');
expect(toolbar.classList).toContain('mat-toolbar-multiple-rows');
});
});
});
@Component({
template: `
<mat-toolbar [color]="toolbarColor()">
<span>First Row</span>
</mat-toolbar>
`,
standalone: true,
imports: [MatToolbarModule],
})
class ToolbarSingleRow {
toolbarColor = signal('');
}
@Component({
template: `
<mat-toolbar>
<mat-toolbar-row>First Row</mat-toolbar-row>
<mat-toolbar-row>Second Row</mat-toolbar-row>
</mat-toolbar>
`,
standalone: true,
imports: [MatToolbarModule],
})
class ToolbarMultipleRows {}
@Component({
template: `
<mat-toolbar>
First Row
@if (showToolbarRow) {
<mat-toolbar-row>Second Row</mat-toolbar-row>
}
</mat-toolbar>
`,
standalone: true,
imports: [MatToolbarModule],
})
class ToolbarMixedRowModes {
showToolbarRow = signal(true);
}
@Component({
// The ng-container is there so we have a node with a directive between the toolbar and the rows.
template: `
<mat-toolbar>
@if (true) {
<mat-toolbar-row>First Row</mat-toolbar-row>
<mat-toolbar-row>Second Row</mat-toolbar-row>
}
</mat-toolbar>
`,
standalone: true,
imports: [MatToolbarModule],
})
class ToolbarMultipleIndirectRows {}
| {
"end_byte": 4693,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/toolbar.spec.ts"
} |
components/src/material/toolbar/toolbar.scss_0_3896 | @use '@angular/cdk';
@use '../core/tokens/token-utils';
@use '../core/tokens/m2/mat/toolbar' as tokens-mat-toolbar;
@use '../core/tokens/m2/mdc/text-button' as tokens-mdc-text-button;
@use '../core/tokens/m2/mdc/outlined-button' as tokens-mdc-outlined-button;
@use '../core/style/variables';
$row-padding: 16px !default;
// @deprecated @breaking-change 8.0.0
// TODO: Remove once internal g3 apps no longer depend on this variable. Tracked with: COMP-303.
$height-mobile-portrait: 56px !default;
.mat-toolbar {
@include token-utils.use-tokens(
tokens-mat-toolbar.$prefix, tokens-mat-toolbar.get-token-slots()) {
@include token-utils.create-token-slot(background, container-background-color);
@include token-utils.create-token-slot(color, container-text-color);
&, h1, h2, h3, h4, h5, h6 {
@include token-utils.create-token-slot(font-family, title-text-font);
@include token-utils.create-token-slot(font-size, title-text-size);
@include token-utils.create-token-slot(line-height, title-text-line-height);
@include token-utils.create-token-slot(font-weight, title-text-weight);
@include token-utils.create-token-slot(letter-spacing, title-text-tracking);
margin: 0;
}
}
@include cdk.high-contrast {
outline: solid 1px;
}
// Overrides so that components projected into the toolbar are visible.
.mat-form-field-underline,
.mat-form-field-ripple,
.mat-focused .mat-form-field-ripple {
background-color: currentColor;
}
.mat-form-field-label,
.mat-focused .mat-form-field-label,
.mat-select-value,
.mat-select-arrow,
.mat-form-field.mat-focused .mat-select-arrow {
color: inherit;
}
.mat-input-element {
caret-color: currentColor;
}
.mat-mdc-button-base.mat-mdc-button-base.mat-unthemed {
$color-token: null;
@include token-utils.use-tokens(
tokens-mat-toolbar.$prefix, tokens-mat-toolbar.get-token-slots()) {
$color-token: token-utils.get-token-variable(container-text-color);
}
@include token-utils.use-tokens(
tokens-mdc-text-button.$prefix, tokens-mdc-text-button.get-token-slots()) {
$token: token-utils.get-token-variable-name(label-text-color);
#{$token}: #{$color-token};
}
@include token-utils.use-tokens(
tokens-mdc-outlined-button.$prefix, tokens-mdc-outlined-button.get-token-slots()) {
$token: token-utils.get-token-variable-name(label-text-color);
#{$token}: #{$color-token};
}
}
}
.mat-toolbar-row, .mat-toolbar-single-row {
display: flex;
box-sizing: border-box;
padding: 0 $row-padding;
width: 100%;
// Flexbox Vertical Alignment
flex-direction: row;
align-items: center;
// Per Material specs a toolbar cannot have multiple lines inside of a single row.
// Disable text wrapping inside of the toolbar. Developers are still able to overwrite it.
white-space: nowrap;
@include token-utils.use-tokens(
tokens-mat-toolbar.$prefix, tokens-mat-toolbar.get-token-slots()) {
@include token-utils.create-token-slot(height, standard-height);
@media (variables.$xsmall) {
@include token-utils.create-token-slot(height, mobile-height);
}
}
}
.mat-toolbar-multiple-rows {
display: flex;
box-sizing: border-box;
flex-direction: column;
width: 100%;
@include token-utils.use-tokens(
tokens-mat-toolbar.$prefix, tokens-mat-toolbar.get-token-slots()) {
@include token-utils.create-token-slot(min-height, standard-height);
// As per specs, toolbars should have a different height in mobile devices. This has been
// specified in the old guidelines and is still observable in the new specifications by
// looking at the spec images. See: https://material.io/design/components/app-bars-top.html#anatomy
@media (variables.$xsmall) {
@include token-utils.create-token-slot(min-height, mobile-height);
}
}
}
| {
"end_byte": 3896,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/toolbar.scss"
} |
components/src/material/toolbar/toolbar-module.ts_0_516 | /**
* @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 {MatToolbar, MatToolbarRow} from './toolbar';
@NgModule({
imports: [MatCommonModule, MatToolbar, MatToolbarRow],
exports: [MatToolbar, MatToolbarRow, MatCommonModule],
})
export class MatToolbarModule {}
| {
"end_byte": 516,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/toolbar-module.ts"
} |
components/src/material/toolbar/BUILD.bazel_0_1415 | 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 = "toolbar",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = [":toolbar.css"] + glob(["**/*.html"]),
deps = [
"//src:dev_mode_types",
"//src/cdk/platform",
"//src/material/core",
"@npm//@angular/common",
"@npm//@angular/core",
],
)
sass_library(
name = "toolbar_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = [
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "toolbar_scss",
src = "toolbar.scss",
deps = [
"//src/cdk:sass_lib",
"//src/material/core:core_scss_lib",
],
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
),
deps = [
":toolbar",
"@npm//@angular/common",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
markdown_to_html(
name = "overview",
srcs = [":toolbar.md"],
)
extract_tokens(
name = "tokens",
srcs = [":toolbar_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1415,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/BUILD.bazel"
} |
components/src/material/toolbar/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/toolbar/index.ts"
} |
components/src/material/toolbar/_toolbar-variables.scss_0_891 | // Minimum height for toolbar's in the highest density is difficult to determine because
// developers can project arbitrary content. We use a minimum value that ensures that most
// common content (e.g. icon buttons) does not exceed the row boundaries in highest density.
$minimum-height: 44px !default;
$height-desktop: 64px !default;
$maximum-height-desktop: $height-desktop !default;
$minimum-height-desktop: $minimum-height !default;
$height-mobile: 56px !default;
$maximum-height-mobile: $height-mobile !default;
$minimum-height-mobile: $minimum-height !default;
$desktop-density-config: (
height: (
default: $height-desktop,
maximum: $maximum-height-desktop,
minimum: $minimum-height-desktop,
)
) !default;
$mobile-density-config: (
height: (
default: $height-mobile,
maximum: $maximum-height-mobile,
minimum: $minimum-height-mobile,
)
) !default;
| {
"end_byte": 891,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/_toolbar-variables.scss"
} |
components/src/material/toolbar/testing/toolbar-harness.ts_0_1903 | /**
* @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 {ContentContainerComponentHarness, HarnessPredicate, parallel} from '@angular/cdk/testing';
import {ToolbarHarnessFilters} from './toolbar-harness-filters';
/** Selectors for different sections of the mat-toolbar that contain user content. */
export enum MatToolbarSection {
ROW = '.mat-toolbar-row',
}
/** Harness for interacting with a standard mat-toolbar in tests. */
export class MatToolbarHarness extends ContentContainerComponentHarness<MatToolbarSection> {
static hostSelector = '.mat-toolbar';
private _getRows = this.locatorForAll(MatToolbarSection.ROW);
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatToolbarHarness` that meets
* certain criteria.
* @param options Options for filtering which card instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: ToolbarHarnessFilters = {}): HarnessPredicate<MatToolbarHarness> {
return new HarnessPredicate(MatToolbarHarness, options).addOption(
'text',
options.text,
(harness, text) => HarnessPredicate.stringMatches(harness._getText(), text),
);
}
/** Whether the toolbar has multiple rows. */
async hasMultipleRows(): Promise<boolean> {
return (await this.host()).hasClass('mat-toolbar-multiple-rows');
}
/** Gets all of the toolbar's content as text. */
private async _getText(): Promise<string> {
return (await this.host()).text();
}
/** Gets the text of each row in the toolbar. */
async getRowsAsText(): Promise<string[]> {
const rows = await this._getRows();
return parallel(() => (rows.length ? rows.map(r => r.text()) : [this._getText()]));
}
}
| {
"end_byte": 1903,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/testing/toolbar-harness.ts"
} |
components/src/material/toolbar/testing/toolbar-harness-filters.ts_0_516 | /**
* @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 `MatToolbarHarness` instances. */
export interface ToolbarHarnessFilters extends BaseHarnessFilters {
/** Only find instances whose text matches the given value. */
text?: string | RegExp;
}
| {
"end_byte": 516,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/testing/toolbar-harness-filters.ts"
} |
components/src/material/toolbar/testing/public-api.ts_0_282 | /**
* @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 './toolbar-harness';
export * from './toolbar-harness-filters';
| {
"end_byte": 282,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/testing/public-api.ts"
} |
components/src/material/toolbar/testing/toolbar-harness.spec.ts_0_2863 | import {Component} from '@angular/core';
import {ComponentHarness, HarnessLoader} from '@angular/cdk/testing';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatToolbarHarness, MatToolbarSection} from '@angular/material/toolbar/testing';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
describe('MatToolbarHarness', () => {
let fixture: ComponentFixture<ToolbarHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatToolbarModule, ToolbarHarnessTest],
});
fixture = TestBed.createComponent(ToolbarHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should find all toolbars', async () => {
const toolbars = await loader.getAllHarnesses(MatToolbarHarness);
expect(toolbars.length).toBe(2);
});
it('should find toolbar with text', async () => {
const toolbars = await loader.getAllHarnesses(MatToolbarHarness.with({text: 'My App'}));
expect(toolbars.length).toBe(1);
expect(await toolbars[0].hasMultipleRows()).toBeFalse();
});
it('should find toolbar with regex', async () => {
const toolbars = await loader.getAllHarnesses(MatToolbarHarness.with({text: /Row/}));
expect(toolbars.length).toBe(1);
expect(await toolbars[0].hasMultipleRows()).toBeTrue();
});
it('should get toolbar text', async () => {
const toolbars = await loader.getAllHarnesses(MatToolbarHarness);
expect(await toolbars[0].getRowsAsText()).toEqual(['My App']);
expect(await toolbars[1].getRowsAsText()).toEqual(['Row 1', 'Row 2 Button 1 Button 2']);
});
it('should get harness loaders for toolbar row', async () => {
const toolbar = await loader.getHarness(MatToolbarHarness.with({text: /Button/}));
const rowLoaders = await toolbar.getAllChildLoaders(MatToolbarSection.ROW);
const row1 = rowLoaders[0] as HarnessLoader;
const row1Subcomponents = await row1.getAllHarnesses(DummyHarness);
const row2 = rowLoaders[1] as HarnessLoader;
const row2Subcomponents = await row2.getAllHarnesses(DummyHarness);
expect(row1Subcomponents.length).toBe(1);
expect(row2Subcomponents.length).toBe(3);
});
});
@Component({
template: `
<mat-toolbar><span>My App</span></mat-toolbar>
<mat-toolbar>
<mat-toolbar-row><span>Row 1</span></mat-toolbar-row>
<mat-toolbar-row><span>Row 2</span>
<button mat-button>
Button 1
</button>
<button mat-button>
Button 2
</button>
</mat-toolbar-row>
</mat-toolbar>
`,
standalone: true,
imports: [MatToolbarModule],
})
class ToolbarHarnessTest {}
class DummyHarness extends ComponentHarness {
static hostSelector = 'span, button';
}
| {
"end_byte": 2863,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/testing/toolbar-harness.spec.ts"
} |
components/src/material/toolbar/testing/BUILD.bazel_0_722 | 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/toolbar",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_tests_lib"],
)
| {
"end_byte": 722,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/testing/BUILD.bazel"
} |
components/src/material/toolbar/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/toolbar/testing/index.ts"
} |
components/src/material/checkbox/checkbox.ts_0_3340 | /**
* @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 {FocusableOption} from '@angular/cdk/a11y';
import {
ANIMATION_MODULE_TYPE,
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
Input,
NgZone,
OnChanges,
Output,
SimpleChanges,
ViewChild,
ViewEncapsulation,
booleanAttribute,
forwardRef,
numberAttribute,
inject,
HostAttributeToken,
} from '@angular/core';
import {
AbstractControl,
ControlValueAccessor,
NG_VALIDATORS,
NG_VALUE_ACCESSOR,
ValidationErrors,
Validator,
} from '@angular/forms';
import {MatRipple, _MatInternalFormField, _StructuralStylesLoader} from '@angular/material/core';
import {
MAT_CHECKBOX_DEFAULT_OPTIONS,
MAT_CHECKBOX_DEFAULT_OPTIONS_FACTORY,
MatCheckboxDefaultOptions,
} from './checkbox-config';
import {_CdkPrivateStyleLoader} from '@angular/cdk/private';
/**
* Represents the different states that require custom transitions between them.
* @docs-private
*/
export enum TransitionCheckState {
/** The initial state of the component before any user interaction. */
Init,
/** The state representing the component when it's becoming checked. */
Checked,
/** The state representing the component when it's becoming unchecked. */
Unchecked,
/** The state representing the component when it's becoming indeterminate. */
Indeterminate,
}
/**
* @deprecated Will stop being exported.
* @breaking-change 19.0.0
*/
export const MAT_CHECKBOX_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MatCheckbox),
multi: true,
};
/** Change event object emitted by checkbox. */
export class MatCheckboxChange {
/** The source checkbox of the event. */
source: MatCheckbox;
/** The new `checked` value of the checkbox. */
checked: boolean;
}
// Increasing integer for generating unique ids for checkbox components.
let nextUniqueId = 0;
// Default checkbox configuration.
const defaults = MAT_CHECKBOX_DEFAULT_OPTIONS_FACTORY();
@Component({
selector: 'mat-checkbox',
templateUrl: 'checkbox.html',
styleUrl: 'checkbox.css',
host: {
'class': 'mat-mdc-checkbox',
'[attr.tabindex]': 'null',
'[attr.aria-label]': 'null',
'[attr.aria-labelledby]': 'null',
'[class._mat-animation-noopable]': `_animationMode === 'NoopAnimations'`,
'[class.mdc-checkbox--disabled]': 'disabled',
'[id]': 'id',
// Add classes that users can use to more easily target disabled or checked checkboxes.
'[class.mat-mdc-checkbox-disabled]': 'disabled',
'[class.mat-mdc-checkbox-checked]': 'checked',
'[class.mat-mdc-checkbox-disabled-interactive]': 'disabledInteractive',
'[class]': 'color ? "mat-" + color : "mat-accent"',
},
providers: [
MAT_CHECKBOX_CONTROL_VALUE_ACCESSOR,
{
provide: NG_VALIDATORS,
useExisting: MatCheckbox,
multi: true,
},
],
exportAs: 'matCheckbox',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [MatRipple, _MatInternalFormField],
})
export class MatCheckbox
implements AfterViewInit, OnChanges, ControlValueAccessor, Validator, FocusableOption | {
"end_byte": 3340,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox.ts"
} |
components/src/material/checkbox/checkbox.ts_3341_11904 | {
_elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private _changeDetectorRef = inject(ChangeDetectorRef);
private _ngZone = inject(NgZone);
_animationMode? = inject(ANIMATION_MODULE_TYPE, {optional: true});
private _options = inject<MatCheckboxDefaultOptions>(MAT_CHECKBOX_DEFAULT_OPTIONS, {
optional: true,
});
/** Focuses the checkbox. */
focus() {
this._inputElement.nativeElement.focus();
}
/** Creates the change event that will be emitted by the checkbox. */
protected _createChangeEvent(isChecked: boolean) {
const event = new MatCheckboxChange();
event.source = this;
event.checked = isChecked;
return event;
}
/** Gets the element on which to add the animation CSS classes. */
protected _getAnimationTargetElement() {
return this._inputElement?.nativeElement;
}
/** CSS classes to add when transitioning between the different checkbox states. */
protected _animationClasses = {
uncheckedToChecked: 'mdc-checkbox--anim-unchecked-checked',
uncheckedToIndeterminate: 'mdc-checkbox--anim-unchecked-indeterminate',
checkedToUnchecked: 'mdc-checkbox--anim-checked-unchecked',
checkedToIndeterminate: 'mdc-checkbox--anim-checked-indeterminate',
indeterminateToChecked: 'mdc-checkbox--anim-indeterminate-checked',
indeterminateToUnchecked: 'mdc-checkbox--anim-indeterminate-unchecked',
};
/**
* Attached to the aria-label attribute of the host element. In most cases, aria-labelledby will
* take precedence so this may be omitted.
*/
@Input('aria-label') ariaLabel: string = '';
/**
* Users can specify the `aria-labelledby` attribute which will be forwarded to the input element
*/
@Input('aria-labelledby') ariaLabelledby: string | null = null;
/** The 'aria-describedby' attribute is read after the element's label and field type. */
@Input('aria-describedby') ariaDescribedby: string;
/**
* Users can specify the `aria-expanded` attribute which will be forwarded to the input element
*/
@Input({alias: 'aria-expanded', transform: booleanAttribute}) ariaExpanded: boolean;
/**
* Users can specify the `aria-controls` attribute which will be forwarded to the input element
*/
@Input('aria-controls') ariaControls: string;
/** Users can specify the `aria-owns` attribute which will be forwarded to the input element */
@Input('aria-owns') ariaOwns: string;
private _uniqueId: string;
/** A unique id for the checkbox input. If none is supplied, it will be auto-generated. */
@Input() id: string;
/** Returns the unique id for the visual hidden input. */
get inputId(): string {
return `${this.id || this._uniqueId}-input`;
}
/** Whether the checkbox is required. */
@Input({transform: booleanAttribute}) required: boolean;
/** Whether the label should appear after or before the checkbox. Defaults to 'after' */
@Input() labelPosition: 'before' | 'after' = 'after';
/** Name value will be applied to the input element if present */
@Input() name: string | null = null;
/** Event emitted when the checkbox's `checked` value changes. */
@Output() readonly change = new EventEmitter<MatCheckboxChange>();
/** Event emitted when the checkbox's `indeterminate` value changes. */
@Output() readonly indeterminateChange: EventEmitter<boolean> = new EventEmitter<boolean>();
/** The value attribute of the native input element */
@Input() value: string;
/** Whether the checkbox has a ripple. */
@Input({transform: booleanAttribute}) disableRipple: boolean;
/** The native `<input type="checkbox">` element */
@ViewChild('input') _inputElement: ElementRef<HTMLInputElement>;
/** The native `<label>` element */
@ViewChild('label') _labelElement: ElementRef<HTMLInputElement>;
/** Tabindex for the checkbox. */
@Input({transform: (value: unknown) => (value == null ? undefined : numberAttribute(value))})
tabIndex: number;
// TODO(crisbeto): this should be a ThemePalette, but some internal apps were abusing
// the lack of type checking previously and assigning random strings.
/**
* Theme color of the checkbox. 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 | undefined;
/** Whether the checkbox should remain interactive when it is disabled. */
@Input({transform: booleanAttribute})
disabledInteractive: boolean;
/**
* Called when the checkbox is blurred. Needed to properly implement ControlValueAccessor.
* @docs-private
*/
_onTouched: () => any = () => {};
private _currentAnimationClass: string = '';
private _currentCheckState: TransitionCheckState = TransitionCheckState.Init;
private _controlValueAccessorChangeFn: (value: any) => void = () => {};
private _validatorChangeFn = () => {};
constructor(...args: unknown[]);
constructor() {
inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader);
const tabIndex = inject(new HostAttributeToken('tabindex'), {optional: true});
this._options = this._options || defaults;
this.color = this._options.color || defaults.color;
this.tabIndex = tabIndex == null ? 0 : parseInt(tabIndex) || 0;
this.id = this._uniqueId = `mat-mdc-checkbox-${++nextUniqueId}`;
this.disabledInteractive = this._options?.disabledInteractive ?? false;
}
ngOnChanges(changes: SimpleChanges) {
if (changes['required']) {
this._validatorChangeFn();
}
}
ngAfterViewInit() {
this._syncIndeterminate(this._indeterminate);
}
/** Whether the checkbox is checked. */
@Input({transform: booleanAttribute})
get checked(): boolean {
return this._checked;
}
set checked(value: boolean) {
if (value != this.checked) {
this._checked = value;
this._changeDetectorRef.markForCheck();
}
}
private _checked: boolean = false;
/** Whether the checkbox is disabled. */
@Input({transform: booleanAttribute})
get disabled(): boolean {
return this._disabled;
}
set disabled(value: boolean) {
if (value !== this.disabled) {
this._disabled = value;
this._changeDetectorRef.markForCheck();
}
}
private _disabled: boolean = false;
/**
* Whether the checkbox is indeterminate. This is also known as "mixed" mode and can be used to
* represent a checkbox with three states, e.g. a checkbox that represents a nested list of
* checkable items. Note that whenever checkbox is manually clicked, indeterminate is immediately
* set to false.
*/
@Input({transform: booleanAttribute})
get indeterminate(): boolean {
return this._indeterminate;
}
set indeterminate(value: boolean) {
const changed = value != this._indeterminate;
this._indeterminate = value;
if (changed) {
if (this._indeterminate) {
this._transitionCheckState(TransitionCheckState.Indeterminate);
} else {
this._transitionCheckState(
this.checked ? TransitionCheckState.Checked : TransitionCheckState.Unchecked,
);
}
this.indeterminateChange.emit(this._indeterminate);
}
this._syncIndeterminate(this._indeterminate);
}
private _indeterminate: boolean = false;
_isRippleDisabled() {
return this.disableRipple || this.disabled;
}
/** Method being called whenever the label text changes. */
_onLabelTextChange() {
// Since the event of the `cdkObserveContent` directive runs outside of the zone, the checkbox
// component will be only marked for check, but no actual change detection runs automatically.
// Instead of going back into the zone in order to trigger a change detection which causes
// *all* components to be checked (if explicitly marked or not using OnPush), we only trigger
// an explicit change detection for the checkbox view and its children.
this._changeDetectorRef.detectChanges();
}
// Implemented as part of ControlValueAccessor.
writeValue(value: any) {
this.checked = !!value;
}
// Implemented as part of ControlValueAccessor.
registerOnChange(fn: (value: any) => void) {
this._controlValueAccessorChangeFn = fn;
}
// Implemented as part of ControlValueAccessor.
registerOnTouched(fn: any) {
this._onTouched = fn;
}
// Implemented as part of ControlValueAccessor.
setDisabledState(isDisabled: boolean) {
this.disabled = isDisabled;
}
// Implemented as a part of Validator. | {
"end_byte": 11904,
"start_byte": 3341,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox.ts"
} |
components/src/material/checkbox/checkbox.ts_11907_19067 | validate(control: AbstractControl<boolean>): ValidationErrors | null {
return this.required && control.value !== true ? {'required': true} : null;
}
// Implemented as a part of Validator.
registerOnValidatorChange(fn: () => void): void {
this._validatorChangeFn = fn;
}
private _transitionCheckState(newState: TransitionCheckState) {
let oldState = this._currentCheckState;
let element = this._getAnimationTargetElement();
if (oldState === newState || !element) {
return;
}
if (this._currentAnimationClass) {
element.classList.remove(this._currentAnimationClass);
}
this._currentAnimationClass = this._getAnimationClassForCheckStateTransition(
oldState,
newState,
);
this._currentCheckState = newState;
if (this._currentAnimationClass.length > 0) {
element.classList.add(this._currentAnimationClass);
// Remove the animation class to avoid animation when the checkbox is moved between containers
const animationClass = this._currentAnimationClass;
this._ngZone.runOutsideAngular(() => {
setTimeout(() => {
element!.classList.remove(animationClass);
}, 1000);
});
}
}
private _emitChangeEvent() {
this._controlValueAccessorChangeFn(this.checked);
this.change.emit(this._createChangeEvent(this.checked));
// Assigning the value again here is redundant, but we have to do it in case it was
// changed inside the `change` listener which will cause the input to be out of sync.
if (this._inputElement) {
this._inputElement.nativeElement.checked = this.checked;
}
}
/** Toggles the `checked` state of the checkbox. */
toggle(): void {
this.checked = !this.checked;
this._controlValueAccessorChangeFn(this.checked);
}
protected _handleInputClick() {
const clickAction = this._options?.clickAction;
// If resetIndeterminate is false, and the current state is indeterminate, do nothing on click
if (!this.disabled && clickAction !== 'noop') {
// When user manually click on the checkbox, `indeterminate` is set to false.
if (this.indeterminate && clickAction !== 'check') {
Promise.resolve().then(() => {
this._indeterminate = false;
this.indeterminateChange.emit(this._indeterminate);
});
}
this._checked = !this._checked;
this._transitionCheckState(
this._checked ? TransitionCheckState.Checked : TransitionCheckState.Unchecked,
);
// Emit our custom change event if the native input emitted one.
// It is important to only emit it, if the native input triggered one, because
// we don't want to trigger a change event, when the `checked` variable changes for example.
this._emitChangeEvent();
} else if (
(this.disabled && this.disabledInteractive) ||
(!this.disabled && clickAction === 'noop')
) {
// Reset native input when clicked with noop. The native checkbox becomes checked after
// click, reset it to be align with `checked` value of `mat-checkbox`.
this._inputElement.nativeElement.checked = this.checked;
this._inputElement.nativeElement.indeterminate = this.indeterminate;
}
}
_onInteractionEvent(event: Event) {
// We always have to stop propagation on the change event.
// Otherwise the change event, from the input element, will bubble up and
// emit its event object to the `change` output.
event.stopPropagation();
}
_onBlur() {
// When a focused element becomes disabled, the browser *immediately* fires a blur event.
// Angular does not expect events to be raised during change detection, so any state change
// (such as a form control's 'ng-touched') will cause a changed-after-checked error.
// See https://github.com/angular/angular/issues/17793. To work around this, we defer
// telling the form control it has been touched until the next tick.
Promise.resolve().then(() => {
this._onTouched();
this._changeDetectorRef.markForCheck();
});
}
private _getAnimationClassForCheckStateTransition(
oldState: TransitionCheckState,
newState: TransitionCheckState,
): string {
// Don't transition if animations are disabled.
if (this._animationMode === 'NoopAnimations') {
return '';
}
switch (oldState) {
case TransitionCheckState.Init:
// Handle edge case where user interacts with checkbox that does not have [(ngModel)] or
// [checked] bound to it.
if (newState === TransitionCheckState.Checked) {
return this._animationClasses.uncheckedToChecked;
} else if (newState == TransitionCheckState.Indeterminate) {
return this._checked
? this._animationClasses.checkedToIndeterminate
: this._animationClasses.uncheckedToIndeterminate;
}
break;
case TransitionCheckState.Unchecked:
return newState === TransitionCheckState.Checked
? this._animationClasses.uncheckedToChecked
: this._animationClasses.uncheckedToIndeterminate;
case TransitionCheckState.Checked:
return newState === TransitionCheckState.Unchecked
? this._animationClasses.checkedToUnchecked
: this._animationClasses.checkedToIndeterminate;
case TransitionCheckState.Indeterminate:
return newState === TransitionCheckState.Checked
? this._animationClasses.indeterminateToChecked
: this._animationClasses.indeterminateToUnchecked;
}
return '';
}
/**
* Syncs the indeterminate value with the checkbox DOM node.
*
* We sync `indeterminate` directly on the DOM node, because in Ivy the check for whether a
* property is supported on an element boils down to `if (propName in element)`. Domino's
* HTMLInputElement doesn't have an `indeterminate` property so Ivy will warn during
* server-side rendering.
*/
private _syncIndeterminate(value: boolean) {
const nativeCheckbox = this._inputElement;
if (nativeCheckbox) {
nativeCheckbox.nativeElement.indeterminate = value;
}
}
_onInputClick() {
this._handleInputClick();
}
_onTouchTargetClick() {
this._handleInputClick();
if (!this.disabled) {
// Normally the input should be focused already, but if the click
// comes from the touch target, then we might have to focus it ourselves.
this._inputElement.nativeElement.focus();
}
}
/**
* Prevent click events that come from the `<label/>` element from bubbling. This prevents the
* click handler on the host from triggering twice when clicking on the `<label/>` element. After
* the click event on the `<label/>` propagates, the browsers dispatches click on the associated
* `<input/>`. By preventing clicks on the label by bubbling, we ensure only one click event
* bubbles when the label is clicked.
*/
_preventBubblingFromLabel(event: MouseEvent) {
if (!!event.target && this._labelElement.nativeElement.contains(event.target as HTMLElement)) {
event.stopPropagation();
}
}
} | {
"end_byte": 19067,
"start_byte": 11907,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox.ts"
} |
components/src/material/checkbox/_checkbox-theme.scss_0_6039 | @use '../core/style/sass-utils';
@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/checkbox' as tokens-mdc-checkbox;
@use '../core/tokens/m2/mat/checkbox' as tokens-mat-checkbox;
/// Outputs base theme styles (styles not dependent on the color, typography, or density settings)
/// for the mat-checkbox.
/// @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-checkbox.$prefix,
tokens-mdc-checkbox.get-unthemable-tokens()
);
@include token-utils.create-token-values(
tokens-mat-checkbox.$prefix,
tokens-mat-checkbox.get-unthemable-tokens()
);
}
}
}
/// Outputs color theme styles for the mat-checkbox.
/// @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 checkbox: primary, secondary, tertiary, or
/// error (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 token-utils.create-token-values(
tokens-mdc-checkbox.$prefix,
tokens-mdc-checkbox.get-color-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-checkbox.$prefix,
tokens-mat-checkbox.get-color-tokens($theme)
);
}
.mat-mdc-checkbox {
&.mat-primary {
@include token-utils.create-token-values(
tokens-mdc-checkbox.$prefix,
tokens-mdc-checkbox.get-color-tokens($theme, primary)
);
}
&.mat-warn {
@include token-utils.create-token-values(
tokens-mdc-checkbox.$prefix,
tokens-mdc-checkbox.get-color-tokens($theme, warn)
);
}
}
}
}
/// Outputs typography theme styles for the mat-checkbox.
/// @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-checkbox.$prefix,
tokens-mdc-checkbox.get-typography-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-checkbox.$prefix,
tokens-mat-checkbox.get-typography-tokens($theme)
);
}
}
}
/// Outputs density theme styles for the mat-checkbox.
/// @param {Map} $theme The theme to generate density styles for.
@mixin density($theme) {
$density-scale: inspection.get-theme-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-checkbox.$prefix,
tokens-mdc-checkbox.get-density-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-checkbox.$prefix,
tokens-mat-checkbox.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-checkbox.$prefix,
tokens: tokens-mat-checkbox.get-token-slots(),
),
(
namespace: tokens-mdc-checkbox.$prefix,
tokens: tokens-mdc-checkbox.get-token-slots(),
),
);
}
/// 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 checkbox: 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-checkbox') {
@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'
);
$mdc-checkbox-tokens: token-utils.get-tokens-for(
$tokens,
tokens-mdc-checkbox.$prefix,
$options...
);
// Don't pass $options here, since the mdc-checkbox doesn't support color options,
// only the mdc-checkbox does.
$mat-checkbox-tokens: token-utils.get-tokens-for($tokens, tokens-mat-checkbox.$prefix);
@include token-utils.create-token-values(tokens-mdc-checkbox.$prefix, $mdc-checkbox-tokens);
@include token-utils.create-token-values(tokens-mat-checkbox.$prefix, $mat-checkbox-tokens);
}
| {
"end_byte": 6039,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/_checkbox-theme.scss"
} |
components/src/material/checkbox/checkbox-required-validator.ts_0_1235 | /**
* @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, forwardRef, Provider} from '@angular/core';
import {CheckboxRequiredValidator, NG_VALIDATORS} from '@angular/forms';
/**
* @deprecated No longer used, `MatCheckbox` implements required validation directly.
* @breaking-change 19.0.0
*/
export const MAT_CHECKBOX_REQUIRED_VALIDATOR: Provider = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => MatCheckboxRequiredValidator),
multi: true,
};
/**
* Validator for Material checkbox's required attribute in template-driven checkbox.
* Current CheckboxRequiredValidator only work with `input type=checkbox` and does not
* work with `mat-checkbox`.
*
* @deprecated No longer used, `MatCheckbox` implements required validation directly.
* @breaking-change 19.0.0
*/
@Directive({
selector: `mat-checkbox[required][formControlName],
mat-checkbox[required][formControl], mat-checkbox[required][ngModel]`,
providers: [MAT_CHECKBOX_REQUIRED_VALIDATOR],
})
export class MatCheckboxRequiredValidator extends CheckboxRequiredValidator {}
| {
"end_byte": 1235,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox-required-validator.ts"
} |
components/src/material/checkbox/module.ts_0_827 | /**
* @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 {MatCheckbox} from './checkbox';
import {MatCheckboxRequiredValidator} from './checkbox-required-validator';
/**
* @deprecated No longer used, `MatCheckbox` implements required validation directly.
* @breaking-change 19.0.0
*/
@NgModule({
imports: [MatCheckboxRequiredValidator],
exports: [MatCheckboxRequiredValidator],
})
export class _MatCheckboxRequiredValidatorModule {}
@NgModule({
imports: [MatCheckbox, MatCommonModule],
exports: [MatCheckbox, MatCommonModule],
})
export class MatCheckboxModule {}
| {
"end_byte": 827,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/module.ts"
} |
components/src/material/checkbox/checkbox.scss_0_3689 | @use '../core/style/layout-common';
@use '../core/tokens/m2/mat/checkbox' as tokens-mat-checkbox;
@use '../core/tokens/token-utils';
@use './checkbox-common';
@include checkbox-common.checkbox-structure(true);
.mat-mdc-checkbox {
// The host node defaults to `display: inline`, we have to change it in order for margins to work.
display: inline-block;
// Avoids issues in some CSS grid layouts (see #25153).
position: relative;
// Disable the browser's tap highlight since we indicate state with the ripple instead.
-webkit-tap-highlight-color: transparent;
@include checkbox-common.checkbox-noop-animations;
// Clicking the label toggles the checkbox, but MDC does not include any styles that inform the
// user of this. Therefore we add the pointer cursor on top of MDC's styles.
label {
cursor: pointer;
}
.mat-internal-form-field {
@include token-utils.use-tokens(
tokens-mat-checkbox.$prefix,
tokens-mat-checkbox.get-token-slots()
) {
@include token-utils.create-token-slot(color, label-text-color);
@include token-utils.create-token-slot(font-family, label-text-font);
@include token-utils.create-token-slot(line-height, label-text-line-height);
@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(font-weight, label-text-weight);
}
}
&.mat-mdc-checkbox-disabled {
&.mat-mdc-checkbox-disabled-interactive {
pointer-events: auto;
input {
cursor: default;
}
}
label {
cursor: default;
@include token-utils.use-tokens(
tokens-mat-checkbox.$prefix,
tokens-mat-checkbox.get-token-slots()
) {
@include token-utils.create-token-slot(color, disabled-label-color);
}
}
}
// The MDC styles result in extra padding if the label is present but empty. To fix this we hide
// the label when it is empty.
label:empty {
display: none;
}
// Apply base styles to the MDC ripple when not hovered, focused, or pressed.
.mdc-checkbox__ripple {
opacity: 0;
}
}
.mat-mdc-checkbox .mat-mdc-checkbox-ripple,
.mdc-checkbox__ripple {
@include layout-common.fill();
// Usually the ripple radius would be specified through the MatRipple input, but
// since we dynamically adjust the size of the ripple container, we cannot use a
// fixed ripple radius.
border-radius: 50%;
pointer-events: none;
// Fixes the ripples not clipping to the border radius on Safari. Uses `:not(:empty)`
// in order to avoid creating extra layers when there aren't any ripples.
&:not(:empty) {
transform: translateZ(0);
}
}
.mat-mdc-checkbox-ripple .mat-ripple-element {
opacity: 0.1;
}
// Element used to provide a larger tap target for users on touch devices.
.mat-mdc-checkbox-touch-target {
position: absolute;
top: 50%;
left: 50%;
height: 48px;
width: 48px;
transform: translate(-50%, -50%);
@include token-utils.use-tokens(
tokens-mat-checkbox.$prefix,
tokens-mat-checkbox.get-token-slots()
) {
@include token-utils.create-token-slot(display, touch-target-display);
}
}
// Checkbox components have to set `border-radius: 50%` in order to support density scaling
// which will clip a square focus indicator so we have to turn it into a circle.
.mat-mdc-checkbox-ripple::before {
border-radius: 50%;
}
// For checkboxes render the focus indicator when we know
// the hidden input is focused (slightly different for each control).
.mdc-checkbox__native-control:focus ~ .mat-focus-indicator::before {
content: '';
}
| {
"end_byte": 3689,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox.scss"
} |
components/src/material/checkbox/checkbox.spec.ts_0_897 | import {dispatchFakeEvent} from '@angular/cdk/testing/private';
import {ChangeDetectionStrategy, Component, DebugElement, Type} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush, flushMicrotasks} 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_CHECKBOX_DEFAULT_OPTIONS,
MatCheckbox,
MatCheckboxChange,
MatCheckboxDefaultOptions,
MatCheckboxModule,
} from './index';
describe('MatCheckbox', () => {
let fixture: ComponentFixture<any>;
function createComponent<T>(componentType: Type<T>) {
TestBed.configureTestingModule({
imports: [MatCheckboxModule, FormsModule, ReactiveFormsModule, componentType],
});
return TestBed.createComponent<T>(componentType);
} | {
"end_byte": 897,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox.spec.ts"
} |
components/src/material/checkbox/checkbox.spec.ts_901_11045 | describe('basic behaviors', () => {
let checkboxDebugElement: DebugElement;
let checkboxNativeElement: HTMLElement;
let checkboxInstance: MatCheckbox;
let testComponent: SingleCheckbox;
let inputElement: HTMLInputElement;
let labelElement: HTMLLabelElement;
let checkboxElement: HTMLElement;
beforeEach(() => {
fixture = createComponent(SingleCheckbox);
fixture.detectChanges();
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
checkboxInstance = checkboxDebugElement.componentInstance;
testComponent = fixture.debugElement.componentInstance;
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
labelElement = <HTMLLabelElement>checkboxNativeElement.querySelector('label');
checkboxElement = <HTMLLabelElement>checkboxNativeElement.querySelector('.mdc-checkbox');
});
it('should add and remove the checked state', fakeAsync(() => {
expect(checkboxInstance.checked).toBe(false);
expect(inputElement.checked).toBe(false);
testComponent.isChecked = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxInstance.checked).toBe(true);
expect(inputElement.checked).toBe(true);
expect(inputElement.hasAttribute('aria-checked'))
.withContext('Expect aria-checked attribute to not be used')
.toBe(false);
testComponent.isChecked = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxInstance.checked).toBe(false);
expect(inputElement.checked).toBe(false);
}));
it('should hide the internal SVG', () => {
const svg = checkboxNativeElement.querySelector('svg')!;
expect(svg.getAttribute('aria-hidden')).toBe('true');
});
it('should toggle checkbox ripple disabledness correctly', fakeAsync(() => {
const rippleSelector = '.mat-ripple-element:not(.mat-checkbox-persistent-ripple)';
testComponent.isDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchFakeEvent(checkboxElement, 'mousedown');
dispatchFakeEvent(checkboxElement, 'mouseup');
checkboxElement.click();
expect(checkboxNativeElement.querySelectorAll(rippleSelector).length).toBe(0);
flush();
testComponent.isDisabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchFakeEvent(checkboxElement, 'mousedown');
dispatchFakeEvent(checkboxElement, 'mouseup');
checkboxElement.click();
expect(checkboxNativeElement.querySelectorAll(rippleSelector).length).toBe(1);
flush();
}));
it('should add and remove indeterminate state', fakeAsync(() => {
expect(inputElement.checked).toBe(false);
expect(inputElement.indeterminate).toBe(false);
testComponent.isIndeterminate = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(inputElement.checked).toBe(false);
expect(inputElement.indeterminate).toBe(true);
testComponent.isIndeterminate = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(inputElement.checked).toBe(false);
expect(inputElement.indeterminate).toBe(false);
}));
it('should set indeterminate to false when input clicked', fakeAsync(() => {
testComponent.isIndeterminate = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxInstance.indeterminate).toBe(true);
expect(inputElement.indeterminate).toBe(true);
expect(testComponent.isIndeterminate).toBe(true);
inputElement.click();
fixture.detectChanges();
// Flush the microtasks because the forms module updates the model state asynchronously.
flush();
// The checked property has been updated from the model and now the view needs
// to reflect the state change.
fixture.detectChanges();
expect(checkboxInstance.checked).toBe(true);
expect(inputElement.indeterminate).toBe(false);
expect(inputElement.checked).toBe(true);
expect(testComponent.isIndeterminate).toBe(false);
testComponent.isIndeterminate = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxInstance.indeterminate).toBe(true);
expect(inputElement.indeterminate).toBe(true);
expect(inputElement.checked).toBe(true);
expect(testComponent.isIndeterminate).toBe(true);
inputElement.click();
fixture.detectChanges();
// Flush the microtasks because the forms module updates the model state asynchronously.
flush();
// The checked property has been updated from the model and now the view needs
// to reflect the state change.
fixture.detectChanges();
expect(checkboxInstance.checked).toBe(false);
expect(inputElement.indeterminate).toBe(false);
expect(inputElement.checked).toBe(false);
expect(testComponent.isIndeterminate).toBe(false);
}));
it('should not set indeterminate to false when checked is set programmatically', fakeAsync(() => {
testComponent.isIndeterminate = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(checkboxInstance.indeterminate).toBe(true);
expect(inputElement.indeterminate).toBe(true);
expect(testComponent.isIndeterminate).toBe(true);
testComponent.isChecked = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxInstance.checked).toBe(true);
expect(inputElement.indeterminate).toBe(true);
expect(inputElement.checked).toBe(true);
expect(testComponent.isIndeterminate).toBe(true);
testComponent.isChecked = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxInstance.checked).toBe(false);
expect(inputElement.indeterminate).toBe(true);
expect(inputElement.checked).toBe(false);
expect(testComponent.isIndeterminate).toBe(true);
}));
it('should change native element checked when check programmatically', () => {
expect(inputElement.checked).toBe(false);
checkboxInstance.checked = true;
fixture.detectChanges();
expect(inputElement.checked).toBe(true);
});
it('should toggle checked state on click', fakeAsync(() => {
expect(checkboxInstance.checked).toBe(false);
labelElement.click();
fixture.detectChanges();
flush();
expect(checkboxInstance.checked).toBe(true);
labelElement.click();
fixture.detectChanges();
flush();
expect(checkboxInstance.checked).toBe(false);
}));
it('should change from indeterminate to checked on click', fakeAsync(() => {
testComponent.isChecked = false;
testComponent.isIndeterminate = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxInstance.checked).toBe(false);
expect(checkboxInstance.indeterminate).toBe(true);
inputElement.click();
fixture.detectChanges();
flush();
expect(checkboxInstance.checked).toBe(true);
expect(checkboxInstance.indeterminate).toBe(false);
inputElement.click();
fixture.detectChanges();
flush();
expect(checkboxInstance.checked).toBe(false);
expect(checkboxInstance.indeterminate).toBe(false);
}));
it('should add and remove disabled state', fakeAsync(() => {
expect(checkboxInstance.disabled).toBe(false);
expect(inputElement.tabIndex).toBe(0);
expect(inputElement.disabled).toBe(false);
testComponent.isDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxInstance.disabled).toBe(true);
expect(inputElement.disabled).toBe(true);
testComponent.isDisabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxInstance.disabled).toBe(false);
expect(inputElement.tabIndex).toBe(0);
expect(inputElement.disabled).toBe(false);
}));
it('should not toggle `checked` state upon interation while disabled', () => {
testComponent.isDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkboxNativeElement.click();
expect(checkboxInstance.checked).toBe(false);
});
it('should overwrite indeterminate state when clicked', fakeAsync(() => {
testComponent.isIndeterminate = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
inputElement.click();
fixture.detectChanges();
// Flush the microtasks because the indeterminate state will be updated in the next tick.
flush();
expect(checkboxInstance.checked).toBe(true);
expect(checkboxInstance.indeterminate).toBe(false);
}));
it('should preserve the user-provided id', fakeAsync(() => {
expect(checkboxNativeElement.id).toBe('simple-check');
expect(inputElement.id).toBe('simple-check-input');
}));
it('should generate a unique id for the checkbox input if no id is set', fakeAsync(() => {
testComponent.checkboxId = null;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxInstance.inputId).toMatch(/mat-mdc-checkbox-\d+/);
expect(inputElement.id).toBe(checkboxInstance.inputId);
}));
it('should project the checkbox content into the label element', fakeAsync(() => {
let label = <HTMLLabelElement>checkboxNativeElement.querySelector('label');
expect(label.textContent!.trim()).toBe('Simple checkbox');
}));
it('should make the host element a tab stop', fakeAsync(() => {
expect(inputElement.tabIndex).toBe(0);
})); | {
"end_byte": 11045,
"start_byte": 901,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox.spec.ts"
} |
components/src/material/checkbox/checkbox.spec.ts_11051_20731 | it('should add a css class to position the label before the checkbox', fakeAsync(() => {
testComponent.labelPos = 'before';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxNativeElement.querySelector('.mdc-form-field')!.classList).toContain(
'mdc-form-field--align-end',
);
}));
it('should trigger the click once when clicking on the <input/>', fakeAsync(() => {
spyOn(testComponent, 'onCheckboxClick');
expect(inputElement.checked).toBe(false);
inputElement.click();
fixture.detectChanges();
flush();
expect(inputElement.checked).toBe(true);
expect(testComponent.onCheckboxClick).toHaveBeenCalledTimes(1);
}));
it('should trigger the click event once when clicking on the label', fakeAsync(() => {
// By default, when clicking on a label element, a generated click will be dispatched
// on the associated input element.
// Since we're using a label element and a visual hidden input, this behavior can led
// to an issue, where the click events on the checkbox are getting executed twice.
spyOn(testComponent, 'onCheckboxClick');
expect(inputElement.checked).toBe(false);
labelElement.click();
fixture.detectChanges();
flush();
expect(inputElement.checked).toBe(true);
expect(testComponent.onCheckboxClick).toHaveBeenCalledTimes(1);
}));
it('should trigger a change event when the native input does', fakeAsync(() => {
spyOn(testComponent, 'onCheckboxChange');
expect(inputElement.checked).toBe(false);
labelElement.click();
fixture.detectChanges();
flush();
expect(inputElement.checked).toBe(true);
expect(testComponent.onCheckboxChange).toHaveBeenCalledTimes(1);
}));
it('should not trigger the change event by changing the native value', fakeAsync(() => {
spyOn(testComponent, 'onCheckboxChange');
expect(inputElement.checked).toBe(false);
testComponent.isChecked = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(inputElement.checked).toBe(true);
expect(testComponent.onCheckboxChange).not.toHaveBeenCalled();
}));
it('should keep the view in sync if the `checked` value changes inside the `change` listener', fakeAsync(() => {
spyOn(testComponent, 'onCheckboxChange').and.callFake(() => {
checkboxInstance.checked = false;
});
labelElement.click();
fixture.detectChanges();
flush();
expect(inputElement.checked).toBe(false);
}));
it('should forward the required attribute', fakeAsync(() => {
testComponent.isRequired = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(inputElement.required).toBe(true);
testComponent.isRequired = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(inputElement.required).toBe(false);
}));
it('should focus on underlying input element when focus() is called', fakeAsync(() => {
expect(document.activeElement).not.toBe(inputElement);
checkboxInstance.focus();
fixture.detectChanges();
expect(document.activeElement).toBe(inputElement);
}));
it('should focus underlying input element when the touch target is clicked', fakeAsync(() => {
const touchTarget = checkboxElement.querySelector(
'.mat-mdc-checkbox-touch-target',
) as HTMLElement;
expect(document.activeElement).not.toBe(inputElement);
touchTarget.click();
fixture.detectChanges();
flush();
expect(document.activeElement).toBe(inputElement);
}));
it('should forward the value to input element', fakeAsync(() => {
testComponent.checkboxValue = 'basic_checkbox';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(inputElement.value).toBe('basic_checkbox');
}));
it('should remove the SVG checkmark from the tab order', fakeAsync(() => {
expect(checkboxNativeElement.querySelector('svg')!.getAttribute('focusable')).toBe('false');
}));
it('should be able to mark a checkbox as disabled while keeping it interactive', fakeAsync(() => {
testComponent.isDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxNativeElement.classList).not.toContain(
'mat-mdc-checkbox-disabled-interactive',
);
expect(inputElement.hasAttribute('aria-disabled')).toBe(false);
expect(inputElement.tabIndex).toBe(-1);
expect(inputElement.disabled).toBe(true);
testComponent.disabledInteractive = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxNativeElement.classList).toContain('mat-mdc-checkbox-disabled-interactive');
expect(inputElement.getAttribute('aria-disabled')).toBe('true');
expect(inputElement.tabIndex).toBe(0);
expect(inputElement.disabled).toBe(false);
}));
it('should not change the checked state if disabled and interactive', fakeAsync(() => {
testComponent.isDisabled = testComponent.disabledInteractive = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(inputElement.checked).toBe(false);
inputElement.click();
fixture.detectChanges();
expect(inputElement.checked).toBe(false);
}));
describe('ripple elements', () => {
it('should show ripples on label mousedown', fakeAsync(() => {
const rippleSelector = '.mat-ripple-element:not(.mat-checkbox-persistent-ripple)';
expect(checkboxNativeElement.querySelector(rippleSelector)).toBeFalsy();
dispatchFakeEvent(checkboxElement, 'mousedown');
dispatchFakeEvent(checkboxElement, 'mouseup');
checkboxElement.click();
expect(checkboxNativeElement.querySelectorAll(rippleSelector).length).toBe(1);
flush();
}));
it('should not show ripples when disabled', fakeAsync(() => {
const rippleSelector = '.mat-ripple-element:not(.mat-checkbox-persistent-ripple)';
testComponent.isDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchFakeEvent(checkboxElement, 'mousedown');
dispatchFakeEvent(checkboxElement, 'mouseup');
checkboxElement.click();
expect(checkboxNativeElement.querySelectorAll(rippleSelector).length).toBe(0);
flush();
testComponent.isDisabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchFakeEvent(checkboxElement, 'mousedown');
dispatchFakeEvent(checkboxElement, 'mouseup');
checkboxElement.click();
expect(checkboxNativeElement.querySelectorAll(rippleSelector).length).toBe(1);
flush();
}));
it('should remove ripple if matRippleDisabled input is set', fakeAsync(() => {
const rippleSelector = '.mat-ripple-element:not(.mat-checkbox-persistent-ripple)';
testComponent.disableRipple = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchFakeEvent(checkboxElement, 'mousedown');
dispatchFakeEvent(checkboxElement, 'mouseup');
checkboxElement.click();
expect(checkboxNativeElement.querySelectorAll(rippleSelector).length).toBe(0);
flush();
testComponent.disableRipple = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchFakeEvent(checkboxElement, 'mousedown');
dispatchFakeEvent(checkboxElement, 'mouseup');
checkboxElement.click();
expect(checkboxNativeElement.querySelectorAll(rippleSelector).length).toBe(1);
flush();
}));
});
describe('color behaviour', () => {
it('should apply class based on color attribute', fakeAsync(() => {
testComponent.checkboxColor = 'primary';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxNativeElement.classList.contains('mat-primary')).toBe(true);
testComponent.checkboxColor = 'accent';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxNativeElement.classList.contains('mat-accent')).toBe(true);
}));
it('should not clear previous defined classes', fakeAsync(() => {
checkboxNativeElement.classList.add('custom-class');
testComponent.checkboxColor = 'primary';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxNativeElement.classList.contains('mat-primary')).toBe(true);
expect(checkboxNativeElement.classList.contains('custom-class')).toBe(true);
testComponent.checkboxColor = 'accent';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxNativeElement.classList.contains('mat-primary')).toBe(false);
expect(checkboxNativeElement.classList.contains('mat-accent')).toBe(true);
expect(checkboxNativeElement.classList.contains('custom-class')).toBe(true);
}));
it('should default to accent if no color is passed in', fakeAsync(() => {
testComponent.checkboxColor = undefined;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(checkboxNativeElement.classList).toContain('mat-accent');
}));
}); | {
"end_byte": 20731,
"start_byte": 11051,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox.spec.ts"
} |
components/src/material/checkbox/checkbox.spec.ts_20737_29933 | describe(`when MAT_CHECKBOX_CLICK_ACTION is 'check'`, () => {
beforeEach(() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
imports: [MatCheckboxModule, FormsModule, ReactiveFormsModule, SingleCheckbox],
providers: [{provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: {clickAction: 'check'}}],
});
fixture = createComponent(SingleCheckbox);
fixture.detectChanges();
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
checkboxInstance = checkboxDebugElement.componentInstance;
testComponent = fixture.debugElement.componentInstance;
inputElement = checkboxNativeElement.querySelector('input') as HTMLInputElement;
labelElement = checkboxNativeElement.querySelector('label') as HTMLLabelElement;
});
it('should not set `indeterminate` to false on click if check is set', fakeAsync(() => {
testComponent.isIndeterminate = true;
fixture.changeDetectorRef.markForCheck();
inputElement.click();
fixture.detectChanges();
flush();
expect(inputElement.checked).toBe(true);
expect(inputElement.indeterminate).toBe(true);
}));
});
describe(`when MAT_CHECKBOX_CLICK_ACTION is 'noop'`, () => {
beforeEach(() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
imports: [MatCheckboxModule, FormsModule, ReactiveFormsModule, SingleCheckbox],
providers: [{provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: {clickAction: 'noop'}}],
});
fixture = createComponent(SingleCheckbox);
fixture.detectChanges();
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
checkboxInstance = checkboxDebugElement.componentInstance;
testComponent = fixture.debugElement.componentInstance;
inputElement = checkboxNativeElement.querySelector('input') as HTMLInputElement;
labelElement = checkboxNativeElement.querySelector('label') as HTMLLabelElement;
});
it('should not change `indeterminate` on click if noop is set', fakeAsync(() => {
testComponent.isIndeterminate = true;
fixture.changeDetectorRef.markForCheck();
inputElement.click();
fixture.detectChanges();
flush();
expect(inputElement.checked).toBe(false);
expect(inputElement.indeterminate).toBe(true);
}));
it(`should not change 'checked' or 'indeterminate' on click if noop is set`, fakeAsync(() => {
testComponent.isChecked = true;
testComponent.isIndeterminate = true;
fixture.changeDetectorRef.markForCheck();
inputElement.click();
fixture.detectChanges();
flush();
expect(inputElement.checked).toBe(true);
expect(inputElement.indeterminate).toBe(true);
testComponent.isChecked = false;
fixture.changeDetectorRef.markForCheck();
inputElement.click();
fixture.detectChanges();
flush();
expect(inputElement.checked).toBe(false);
expect(inputElement.indeterminate)
.withContext('indeterminate should not change')
.toBe(true);
}));
});
it('should have a focus indicator', () => {
const checkboxRippleNativeElement = checkboxNativeElement.querySelector(
'.mat-mdc-checkbox-ripple',
)!;
expect(checkboxRippleNativeElement.classList.contains('mat-focus-indicator')).toBe(true);
});
});
describe('with change event and no initial value', () => {
let checkboxDebugElement: DebugElement;
let checkboxNativeElement: HTMLElement;
let checkboxInstance: MatCheckbox;
let testComponent: CheckboxWithChangeEvent;
let inputElement: HTMLInputElement;
let labelElement: HTMLLabelElement;
beforeEach(() => {
fixture = createComponent(CheckboxWithChangeEvent);
fixture.detectChanges();
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
checkboxInstance = checkboxDebugElement.componentInstance;
testComponent = fixture.debugElement.componentInstance;
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
labelElement = <HTMLLabelElement>checkboxNativeElement.querySelector('label');
});
it('should emit the event to the change observable', fakeAsync(() => {
let changeSpy = jasmine.createSpy('onChangeObservable');
checkboxInstance.change.subscribe(changeSpy);
fixture.detectChanges();
expect(changeSpy).not.toHaveBeenCalled();
// When changing the native `checked` property the checkbox will not fire a change event,
// because the element is not focused and it's not the native behavior of the input
// element.
labelElement.click();
fixture.detectChanges();
flush();
expect(changeSpy).toHaveBeenCalledTimes(1);
}));
it('should not emit a DOM event to the change output', fakeAsync(() => {
fixture.detectChanges();
expect(testComponent.lastEvent).toBeUndefined();
// Trigger the click on the inputElement, because the input will probably
// emit a DOM event to the change output.
inputElement.click();
fixture.detectChanges();
flush();
// We're checking the arguments type / emitted value to be a boolean, because sometimes the
// emitted value can be a DOM Event, which is not valid.
// See angular/angular#4059
expect(testComponent.lastEvent.checked).toBe(true);
}));
});
describe('aria handling', () => {
it('should use the provided aria-label', fakeAsync(() => {
fixture = createComponent(CheckboxWithAriaLabel);
const checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
const checkboxNativeElement = checkboxDebugElement.nativeElement;
const inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
fixture.detectChanges();
expect(inputElement.getAttribute('aria-label')).toBe('Super effective');
}));
it('should not set the aria-label attribute if no value is provided', fakeAsync(() => {
fixture = createComponent(SingleCheckbox);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('input').hasAttribute('aria-label')).toBe(false);
}));
it('should use the provided aria-labelledby', fakeAsync(() => {
fixture = createComponent(CheckboxWithAriaLabelledby);
const checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
const checkboxNativeElement = checkboxDebugElement.nativeElement;
const inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
fixture.detectChanges();
expect(inputElement.getAttribute('aria-labelledby')).toBe('some-id');
}));
it('should not assign aria-labelledby if none is provided', fakeAsync(() => {
fixture = createComponent(SingleCheckbox);
const checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
const checkboxNativeElement = checkboxDebugElement.nativeElement;
const inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
fixture.detectChanges();
expect(inputElement.getAttribute('aria-labelledby')).toBe(null);
}));
it('should clear the static aria attributes from the host node', () => {
fixture = createComponent(CheckboxWithStaticAriaAttributes);
const checkbox = fixture.debugElement.query(By.directive(MatCheckbox))!.nativeElement;
fixture.detectChanges();
expect(checkbox.hasAttribute('aria')).toBe(false);
expect(checkbox.hasAttribute('aria-labelledby')).toBe(false);
});
});
describe('with provided aria-describedby ', () => {
let checkboxDebugElement: DebugElement;
let checkboxNativeElement: HTMLElement;
let inputElement: HTMLInputElement;
it('should use the provided aria-describedby', () => {
fixture = createComponent(CheckboxWithAriaDescribedby);
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
fixture.detectChanges();
expect(inputElement.getAttribute('aria-describedby')).toBe('some-id');
});
it('should not assign aria-describedby if none is provided', () => {
fixture = createComponent(SingleCheckbox);
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
fixture.detectChanges();
expect(inputElement.getAttribute('aria-describedby')).toBe(null);
});
}); | {
"end_byte": 29933,
"start_byte": 20737,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox.spec.ts"
} |
components/src/material/checkbox/checkbox.spec.ts_29937_36478 | describe('with provided aria-expanded', () => {
let checkboxDebugElement: DebugElement;
let checkboxNativeElement: HTMLElement;
let inputElement: HTMLInputElement;
it('should use the provided postive aria-expanded', () => {
fixture = createComponent(CheckboxWithPositiveAriaExpanded);
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
fixture.detectChanges();
expect(inputElement.getAttribute('aria-expanded')).toBe('true');
});
it('should use the provided negative aria-expanded', () => {
fixture = createComponent(CheckboxWithNegativeAriaExpanded);
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
fixture.detectChanges();
expect(inputElement.getAttribute('aria-expanded')).toBe('false');
});
it('should not assign aria-expanded if none is provided', () => {
fixture = createComponent(SingleCheckbox);
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
fixture.detectChanges();
expect(inputElement.getAttribute('aria-expanded')).toBe(null);
});
});
describe('with provided aria-controls', () => {
let checkboxDebugElement: DebugElement;
let checkboxNativeElement: HTMLElement;
let inputElement: HTMLInputElement;
it('should use the provided aria-controls', () => {
fixture = createComponent(CheckboxWithAriaControls);
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
fixture.detectChanges();
expect(inputElement.getAttribute('aria-controls')).toBe('some-id');
});
it('should not assign aria-controls if none is provided', () => {
fixture = createComponent(SingleCheckbox);
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
fixture.detectChanges();
expect(inputElement.getAttribute('aria-controls')).toBe(null);
});
});
describe('with provided aria-owns', () => {
let checkboxDebugElement: DebugElement;
let checkboxNativeElement: HTMLElement;
let inputElement: HTMLInputElement;
it('should use the provided aria-owns', () => {
fixture = createComponent(CheckboxWithAriaOwns);
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
fixture.detectChanges();
expect(inputElement.getAttribute('aria-owns')).toBe('some-id');
});
it('should not assign aria-owns if none is provided', () => {
fixture = createComponent(SingleCheckbox);
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
fixture.detectChanges();
expect(inputElement.getAttribute('aria-owns')).toBe(null);
});
});
describe('with provided tabIndex', () => {
let checkboxDebugElement: DebugElement;
let checkboxNativeElement: HTMLElement;
let testComponent: CheckboxWithTabIndex;
let inputElement: HTMLInputElement;
beforeEach(() => {
fixture = createComponent(CheckboxWithTabIndex);
fixture.detectChanges();
testComponent = fixture.debugElement.componentInstance;
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
});
it('should preserve any given tabIndex', fakeAsync(() => {
expect(inputElement.tabIndex).toBe(7);
}));
it('should preserve given tabIndex when the checkbox is disabled then enabled', fakeAsync(() => {
testComponent.isDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
testComponent.customTabIndex = 13;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
testComponent.isDisabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(inputElement.tabIndex).toBe(13);
}));
});
describe('with native tabindex attribute', () => {
it('should properly detect native tabindex attribute', fakeAsync(() => {
fixture = createComponent(CheckboxWithTabindexAttr);
fixture.detectChanges();
const checkbox = fixture.debugElement.query(By.directive(MatCheckbox))!
.componentInstance as MatCheckbox;
expect(checkbox.tabIndex)
.withContext('Expected tabIndex property to have been set based on the native attribute')
.toBe(5);
}));
it('should clear the tabindex attribute from the host element', fakeAsync(() => {
fixture = createComponent(CheckboxWithTabindexAttr);
fixture.detectChanges();
const checkbox = fixture.debugElement.query(By.directive(MatCheckbox))!.nativeElement;
expect(checkbox.getAttribute('tabindex')).toBeFalsy();
}));
});
describe('with multiple checkboxes', () => {
beforeEach(() => {
fixture = createComponent(MultipleCheckboxes);
fixture.detectChanges();
});
it('should assign a unique id to each checkbox', fakeAsync(() => {
let [firstId, secondId] = fixture.debugElement
.queryAll(By.directive(MatCheckbox))
.map(debugElement => debugElement.nativeElement.querySelector('input').id);
expect(firstId).toMatch(/mat-mdc-checkbox-\d+-input/);
expect(secondId).toMatch(/mat-mdc-checkbox-\d+-input/);
expect(firstId).not.toEqual(secondId);
}));
}); | {
"end_byte": 36478,
"start_byte": 29937,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox.spec.ts"
} |
components/src/material/checkbox/checkbox.spec.ts_36482_45562 | describe('with ngModel', () => {
let checkboxDebugElement: DebugElement;
let checkboxNativeElement: HTMLElement;
let checkboxInstance: MatCheckbox;
let inputElement: HTMLInputElement;
let ngModel: NgModel;
beforeEach(() => {
fixture = createComponent(CheckboxWithNgModel);
fixture.componentInstance.isRequired = false;
fixture.detectChanges();
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
checkboxInstance = checkboxDebugElement.componentInstance;
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
ngModel = checkboxDebugElement.injector.get<NgModel>(NgModel);
});
it('should be pristine, untouched, and valid initially', fakeAsync(() => {
expect(ngModel.valid).toBe(true);
expect(ngModel.pristine).toBe(true);
expect(ngModel.touched).toBe(false);
}));
it('should have correct control states after interaction', fakeAsync(() => {
inputElement.click();
fixture.detectChanges();
// Flush the timeout that is being created whenever a `click` event has been fired by
// the underlying input.
flush();
// After the value change through interaction, the control should be dirty, but remain
// untouched as long as the focus is still on the underlying input.
expect(ngModel.pristine).toBe(false);
expect(ngModel.touched).toBe(false);
// If the input element loses focus, the control should remain dirty but should
// also turn touched.
dispatchFakeEvent(inputElement, 'blur');
fixture.detectChanges();
flush();
expect(ngModel.pristine).toBe(false);
expect(ngModel.touched).toBe(true);
}));
it('should mark the element as touched on blur when inside an OnPush parent', fakeAsync(() => {
fixture.destroy();
TestBed.resetTestingModule();
fixture = createComponent(CheckboxWithNgModelAndOnPush);
fixture.detectChanges();
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
checkboxInstance = checkboxDebugElement.componentInstance;
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
ngModel = checkboxDebugElement.injector.get<NgModel>(NgModel);
inputElement.click();
fixture.detectChanges();
flush();
expect(checkboxNativeElement.classList).not.toContain('ng-touched');
dispatchFakeEvent(inputElement, 'blur');
fixture.detectChanges();
flushMicrotasks();
fixture.detectChanges();
expect(checkboxNativeElement.classList).toContain('ng-touched');
}));
it('should not throw an error when disabling while focused', fakeAsync(() => {
expect(() => {
// Focus the input element because after disabling, the `blur` event should automatically
// fire and not result in a changed after checked exception. Related: #12323
inputElement.focus();
fixture.componentInstance.isDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
}).not.toThrow();
}));
it('should toggle checked state on click', fakeAsync(() => {
expect(checkboxInstance.checked).toBe(false);
inputElement.click();
fixture.detectChanges();
flush();
expect(checkboxInstance.checked).toBe(true);
inputElement.click();
fixture.detectChanges();
flush();
expect(checkboxInstance.checked).toBe(false);
}));
it('should validate with RequiredTrue validator', fakeAsync(() => {
fixture.componentInstance.isRequired = true;
inputElement.click();
fixture.detectChanges();
flush();
expect(checkboxInstance.checked).toBe(true);
expect(ngModel.valid).toBe(true);
inputElement.click();
fixture.detectChanges();
flush();
expect(checkboxInstance.checked).toBe(false);
expect(ngModel.valid).toBe(false);
}));
it('should update the ngModel value when using the `toggle` method', fakeAsync(() => {
const checkbox = fixture.debugElement.query(By.directive(MatCheckbox)).componentInstance;
expect(fixture.componentInstance.isGood).toBe(false);
checkbox.toggle();
fixture.detectChanges();
expect(fixture.componentInstance.isGood).toBe(true);
}));
});
describe('with name attribute', () => {
beforeEach(() => {
fixture = createComponent(CheckboxWithNameAttribute);
fixture.detectChanges();
});
it('should forward name value to input element', fakeAsync(() => {
let checkboxElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
let inputElement = <HTMLInputElement>checkboxElement.nativeElement.querySelector('input');
expect(inputElement.getAttribute('name')).toBe('test-name');
}));
});
describe('with form control', () => {
let checkboxDebugElement: DebugElement;
let checkboxInstance: MatCheckbox;
let testComponent: CheckboxWithFormControl;
let inputElement: HTMLInputElement;
beforeEach(() => {
fixture = createComponent(CheckboxWithFormControl);
fixture.detectChanges();
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxInstance = checkboxDebugElement.componentInstance;
testComponent = fixture.debugElement.componentInstance;
inputElement = <HTMLInputElement>checkboxDebugElement.nativeElement.querySelector('input');
});
it('should toggle the disabled state', fakeAsync(() => {
expect(checkboxInstance.disabled).toBe(false);
testComponent.formControl.disable();
fixture.detectChanges();
expect(checkboxInstance.disabled).toBe(true);
expect(inputElement.disabled).toBe(true);
testComponent.formControl.enable();
fixture.detectChanges();
expect(checkboxInstance.disabled).toBe(false);
expect(inputElement.disabled).toBe(false);
}));
});
describe('without label', () => {
let checkboxInnerContainer: HTMLElement;
beforeEach(() => {
fixture = createComponent(CheckboxWithoutLabel);
const checkboxDebugEl = fixture.debugElement.query(By.directive(MatCheckbox))!;
checkboxInnerContainer = checkboxDebugEl.query(By.css('.mdc-form-field'))!.nativeElement;
});
it('should not add the "name" attribute if it is not passed in', fakeAsync(() => {
fixture.detectChanges();
expect(checkboxInnerContainer.querySelector('input')!.hasAttribute('name')).toBe(false);
}));
it('should not add the "value" attribute if it is not passed in', fakeAsync(() => {
fixture.detectChanges();
expect(checkboxInnerContainer.querySelector('input')!.hasAttribute('value')).toBe(false);
}));
});
});
describe('MatCheckboxDefaultOptions', () => {
describe('when MAT_CHECKBOX_DEFAULT_OPTIONS overridden', () => {
function configure(defaults: MatCheckboxDefaultOptions) {
TestBed.configureTestingModule({
imports: [MatCheckboxModule, FormsModule, SingleCheckbox, SingleCheckbox],
providers: [{provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: defaults}],
});
}
it('should override default color in component', () => {
configure({color: 'primary'});
const fixture: ComponentFixture<SingleCheckbox> = TestBed.createComponent(SingleCheckbox);
fixture.detectChanges();
const checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
expect(checkboxDebugElement.nativeElement.classList).toContain('mat-primary');
});
it('should not override explicit input bindings', () => {
configure({color: 'primary'});
const fixture: ComponentFixture<SingleCheckbox> = TestBed.createComponent(SingleCheckbox);
fixture.componentInstance.checkboxColor = 'warn';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
expect(checkboxDebugElement.nativeElement.classList).not.toContain('mat-primary');
expect(checkboxDebugElement.nativeElement.classList).toContain('mat-warn');
expect(checkboxDebugElement.nativeElement.classList).toContain('mat-warn');
});
it('should default to accent if config does not specify color', () => {
configure({clickAction: 'noop'});
const fixture: ComponentFixture<SingleCheckbox> = TestBed.createComponent(SingleCheckbox);
fixture.componentInstance.checkboxColor = undefined;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!;
expect(checkboxDebugElement.nativeElement.classList).toContain('mat-accent');
});
});
});
/** Simple component for testing a single checkbox. */ | {
"end_byte": 45562,
"start_byte": 36482,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox.spec.ts"
} |
components/src/material/checkbox/checkbox.spec.ts_45563_50945 | @Component({
template: `
<div (click)="parentElementClicked = true" (keyup)="parentElementKeyedUp = true" (click)="onCheckboxClick($event)">
<mat-checkbox
[id]="checkboxId"
[required]="isRequired"
[labelPosition]="labelPos"
[checked]="isChecked"
[(indeterminate)]="isIndeterminate"
[disabled]="isDisabled"
[color]="checkboxColor"
[disableRipple]="disableRipple"
[value]="checkboxValue"
[disabledInteractive]="disabledInteractive"
(change)="onCheckboxChange($event)">
Simple checkbox
</mat-checkbox>
</div>`,
standalone: true,
imports: [MatCheckbox],
})
class SingleCheckbox {
labelPos: 'before' | 'after' = 'after';
isChecked = false;
isRequired = false;
isIndeterminate = false;
isDisabled = false;
disableRipple = false;
parentElementClicked = false;
parentElementKeyedUp = false;
disabledInteractive = false;
checkboxId: string | null = 'simple-check';
checkboxColor: ThemePalette = 'primary';
checkboxValue: string = 'single_checkbox';
onCheckboxClick: (event?: Event) => void = () => {};
onCheckboxChange: (event?: MatCheckboxChange) => void = () => {};
}
/** Simple component for testing an MatCheckbox with required ngModel. */
@Component({
template: `<mat-checkbox [required]="isRequired" [(ngModel)]="isGood"
[disabled]="isDisabled">Be good</mat-checkbox>`,
standalone: true,
imports: [MatCheckbox, FormsModule],
})
class CheckboxWithNgModel {
isGood = false;
isRequired = true;
isDisabled = false;
}
@Component({
template: `<mat-checkbox [required]="isRequired" [(ngModel)]="isGood">Be good</mat-checkbox>`,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [MatCheckbox, FormsModule],
})
class CheckboxWithNgModelAndOnPush extends CheckboxWithNgModel {}
/** Simple test component with multiple checkboxes. */
@Component({
template: `
<mat-checkbox>Option 1</mat-checkbox>
<mat-checkbox>Option 2</mat-checkbox>
`,
standalone: true,
imports: [MatCheckbox],
})
class MultipleCheckboxes {}
/** Simple test component with tabIndex */
@Component({
template: `
<mat-checkbox
[tabIndex]="customTabIndex"
[disabled]="isDisabled">
</mat-checkbox>`,
standalone: true,
imports: [MatCheckbox],
})
class CheckboxWithTabIndex {
customTabIndex: number = 7;
isDisabled: boolean = false;
}
/** Simple test component with an aria-label set. */
@Component({
template: `<mat-checkbox aria-label="Super effective"></mat-checkbox>`,
standalone: true,
imports: [MatCheckbox],
})
class CheckboxWithAriaLabel {}
/** Simple test component with an aria-label set. */
@Component({
template: `<mat-checkbox aria-labelledby="some-id"></mat-checkbox>`,
standalone: true,
imports: [MatCheckbox],
})
class CheckboxWithAriaLabelledby {}
/** Simple test component with an aria-describedby set. */
@Component({
template: `<mat-checkbox aria-describedby="some-id"></mat-checkbox>`,
standalone: true,
imports: [MatCheckbox],
})
class CheckboxWithAriaDescribedby {}
/** Simple test component with an aria-expanded set with true. */
@Component({
template: `<mat-checkbox aria-expanded="true"></mat-checkbox>`,
standalone: true,
imports: [MatCheckbox],
})
class CheckboxWithPositiveAriaExpanded {}
/** Simple test component with an aria-expanded set with false. */
@Component({
template: `<mat-checkbox aria-expanded="false"></mat-checkbox>`,
standalone: true,
imports: [MatCheckbox],
})
class CheckboxWithNegativeAriaExpanded {}
/** Simple test component with an aria-controls set. */
@Component({
template: `<mat-checkbox aria-controls="some-id"></mat-checkbox>`,
standalone: true,
imports: [MatCheckbox],
})
class CheckboxWithAriaControls {}
/** Simple test component with an aria-owns set. */
@Component({
template: `<mat-checkbox aria-owns="some-id"></mat-checkbox>`,
standalone: true,
imports: [MatCheckbox],
})
class CheckboxWithAriaOwns {}
/** Simple test component with name attribute */
@Component({
template: `<mat-checkbox name="test-name"></mat-checkbox>`,
standalone: true,
imports: [MatCheckbox],
})
class CheckboxWithNameAttribute {}
/** Simple test component with change event */
@Component({
template: `<mat-checkbox (change)="lastEvent = $event"></mat-checkbox>`,
standalone: true,
imports: [MatCheckbox],
})
class CheckboxWithChangeEvent {
lastEvent: MatCheckboxChange;
}
/** Test component with reactive forms */
@Component({
template: `<mat-checkbox [formControl]="formControl"></mat-checkbox>`,
standalone: true,
imports: [MatCheckbox, ReactiveFormsModule],
})
class CheckboxWithFormControl {
formControl = new FormControl(false);
}
/** Test component without label */
@Component({
template: `<mat-checkbox>{{ label }}</mat-checkbox>`,
standalone: true,
imports: [MatCheckbox],
})
class CheckboxWithoutLabel {
label: string;
}
/** Test component with the native tabindex attribute. */
@Component({
template: `<mat-checkbox tabindex="5"></mat-checkbox>`,
standalone: true,
imports: [MatCheckbox],
})
class CheckboxWithTabindexAttr {}
@Component({
template: `<mat-checkbox aria-label="Checkbox" aria-labelledby="something"></mat-checkbox>`,
standalone: true,
imports: [MatCheckbox],
})
class CheckboxWithStaticAriaAttributes {} | {
"end_byte": 50945,
"start_byte": 45563,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox.spec.ts"
} |
components/src/material/checkbox/public-api.ts_0_340 | /**
* @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 './checkbox';
export * from './checkbox-config';
export * from './module';
export * from './checkbox-required-validator';
| {
"end_byte": 340,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/public-api.ts"
} |
components/src/material/checkbox/checkbox.md_0_3413 | `<mat-checkbox>` provides the same functionality as a native `<input type="checkbox">`
enhanced with Material Design styling and animations.
<!-- example(checkbox-overview) -->
### Checkbox label
The checkbox label is provided as the content to the `<mat-checkbox>` element. The label can be
positioned before or after the checkbox by setting the `labelPosition` property to `'before'` or
`'after'`.
If you don't want the label to appear next to the checkbox, you can use
[`aria-label`](https://www.w3.org/TR/wai-aria/states_and_properties#aria-label) or
[`aria-labelledby`](https://www.w3.org/TR/wai-aria/states_and_properties#aria-labelledby) to
specify an appropriate label.
### Use with `@angular/forms`
`<mat-checkbox>` is compatible with `@angular/forms` and supports both `FormsModule`
and `ReactiveFormsModule`.
### Indeterminate state
`<mat-checkbox>` supports an `indeterminate` state, similar to the native `<input type="checkbox">`.
While the `indeterminate` property of the checkbox is true, it will render as indeterminate
regardless of the `checked` value. Any interaction with the checkbox by a user (i.e., clicking) will
remove the indeterminate state.
### Click action config
When user clicks on the `mat-checkbox`, the default behavior is toggle `checked` value and set
`indeterminate` to `false`. This behavior can be customized by
[providing a new value](https://angular.dev/guide/di/dependency-injection)
of `MAT_CHECKBOX_DEFAULT_OPTIONS` to the checkbox.
```
providers: [
{provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: { clickAction: 'noop' } as MatCheckboxDefaultOptions}
]
```
The possible values are:
#### `noop`
Do not change the `checked` value or `indeterminate` value. Developers have the power to
implement customized click actions.
#### `check`
Toggle `checked` value of the checkbox, ignore `indeterminate` value. If the
checkbox is in `indeterminate` state, the checkbox will display as an `indeterminate` checkbox
regardless the `checked` value.
#### `check-indeterminate`
Default behavior of `mat-checkbox`. Always set `indeterminate` to `false`
when user click on the `mat-checkbox`.
This matches the behavior of native `<input type="checkbox">`.
### Accessibility
`MatCheckbox` uses an internal `<input type="checkbox">` to provide an accessible experience.
This internal checkbox receives focus and is automatically labelled by the text content of the
`<mat-checkbox>` element. Avoid adding other interactive controls into the content of
`<mat-checkbox>`, as this degrades the experience for users of assistive technology.
Always provide an accessible label via `aria-label` or `aria-labelledby` for checkboxes without
descriptive text content. For dynamic labels, `MatCheckbox` provides input properties for binding
`aria-label` and `aria-labelledby`. This means that you should not use the `attr.` prefix when
binding these properties, as demonstrated below.
```html
<mat-checkbox [aria-label]="isSubscribedToEmailsMessage">
</mat-checkbox>
```
Additionally, `MatCheckbox` now supports the following accessibility properties:
- **`aria-expanded`**: Indicates whether the checkbox controls the visibility of another element. This should be a boolean value (`true` or `false`).
- **`aria-controls`**: Specifies the ID of the element that the checkbox controls.
- **`aria-owns`**: Specifies the ID of the element that the checkbox visually owns.
| {
"end_byte": 3413,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox.md"
} |
components/src/material/checkbox/checkbox-config.ts_0_1821 | /**
* @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';
import {ThemePalette} from '@angular/material/core';
/** Default `mat-checkbox` options that can be overridden. */
export interface MatCheckboxDefaultOptions {
/**
* Default theme color of the checkbox. 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;
/** Default checkbox click action for checkboxes. */
clickAction?: MatCheckboxClickAction;
/** Whether disabled checkboxes should be interactive. */
disabledInteractive?: boolean;
}
/** Injection token to be used to override the default options for `mat-checkbox`. */
export const MAT_CHECKBOX_DEFAULT_OPTIONS = new InjectionToken<MatCheckboxDefaultOptions>(
'mat-checkbox-default-options',
{
providedIn: 'root',
factory: MAT_CHECKBOX_DEFAULT_OPTIONS_FACTORY,
},
);
/** @docs-private */
export function MAT_CHECKBOX_DEFAULT_OPTIONS_FACTORY(): MatCheckboxDefaultOptions {
return {
color: 'accent',
clickAction: 'check-indeterminate',
disabledInteractive: false,
};
}
/**
* Checkbox click action when user click on input element.
* noop: Do not toggle checked or indeterminate.
* check: Only toggle checked status, ignore indeterminate.
* check-indeterminate: Toggle checked status, set indeterminate to false. Default behavior.
* undefined: Same as `check-indeterminate`.
*/
export type MatCheckboxClickAction = 'noop' | 'check' | 'check-indeterminate' | undefined;
| {
"end_byte": 1821,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox-config.ts"
} |
components/src/material/checkbox/checkbox.html_0_2301 | <div mat-internal-form-field [labelPosition]="labelPosition" (click)="_preventBubblingFromLabel($event)">
<div #checkbox class="mdc-checkbox">
<!-- Render this element first so the input is on top. -->
<div class="mat-mdc-checkbox-touch-target" (click)="_onTouchTargetClick()"></div>
<input #input
type="checkbox"
class="mdc-checkbox__native-control"
[class.mdc-checkbox--selected]="checked"
[attr.aria-label]="ariaLabel || null"
[attr.aria-labelledby]="ariaLabelledby"
[attr.aria-describedby]="ariaDescribedby"
[attr.aria-checked]="indeterminate ? 'mixed' : null"
[attr.aria-controls]="ariaControls"
[attr.aria-disabled]="disabled && disabledInteractive ? true : null"
[attr.aria-expanded]="ariaExpanded"
[attr.aria-owns]="ariaOwns"
[attr.name]="name"
[attr.value]="value"
[checked]="checked"
[indeterminate]="indeterminate"
[disabled]="disabled && !disabledInteractive"
[id]="inputId"
[required]="required"
[tabIndex]="disabled && !disabledInteractive ? -1 : tabIndex"
(blur)="_onBlur()"
(click)="_onInputClick()"
(change)="_onInteractionEvent($event)"/>
<div class="mdc-checkbox__ripple"></div>
<div class="mdc-checkbox__background">
<svg class="mdc-checkbox__checkmark"
focusable="false"
viewBox="0 0 24 24"
aria-hidden="true">
<path class="mdc-checkbox__checkmark-path"
fill="none"
d="M1.73,12.91 8.1,19.28 22.79,4.59"/>
</svg>
<div class="mdc-checkbox__mixedmark"></div>
</div>
<div class="mat-mdc-checkbox-ripple mat-focus-indicator" mat-ripple
[matRippleTrigger]="checkbox"
[matRippleDisabled]="disableRipple || disabled"
[matRippleCentered]="true"></div>
</div>
<!--
Avoid putting a click handler on the <label/> to fix duplicate navigation stop on Talk Back
(#14385). Putting a click handler on the <label/> caused this bug because the browser produced
an unnecessary accessibility tree node.
-->
<label class="mdc-label" #label [for]="inputId">
<ng-content></ng-content>
</label>
</div>
| {
"end_byte": 2301,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/checkbox.html"
} |
components/src/material/checkbox/README.md_0_99 | Please see the official documentation at https://material.angular.io/components/component/checkbox
| {
"end_byte": 99,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/README.md"
} |
components/src/material/checkbox/_checkbox-common.scss_0_4926 | @use 'sass:math';
@use '@angular/cdk';
@use '../core/tokens/m2/mdc/checkbox' as tokens-mdc-checkbox;
@use '../core/tokens/token-utils';
@use '../core/style/vendor-prefixes';
$_path-length: 29.7833385;
$_transition-duration: 90ms;
$_icon-size: 18px;
$_mark-stroke-size: math.div(2, 15) * $_icon-size;
$_indeterminate-checked-curve: cubic-bezier(0.14, 0, 0, 1);
$_indeterminate-change-duration: 500ms;
$_enter-curve: cubic-bezier(0, 0, 0.2, 1);
$_exit-curve: cubic-bezier(0.4, 0, 0.6, 1);
$_fallback-size: 40px;
// Structural styles for a checkbox. Shared with the selection list.
@mixin checkbox-structure($include-state-layer-styles) {
$prefix: tokens-mdc-checkbox.$prefix;
$slots: tokens-mdc-checkbox.get-token-slots();
.mdc-checkbox {
display: inline-block;
position: relative;
flex: 0 0 $_icon-size;
box-sizing: content-box;
width: $_icon-size;
height: $_icon-size;
line-height: 0;
white-space: nowrap;
cursor: pointer;
vertical-align: bottom;
@include token-utils.use-tokens($prefix, $slots) {
$layer-size: token-utils.get-token-variable(state-layer-size, $fallback: $_fallback-size);
padding: calc((#{$layer-size} - #{$_icon-size}) / 2);
margin: calc((#{$layer-size} - #{$layer-size}) / 2);
@if ($include-state-layer-styles) {
@include _state-layer-styles;
}
}
// These styles have to be nested in order to override overly-broad
// user selectors like `input[type='checkbox']`.
.mdc-checkbox__native-control {
position: absolute;
margin: 0;
padding: 0;
opacity: 0;
cursor: inherit;
@include token-utils.use-tokens($prefix, $slots) {
$layer-size: token-utils.get-token-variable(state-layer-size, $fallback: $_fallback-size);
$offset: calc((#{$layer-size} - #{$layer-size}) / 2);
width: $layer-size;
height: $layer-size;
top: $offset;
right: $offset;
left: $offset;
}
}
}
.mdc-checkbox--disabled {
cursor: default;
pointer-events: none;
@include cdk.high-contrast {
opacity: 0.5;
}
}
.mdc-checkbox__background {
display: inline-flex;
position: absolute;
align-items: center;
justify-content: center;
box-sizing: border-box;
width: $_icon-size;
height: $_icon-size;
border: 2px solid currentColor;
border-radius: 2px;
background-color: transparent;
pointer-events: none;
will-change: background-color, border-color;
transition: background-color $_transition-duration $_exit-curve,
border-color $_transition-duration $_exit-curve;
// Force browser to show background-color when using the print function
@include vendor-prefixes.color-adjust(exact);
@include token-utils.use-tokens($prefix, $slots) {
$layer-size: token-utils.get-token-variable(state-layer-size, $fallback: $_fallback-size);
$offset: calc((#{$layer-size} - #{$_icon-size}) / 2);
@include token-utils.create-token-slot(border-color, unselected-icon-color);
top: $offset;
left: $offset;
}
}
// These can't be under `.mdc-checkbox__background` because
// the selectors will break when the mixin is nested.
@include token-utils.use-tokens($prefix, $slots) {
.mdc-checkbox__native-control:enabled:checked ~ .mdc-checkbox__background,
.mdc-checkbox__native-control:enabled:indeterminate ~ .mdc-checkbox__background {
@include token-utils.create-token-slot(border-color, selected-icon-color);
@include token-utils.create-token-slot(background-color, selected-icon-color);
}
.mdc-checkbox--disabled .mdc-checkbox__background {
@include token-utils.create-token-slot(border-color, disabled-unselected-icon-color);
}
.mdc-checkbox__native-control:disabled:checked ~ .mdc-checkbox__background,
.mdc-checkbox__native-control:disabled:indeterminate ~ .mdc-checkbox__background {
@include token-utils.create-token-slot(background-color, disabled-selected-icon-color);
border-color: transparent;
}
.mdc-checkbox:hover .mdc-checkbox__native-control:not(:checked) ~ .mdc-checkbox__background,
.mdc-checkbox:hover
.mdc-checkbox__native-control:not(:indeterminate) ~ .mdc-checkbox__background {
@include token-utils.create-token-slot(border-color, unselected-hover-icon-color);
background-color: transparent;
}
.mdc-checkbox:hover .mdc-checkbox__native-control:checked ~ .mdc-checkbox__background,
.mdc-checkbox:hover .mdc-checkbox__native-control:indeterminate ~ .mdc-checkbox__background {
@include token-utils.create-token-slot(border-color, selected-hover-icon-color);
@include token-utils.create-token-slot(background-color, selected-hover-icon-color);
}
// Note: this must be more specific than the hover styles above.
// Double :focus is added for increased specificity. | {
"end_byte": 4926,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/_checkbox-common.scss"
} |
components/src/material/checkbox/_checkbox-common.scss_4931_12994 | .mdc-checkbox__native-control:focus:focus:not(:checked) ~ .mdc-checkbox__background,
.mdc-checkbox__native-control:focus:focus:not(:indeterminate) ~ .mdc-checkbox__background {
@include token-utils.create-token-slot(border-color, unselected-focus-icon-color);
}
.mdc-checkbox__native-control:focus:focus:checked ~ .mdc-checkbox__background,
.mdc-checkbox__native-control:focus:focus:indeterminate ~ .mdc-checkbox__background {
@include token-utils.create-token-slot(border-color, selected-focus-icon-color);
@include token-utils.create-token-slot(background-color, selected-focus-icon-color);
}
// Needs extra specificity to override the focus, hover, active states.
.mdc-checkbox--disabled.mat-mdc-checkbox-disabled-interactive {
.mdc-checkbox:hover .mdc-checkbox__native-control ~ .mdc-checkbox__background,
.mdc-checkbox .mdc-checkbox__native-control:focus ~ .mdc-checkbox__background,
.mdc-checkbox__background {
@include token-utils.create-token-slot(border-color, disabled-unselected-icon-color);
}
.mdc-checkbox__native-control:checked ~ .mdc-checkbox__background,
.mdc-checkbox__native-control:indeterminate ~ .mdc-checkbox__background {
@include token-utils.create-token-slot(background-color, disabled-selected-icon-color);
border-color: transparent;
}
}
}
.mdc-checkbox__checkmark {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100%;
opacity: 0;
transition: opacity $_transition-duration * 2 $_exit-curve;
@include token-utils.use-tokens($prefix, $slots) {
// Always apply the color since the element becomes `opacity: 0`
// when unchecked. This makes the animation look better.
@include token-utils.create-token-slot(color, selected-checkmark-color);
}
@include cdk.high-contrast {
color: CanvasText;
}
}
@include token-utils.use-tokens($prefix, $slots) {
.mdc-checkbox--disabled {
&, &.mat-mdc-checkbox-disabled-interactive {
.mdc-checkbox__checkmark {
@include token-utils.create-token-slot(color, disabled-selected-checkmark-color);
@include cdk.high-contrast {
color: CanvasText;
}
}
}
}
}
.mdc-checkbox__checkmark-path {
transition: stroke-dashoffset $_transition-duration * 2 $_exit-curve;
stroke: currentColor;
stroke-width: $_mark-stroke-size * 1.3;
stroke-dashoffset: $_path-length;
stroke-dasharray: $_path-length;
}
.mdc-checkbox__mixedmark {
width: 100%;
height: 0;
transform: scaleX(0) rotate(0deg);
border-width: math.div(math.floor($_mark-stroke-size), 2);
border-style: solid;
opacity: 0;
transition: opacity $_transition-duration $_exit-curve,
transform $_transition-duration $_exit-curve;
@include token-utils.use-tokens($prefix, $slots) {
// Always apply the color since the element becomes `opacity: 0`
// when unchecked. This makes the animation look better.
@include token-utils.create-token-slot(border-color, selected-checkmark-color);
}
@include cdk.high-contrast {
margin: 0 1px;
}
}
@include token-utils.use-tokens($prefix, $slots) {
.mdc-checkbox--disabled {
&, &.mat-mdc-checkbox-disabled-interactive {
.mdc-checkbox__mixedmark {
@include token-utils.create-token-slot(border-color, disabled-selected-checkmark-color);
}
}
}
}
.mdc-checkbox--anim-unchecked-checked,
.mdc-checkbox--anim-unchecked-indeterminate,
.mdc-checkbox--anim-checked-unchecked,
.mdc-checkbox--anim-indeterminate-unchecked {
.mdc-checkbox__background {
animation-duration: $_transition-duration * 2;
animation-timing-function: linear;
}
}
.mdc-checkbox--anim-unchecked-checked {
.mdc-checkbox__checkmark-path {
animation: mdc-checkbox-unchecked-checked-checkmark-path
$_transition-duration * 2 linear;
transition: none;
}
}
.mdc-checkbox--anim-unchecked-indeterminate {
.mdc-checkbox__mixedmark {
animation: mdc-checkbox-unchecked-indeterminate-mixedmark $_transition-duration linear;
transition: none;
}
}
.mdc-checkbox--anim-checked-unchecked {
.mdc-checkbox__checkmark-path {
animation: mdc-checkbox-checked-unchecked-checkmark-path $_transition-duration linear;
transition: none;
}
}
.mdc-checkbox--anim-checked-indeterminate {
.mdc-checkbox__checkmark {
animation: mdc-checkbox-checked-indeterminate-checkmark $_transition-duration linear;
transition: none;
}
.mdc-checkbox__mixedmark {
animation: mdc-checkbox-checked-indeterminate-mixedmark $_transition-duration linear;
transition: none;
}
}
.mdc-checkbox--anim-indeterminate-checked {
.mdc-checkbox__checkmark {
animation: mdc-checkbox-indeterminate-checked-checkmark
$_indeterminate-change-duration linear;
transition: none;
}
.mdc-checkbox__mixedmark {
animation: mdc-checkbox-indeterminate-checked-mixedmark
$_indeterminate-change-duration linear;
transition: none;
}
}
.mdc-checkbox--anim-indeterminate-unchecked {
.mdc-checkbox__mixedmark {
animation: mdc-checkbox-indeterminate-unchecked-mixedmark
$_indeterminate-change-duration * 0.6 linear;
transition: none;
}
}
.mdc-checkbox__native-control:checked ~ .mdc-checkbox__background,
.mdc-checkbox__native-control:indeterminate ~ .mdc-checkbox__background {
transition: border-color $_transition-duration $_enter-curve,
background-color $_transition-duration $_enter-curve;
.mdc-checkbox__checkmark-path {
stroke-dashoffset: 0;
}
}
.mdc-checkbox__native-control:checked ~ .mdc-checkbox__background {
.mdc-checkbox__checkmark {
transition: opacity $_transition-duration * 2 $_enter-curve,
transform $_transition-duration * 2 $_enter-curve;
opacity: 1;
}
.mdc-checkbox__mixedmark {
transform: scaleX(1) rotate(-45deg);
}
}
.mdc-checkbox__native-control:indeterminate ~ .mdc-checkbox__background {
.mdc-checkbox__checkmark {
transform: rotate(45deg);
opacity: 0;
transition: opacity $_transition-duration $_exit-curve,
transform $_transition-duration $_exit-curve;
}
.mdc-checkbox__mixedmark {
transform: scaleX(1) rotate(0deg);
opacity: 1;
}
}
@keyframes mdc-checkbox-unchecked-checked-checkmark-path {
0%, 50% {
stroke-dashoffset: $_path-length;
}
50% {
animation-timing-function: $_enter-curve;
}
100% {
stroke-dashoffset: 0;
}
}
@keyframes mdc-checkbox-unchecked-indeterminate-mixedmark {
0%, 68.2% {
transform: scaleX(0);
}
68.2% {
animation-timing-function: cubic-bezier(0, 0, 0, 1);
}
100% {
transform: scaleX(1);
}
}
@keyframes mdc-checkbox-checked-unchecked-checkmark-path {
from {
animation-timing-function: cubic-bezier(0.4, 0, 1, 1);
opacity: 1;
stroke-dashoffset: 0;
}
to {
opacity: 0;
stroke-dashoffset: $_path-length * -1;
}
}
@keyframes mdc-checkbox-checked-indeterminate-checkmark {
from {
animation-timing-function: $_enter-curve;
transform: rotate(0deg);
opacity: 1;
}
to {
transform: rotate(45deg);
opacity: 0;
}
}
@keyframes mdc-checkbox-indeterminate-checked-checkmark {
from {
animation-timing-function: $_indeterminate-checked-curve;
transform: rotate(45deg);
opacity: 0;
}
to {
transform: rotate(360deg);
opacity: 1;
}
}
@keyframes mdc-checkbox-checked-indeterminate-mixedmark {
from {
animation-timing-function: $_enter-curve;
transform: rotate(-45deg);
opacity: 0;
}
to {
transform: rotate(0deg);
opacity: 1;
}
} | {
"end_byte": 12994,
"start_byte": 4931,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/_checkbox-common.scss"
} |
components/src/material/checkbox/_checkbox-common.scss_12998_17260 | @keyframes mdc-checkbox-indeterminate-checked-mixedmark {
from {
animation-timing-function: $_indeterminate-checked-curve;
transform: rotate(0deg);
opacity: 1;
}
to {
transform: rotate(315deg);
opacity: 0;
}
}
@keyframes mdc-checkbox-indeterminate-unchecked-mixedmark {
0% {
animation-timing-function: linear;
transform: scaleX(1);
opacity: 1;
}
32.8%, 100% {
transform: scaleX(0);
opacity: 0;
}
}
}
// Conditionally disables the animations of the checkbox.
@mixin checkbox-noop-animations() {
&._mat-animation-noopable .mdc-checkbox {
*, *::before {
transition: none !important;
animation: none !important;
}
}
}
@mixin _state-layer-styles() {
// MDC expects `.mdc-checkbox__ripple::before` to be the state layer, but we use
// `.mdc-checkbox__ripple` instead, so we emit the state layer slots ourselves.
&:hover {
.mdc-checkbox__ripple {
@include token-utils.create-token-slot(opacity, unselected-hover-state-layer-opacity);
@include token-utils.create-token-slot(
background-color,
unselected-hover-state-layer-color
);
}
.mat-mdc-checkbox-ripple .mat-ripple-element {
@include token-utils.create-token-slot(
background-color,
unselected-hover-state-layer-color
);
}
}
.mdc-checkbox__native-control:focus {
& ~ .mdc-checkbox__ripple {
@include token-utils.create-token-slot(opacity, unselected-focus-state-layer-opacity);
@include token-utils.create-token-slot(
background-color,
unselected-focus-state-layer-color
);
}
& ~ .mat-mdc-checkbox-ripple .mat-ripple-element {
@include token-utils.create-token-slot(
background-color,
unselected-focus-state-layer-color
);
}
}
&:active .mdc-checkbox__native-control {
& ~ .mdc-checkbox__ripple {
@include token-utils.create-token-slot(opacity, unselected-pressed-state-layer-opacity);
@include token-utils.create-token-slot(
background-color,
unselected-pressed-state-layer-color
);
}
& ~ .mat-mdc-checkbox-ripple .mat-ripple-element {
@include token-utils.create-token-slot(
background-color,
unselected-pressed-state-layer-color
);
}
}
&:hover .mdc-checkbox__native-control:checked {
& ~ .mdc-checkbox__ripple {
@include token-utils.create-token-slot(opacity, selected-hover-state-layer-opacity);
@include token-utils.create-token-slot(
background-color,
selected-hover-state-layer-color
);
}
& ~ .mat-mdc-checkbox-ripple .mat-ripple-element {
@include token-utils.create-token-slot(
background-color,
selected-hover-state-layer-color
);
}
}
.mdc-checkbox__native-control:focus:checked {
& ~ .mdc-checkbox__ripple {
@include token-utils.create-token-slot(opacity, selected-focus-state-layer-opacity);
@include token-utils.create-token-slot(
background-color,
selected-focus-state-layer-color
);
}
& ~ .mat-mdc-checkbox-ripple .mat-ripple-element {
@include token-utils.create-token-slot(
background-color,
selected-focus-state-layer-color
);
}
}
&:active .mdc-checkbox__native-control:checked {
& ~ .mdc-checkbox__ripple {
@include token-utils.create-token-slot(opacity, selected-pressed-state-layer-opacity);
@include token-utils.create-token-slot(
background-color,
selected-pressed-state-layer-color
);
}
& ~ .mat-mdc-checkbox-ripple .mat-ripple-element {
@include token-utils.create-token-slot(
background-color,
selected-pressed-state-layer-color
);
}
}
// Needs extra specificity to override the focus, hover, active states.
.mdc-checkbox--disabled.mat-mdc-checkbox-disabled-interactive & {
.mdc-checkbox__native-control ~ .mat-mdc-checkbox-ripple .mat-ripple-element,
.mdc-checkbox__native-control ~ .mdc-checkbox__ripple {
@include token-utils.create-token-slot(
background-color,
unselected-hover-state-layer-color
);
}
}
} | {
"end_byte": 17260,
"start_byte": 12998,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/_checkbox-common.scss"
} |
components/src/material/checkbox/BUILD.bazel_0_1577 | 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 = "checkbox",
srcs = glob(
["**/*.ts"],
exclude = [
"**/*.spec.ts",
],
),
assets = [":checkbox_scss"] + glob(["**/*.html"]),
deps = [
"//src/material/core",
"@npm//@angular/animations",
"@npm//@angular/core",
"@npm//@angular/forms",
],
)
sass_library(
name = "checkbox_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = [
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "checkbox_scss",
src = "checkbox.scss",
deps = [
":checkbox_scss_lib",
"//src/material:sass_lib",
"//src/material/core:core_scss_lib",
],
)
ng_test_library(
name = "checkbox_tests_lib",
srcs = glob(
["**/*.spec.ts"],
),
deps = [
":checkbox",
"//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 = [
":checkbox_tests_lib",
],
)
markdown_to_html(
name = "overview",
srcs = [":checkbox.md"],
)
extract_tokens(
name = "tokens",
srcs = [":checkbox_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1577,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/BUILD.bazel"
} |
components/src/material/checkbox/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/checkbox/index.ts"
} |
components/src/material/checkbox/testing/public-api.ts_0_307 | /**
* @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 './checkbox-harness';
export {CheckboxHarnessFilters} from './checkbox-harness-filters';
| {
"end_byte": 307,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/testing/public-api.ts"
} |
components/src/material/checkbox/testing/checkbox-harness.ts_0_6047 | /**
* @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,
} from '@angular/cdk/testing';
import {CheckboxHarnessFilters} from './checkbox-harness-filters';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
/** Harness for interacting with a mat-checkbox in tests. */
export class MatCheckboxHarness extends ComponentHarness {
static hostSelector = '.mat-mdc-checkbox';
_input = this.locatorFor('input');
private _label = this.locatorFor('label');
private _inputContainer = this.locatorFor('.mdc-checkbox');
/**
* Gets a `HarnessPredicate` that can be used to search for a checkbox with specific attributes.
* @param options Options for narrowing the search:
* - `selector` finds a checkbox whose host element matches the given selector.
* - `label` finds a checkbox with specific label text.
* - `name` finds a checkbox with specific name.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatCheckboxHarness>(
this: ComponentHarnessConstructor<T>,
options: CheckboxHarnessFilters = {},
): HarnessPredicate<T> {
return (
new HarnessPredicate(this, options)
.addOption('label', options.label, (harness, label) =>
HarnessPredicate.stringMatches(harness.getLabelText(), label),
)
// We want to provide a filter option for "name" because the name of the checkbox is
// only set on the underlying input. This means that it's not possible for developers
// to retrieve the harness of a specific checkbox with name through a CSS selector.
.addOption(
'name',
options.name,
async (harness, name) => (await harness.getName()) === name,
)
.addOption(
'checked',
options.checked,
async (harness, checked) => (await harness.isChecked()) == checked,
)
.addOption('disabled', options.disabled, async (harness, disabled) => {
return (await harness.isDisabled()) === disabled;
})
);
}
/** Whether the checkbox is checked. */
async isChecked(): Promise<boolean> {
const checked = (await this._input()).getProperty<boolean>('checked');
return coerceBooleanProperty(await checked);
}
/** Whether the checkbox is in an indeterminate state. */
async isIndeterminate(): Promise<boolean> {
const indeterminate = (await this._input()).getProperty<string>('indeterminate');
return coerceBooleanProperty(await indeterminate);
}
/** Whether the checkbox is disabled. */
async isDisabled(): Promise<boolean> {
const input = await this._input();
const disabled = await input.getAttribute('disabled');
if (disabled !== null) {
return coerceBooleanProperty(disabled);
}
return (await input.getAttribute('aria-disabled')) === 'true';
}
/** Whether the checkbox is required. */
async isRequired(): Promise<boolean> {
const required = (await this._input()).getProperty<boolean>('required');
return coerceBooleanProperty(await required);
}
/** Whether the checkbox is valid. */
async isValid(): Promise<boolean> {
const invalid = (await this.host()).hasClass('ng-invalid');
return !(await invalid);
}
/** Gets the checkbox's name. */
async getName(): Promise<string | null> {
return (await this._input()).getAttribute('name');
}
/** Gets the checkbox's value. */
async getValue(): Promise<string | null> {
return (await this._input()).getProperty<string | null>('value');
}
/** Gets the checkbox's aria-label. */
async getAriaLabel(): Promise<string | null> {
return (await this._input()).getAttribute('aria-label');
}
/** Gets the checkbox's aria-labelledby. */
async getAriaLabelledby(): Promise<string | null> {
return (await this._input()).getAttribute('aria-labelledby');
}
/** Gets the checkbox's label text. */
async getLabelText(): Promise<string> {
return (await this._label()).text();
}
/** Focuses the checkbox. */
async focus(): Promise<void> {
return (await this._input()).focus();
}
/** Blurs the checkbox. */
async blur(): Promise<void> {
return (await this._input()).blur();
}
/** Whether the checkbox is focused. */
async isFocused(): Promise<boolean> {
return (await this._input()).isFocused();
}
/**
* Toggles the checked state of the checkbox.
*
* Note: This attempts to toggle the checkbox as a user would, by clicking it. Therefore if you
* are using `MAT_CHECKBOX_DEFAULT_OPTIONS` to change the behavior on click, calling this method
* might not have the expected result.
*/
async toggle(): Promise<void> {
const elToClick = await ((await this.isDisabled()) ? this._inputContainer() : this._input());
return elToClick.click();
}
/**
* Puts the checkbox in a checked state by toggling it if it is currently unchecked, or doing
* nothing if it is already checked.
*
* Note: This attempts to check the checkbox as a user would, by clicking it. Therefore if you
* are using `MAT_CHECKBOX_DEFAULT_OPTIONS` to change the behavior on click, calling this method
* might not have the expected result.
*/
async check(): Promise<void> {
if (!(await this.isChecked())) {
await this.toggle();
}
}
/**
* Puts the checkbox in an unchecked state by toggling it if it is currently checked, or doing
* nothing if it is already unchecked.
*
* Note: This attempts to uncheck the checkbox as a user would, by clicking it. Therefore if you
* are using `MAT_CHECKBOX_DEFAULT_OPTIONS` to change the behavior on click, calling this method
* might not have the expected result.
*/
async uncheck(): Promise<void> {
if (await this.isChecked()) {
await this.toggle();
}
}
}
| {
"end_byte": 6047,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/testing/checkbox-harness.ts"
} |
components/src/material/checkbox/testing/checkbox-harness.spec.ts_0_8308 | import {Component, signal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {FormControl, ReactiveFormsModule} from '@angular/forms';
import {MatCheckboxModule} from '@angular/material/checkbox';
import {MatCheckboxHarness} from './checkbox-harness';
describe('MatCheckboxHarness', () => {
let fixture: ComponentFixture<CheckboxHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatCheckboxModule, ReactiveFormsModule, CheckboxHarnessTest],
});
fixture = TestBed.createComponent(CheckboxHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all checkbox harnesses', async () => {
const checkboxes = await loader.getAllHarnesses(MatCheckboxHarness);
expect(checkboxes.length).toBe(2);
});
it('should load checkbox with exact label', async () => {
const checkboxes = await loader.getAllHarnesses(MatCheckboxHarness.with({label: 'First'}));
expect(checkboxes.length).toBe(1);
expect(await checkboxes[0].getLabelText()).toBe('First');
});
it('should load checkbox with name', async () => {
const checkboxes = await loader.getAllHarnesses(MatCheckboxHarness.with({name: 'first-name'}));
expect(checkboxes.length).toBe(1);
expect(await checkboxes[0].getLabelText()).toBe('First');
});
it('should load checkbox with regex label match', async () => {
const checkboxes = await loader.getAllHarnesses(MatCheckboxHarness.with({label: /^s/i}));
expect(checkboxes.length).toBe(1);
expect(await checkboxes[0].getLabelText()).toBe('Second');
});
it('should load checkbox with disabled state', async () => {
let enabledCheckboxes = await loader.getAllHarnesses(
MatCheckboxHarness.with({disabled: false}),
);
let disabledCheckboxes = await loader.getAllHarnesses(
MatCheckboxHarness.with({disabled: true}),
);
expect(enabledCheckboxes.length).toBe(1);
expect(disabledCheckboxes.length).toBe(1);
fixture.componentInstance.disabled.set(false);
enabledCheckboxes = await loader.getAllHarnesses(MatCheckboxHarness.with({disabled: false}));
disabledCheckboxes = await loader.getAllHarnesses(MatCheckboxHarness.with({disabled: true}));
expect(enabledCheckboxes.length).toBe(2);
expect(disabledCheckboxes.length).toBe(0);
});
it('should get checked state', async () => {
const [checkedCheckbox, uncheckedCheckbox] = await loader.getAllHarnesses(MatCheckboxHarness);
expect(await checkedCheckbox.isChecked()).toBe(true);
expect(await uncheckedCheckbox.isChecked()).toBe(false);
});
it('should get indeterminate state', async () => {
const [checkedCheckbox, indeterminateCheckbox] =
await loader.getAllHarnesses(MatCheckboxHarness);
expect(await checkedCheckbox.isIndeterminate()).toBe(false);
expect(await indeterminateCheckbox.isIndeterminate()).toBe(true);
});
it('should get disabled state', async () => {
const [enabledCheckbox, disabledCheckbox] = await loader.getAllHarnesses(MatCheckboxHarness);
expect(await enabledCheckbox.isDisabled()).toBe(false);
expect(await disabledCheckbox.isDisabled()).toBe(true);
});
it('should get required state', async () => {
const [requiredCheckbox, optionalCheckbox] = await loader.getAllHarnesses(MatCheckboxHarness);
expect(await requiredCheckbox.isRequired()).toBe(true);
expect(await optionalCheckbox.isRequired()).toBe(false);
});
it('should get valid state', async () => {
const [requiredCheckbox, optionalCheckbox] = await loader.getAllHarnesses(MatCheckboxHarness);
expect(await optionalCheckbox.isValid()).toBe(true);
expect(await requiredCheckbox.isValid()).toBe(true);
await requiredCheckbox.uncheck();
expect(await requiredCheckbox.isValid()).toBe(false);
});
it('should get name', async () => {
const checkbox = await loader.getHarness(MatCheckboxHarness.with({label: 'First'}));
expect(await checkbox.getName()).toBe('first-name');
});
it('should get value', async () => {
const checkbox = await loader.getHarness(MatCheckboxHarness.with({label: 'First'}));
expect(await checkbox.getValue()).toBe('first-value');
});
it('should get aria-label', async () => {
const checkbox = await loader.getHarness(MatCheckboxHarness.with({label: 'First'}));
expect(await checkbox.getAriaLabel()).toBe('First checkbox');
});
it('should get aria-labelledby', async () => {
const checkbox = await loader.getHarness(MatCheckboxHarness.with({label: 'Second'}));
expect(await checkbox.getAriaLabelledby()).toBe('second-label');
});
it('should get label text', async () => {
const [firstCheckbox, secondCheckbox] = await loader.getAllHarnesses(MatCheckboxHarness);
expect(await firstCheckbox.getLabelText()).toBe('First');
expect(await secondCheckbox.getLabelText()).toBe('Second');
});
it('should focus checkbox', async () => {
const checkbox = await loader.getHarness(MatCheckboxHarness.with({label: 'First'}));
expect(await checkbox.isFocused()).toBe(false);
await checkbox.focus();
expect(await checkbox.isFocused()).toBe(true);
});
it('should blur checkbox', async () => {
const checkbox = await loader.getHarness(MatCheckboxHarness.with({label: 'First'}));
await checkbox.focus();
expect(await checkbox.isFocused()).toBe(true);
await checkbox.blur();
expect(await checkbox.isFocused()).toBe(false);
});
it('should toggle checkbox', async () => {
fixture.componentInstance.disabled.set(false);
const [checkedCheckbox, uncheckedCheckbox] = await loader.getAllHarnesses(MatCheckboxHarness);
await checkedCheckbox.toggle();
await uncheckedCheckbox.toggle();
expect(await checkedCheckbox.isChecked()).toBe(false);
expect(await uncheckedCheckbox.isChecked()).toBe(true);
});
it('should check checkbox', async () => {
fixture.componentInstance.disabled.set(false);
const [checkedCheckbox, uncheckedCheckbox] = await loader.getAllHarnesses(MatCheckboxHarness);
await checkedCheckbox.check();
await uncheckedCheckbox.check();
expect(await checkedCheckbox.isChecked()).toBe(true);
expect(await uncheckedCheckbox.isChecked()).toBe(true);
});
it('should uncheck checkbox', async () => {
fixture.componentInstance.disabled.set(false);
const [checkedCheckbox, uncheckedCheckbox] = await loader.getAllHarnesses(MatCheckboxHarness);
await checkedCheckbox.uncheck();
await uncheckedCheckbox.uncheck();
expect(await checkedCheckbox.isChecked()).toBe(false);
expect(await uncheckedCheckbox.isChecked()).toBe(false);
});
it('should not toggle disabled checkbox', async () => {
const disabledCheckbox = await loader.getHarness(MatCheckboxHarness.with({label: 'Second'}));
expect(await disabledCheckbox.isChecked()).toBe(false);
await disabledCheckbox.toggle();
expect(await disabledCheckbox.isChecked()).toBe(false);
});
it('should get disabled state for checkbox with disabledInteractive', async () => {
fixture.componentInstance.disabled.set(false);
fixture.componentInstance.disabledInteractive.set(true);
const checkbox = await loader.getHarness(MatCheckboxHarness.with({label: 'Second'}));
expect(await checkbox.isDisabled()).toBe(false);
fixture.componentInstance.disabled.set(true);
expect(await checkbox.isDisabled()).toBe(true);
});
});
@Component({
template: `
<mat-checkbox
[formControl]="ctrl"
required
name="first-name"
value="first-value"
aria-label="First checkbox">
First
</mat-checkbox>
<mat-checkbox
indeterminate="true"
[disabled]="disabled()"
aria-labelledby="second-label"
[disabledInteractive]="disabledInteractive()">
Second
</mat-checkbox>
<span id="second-label">Second checkbox</span>
`,
standalone: true,
imports: [MatCheckboxModule, ReactiveFormsModule],
})
class CheckboxHarnessTest {
ctrl = new FormControl(true);
disabled = signal(true);
disabledInteractive = signal(false);
}
| {
"end_byte": 8308,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/testing/checkbox-harness.spec.ts"
} |
components/src/material/checkbox/testing/checkbox-harness-filters.ts_0_776 | /**
* @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 `MatCheckboxHarness` instances. */
export interface CheckboxHarnessFilters extends BaseHarnessFilters {
/** Only find instances whose label matches the given value. */
label?: string | RegExp;
/** Only find instances whose name attribute is the given value. */
name?: string;
/** Only find instances with the given checked value. */
checked?: boolean;
/** Only find instances which match the given disabled state. */
disabled?: boolean;
}
| {
"end_byte": 776,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/testing/checkbox-harness-filters.ts"
} |
components/src/material/checkbox/testing/BUILD.bazel_0_800 | 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",
],
)
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/checkbox",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":unit_tests_lib",
],
)
| {
"end_byte": 800,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/checkbox/testing/BUILD.bazel"
} |
components/src/material/checkbox/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/checkbox/testing/index.ts"
} |
components/src/material/slider/slider.md_0_3267 | `<mat-slider>` allows for the selection of a value from a range via mouse, touch, or keyboard,
similar to `<input type="range">`.
<!-- example(slider-overview) -->
### Selecting a value
By default the minimum value of the slider is `0`, the maximum value is `100`, and the thumb moves
in increments of `1`. These values can be changed by setting the `min`, `max`, and `step` attributes
respectively. The initial value is set to the minimum value unless otherwise specified.
```html
<mat-slider min="1" max="5" step="0.5">
<input matSliderThumb value="1.5">
</mat-slider>
```
### Selecting a range
A `<mat-slider>` can be converted into a range slider by projecting both a `matSliderStartThumb` and a
`matSliderEndThumb` into it. Each thumb has its own value, but both are still
constrained by the slider's `min` and `max` values. The `matSliderStartThumb` cannot have a value
greater than that of the `matSliderEndThumb` and the `matSliderEndThumb` cannot have a value less than
that of the `matSliderStartThumb`, though they both may have the same value.
```html
<mat-slider>
<input matSliderStartThumb>
<input matSliderEndThumb>
</mat-slider>
```
<!-- example(slider-range) -->
### Thumb label
By default, the exact selected value of a slider is not visible to the user. However, this value can
be added to the thumb by adding the `discrete` attribute.
```html
<mat-slider discrete>
<input matSliderThumb>
</mat-slider>
```
### Formatting the thumb label
By default, the value in the slider's thumb label will be the same as the model value, however this
may end up being too large to fit into the label. If you want to control the value that is being
displayed, you can do so using the `displayWith` input.
<!-- example(slider-formatting) -->
### Tick marks
By default, sliders do not show tick marks along the thumb track. This can be enabled using the
`showTickMarks` attribute.
```html
<mat-slider showTickMarks>
<input matSliderThumb>
</mat-slider>
```
### Keyboard interaction
The slider has the following keyboard bindings:
| Key | Action |
|-------------|------------------------------------------------------------------------------------|
| Right arrow | Increment the slider value by one step (decrements in RTL). |
| Up arrow | Increment the slider value by one step. |
| Left arrow | Decrement the slider value by one step (increments in RTL). |
| Down arrow | Decrement the slider value by one step. |
| Page up | Increment the slider value by 10% (of the max value). |
| Page down | Decrement the slider value by 10% (of the max value). |
| End | Set the value to the maximum possible. |
| Home | Set the value to the minimum possible. |
### Accessibility
`MatSlider` uses an internal `<input type="range">` to provide an accessible experience. The input
receives focus and it can be labelled using `aria-label` or `aria-labelledby`.
| {
"end_byte": 3267,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.md"
} |
components/src/material/slider/module.ts_0_729 | /**
* @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 {MatSlider} from './slider';
import {MatSliderVisualThumb} from './slider-thumb';
import {MatSliderThumb, MatSliderRangeThumb} from './slider-input';
@NgModule({
imports: [
MatCommonModule,
MatRippleModule,
MatSlider,
MatSliderThumb,
MatSliderRangeThumb,
MatSliderVisualThumb,
],
exports: [MatSlider, MatSliderThumb, MatSliderRangeThumb],
})
export class MatSliderModule {}
| {
"end_byte": 729,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/module.ts"
} |
components/src/material/slider/slider-input.ts_0_2330 | /**
* @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,
ChangeDetectorRef,
Directive,
ElementRef,
EventEmitter,
forwardRef,
inject,
Input,
NgZone,
numberAttribute,
OnDestroy,
Output,
signal,
} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR} from '@angular/forms';
import {Subject} from 'rxjs';
import {
_MatThumb,
MatSliderDragEvent,
_MatSlider,
_MatSliderRangeThumb,
_MatSliderThumb,
MAT_SLIDER_RANGE_THUMB,
MAT_SLIDER_THUMB,
MAT_SLIDER,
} from './slider-interface';
import {Platform} from '@angular/cdk/platform';
/**
* Provider that allows the slider thumb to register as a ControlValueAccessor.
* @docs-private
*/
export const MAT_SLIDER_THUMB_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MatSliderThumb),
multi: true,
};
/**
* Provider that allows the range slider thumb to register as a ControlValueAccessor.
* @docs-private
*/
export const MAT_SLIDER_RANGE_THUMB_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MatSliderRangeThumb),
multi: true,
};
/**
* Directive that adds slider-specific behaviors to an input element inside `<mat-slider>`.
* Up to two may be placed inside of a `<mat-slider>`.
*
* If one is used, the selector `matSliderThumb` must be used, and the outcome will be a normal
* slider. If two are used, the selectors `matSliderStartThumb` and `matSliderEndThumb` must be
* used, and the outcome will be a range slider with two slider thumbs.
*/
@Directive({
selector: 'input[matSliderThumb]',
exportAs: 'matSliderThumb',
host: {
'class': 'mdc-slider__input',
'type': 'range',
'[attr.aria-valuetext]': '_valuetext()',
'(change)': '_onChange()',
'(input)': '_onInput()',
// TODO(wagnermaciel): Consider using a global event listener instead.
// Reason: I have found a semi-consistent way to mouse up without triggering this event.
'(blur)': '_onBlur()',
'(focus)': '_onFocus()',
},
providers: [
MAT_SLIDER_THUMB_VALUE_ACCESSOR,
{provide: MAT_SLIDER_THUMB, useExisting: MatSliderThumb},
],
})
export | {
"end_byte": 2330,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider-input.ts"
} |
components/src/material/slider/slider-input.ts_2331_10293 | class MatSliderThumb implements _MatSliderThumb, OnDestroy, ControlValueAccessor {
readonly _ngZone = inject(NgZone);
readonly _elementRef = inject<ElementRef<HTMLInputElement>>(ElementRef);
readonly _cdr = inject(ChangeDetectorRef);
protected _slider = inject<_MatSlider>(MAT_SLIDER);
@Input({transform: numberAttribute})
get value(): number {
return numberAttribute(this._hostElement.value, 0);
}
set value(value: number) {
value = isNaN(value) ? 0 : value;
const stringValue = value + '';
if (!this._hasSetInitialValue) {
this._initialValue = stringValue;
return;
}
if (this._isActive) {
return;
}
this._setValue(stringValue);
}
/**
* Handles programmatic value setting. This has been split out to
* allow the range thumb to override it and add additional necessary logic.
*/
protected _setValue(value: string) {
this._hostElement.value = value;
this._updateThumbUIByValue();
this._slider._onValueChange(this);
this._cdr.detectChanges();
this._slider._cdr.markForCheck();
}
/** Event emitted when the `value` is changed. */
@Output() readonly valueChange: EventEmitter<number> = new EventEmitter<number>();
/** Event emitted when the slider thumb starts being dragged. */
@Output() readonly dragStart: EventEmitter<MatSliderDragEvent> =
new EventEmitter<MatSliderDragEvent>();
/** Event emitted when the slider thumb stops being dragged. */
@Output() readonly dragEnd: EventEmitter<MatSliderDragEvent> =
new EventEmitter<MatSliderDragEvent>();
/**
* The current translateX in px of the slider visual thumb.
* @docs-private
*/
get translateX(): number {
if (this._slider.min >= this._slider.max) {
this._translateX = this._tickMarkOffset;
return this._translateX;
}
if (this._translateX === undefined) {
this._translateX = this._calcTranslateXByValue();
}
return this._translateX;
}
set translateX(v: number) {
this._translateX = v;
}
private _translateX: number | undefined;
/**
* Indicates whether this thumb is the start or end thumb.
* @docs-private
*/
thumbPosition: _MatThumb = _MatThumb.END;
/** @docs-private */
get min(): number {
return numberAttribute(this._hostElement.min, 0);
}
set min(v: number) {
this._hostElement.min = v + '';
this._cdr.detectChanges();
}
/** @docs-private */
get max(): number {
return numberAttribute(this._hostElement.max, 0);
}
set max(v: number) {
this._hostElement.max = v + '';
this._cdr.detectChanges();
}
get step(): number {
return numberAttribute(this._hostElement.step, 0);
}
set step(v: number) {
this._hostElement.step = v + '';
this._cdr.detectChanges();
}
/** @docs-private */
get disabled(): boolean {
return booleanAttribute(this._hostElement.disabled);
}
set disabled(v: boolean) {
this._hostElement.disabled = v;
this._cdr.detectChanges();
if (this._slider.disabled !== this.disabled) {
this._slider.disabled = this.disabled;
}
}
/** The percentage of the slider that coincides with the value. */
get percentage(): number {
if (this._slider.min >= this._slider.max) {
return this._slider._isRtl ? 1 : 0;
}
return (this.value - this._slider.min) / (this._slider.max - this._slider.min);
}
/** @docs-private */
get fillPercentage(): number {
if (!this._slider._cachedWidth) {
return this._slider._isRtl ? 1 : 0;
}
if (this._translateX === 0) {
return 0;
}
return this.translateX / this._slider._cachedWidth;
}
/** The host native HTML input element. */
_hostElement = this._elementRef.nativeElement;
/** The aria-valuetext string representation of the input's value. */
_valuetext = signal('');
/** The radius of a native html slider's knob. */
_knobRadius: number = 8;
/** The distance in px from the start of the slider track to the first tick mark. */
_tickMarkOffset = 3;
/** Whether user's cursor is currently in a mouse down state on the input. */
_isActive: boolean = false;
/** Whether the input is currently focused (either by tab or after clicking). */
_isFocused: boolean = false;
/** Used to relay updates to _isFocused to the slider visual thumbs. */
private _setIsFocused(v: boolean): void {
this._isFocused = v;
}
/**
* Whether the initial value has been set.
* This exists because the initial value cannot be immediately set because the min and max
* must first be relayed from the parent MatSlider component, which can only happen later
* in the component lifecycle.
*/
private _hasSetInitialValue: boolean = false;
/** The stored initial value. */
_initialValue: string | undefined;
/** Defined when a user is using a form control to manage slider value & validation. */
private _formControl: FormControl | undefined;
/** Emits when the component is destroyed. */
protected readonly _destroyed = new Subject<void>();
/**
* Indicates whether UI updates should be skipped.
*
* This flag is used to avoid flickering
* when correcting values on pointer up/down.
*/
_skipUIUpdate: boolean = false;
/** Callback called when the slider input value changes. */
protected _onChangeFn: ((value: any) => void) | undefined;
/** Callback called when the slider input has been touched. */
private _onTouchedFn: () => void = () => {};
/**
* Whether the NgModel has been initialized.
*
* This flag is used to ignore ghost null calls to
* writeValue which can break slider initialization.
*
* See https://github.com/angular/angular/issues/14988.
*/
protected _isControlInitialized = false;
private _platform = inject(Platform);
constructor(...args: unknown[]);
constructor() {
this._ngZone.runOutsideAngular(() => {
this._hostElement.addEventListener('pointerdown', this._onPointerDown.bind(this));
this._hostElement.addEventListener('pointermove', this._onPointerMove.bind(this));
this._hostElement.addEventListener('pointerup', this._onPointerUp.bind(this));
});
}
ngOnDestroy(): void {
this._hostElement.removeEventListener('pointerdown', this._onPointerDown);
this._hostElement.removeEventListener('pointermove', this._onPointerMove);
this._hostElement.removeEventListener('pointerup', this._onPointerUp);
this._destroyed.next();
this._destroyed.complete();
this.dragStart.complete();
this.dragEnd.complete();
}
/** @docs-private */
initProps(): void {
this._updateWidthInactive();
// If this or the parent slider is disabled, just make everything disabled.
if (this.disabled !== this._slider.disabled) {
// The MatSlider setter for disabled will relay this and disable both inputs.
this._slider.disabled = true;
}
this.step = this._slider.step;
this.min = this._slider.min;
this.max = this._slider.max;
this._initValue();
}
/** @docs-private */
initUI(): void {
this._updateThumbUIByValue();
}
_initValue(): void {
this._hasSetInitialValue = true;
if (this._initialValue === undefined) {
this.value = this._getDefaultValue();
} else {
this._hostElement.value = this._initialValue;
this._updateThumbUIByValue();
this._slider._onValueChange(this);
this._cdr.detectChanges();
}
}
_getDefaultValue(): number {
return this.min;
}
_onBlur(): void {
this._setIsFocused(false);
this._onTouchedFn();
}
_onFocus(): void {
this._slider._setTransition(false);
this._slider._updateTrackUI(this);
this._setIsFocused(true);
}
_onChange(): void {
this.valueChange.emit(this.value);
// only used to handle the edge case where user
// mousedown on the slider then uses arrow keys.
if (this._isActive) {
this._updateThumbUIByValue({withAnimation: true});
}
} | {
"end_byte": 10293,
"start_byte": 2331,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider-input.ts"
} |
components/src/material/slider/slider-input.ts_10297_18249 | _onInput(): void {
this._onChangeFn?.(this.value);
// handles arrowing and updating the value when
// a step is defined.
if (this._slider.step || !this._isActive) {
this._updateThumbUIByValue({withAnimation: true});
}
this._slider._onValueChange(this);
}
_onNgControlValueChange(): void {
// only used to handle when the value change
// originates outside of the slider.
if (!this._isActive || !this._isFocused) {
this._slider._onValueChange(this);
this._updateThumbUIByValue();
}
this._slider.disabled = this._formControl!.disabled;
}
_onPointerDown(event: PointerEvent): void {
if (this.disabled || event.button !== 0) {
return;
}
// On IOS, dragging only works if the pointer down happens on the
// slider thumb and the slider does not receive focus from pointer events.
if (this._platform.IOS) {
const isCursorOnSliderThumb = this._slider._isCursorOnSliderThumb(
event,
this._slider._getThumb(this.thumbPosition)._hostElement.getBoundingClientRect(),
);
this._isActive = isCursorOnSliderThumb;
this._updateWidthActive();
this._slider._updateDimensions();
return;
}
this._isActive = true;
this._setIsFocused(true);
this._updateWidthActive();
this._slider._updateDimensions();
// Does nothing if a step is defined because we
// want the value to snap to the values on input.
if (!this._slider.step) {
this._updateThumbUIByPointerEvent(event, {withAnimation: true});
}
if (!this.disabled) {
this._handleValueCorrection(event);
this.dragStart.emit({source: this, parent: this._slider, value: this.value});
}
}
/**
* Corrects the value of the slider on pointer up/down.
*
* Called on pointer down and up because the value is set based
* on the inactive width instead of the active width.
*/
private _handleValueCorrection(event: PointerEvent): void {
// Don't update the UI with the current value! The value on pointerdown
// and pointerup is calculated in the split second before the input(s)
// resize. See _updateWidthInactive() and _updateWidthActive() for more
// details.
this._skipUIUpdate = true;
// Note that this function gets triggered before the actual value of the
// slider is updated. This means if we were to set the value here, it
// would immediately be overwritten. Using setTimeout ensures the setting
// of the value happens after the value has been updated by the
// pointerdown event.
setTimeout(() => {
this._skipUIUpdate = false;
this._fixValue(event);
}, 0);
}
/** Corrects the value of the slider based on the pointer event's position. */
_fixValue(event: PointerEvent): void {
const xPos = event.clientX - this._slider._cachedLeft;
const width = this._slider._cachedWidth;
const step = this._slider.step === 0 ? 1 : this._slider.step;
const numSteps = Math.floor((this._slider.max - this._slider.min) / step);
const percentage = this._slider._isRtl ? 1 - xPos / width : xPos / width;
// To ensure the percentage is rounded to the necessary number of decimals.
const fixedPercentage = Math.round(percentage * numSteps) / numSteps;
const impreciseValue =
fixedPercentage * (this._slider.max - this._slider.min) + this._slider.min;
const value = Math.round(impreciseValue / step) * step;
const prevValue = this.value;
if (value === prevValue) {
// Because we prevented UI updates, if it turns out that the race
// condition didn't happen and the value is already correct, we
// have to apply the ui updates now.
this._slider._onValueChange(this);
this._slider.step > 0
? this._updateThumbUIByValue()
: this._updateThumbUIByPointerEvent(event, {withAnimation: this._slider._hasAnimation});
return;
}
this.value = value;
this.valueChange.emit(this.value);
this._onChangeFn?.(this.value);
this._slider._onValueChange(this);
this._slider.step > 0
? this._updateThumbUIByValue()
: this._updateThumbUIByPointerEvent(event, {withAnimation: this._slider._hasAnimation});
}
_onPointerMove(event: PointerEvent): void {
// Again, does nothing if a step is defined because
// we want the value to snap to the values on input.
if (!this._slider.step && this._isActive) {
this._updateThumbUIByPointerEvent(event);
}
}
_onPointerUp(): void {
if (this._isActive) {
this._isActive = false;
if (this._platform.SAFARI) {
this._setIsFocused(false);
}
this.dragEnd.emit({source: this, parent: this._slider, value: this.value});
// This setTimeout is to prevent the pointerup from triggering a value
// change on the input based on the inactive width. It's not clear why
// but for some reason on IOS this race condition is even more common so
// the timeout needs to be increased.
setTimeout(() => this._updateWidthInactive(), this._platform.IOS ? 10 : 0);
}
}
_clamp(v: number): number {
const min = this._tickMarkOffset;
const max = this._slider._cachedWidth - this._tickMarkOffset;
return Math.max(Math.min(v, max), min);
}
_calcTranslateXByValue(): number {
if (this._slider._isRtl) {
return (
(1 - this.percentage) * (this._slider._cachedWidth - this._tickMarkOffset * 2) +
this._tickMarkOffset
);
}
return (
this.percentage * (this._slider._cachedWidth - this._tickMarkOffset * 2) +
this._tickMarkOffset
);
}
_calcTranslateXByPointerEvent(event: PointerEvent): number {
return event.clientX - this._slider._cachedLeft;
}
/**
* Used to set the slider width to the correct
* dimensions while the user is dragging.
*/
_updateWidthActive(): void {}
/**
* Sets the slider input to disproportionate dimensions to allow for touch
* events to be captured on touch devices.
*/
_updateWidthInactive(): void {
this._hostElement.style.padding = `0 ${this._slider._inputPadding}px`;
this._hostElement.style.width = `calc(100% + ${
this._slider._inputPadding - this._tickMarkOffset * 2
}px)`;
this._hostElement.style.left = `-${this._slider._rippleRadius - this._tickMarkOffset}px`;
}
_updateThumbUIByValue(options?: {withAnimation: boolean}): void {
this.translateX = this._clamp(this._calcTranslateXByValue());
this._updateThumbUI(options);
}
_updateThumbUIByPointerEvent(event: PointerEvent, options?: {withAnimation: boolean}): void {
this.translateX = this._clamp(this._calcTranslateXByPointerEvent(event));
this._updateThumbUI(options);
}
_updateThumbUI(options?: {withAnimation: boolean}) {
this._slider._setTransition(!!options?.withAnimation);
this._slider._onTranslateXChange(this);
}
/**
* Sets the input's value.
* @param value The new value of the input
* @docs-private
*/
writeValue(value: any): void {
if (this._isControlInitialized || value !== null) {
this.value = value;
}
}
/**
* Registers a callback to be invoked when the input's value changes from user input.
* @param fn The callback to register
* @docs-private
*/
registerOnChange(fn: any): void {
this._onChangeFn = fn;
this._isControlInitialized = true;
}
/**
* Registers a callback to be invoked when the input is blurred by the user.
* @param fn The callback to register
* @docs-private
*/
registerOnTouched(fn: any): void {
this._onTouchedFn = fn;
}
/**
* Sets the disabled state of the slider.
* @param isDisabled The new disabled state
* @docs-private
*/
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
focus(): void {
this._hostElement.focus();
}
blur(): void {
this._hostElement.blur();
}
} | {
"end_byte": 18249,
"start_byte": 10297,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider-input.ts"
} |
components/src/material/slider/slider-input.ts_18251_24917 | @Directive({
selector: 'input[matSliderStartThumb], input[matSliderEndThumb]',
exportAs: 'matSliderRangeThumb',
providers: [
MAT_SLIDER_RANGE_THUMB_VALUE_ACCESSOR,
{provide: MAT_SLIDER_RANGE_THUMB, useExisting: MatSliderRangeThumb},
],
})
export class MatSliderRangeThumb extends MatSliderThumb implements _MatSliderRangeThumb {
override readonly _cdr = inject(ChangeDetectorRef);
/** @docs-private */
getSibling(): _MatSliderRangeThumb | undefined {
if (!this._sibling) {
this._sibling = this._slider._getInput(this._isEndThumb ? _MatThumb.START : _MatThumb.END) as
| MatSliderRangeThumb
| undefined;
}
return this._sibling;
}
private _sibling: MatSliderRangeThumb | undefined;
/**
* Returns the minimum translateX position allowed for this slider input's visual thumb.
* @docs-private
*/
getMinPos(): number {
const sibling = this.getSibling();
if (!this._isLeftThumb && sibling) {
return sibling.translateX;
}
return this._tickMarkOffset;
}
/**
* Returns the maximum translateX position allowed for this slider input's visual thumb.
* @docs-private
*/
getMaxPos(): number {
const sibling = this.getSibling();
if (this._isLeftThumb && sibling) {
return sibling.translateX;
}
return this._slider._cachedWidth - this._tickMarkOffset;
}
_setIsLeftThumb(): void {
this._isLeftThumb =
(this._isEndThumb && this._slider._isRtl) || (!this._isEndThumb && !this._slider._isRtl);
}
/** Whether this slider corresponds to the input on the left hand side. */
_isLeftThumb: boolean;
/** Whether this slider corresponds to the input with greater value. */
_isEndThumb: boolean;
constructor(...args: unknown[]);
constructor() {
super();
this._isEndThumb = this._hostElement.hasAttribute('matSliderEndThumb');
this._setIsLeftThumb();
this.thumbPosition = this._isEndThumb ? _MatThumb.END : _MatThumb.START;
}
override _getDefaultValue(): number {
return this._isEndThumb && this._slider._isRange ? this.max : this.min;
}
override _onInput(): void {
super._onInput();
this._updateSibling();
if (!this._isActive) {
this._updateWidthInactive();
}
}
override _onNgControlValueChange(): void {
super._onNgControlValueChange();
this.getSibling()?._updateMinMax();
}
override _onPointerDown(event: PointerEvent): void {
if (this.disabled || event.button !== 0) {
return;
}
if (this._sibling) {
this._sibling._updateWidthActive();
this._sibling._hostElement.classList.add('mat-mdc-slider-input-no-pointer-events');
}
super._onPointerDown(event);
}
override _onPointerUp(): void {
super._onPointerUp();
if (this._sibling) {
setTimeout(() => {
this._sibling!._updateWidthInactive();
this._sibling!._hostElement.classList.remove('mat-mdc-slider-input-no-pointer-events');
});
}
}
override _onPointerMove(event: PointerEvent): void {
super._onPointerMove(event);
if (!this._slider.step && this._isActive) {
this._updateSibling();
}
}
override _fixValue(event: PointerEvent): void {
super._fixValue(event);
this._sibling?._updateMinMax();
}
override _clamp(v: number): number {
return Math.max(Math.min(v, this.getMaxPos()), this.getMinPos());
}
_updateMinMax(): void {
const sibling = this.getSibling();
if (!sibling) {
return;
}
if (this._isEndThumb) {
this.min = Math.max(this._slider.min, sibling.value);
this.max = this._slider.max;
} else {
this.min = this._slider.min;
this.max = Math.min(this._slider.max, sibling.value);
}
}
override _updateWidthActive(): void {
const minWidth = this._slider._rippleRadius * 2 - this._slider._inputPadding * 2;
const maxWidth =
this._slider._cachedWidth + this._slider._inputPadding - minWidth - this._tickMarkOffset * 2;
const percentage =
this._slider.min < this._slider.max
? (this.max - this.min) / (this._slider.max - this._slider.min)
: 1;
const width = maxWidth * percentage + minWidth;
this._hostElement.style.width = `${width}px`;
this._hostElement.style.padding = `0 ${this._slider._inputPadding}px`;
}
override _updateWidthInactive(): void {
const sibling = this.getSibling();
if (!sibling) {
return;
}
const maxWidth = this._slider._cachedWidth - this._tickMarkOffset * 2;
const midValue = this._isEndThumb
? this.value - (this.value - sibling.value) / 2
: this.value + (sibling.value - this.value) / 2;
const _percentage = this._isEndThumb
? (this.max - midValue) / (this._slider.max - this._slider.min)
: (midValue - this.min) / (this._slider.max - this._slider.min);
const percentage = this._slider.min < this._slider.max ? _percentage : 1;
// Extend the native input width by the radius of the ripple
let ripplePadding = this._slider._rippleRadius;
// If one of the inputs is maximally sized (the value of both thumbs is
// equal to the min or max), make that input take up all of the width and
// make the other unselectable.
if (percentage === 1) {
ripplePadding = 48;
} else if (percentage === 0) {
ripplePadding = 0;
}
const width = maxWidth * percentage + ripplePadding;
this._hostElement.style.width = `${width}px`;
this._hostElement.style.padding = '0px';
if (this._isLeftThumb) {
this._hostElement.style.left = `-${this._slider._rippleRadius - this._tickMarkOffset}px`;
this._hostElement.style.right = 'auto';
} else {
this._hostElement.style.left = 'auto';
this._hostElement.style.right = `-${this._slider._rippleRadius - this._tickMarkOffset}px`;
}
}
_updateStaticStyles(): void {
this._hostElement.classList.toggle('mat-slider__right-input', !this._isLeftThumb);
}
private _updateSibling(): void {
const sibling = this.getSibling();
if (!sibling) {
return;
}
sibling._updateMinMax();
if (this._isActive) {
sibling._updateWidthActive();
} else {
sibling._updateWidthInactive();
}
}
/**
* Sets the input's value.
* @param value The new value of the input
* @docs-private
*/
override writeValue(value: any): void {
if (this._isControlInitialized || value !== null) {
this.value = value;
this._updateWidthInactive();
this._updateSibling();
}
}
override _setValue(value: string) {
super._setValue(value);
this._updateWidthInactive();
this._updateSibling();
}
} | {
"end_byte": 24917,
"start_byte": 18251,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider-input.ts"
} |
components/src/material/slider/public-api.ts_0_475 | /**
* @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 {MatSlider} from './slider';
export {MatSliderVisualThumb} from './slider-thumb';
export {MatSliderThumb, MatSliderRangeThumb} from './slider-input';
export {MatSliderDragEvent, MatSliderChange} from './slider-interface';
export {MatSliderModule} from './module';
| {
"end_byte": 475,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/public-api.ts"
} |
components/src/material/slider/slider.e2e.spec.ts_0_6516 | /**
* @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 {$, browser, by, element, ElementFinder} from 'protractor';
import {logging} from 'selenium-webdriver';
describe('MatSlider', () => {
const getStandardSlider = () => element(by.id('standard-slider'));
const getDisabledSlider = () => element(by.id('disabled-slider'));
const getRangeSlider = () => element(by.id('range-slider'));
beforeEach(async () => await browser.get('/slider'));
describe('standard slider', async () => {
let slider: ElementFinder;
beforeEach(() => {
slider = getStandardSlider();
});
it('should update the value on click', async () => {
await setValueByClick(slider, 49);
expect(await getSliderValue(slider, Thumb.END)).toBe(49);
});
it('should update the value on slide', async () => {
await slideToValue(slider, 35, Thumb.END);
expect(await getSliderValue(slider, Thumb.END)).toBe(35);
});
it('should display the value indicator when focused', async () => {
await focusSliderThumb(slider, Thumb.END);
const rect: DOMRect = await browser.executeScript(
'return arguments[0].getBoundingClientRect();',
$('.mdc-slider__value-indicator'),
);
expect(rect.width).not.toBe(0);
expect(rect.height).not.toBe(0);
await browser.actions().mouseUp().perform();
});
it('should not cause passive event listener errors when changing the value', async () => {
// retrieving the logs clears the collection
await browser.manage().logs().get('browser');
await setValueByClick(slider, 15);
expect(await browser.manage().logs().get('browser')).not.toContain(
jasmine.objectContaining({level: logging.Level.SEVERE}),
);
});
});
describe('disabled slider', async () => {
let slider: ElementFinder;
beforeEach(() => {
slider = getDisabledSlider();
});
it('should not update the value on click', async () => {
await setValueByClick(slider, 15);
expect(await getSliderValue(slider, Thumb.END)).not.toBe(15);
});
it('should not update the value on slide', async () => {
await slideToValue(slider, 35, Thumb.END);
expect(await getSliderValue(slider, Thumb.END)).not.toBe(35);
});
});
describe('range slider', async () => {
let slider: ElementFinder;
beforeEach(() => {
slider = getRangeSlider();
});
it('should update the start thumb value on slide', async () => {
await slideToValue(slider, 35, Thumb.START);
expect(await getSliderValue(slider, Thumb.START)).toBe(35);
});
it('should update the end thumb value on slide', async () => {
await slideToValue(slider, 55, Thumb.END);
expect(await getSliderValue(slider, Thumb.END)).toBe(55);
});
it(
'should update the start thumb value on click between thumbs ' +
'but closer to the start thumb',
async () => {
await setValueByClick(slider, 49);
expect(await getSliderValue(slider, Thumb.START)).toBe(49);
expect(await getSliderValue(slider, Thumb.END)).toBe(100);
},
);
it(
'should update the end thumb value on click between thumbs ' + 'but closer to the end thumb',
async () => {
await setValueByClick(slider, 51);
expect(await getSliderValue(slider, Thumb.START)).toBe(0);
expect(await getSliderValue(slider, Thumb.END)).toBe(51);
},
);
});
});
/** Returns the current value of the slider. */
async function getSliderValue(slider: ElementFinder, thumbPosition: Thumb): Promise<number> {
const inputs = await slider.all(by.css('.mdc-slider__input'));
return thumbPosition === Thumb.END
? Number(await inputs[inputs.length - 1].getAttribute('value'))
: Number(await inputs[0].getAttribute('value'));
}
/** Focuses on the MatSlider at the coordinates corresponding to the given thumb. */
async function focusSliderThumb(slider: ElementFinder, thumbPosition: Thumb): Promise<void> {
const webElement = await slider.getWebElement();
const coords = await getCoordsForValue(slider, await getSliderValue(slider, thumbPosition));
return await browser.actions().mouseMove(webElement, coords).mouseDown().perform();
}
/** Clicks on the MatSlider at the coordinates corresponding to the given value. */
async function setValueByClick(slider: ElementFinder, value: number): Promise<void> {
return clickElementAtPoint(slider, await getCoordsForValue(slider, value));
}
/** Clicks on the MatSlider at the coordinates corresponding to the given value. */
async function slideToValue(
slider: ElementFinder,
value: number,
thumbPosition: Thumb,
): Promise<void> {
const webElement = await slider.getWebElement();
const startCoords = await getCoordsForValue(slider, await getSliderValue(slider, thumbPosition));
const endCoords = await getCoordsForValue(slider, value);
return await browser
.actions()
.mouseMove(webElement, startCoords)
.mouseDown()
.mouseMove(webElement, endCoords)
.mouseUp()
.perform();
}
/** Returns the x and y coordinates for the given slider value. */
async function getCoordsForValue(slider: ElementFinder, value: number): Promise<Point> {
const inputs = await slider.all(by.css('.mdc-slider__input'));
const min = Number(await inputs[0].getAttribute('min'));
const max = Number(await inputs[inputs.length - 1].getAttribute('max'));
const percent = (value - min) / (max - min);
const {width, height} = await slider.getSize();
// NOTE: We use Math.round here because protractor silently breaks if you pass in an imprecise
// floating point number with lots of decimals. This allows us to avoid the headache but it may
// cause some innaccuracies in places where these decimals mean the difference between values.
const x = Math.round(width * percent);
const y = Math.round(height / 2);
return {x, y};
}
enum Thumb {
START = 1,
END = 2,
}
interface Point {
x: number;
y: number;
}
/**
* Clicks an element at a specific point. Useful if there's another element
* that covers part of the target and can catch the click.
*/
async function clickElementAtPoint(target: ElementFinder, coords: Point) {
const webElement = await target.getWebElement();
await browser.actions().mouseMove(webElement, coords).click().perform();
}
| {
"end_byte": 6516,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.e2e.spec.ts"
} |
components/src/material/slider/slider.ts_0_2166 | /**
* @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 {Directionality} from '@angular/cdk/bidi';
import {Platform} from '@angular/cdk/platform';
import {
AfterViewInit,
booleanAttribute,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ContentChildren,
ElementRef,
inject,
Input,
NgZone,
numberAttribute,
OnDestroy,
QueryList,
ViewChild,
ViewChildren,
ViewEncapsulation,
ANIMATION_MODULE_TYPE,
} from '@angular/core';
import {
_StructuralStylesLoader,
MAT_RIPPLE_GLOBAL_OPTIONS,
RippleGlobalOptions,
ThemePalette,
} from '@angular/material/core';
import {Subscription} from 'rxjs';
import {
_MatThumb,
_MatTickMark,
_MatSlider,
_MatSliderRangeThumb,
_MatSliderThumb,
_MatSliderVisualThumb,
MAT_SLIDER_RANGE_THUMB,
MAT_SLIDER_THUMB,
MAT_SLIDER,
MAT_SLIDER_VISUAL_THUMB,
} from './slider-interface';
import {MatSliderVisualThumb} from './slider-thumb';
import {_CdkPrivateStyleLoader} from '@angular/cdk/private';
// TODO(wagnermaciel): maybe handle the following edge case:
// 1. start dragging discrete slider
// 2. tab to disable checkbox
// 3. without ending drag, disable the slider
/**
* Allows users to select from a range of values by moving the slider thumb. It is similar in
* behavior to the native `<input type="range">` element.
*/
@Component({
selector: 'mat-slider',
templateUrl: 'slider.html',
styleUrl: 'slider.css',
host: {
'class': 'mat-mdc-slider mdc-slider',
'[class]': '"mat-" + (color || "primary")',
'[class.mdc-slider--range]': '_isRange',
'[class.mdc-slider--disabled]': 'disabled',
'[class.mdc-slider--discrete]': 'discrete',
'[class.mdc-slider--tick-marks]': 'showTickMarks',
'[class._mat-animation-noopable]': '_noopAnimations',
},
exportAs: 'matSlider',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
providers: [{provide: MAT_SLIDER, useExisting: MatSlider}],
imports: [MatSliderVisualThumb],
})
export | {
"end_byte": 2166,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.ts"
} |
components/src/material/slider/slider.ts_2167_9511 | class MatSlider implements AfterViewInit, OnDestroy, _MatSlider {
readonly _ngZone = inject(NgZone);
readonly _cdr = inject(ChangeDetectorRef);
readonly _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
readonly _dir = inject(Directionality, {optional: true});
readonly _globalRippleOptions = inject<RippleGlobalOptions>(MAT_RIPPLE_GLOBAL_OPTIONS, {
optional: true,
});
/** The active portion of the slider track. */
@ViewChild('trackActive') _trackActive: ElementRef<HTMLElement>;
/** The slider thumb(s). */
@ViewChildren(MAT_SLIDER_VISUAL_THUMB) _thumbs: QueryList<_MatSliderVisualThumb>;
/** The sliders hidden range input(s). */
@ContentChild(MAT_SLIDER_THUMB) _input: _MatSliderThumb;
/** The sliders hidden range input(s). */
@ContentChildren(MAT_SLIDER_RANGE_THUMB, {descendants: false})
_inputs: QueryList<_MatSliderRangeThumb>;
/** Whether the slider is disabled. */
@Input({transform: booleanAttribute})
get disabled(): boolean {
return this._disabled;
}
set disabled(v: boolean) {
this._disabled = v;
const endInput = this._getInput(_MatThumb.END);
const startInput = this._getInput(_MatThumb.START);
if (endInput) {
endInput.disabled = this._disabled;
}
if (startInput) {
startInput.disabled = this._disabled;
}
}
private _disabled: boolean = false;
/** Whether the slider displays a numeric value label upon pressing the thumb. */
@Input({transform: booleanAttribute})
get discrete(): boolean {
return this._discrete;
}
set discrete(v: boolean) {
this._discrete = v;
this._updateValueIndicatorUIs();
}
private _discrete: boolean = false;
/** Whether the slider displays tick marks along the slider track. */
@Input({transform: booleanAttribute})
showTickMarks: boolean = false;
/** The minimum value that the slider can have. */
@Input({transform: numberAttribute})
get min(): number {
return this._min;
}
set min(v: number) {
const min = isNaN(v) ? this._min : v;
if (this._min !== min) {
this._updateMin(min);
}
}
private _min: number = 0;
/**
* Theme color of the slider. 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;
/** Whether ripples are disabled in the slider. */
@Input({transform: booleanAttribute})
disableRipple: boolean = false;
private _updateMin(min: number): void {
const prevMin = this._min;
this._min = min;
this._isRange ? this._updateMinRange({old: prevMin, new: min}) : this._updateMinNonRange(min);
this._onMinMaxOrStepChange();
}
private _updateMinRange(min: {old: number; new: number}): void {
const endInput = this._getInput(_MatThumb.END) as _MatSliderRangeThumb;
const startInput = this._getInput(_MatThumb.START) as _MatSliderRangeThumb;
const oldEndValue = endInput.value;
const oldStartValue = startInput.value;
startInput.min = min.new;
endInput.min = Math.max(min.new, startInput.value);
startInput.max = Math.min(endInput.max, endInput.value);
startInput._updateWidthInactive();
endInput._updateWidthInactive();
min.new < min.old
? this._onTranslateXChangeBySideEffect(endInput, startInput)
: this._onTranslateXChangeBySideEffect(startInput, endInput);
if (oldEndValue !== endInput.value) {
this._onValueChange(endInput);
}
if (oldStartValue !== startInput.value) {
this._onValueChange(startInput);
}
}
private _updateMinNonRange(min: number): void {
const input = this._getInput(_MatThumb.END);
if (input) {
const oldValue = input.value;
input.min = min;
input._updateThumbUIByValue();
this._updateTrackUI(input);
if (oldValue !== input.value) {
this._onValueChange(input);
}
}
}
/** The maximum value that the slider can have. */
@Input({transform: numberAttribute})
get max(): number {
return this._max;
}
set max(v: number) {
const max = isNaN(v) ? this._max : v;
if (this._max !== max) {
this._updateMax(max);
}
}
private _max: number = 100;
private _updateMax(max: number): void {
const prevMax = this._max;
this._max = max;
this._isRange ? this._updateMaxRange({old: prevMax, new: max}) : this._updateMaxNonRange(max);
this._onMinMaxOrStepChange();
}
private _updateMaxRange(max: {old: number; new: number}): void {
const endInput = this._getInput(_MatThumb.END) as _MatSliderRangeThumb;
const startInput = this._getInput(_MatThumb.START) as _MatSliderRangeThumb;
const oldEndValue = endInput.value;
const oldStartValue = startInput.value;
endInput.max = max.new;
startInput.max = Math.min(max.new, endInput.value);
endInput.min = startInput.value;
endInput._updateWidthInactive();
startInput._updateWidthInactive();
max.new > max.old
? this._onTranslateXChangeBySideEffect(startInput, endInput)
: this._onTranslateXChangeBySideEffect(endInput, startInput);
if (oldEndValue !== endInput.value) {
this._onValueChange(endInput);
}
if (oldStartValue !== startInput.value) {
this._onValueChange(startInput);
}
}
private _updateMaxNonRange(max: number): void {
const input = this._getInput(_MatThumb.END);
if (input) {
const oldValue = input.value;
input.max = max;
input._updateThumbUIByValue();
this._updateTrackUI(input);
if (oldValue !== input.value) {
this._onValueChange(input);
}
}
}
/** The values at which the thumb will snap. */
@Input({transform: numberAttribute})
get step(): number {
return this._step;
}
set step(v: number) {
const step = isNaN(v) ? this._step : v;
if (this._step !== step) {
this._updateStep(step);
}
}
private _step: number = 1;
private _updateStep(step: number): void {
this._step = step;
this._isRange ? this._updateStepRange() : this._updateStepNonRange();
this._onMinMaxOrStepChange();
}
private _updateStepRange(): void {
const endInput = this._getInput(_MatThumb.END) as _MatSliderRangeThumb;
const startInput = this._getInput(_MatThumb.START) as _MatSliderRangeThumb;
const oldEndValue = endInput.value;
const oldStartValue = startInput.value;
const prevStartValue = startInput.value;
endInput.min = this._min;
startInput.max = this._max;
endInput.step = this._step;
startInput.step = this._step;
if (this._platform.SAFARI) {
endInput.value = endInput.value;
startInput.value = startInput.value;
}
endInput.min = Math.max(this._min, startInput.value);
startInput.max = Math.min(this._max, endInput.value);
startInput._updateWidthInactive();
endInput._updateWidthInactive();
endInput.value < prevStartValue
? this._onTranslateXChangeBySideEffect(startInput, endInput)
: this._onTranslateXChangeBySideEffect(endInput, startInput);
if (oldEndValue !== endInput.value) {
this._onValueChange(endInput);
}
if (oldStartValue !== startInput.value) {
this._onValueChange(startInput);
}
} | {
"end_byte": 9511,
"start_byte": 2167,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.ts"
} |
components/src/material/slider/slider.ts_9515_17406 | private _updateStepNonRange(): void {
const input = this._getInput(_MatThumb.END);
if (input) {
const oldValue = input.value;
input.step = this._step;
if (this._platform.SAFARI) {
input.value = input.value;
}
input._updateThumbUIByValue();
if (oldValue !== input.value) {
this._onValueChange(input);
}
}
}
/**
* Function that will be used to format the value before it is displayed
* in the thumb label. Can be used to format very large number in order
* for them to fit into the slider thumb.
*/
@Input() displayWith: (value: number) => string = (value: number) => `${value}`;
/** Used to keep track of & render the active & inactive tick marks on the slider track. */
_tickMarks: _MatTickMark[];
/** Whether animations have been disabled. */
_noopAnimations: boolean;
/** Subscription to changes to the directionality (LTR / RTL) context for the application. */
private _dirChangeSubscription: Subscription;
/** Observer used to monitor size changes in the slider. */
private _resizeObserver: ResizeObserver | null;
// Stored dimensions to avoid calling getBoundingClientRect redundantly.
_cachedWidth: number;
_cachedLeft: number;
_rippleRadius: number = 24;
// The value indicator tooltip text for the visual slider thumb(s).
/** @docs-private */
protected startValueIndicatorText: string = '';
/** @docs-private */
protected endValueIndicatorText: string = '';
// Used to control the translateX of the visual slider thumb(s).
_endThumbTransform: string;
_startThumbTransform: string;
_isRange: boolean = false;
/** Whether the slider is rtl. */
_isRtl: boolean = false;
private _hasViewInitialized: boolean = false;
/**
* The width of the tick mark track.
* The tick mark track width is different from full track width
*/
_tickMarkTrackWidth: number = 0;
_hasAnimation: boolean = false;
private _resizeTimer: null | ReturnType<typeof setTimeout> = null;
private _platform = inject(Platform);
constructor(...args: unknown[]);
constructor() {
inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader);
const animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true});
this._noopAnimations = animationMode === 'NoopAnimations';
if (this._dir) {
this._dirChangeSubscription = this._dir.change.subscribe(() => this._onDirChange());
this._isRtl = this._dir.value === 'rtl';
}
}
/** The radius of the native slider's knob. AFAIK there is no way to avoid hardcoding this. */
_knobRadius: number = 8;
_inputPadding: number;
ngAfterViewInit(): void {
if (this._platform.isBrowser) {
this._updateDimensions();
}
const eInput = this._getInput(_MatThumb.END);
const sInput = this._getInput(_MatThumb.START);
this._isRange = !!eInput && !!sInput;
this._cdr.detectChanges();
if (typeof ngDevMode === 'undefined' || ngDevMode) {
_validateInputs(
this._isRange,
this._getInput(_MatThumb.END),
this._getInput(_MatThumb.START),
);
}
const thumb = this._getThumb(_MatThumb.END);
this._rippleRadius = thumb._ripple.radius;
this._inputPadding = this._rippleRadius - this._knobRadius;
this._isRange
? this._initUIRange(eInput as _MatSliderRangeThumb, sInput as _MatSliderRangeThumb)
: this._initUINonRange(eInput!);
this._updateTrackUI(eInput!);
this._updateTickMarkUI();
this._updateTickMarkTrackUI();
this._observeHostResize();
this._cdr.detectChanges();
}
private _initUINonRange(eInput: _MatSliderThumb): void {
eInput.initProps();
eInput.initUI();
this._updateValueIndicatorUI(eInput);
this._hasViewInitialized = true;
eInput._updateThumbUIByValue();
}
private _initUIRange(eInput: _MatSliderRangeThumb, sInput: _MatSliderRangeThumb): void {
eInput.initProps();
eInput.initUI();
sInput.initProps();
sInput.initUI();
eInput._updateMinMax();
sInput._updateMinMax();
eInput._updateStaticStyles();
sInput._updateStaticStyles();
this._updateValueIndicatorUIs();
this._hasViewInitialized = true;
eInput._updateThumbUIByValue();
sInput._updateThumbUIByValue();
}
ngOnDestroy(): void {
this._dirChangeSubscription.unsubscribe();
this._resizeObserver?.disconnect();
this._resizeObserver = null;
}
/** Handles updating the slider ui after a dir change. */
private _onDirChange(): void {
this._isRtl = this._dir?.value === 'rtl';
this._isRange ? this._onDirChangeRange() : this._onDirChangeNonRange();
this._updateTickMarkUI();
}
private _onDirChangeRange(): void {
const endInput = this._getInput(_MatThumb.END) as _MatSliderRangeThumb;
const startInput = this._getInput(_MatThumb.START) as _MatSliderRangeThumb;
endInput._setIsLeftThumb();
startInput._setIsLeftThumb();
endInput.translateX = endInput._calcTranslateXByValue();
startInput.translateX = startInput._calcTranslateXByValue();
endInput._updateStaticStyles();
startInput._updateStaticStyles();
endInput._updateWidthInactive();
startInput._updateWidthInactive();
endInput._updateThumbUIByValue();
startInput._updateThumbUIByValue();
}
private _onDirChangeNonRange(): void {
const input = this._getInput(_MatThumb.END)!;
input._updateThumbUIByValue();
}
/** Starts observing and updating the slider if the host changes its size. */
private _observeHostResize() {
if (typeof ResizeObserver === 'undefined' || !ResizeObserver) {
return;
}
this._ngZone.runOutsideAngular(() => {
this._resizeObserver = new ResizeObserver(() => {
if (this._isActive()) {
return;
}
if (this._resizeTimer) {
clearTimeout(this._resizeTimer);
}
this._onResize();
});
this._resizeObserver.observe(this._elementRef.nativeElement);
});
}
/** Whether any of the thumbs are currently active. */
private _isActive(): boolean {
return this._getThumb(_MatThumb.START)._isActive || this._getThumb(_MatThumb.END)._isActive;
}
private _getValue(thumbPosition: _MatThumb = _MatThumb.END): number {
const input = this._getInput(thumbPosition);
if (!input) {
return this.min;
}
return input.value;
}
private _skipUpdate(): boolean {
return !!(
this._getInput(_MatThumb.START)?._skipUIUpdate || this._getInput(_MatThumb.END)?._skipUIUpdate
);
}
/** Stores the slider dimensions. */
_updateDimensions(): void {
this._cachedWidth = this._elementRef.nativeElement.offsetWidth;
this._cachedLeft = this._elementRef.nativeElement.getBoundingClientRect().left;
}
/** Sets the styles for the active portion of the track. */
_setTrackActiveStyles(styles: {
left: string;
right: string;
transform: string;
transformOrigin: string;
}): void {
const trackStyle = this._trackActive.nativeElement.style;
trackStyle.left = styles.left;
trackStyle.right = styles.right;
trackStyle.transformOrigin = styles.transformOrigin;
trackStyle.transform = styles.transform;
}
/** Returns the translateX positioning for a tick mark based on it's index. */
_calcTickMarkTransform(index: number): string {
// TODO(wagnermaciel): See if we can avoid doing this and just using flex to position these.
const translateX = index * (this._tickMarkTrackWidth / (this._tickMarks.length - 1));
return `translateX(${translateX}px`;
}
// Handlers for updating the slider ui.
_onTranslateXChange(source: _MatSliderThumb): void {
if (!this._hasViewInitialized) {
return;
}
this._updateThumbUI(source);
this._updateTrackUI(source);
this._updateOverlappingThumbUI(source as _MatSliderRangeThumb);
} | {
"end_byte": 17406,
"start_byte": 9515,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.ts"
} |
components/src/material/slider/slider.ts_17410_24831 | _onTranslateXChangeBySideEffect(
input1: _MatSliderRangeThumb,
input2: _MatSliderRangeThumb,
): void {
if (!this._hasViewInitialized) {
return;
}
input1._updateThumbUIByValue();
input2._updateThumbUIByValue();
}
_onValueChange(source: _MatSliderThumb): void {
if (!this._hasViewInitialized) {
return;
}
this._updateValueIndicatorUI(source);
this._updateTickMarkUI();
this._cdr.detectChanges();
}
_onMinMaxOrStepChange(): void {
if (!this._hasViewInitialized) {
return;
}
this._updateTickMarkUI();
this._updateTickMarkTrackUI();
this._cdr.markForCheck();
}
_onResize(): void {
if (!this._hasViewInitialized) {
return;
}
this._updateDimensions();
if (this._isRange) {
const eInput = this._getInput(_MatThumb.END) as _MatSliderRangeThumb;
const sInput = this._getInput(_MatThumb.START) as _MatSliderRangeThumb;
eInput._updateThumbUIByValue();
sInput._updateThumbUIByValue();
eInput._updateStaticStyles();
sInput._updateStaticStyles();
eInput._updateMinMax();
sInput._updateMinMax();
eInput._updateWidthInactive();
sInput._updateWidthInactive();
} else {
const eInput = this._getInput(_MatThumb.END);
if (eInput) {
eInput._updateThumbUIByValue();
}
}
this._updateTickMarkUI();
this._updateTickMarkTrackUI();
this._cdr.detectChanges();
}
/** Whether or not the slider thumbs overlap. */
private _thumbsOverlap: boolean = false;
/** Returns true if the slider knobs are overlapping one another. */
private _areThumbsOverlapping(): boolean {
const startInput = this._getInput(_MatThumb.START);
const endInput = this._getInput(_MatThumb.END);
if (!startInput || !endInput) {
return false;
}
return endInput.translateX - startInput.translateX < 20;
}
/**
* Updates the class names of overlapping slider thumbs so
* that the current active thumb is styled to be on "top".
*/
private _updateOverlappingThumbClassNames(source: _MatSliderRangeThumb): void {
const sibling = source.getSibling()!;
const sourceThumb = this._getThumb(source.thumbPosition);
const siblingThumb = this._getThumb(sibling.thumbPosition);
siblingThumb._hostElement.classList.remove('mdc-slider__thumb--top');
sourceThumb._hostElement.classList.toggle('mdc-slider__thumb--top', this._thumbsOverlap);
}
/** Updates the UI of slider thumbs when they begin or stop overlapping. */
private _updateOverlappingThumbUI(source: _MatSliderRangeThumb): void {
if (!this._isRange || this._skipUpdate()) {
return;
}
if (this._thumbsOverlap !== this._areThumbsOverlapping()) {
this._thumbsOverlap = !this._thumbsOverlap;
this._updateOverlappingThumbClassNames(source);
}
}
// _MatThumb styles update conditions
//
// 1. TranslateX, resize, or dir change
// - Reason: The thumb styles need to be updated according to the new translateX.
// 2. Min, max, or step
// - Reason: The value may have silently changed.
/** Updates the translateX of the given thumb. */
_updateThumbUI(source: _MatSliderThumb) {
if (this._skipUpdate()) {
return;
}
const thumb = this._getThumb(
source.thumbPosition === _MatThumb.END ? _MatThumb.END : _MatThumb.START,
)!;
thumb._hostElement.style.transform = `translateX(${source.translateX}px)`;
}
// Value indicator text update conditions
//
// 1. Value
// - Reason: The value displayed needs to be updated.
// 2. Min, max, or step
// - Reason: The value may have silently changed.
/** Updates the value indicator tooltip ui for the given thumb. */
_updateValueIndicatorUI(source: _MatSliderThumb): void {
if (this._skipUpdate()) {
return;
}
const valuetext = this.displayWith(source.value);
this._hasViewInitialized
? source._valuetext.set(valuetext)
: source._hostElement.setAttribute('aria-valuetext', valuetext);
if (this.discrete) {
source.thumbPosition === _MatThumb.START
? (this.startValueIndicatorText = valuetext)
: (this.endValueIndicatorText = valuetext);
const visualThumb = this._getThumb(source.thumbPosition);
valuetext.length < 3
? visualThumb._hostElement.classList.add('mdc-slider__thumb--short-value')
: visualThumb._hostElement.classList.remove('mdc-slider__thumb--short-value');
}
}
/** Updates all value indicator UIs in the slider. */
private _updateValueIndicatorUIs(): void {
const eInput = this._getInput(_MatThumb.END);
const sInput = this._getInput(_MatThumb.START);
if (eInput) {
this._updateValueIndicatorUI(eInput);
}
if (sInput) {
this._updateValueIndicatorUI(sInput);
}
}
// Update Tick Mark Track Width
//
// 1. Min, max, or step
// - Reason: The maximum reachable value may have changed.
// - Side note: The maximum reachable value is different from the maximum value set by the
// user. For example, a slider with [min: 5, max: 100, step: 10] would have a maximum
// reachable value of 95.
// 2. Resize
// - Reason: The position for the maximum reachable value needs to be recalculated.
/** Updates the width of the tick mark track. */
private _updateTickMarkTrackUI(): void {
if (!this.showTickMarks || this._skipUpdate()) {
return;
}
const step = this._step && this._step > 0 ? this._step : 1;
const maxValue = Math.floor(this.max / step) * step;
const percentage = (maxValue - this.min) / (this.max - this.min);
this._tickMarkTrackWidth = this._cachedWidth * percentage - 6;
}
// Track active update conditions
//
// 1. TranslateX
// - Reason: The track active should line up with the new thumb position.
// 2. Min or max
// - Reason #1: The 'active' percentage needs to be recalculated.
// - Reason #2: The value may have silently changed.
// 3. Step
// - Reason: The value may have silently changed causing the thumb(s) to shift.
// 4. Dir change
// - Reason: The track active will need to be updated according to the new thumb position(s).
// 5. Resize
// - Reason: The total width the 'active' tracks translateX is based on has changed.
/** Updates the scale on the active portion of the track. */
_updateTrackUI(source: _MatSliderThumb): void {
if (this._skipUpdate()) {
return;
}
this._isRange
? this._updateTrackUIRange(source as _MatSliderRangeThumb)
: this._updateTrackUINonRange(source as _MatSliderThumb);
}
private _updateTrackUIRange(source: _MatSliderRangeThumb): void {
const sibling = source.getSibling();
if (!sibling || !this._cachedWidth) {
return;
}
const activePercentage = Math.abs(sibling.translateX - source.translateX) / this._cachedWidth;
if (source._isLeftThumb && this._cachedWidth) {
this._setTrackActiveStyles({
left: 'auto',
right: `${this._cachedWidth - sibling.translateX}px`,
transformOrigin: 'right',
transform: `scaleX(${activePercentage})`,
});
} else {
this._setTrackActiveStyles({
left: `${sibling.translateX}px`,
right: 'auto',
transformOrigin: 'left',
transform: `scaleX(${activePercentage})`,
});
}
} | {
"end_byte": 24831,
"start_byte": 17410,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.ts"
} |
components/src/material/slider/slider.ts_24835_29382 | private _updateTrackUINonRange(source: _MatSliderThumb): void {
this._isRtl
? this._setTrackActiveStyles({
left: 'auto',
right: '0px',
transformOrigin: 'right',
transform: `scaleX(${1 - source.fillPercentage})`,
})
: this._setTrackActiveStyles({
left: '0px',
right: 'auto',
transformOrigin: 'left',
transform: `scaleX(${source.fillPercentage})`,
});
}
// Tick mark update conditions
//
// 1. Value
// - Reason: a tick mark which was once active might now be inactive or vice versa.
// 2. Min, max, or step
// - Reason #1: the number of tick marks may have changed.
// - Reason #2: The value may have silently changed.
/** Updates the dots along the slider track. */
_updateTickMarkUI(): void {
if (
!this.showTickMarks ||
this.step === undefined ||
this.min === undefined ||
this.max === undefined
) {
return;
}
const step = this.step > 0 ? this.step : 1;
this._isRange ? this._updateTickMarkUIRange(step) : this._updateTickMarkUINonRange(step);
if (this._isRtl) {
this._tickMarks.reverse();
}
}
private _updateTickMarkUINonRange(step: number): void {
const value = this._getValue();
let numActive = Math.max(Math.round((value - this.min) / step), 0);
let numInactive = Math.max(Math.round((this.max - value) / step), 0);
this._isRtl ? numActive++ : numInactive++;
this._tickMarks = Array(numActive)
.fill(_MatTickMark.ACTIVE)
.concat(Array(numInactive).fill(_MatTickMark.INACTIVE));
}
private _updateTickMarkUIRange(step: number): void {
const endValue = this._getValue();
const startValue = this._getValue(_MatThumb.START);
const numInactiveBeforeStartThumb = Math.max(Math.round((startValue - this.min) / step), 0);
const numActive = Math.max(Math.round((endValue - startValue) / step) + 1, 0);
const numInactiveAfterEndThumb = Math.max(Math.round((this.max - endValue) / step), 0);
this._tickMarks = Array(numInactiveBeforeStartThumb)
.fill(_MatTickMark.INACTIVE)
.concat(
Array(numActive).fill(_MatTickMark.ACTIVE),
Array(numInactiveAfterEndThumb).fill(_MatTickMark.INACTIVE),
);
}
/** Gets the slider thumb input of the given thumb position. */
_getInput(thumbPosition: _MatThumb): _MatSliderThumb | _MatSliderRangeThumb | undefined {
if (thumbPosition === _MatThumb.END && this._input) {
return this._input;
}
if (this._inputs?.length) {
return thumbPosition === _MatThumb.START ? this._inputs.first : this._inputs.last;
}
return;
}
/** Gets the slider thumb HTML input element of the given thumb position. */
_getThumb(thumbPosition: _MatThumb): _MatSliderVisualThumb {
return thumbPosition === _MatThumb.END ? this._thumbs?.last! : this._thumbs?.first!;
}
_setTransition(withAnimation: boolean): void {
this._hasAnimation = !this._platform.IOS && withAnimation && !this._noopAnimations;
this._elementRef.nativeElement.classList.toggle(
'mat-mdc-slider-with-animation',
this._hasAnimation,
);
}
/** Whether the given pointer event occurred within the bounds of the slider pointer's DOM Rect. */
_isCursorOnSliderThumb(event: PointerEvent, rect: DOMRect) {
const radius = rect.width / 2;
const centerX = rect.x + radius;
const centerY = rect.y + radius;
const dx = event.clientX - centerX;
const dy = event.clientY - centerY;
return Math.pow(dx, 2) + Math.pow(dy, 2) < Math.pow(radius, 2);
}
}
/** Ensures that there is not an invalid configuration for the slider thumb inputs. */
function _validateInputs(
isRange: boolean,
endInputElement: _MatSliderThumb | _MatSliderRangeThumb | undefined,
startInputElement: _MatSliderThumb | undefined,
): void {
const startValid =
!isRange || startInputElement?._hostElement.hasAttribute('matSliderStartThumb');
const endValid = endInputElement?._hostElement.hasAttribute(
isRange ? 'matSliderEndThumb' : 'matSliderThumb',
);
if (!startValid || !endValid) {
_throwInvalidInputConfigurationError();
}
}
function _throwInvalidInputConfigurationError(): void {
throw Error(`Invalid slider thumb input configuration!
Valid configurations are as follows:
<mat-slider>
<input matSliderThumb>
</mat-slider>
or
<mat-slider>
<input matSliderStartThumb>
<input matSliderEndThumb>
</mat-slider>
`);
} | {
"end_byte": 29382,
"start_byte": 24835,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.ts"
} |
components/src/material/slider/slider-thumb.ts_0_1294 | /**
* @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 {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
Input,
NgZone,
OnDestroy,
ViewChild,
ViewEncapsulation,
inject,
} from '@angular/core';
import {MatRipple, RippleAnimationConfig, RippleRef, RippleState} from '@angular/material/core';
import {
_MatThumb,
_MatSlider,
_MatSliderThumb,
_MatSliderVisualThumb,
MAT_SLIDER,
MAT_SLIDER_VISUAL_THUMB,
} from './slider-interface';
import {Platform} from '@angular/cdk/platform';
/**
* The visual slider thumb.
*
* Handles the slider thumb ripple states (hover, focus, and active),
* and displaying the value tooltip on discrete sliders.
* @docs-private
*/
@Component({
selector: 'mat-slider-visual-thumb',
templateUrl: './slider-thumb.html',
styleUrl: 'slider-thumb.css',
host: {
'class': 'mdc-slider__thumb mat-mdc-slider-visual-thumb',
},
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
providers: [{provide: MAT_SLIDER_VISUAL_THUMB, useExisting: MatSliderVisualThumb}],
imports: [MatRipple],
})
export | {
"end_byte": 1294,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider-thumb.ts"
} |
components/src/material/slider/slider-thumb.ts_1295_9451 | class MatSliderVisualThumb implements _MatSliderVisualThumb, AfterViewInit, OnDestroy {
readonly _cdr = inject(ChangeDetectorRef);
private readonly _ngZone = inject(NgZone);
private _slider = inject<_MatSlider>(MAT_SLIDER);
/** Whether the slider displays a numeric value label upon pressing the thumb. */
@Input() discrete: boolean;
/** Indicates which slider thumb this input corresponds to. */
@Input() thumbPosition: _MatThumb;
/** The display value of the slider thumb. */
@Input() valueIndicatorText: string;
/** The MatRipple for this slider thumb. */
@ViewChild(MatRipple) readonly _ripple: MatRipple;
/** The slider thumb knob. */
@ViewChild('knob') _knob: ElementRef<HTMLElement>;
/** The slider thumb value indicator container. */
@ViewChild('valueIndicatorContainer')
_valueIndicatorContainer: ElementRef<HTMLElement>;
/** The slider input corresponding to this slider thumb. */
private _sliderInput: _MatSliderThumb;
/** The native html element of the slider input corresponding to this thumb. */
private _sliderInputEl: HTMLInputElement | undefined;
/** The RippleRef for the slider thumbs hover state. */
private _hoverRippleRef: RippleRef | undefined;
/** The RippleRef for the slider thumbs focus state. */
private _focusRippleRef: RippleRef | undefined;
/** The RippleRef for the slider thumbs active state. */
private _activeRippleRef: RippleRef | undefined;
/** Whether the slider thumb is currently being hovered. */
private _isHovered: boolean = false;
/** Whether the slider thumb is currently being pressed. */
_isActive = false;
/** Whether the value indicator tooltip is visible. */
_isValueIndicatorVisible: boolean = false;
/** The host native HTML input element. */
_hostElement = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
private _platform = inject(Platform);
constructor(...args: unknown[]);
constructor() {}
ngAfterViewInit() {
const sliderInput = this._slider._getInput(this.thumbPosition);
// No-op if the slider isn't configured properly. `MatSlider` will
// throw an error instructing the user how to set up the slider.
if (!sliderInput) {
return;
}
this._ripple.radius = 24;
this._sliderInput = sliderInput;
this._sliderInputEl = this._sliderInput._hostElement;
// These listeners don't update any data bindings so we bind them outside
// of the NgZone to prevent Angular from needlessly running change detection.
this._ngZone.runOutsideAngular(() => {
const input = this._sliderInputEl!;
input.addEventListener('pointermove', this._onPointerMove);
input.addEventListener('pointerdown', this._onDragStart);
input.addEventListener('pointerup', this._onDragEnd);
input.addEventListener('pointerleave', this._onMouseLeave);
input.addEventListener('focus', this._onFocus);
input.addEventListener('blur', this._onBlur);
});
}
ngOnDestroy() {
const input = this._sliderInputEl;
if (input) {
input.removeEventListener('pointermove', this._onPointerMove);
input.removeEventListener('pointerdown', this._onDragStart);
input.removeEventListener('pointerup', this._onDragEnd);
input.removeEventListener('pointerleave', this._onMouseLeave);
input.removeEventListener('focus', this._onFocus);
input.removeEventListener('blur', this._onBlur);
}
}
private _onPointerMove = (event: PointerEvent): void => {
if (this._sliderInput._isFocused) {
return;
}
const rect = this._hostElement.getBoundingClientRect();
const isHovered = this._slider._isCursorOnSliderThumb(event, rect);
this._isHovered = isHovered;
if (isHovered) {
this._showHoverRipple();
} else {
this._hideRipple(this._hoverRippleRef);
}
};
private _onMouseLeave = (): void => {
this._isHovered = false;
this._hideRipple(this._hoverRippleRef);
};
private _onFocus = (): void => {
// We don't want to show the hover ripple on top of the focus ripple.
// Happen when the users cursor is over a thumb and then the user tabs to it.
this._hideRipple(this._hoverRippleRef);
this._showFocusRipple();
this._hostElement.classList.add('mdc-slider__thumb--focused');
};
private _onBlur = (): void => {
// Happens when the user tabs away while still dragging a thumb.
if (!this._isActive) {
this._hideRipple(this._focusRippleRef);
}
// Happens when the user tabs away from a thumb but their cursor is still over it.
if (this._isHovered) {
this._showHoverRipple();
}
this._hostElement.classList.remove('mdc-slider__thumb--focused');
};
private _onDragStart = (event: PointerEvent): void => {
if (event.button !== 0) {
return;
}
this._isActive = true;
this._showActiveRipple();
};
private _onDragEnd = (): void => {
this._isActive = false;
this._hideRipple(this._activeRippleRef);
// Happens when the user starts dragging a thumb, tabs away, and then stops dragging.
if (!this._sliderInput._isFocused) {
this._hideRipple(this._focusRippleRef);
}
// On Safari we need to immediately re-show the hover ripple because
// sliders do not retain focus from pointer events on that platform.
if (this._platform.SAFARI) {
this._showHoverRipple();
}
};
/** Handles displaying the hover ripple. */
private _showHoverRipple(): void {
if (!this._isShowingRipple(this._hoverRippleRef)) {
this._hoverRippleRef = this._showRipple({enterDuration: 0, exitDuration: 0});
this._hoverRippleRef?.element.classList.add('mat-mdc-slider-hover-ripple');
}
}
/** Handles displaying the focus ripple. */
private _showFocusRipple(): void {
// Show the focus ripple event if noop animations are enabled.
if (!this._isShowingRipple(this._focusRippleRef)) {
this._focusRippleRef = this._showRipple({enterDuration: 0, exitDuration: 0}, true);
this._focusRippleRef?.element.classList.add('mat-mdc-slider-focus-ripple');
}
}
/** Handles displaying the active ripple. */
private _showActiveRipple(): void {
if (!this._isShowingRipple(this._activeRippleRef)) {
this._activeRippleRef = this._showRipple({enterDuration: 225, exitDuration: 400});
this._activeRippleRef?.element.classList.add('mat-mdc-slider-active-ripple');
}
}
/** Whether the given rippleRef is currently fading in or visible. */
private _isShowingRipple(rippleRef?: RippleRef): boolean {
return rippleRef?.state === RippleState.FADING_IN || rippleRef?.state === RippleState.VISIBLE;
}
/** Manually launches the slider thumb ripple using the specified ripple animation config. */
private _showRipple(
animation: RippleAnimationConfig,
ignoreGlobalRippleConfig?: boolean,
): RippleRef | undefined {
if (this._slider.disabled) {
return;
}
this._showValueIndicator();
if (this._slider._isRange) {
const sibling = this._slider._getThumb(
this.thumbPosition === _MatThumb.START ? _MatThumb.END : _MatThumb.START,
);
sibling._showValueIndicator();
}
if (this._slider._globalRippleOptions?.disabled && !ignoreGlobalRippleConfig) {
return;
}
return this._ripple.launch({
animation: this._slider._noopAnimations ? {enterDuration: 0, exitDuration: 0} : animation,
centered: true,
persistent: true,
});
}
/**
* Fades out the given ripple.
* Also hides the value indicator if no ripple is showing.
*/
private _hideRipple(rippleRef?: RippleRef): void {
rippleRef?.fadeOut();
if (this._isShowingAnyRipple()) {
return;
}
if (!this._slider._isRange) {
this._hideValueIndicator();
}
const sibling = this._getSibling();
if (!sibling._isShowingAnyRipple()) {
this._hideValueIndicator();
sibling._hideValueIndicator();
}
}
/** Shows the value indicator ui. */
_showValueIndicator(): void {
this._hostElement.classList.add('mdc-slider__thumb--with-indicator');
}
/** Hides the value indicator ui. */ | {
"end_byte": 9451,
"start_byte": 1295,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider-thumb.ts"
} |
components/src/material/slider/slider-thumb.ts_9454_10273 | _hideValueIndicator(): void {
this._hostElement.classList.remove('mdc-slider__thumb--with-indicator');
}
_getSibling(): _MatSliderVisualThumb {
return this._slider._getThumb(
this.thumbPosition === _MatThumb.START ? _MatThumb.END : _MatThumb.START,
);
}
/** Gets the value indicator container's native HTML element. */
_getValueIndicatorContainer(): HTMLElement | undefined {
return this._valueIndicatorContainer?.nativeElement;
}
/** Gets the native HTML element of the slider thumb knob. */
_getKnob(): HTMLElement {
return this._knob.nativeElement;
}
_isShowingAnyRipple(): boolean {
return (
this._isShowingRipple(this._hoverRippleRef) ||
this._isShowingRipple(this._focusRippleRef) ||
this._isShowingRipple(this._activeRippleRef)
);
}
} | {
"end_byte": 10273,
"start_byte": 9454,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider-thumb.ts"
} |
components/src/material/slider/README.md_0_97 | Please see the official documentation at https://material.angular.io/components/component/slider
| {
"end_byte": 97,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/README.md"
} |
components/src/material/slider/slider.scss_0_6980 | @use '@angular/cdk';
@use '../core/tokens/m2/mat/slider' as tokens-mat-slider;
@use '../core/tokens/m2/mdc/slider' as tokens-mdc-slider;
@use '../core/tokens/token-utils';
@use '../core/style/vendor-prefixes';
$mat-slider-min-size: 128px !default;
$mat-slider-horizontal-margin: 8px !default;
$_mdc-slots: (tokens-mdc-slider.$prefix, tokens-mdc-slider.get-token-slots());
$_mat-slots: (tokens-mat-slider.$prefix, tokens-mat-slider.get-token-slots());
.mdc-slider__track {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100%;
pointer-events: none;
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(height, inactive-track-height);
}
}
.mdc-slider__track--active,
.mdc-slider__track--inactive {
display: flex;
height: 100%;
position: absolute;
width: 100%;
}
.mdc-slider__track--active {
overflow: hidden;
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(border-radius, active-track-shape);
$active-height-ref: token-utils.get-token-variable(active-track-height);
$inactive-height-ref: token-utils.get-token-variable(inactive-track-height);
height: $active-height-ref;
top: calc((#{$inactive-height-ref} - #{$active-height-ref}) / 2);
}
}
.mdc-slider__track--active_fill {
border-top-style: solid;
box-sizing: border-box;
height: 100%;
width: 100%;
position: relative;
transform-origin: left;
transition: transform 80ms ease;
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(border-color, active-track-color);
@include token-utils.create-token-slot(border-top-width, active-track-height);
.mdc-slider--disabled & {
@include token-utils.create-token-slot(border-color, disabled-active-track-color);
}
}
[dir='rtl'] & {
-webkit-transform-origin: right;
transform-origin: right;
}
}
.mdc-slider__track--inactive {
left: 0;
top: 0;
opacity: 0.24;
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(background-color, inactive-track-color);
@include token-utils.create-token-slot(height, inactive-track-height);
@include token-utils.create-token-slot(border-radius, inactive-track-shape);
.mdc-slider--disabled & {
@include token-utils.create-token-slot(background-color, disabled-inactive-track-color);
opacity: 0.24;
}
}
&::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;
@include cdk.high-contrast {
border-color: CanvasText;
}
}
}
.mdc-slider__value-indicator-container {
bottom: 44px;
left: 50%;
pointer-events: none;
position: absolute;
transform: translateX(-50%);
@include token-utils.use-tokens($_mat-slots...) {
@include token-utils.create-token-slot(transform, value-indicator-container-transform);
}
.mdc-slider__thumb--with-indicator & {
pointer-events: auto;
}
}
.mdc-slider__value-indicator {
display: flex;
align-items: center;
border-radius: 4px;
height: 32px;
padding: 0 12px;
transform: scale(0);
transform-origin: bottom;
opacity: 1;
transition: transform 100ms cubic-bezier(0.4, 0, 1, 1);
// Stop parent word-break from altering
// the word-break of the value indicator.
word-break: normal;
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(background-color, label-container-color);
@include token-utils.create-token-slot(color, label-label-text-color);
}
@include token-utils.use-tokens($_mat-slots...) {
@include token-utils.create-token-slot(width, value-indicator-width);
@include token-utils.create-token-slot(height, value-indicator-height);
@include token-utils.create-token-slot(padding, value-indicator-padding);
@include token-utils.create-token-slot(opacity, value-indicator-opacity);
@include token-utils.create-token-slot(border-radius, value-indicator-border-radius);
}
.mdc-slider__thumb--with-indicator & {
transition: transform 100ms cubic-bezier(0, 0, 0.2, 1);
transform: scale(1);
}
&::before {
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-top: 6px solid;
bottom: -5px;
content: '';
height: 0;
left: 50%;
position: absolute;
transform: translateX(-50%);
width: 0;
@include token-utils.use-tokens($_mat-slots...) {
@include token-utils.create-token-slot(display, value-indicator-caret-display);
}
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(border-top-color, label-container-color);
}
}
&::after {
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;
@include cdk.high-contrast {
border-color: CanvasText;
}
}
}
.mdc-slider__value-indicator-text {
text-align: center;
@include token-utils.use-tokens($_mat-slots...) {
@include token-utils.create-token-slot(width, value-indicator-width);
@include token-utils.create-token-slot(transform, value-indicator-text-transform);
}
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(font-family, label-label-text-font);
@include token-utils.create-token-slot(font-size, label-label-text-size);
@include token-utils.create-token-slot(font-weight, label-label-text-weight);
@include token-utils.create-token-slot(line-height, label-label-text-line-height);
@include token-utils.create-token-slot(letter-spacing, label-label-text-tracking);
}
}
.mdc-slider__thumb {
@include vendor-prefixes.user-select(none);
display: flex;
left: -24px;
outline: none;
position: absolute;
height: 48px;
width: 48px;
pointer-events: none;
.mdc-slider--discrete & {
transition: transform 80ms ease;
}
.mdc-slider--disabled & {
pointer-events: none;
}
}
.mdc-slider__thumb--top {
z-index: 1;
}
.mdc-slider__thumb-knob {
position: absolute;
box-sizing: border-box;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
border-style: solid;
@include token-utils.use-tokens($_mdc-slots...) {
$width-ref: token-utils.get-token-variable(handle-width);
$height-ref: token-utils.get-token-variable(handle-height);
width: $width-ref;
height: $height-ref;
border-width: calc(#{$height-ref} / 2) calc(#{$width-ref} / 2);
@include token-utils.create-token-slot(box-shadow, handle-elevation);
@include token-utils.create-token-slot(background-color, handle-color);
@include token-utils.create-token-slot(border-color, handle-color);
@include token-utils | {
"end_byte": 6980,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.scss"
} |
components/src/material/slider/slider.scss_6980_12492 | .create-token-slot(border-radius, handle-shape);
.mdc-slider__thumb:hover & {
@include token-utils.create-token-slot(background-color, hover-handle-color);
@include token-utils.create-token-slot(border-color, hover-handle-color);
}
.mdc-slider__thumb--focused & {
@include token-utils.create-token-slot(background-color, focus-handle-color);
@include token-utils.create-token-slot(border-color, focus-handle-color);
}
.mdc-slider--disabled & {
@include token-utils.create-token-slot(background-color, disabled-handle-color);
@include token-utils.create-token-slot(border-color, disabled-handle-color);
}
}
.mdc-slider__thumb--top &,
.mdc-slider__thumb--top.mdc-slider__thumb:hover &,
.mdc-slider__thumb--top.mdc-slider__thumb--focused & {
border: solid 1px #fff;
box-sizing: content-box;
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(border-color, with-overlap-handle-outline-color);
@include token-utils.create-token-slot(border-width, with-overlap-handle-outline-width);
}
}
}
.mdc-slider__tick-marks {
align-items: center;
box-sizing: border-box;
display: flex;
height: 100%;
justify-content: space-between;
padding: 0 1px;
position: absolute;
width: 100%;
}
.mdc-slider__tick-mark--active,
.mdc-slider__tick-mark--inactive {
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(width, with-tick-marks-container-size);
@include token-utils.create-token-slot(height, with-tick-marks-container-size);
@include token-utils.create-token-slot(border-radius, with-tick-marks-container-shape);
}
}
.mdc-slider__tick-mark--inactive {
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(opacity, with-tick-marks-inactive-container-opacity);
@include token-utils.create-token-slot(background-color,
with-tick-marks-inactive-container-color);
.mdc-slider--disabled & {
@include token-utils.create-token-slot(opacity, with-tick-marks-inactive-container-opacity);
@include token-utils.create-token-slot(background-color,
with-tick-marks-disabled-container-color);
}
}
}
.mdc-slider__tick-mark--active {
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(opacity, with-tick-marks-active-container-opacity);
@include token-utils.create-token-slot(background-color,
with-tick-marks-active-container-color);
}
}
.mdc-slider__input {
cursor: pointer;
left: 2px;
margin: 0;
height: 44px;
opacity: 0;
position: absolute;
top: 2px;
width: 44px;
// It's common for apps to globally set `box-sizing: border-box` which messes up our
// measurements. Explicitly set `content-box` to avoid issues like #26246.
box-sizing: content-box;
&.mat-mdc-slider-input-no-pointer-events {
pointer-events: none;
}
&.mat-slider__right-input {
left: auto;
right: 0;
}
}
.mat-mdc-slider {
display: inline-block;
box-sizing: border-box;
outline: none;
vertical-align: middle;
cursor: pointer;
height: 48px;
margin: 0 $mat-slider-horizontal-margin;
position: relative;
touch-action: pan-y;
// Unset the default "width" property from the MDC slider class. We don't want
// the slider to automatically expand horizontally for backwards compatibility.
width: auto;
min-width: $mat-slider-min-size - (2 * $mat-slider-horizontal-margin);
-webkit-tap-highlight-color: transparent;
&.mdc-slider--disabled {
cursor: auto;
opacity: 0.38;
}
.mdc-slider__thumb,
.mdc-slider__track--active_fill {
transition-duration: 0ms;
}
&.mat-mdc-slider-with-animation {
.mdc-slider__thumb,
.mdc-slider__track--active_fill {
transition-duration: 80ms;
}
}
// We need to repeat these styles to override discrete slider styling.
&.mdc-slider--discrete {
.mdc-slider__thumb,
.mdc-slider__track--active_fill {
transition-duration: 0ms;
}
}
&.mat-mdc-slider-with-animation {
.mdc-slider__thumb,
.mdc-slider__track--active_fill {
transition-duration: 80ms;
}
}
// Add slots for custom Angular Material slider tokens.
@include token-utils.use-tokens($_mat-slots...) {
// The `.mat-ripple` wrapper here is redundant, but we need it to
// increase the specificity due to how some styles are setup in g3.
.mat-ripple {
.mat-ripple-element {
@include token-utils.create-token-slot(background-color, ripple-color);
}
.mat-mdc-slider-hover-ripple {
@include token-utils.create-token-slot(background-color, hover-state-layer-color);
}
.mat-mdc-slider-focus-ripple,
.mat-mdc-slider-active-ripple {
@include token-utils.create-token-slot(background-color, focus-state-layer-color);
}
}
}
&._mat-animation-noopable {
&.mdc-slider--discrete .mdc-slider__thumb,
&.mdc-slider--discrete .mdc-slider__track--active_fill,
.mdc-slider__value-indicator {
transition: none;
}
}
// Slider components have to set `border-radius: 50%` in order to support density scaling
// which will clip a square focus indicator so we have to turn it into a circle.
.mat-focus-indicator::before {
border-radius: 50%;
}
}
// In the MDC slider the focus indicator is inside the thumb.
.mdc-slider__thumb--focused .mat-focus-indicator::before {
content: '';
} | {
"end_byte": 12492,
"start_byte": 6980,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.scss"
} |
components/src/material/slider/_slider-theme.scss_0_5850 | @use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/typography/typography';
@use '../core/style/sass-utils';
@use '../core/tokens/token-utils';
@use '../core/tokens/m2/mat/slider' as tokens-mat-slider;
@use '../core/tokens/m2/mdc/slider' as tokens-mdc-slider;
/// Outputs base theme styles (styles not dependent on the color, typography, or density settings)
/// for the mat-slider.
/// @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-slider.$prefix,
tokens-mdc-slider.get-unthemable-tokens()
);
@include token-utils.create-token-values(
tokens-mat-slider.$prefix,
tokens-mat-slider.get-unthemable-tokens()
);
}
}
}
/// Outputs color theme styles for the mat-slider.
/// @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 slider: primary, secondary, tertiary,
/// or error (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 token-utils.create-token-values(
tokens-mdc-slider.$prefix,
tokens-mdc-slider.get-color-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-slider.$prefix,
tokens-mat-slider.get-color-tokens($theme)
);
.mat-accent {
@include token-utils.create-token-values(
tokens-mdc-slider.$prefix,
tokens-mdc-slider.private-get-color-palette-color-tokens($theme, accent)
);
@include token-utils.create-token-values(
tokens-mat-slider.$prefix,
tokens-mat-slider.private-get-color-palette-color-tokens($theme, accent)
);
}
.mat-warn {
@include token-utils.create-token-values(
tokens-mdc-slider.$prefix,
tokens-mdc-slider.private-get-color-palette-color-tokens($theme, warn)
);
@include token-utils.create-token-values(
tokens-mat-slider.$prefix,
tokens-mat-slider.private-get-color-palette-color-tokens($theme, warn)
);
}
}
}
}
/// Outputs typography theme styles for the mat-slider.
/// @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-slider.$prefix,
tokens-mdc-slider.get-typography-tokens($theme)
);
}
}
}
/// Outputs density theme styles for the mat-slider.
/// @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-slider.$prefix,
tokens-mdc-slider.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-slider.$prefix,
tokens: tokens-mat-slider.get-token-slots(),
),
(
namespace: tokens-mdc-slider.$prefix,
tokens: tokens-mdc-slider.get-token-slots(),
),
);
}
/// 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-option.
/// @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 slider: 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-slider') {
@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'
);
$mdc-slider-tokens: token-utils.get-tokens-for($tokens, tokens-mdc-slider.$prefix, $options...);
$mat-slider-tokens: token-utils.get-tokens-for($tokens, tokens-mat-slider.$prefix, $options...);
@include token-utils.create-token-values(tokens-mdc-slider.$prefix, $mdc-slider-tokens);
@include token-utils.create-token-values(tokens-mat-slider.$prefix, $mat-slider-tokens);
}
| {
"end_byte": 5850,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/_slider-theme.scss"
} |
components/src/material/slider/slider-thumb.html_0_373 | @if (discrete) {
<div class="mdc-slider__value-indicator-container" #valueIndicatorContainer>
<div class="mdc-slider__value-indicator">
<span class="mdc-slider__value-indicator-text">{{valueIndicatorText}}</span>
</div>
</div>
}
<div class="mdc-slider__thumb-knob" #knob></div>
<div matRipple class="mat-focus-indicator" [matRippleDisabled]="true"></div>
| {
"end_byte": 373,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider-thumb.html"
} |
components/src/material/slider/slider-thumb.scss_0_261 | .mat-mdc-slider-visual-thumb .mat-ripple {
height: 100%;
width: 100%;
}
.mat-mdc-slider .mdc-slider__tick-marks {
justify-content: start;
.mdc-slider__tick-mark--active,
.mdc-slider__tick-mark--inactive {
position: absolute;
left: 2px;
}
}
| {
"end_byte": 261,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider-thumb.scss"
} |
components/src/material/slider/slider.spec.ts_0_6498 | /**
* @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 {BidiModule, Directionality} from '@angular/cdk/bidi';
import {Platform} from '@angular/cdk/platform';
import {dispatchEvent, dispatchFakeEvent, dispatchPointerEvent} from '@angular/cdk/testing/private';
import {Component, Provider, QueryList, Type, ViewChild, ViewChildren} from '@angular/core';
import {
ComponentFixture,
TestBed,
fakeAsync,
flush,
tick,
waitForAsync,
} from '@angular/core/testing';
import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {By} from '@angular/platform-browser';
import {of} from 'rxjs';
import {MatSliderModule} from './module';
import {MatSlider} from './slider';
import {MatSliderRangeThumb, MatSliderThumb} from './slider-input';
import {_MatThumb} from './slider-interface';
import {MatSliderVisualThumb} from './slider-thumb';
interface Point {
x: number;
y: number;
}
describe('MatSlider', () => {
let platform: Platform;
function createComponent<T>(component: Type<T>, providers: Provider[] = []): ComponentFixture<T> {
TestBed.configureTestingModule({
imports: [FormsModule, MatSliderModule, ReactiveFormsModule, BidiModule],
providers: [...providers],
declarations: [component],
});
platform = TestBed.inject(Platform);
return TestBed.createComponent<T>(component);
}
function checkInput(
input: MatSliderThumb,
{
min,
max,
value,
translateX,
width,
step,
}: {min: number; max: number; value: number; translateX: number; width?: number; step?: number},
): void {
expect(input.min).withContext('min').toBe(min);
expect(input.max).withContext('max').toBe(max);
expect(input.value).withContext('value').toBe(value);
// The discrepancy between the "ideal" and "actual" translateX comes from
// the 3px offset from the start & end of the slider track to the first
// and last tick marks.
//
// The "actual" translateX is calculated based on a slider that is 6px
// smaller than the width of the slider. Using this "actual" translateX in
// tests would make it even more difficult than it already is to tell if
// the translateX is off, so we abstract things in here so tests can be
// more intuitive.
//
// The most clear way to compare the two tx's is to just turn them into
// percentages by dividing by their (total height) / 100.
const idealTXPercentage = Math.round(translateX / 3);
const actualTXPercentage = Math.round((input.translateX - 3) / 2.94);
expect(actualTXPercentage)
.withContext(`translateX: ${input.translateX} should be close to ${translateX}`)
.toBe(idealTXPercentage);
if (step !== undefined) {
expect(input.step).withContext('step').toBe(step);
}
if (width !== undefined) {
const realWidth = parseInt(
(input as MatSliderRangeThumb)._hostElement.style.width.match(/\d+/)![0],
10,
);
expect(realWidth)
.withContext('width')
.toBeCloseTo((300 * width) / 100 + 16, 0);
}
}
// Note that this test is outside of the other `describe` blocks, because they all run
// `detectChanges` in the `beforeEach` and we're testing specifically what happens if it
// is destroyed before change detection has run.
it('should not throw if a slider is destroyed before the first change detection run', () => {
expect(() => {
const fixture = createComponent(StandardSlider);
fixture.destroy();
}).not.toThrow();
});
describe('standard slider', () => {
let fixture: ComponentFixture<StandardSlider>;
let slider: MatSlider;
let input: MatSliderThumb;
beforeEach(waitForAsync(() => {
fixture = createComponent(StandardSlider);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
input = slider._getInput(_MatThumb.END) as MatSliderThumb;
}));
it('should set the default values', () => {
expect(slider.min).toBe(0);
expect(slider.max).toBe(100);
expect(slider.step).toBe(1);
checkInput(input, {min: 0, max: 100, value: 0, step: 1, translateX: 0});
});
it('should update by click', fakeAsync(() => {
setValueByClick(slider, input, 25);
checkInput(input, {min: 0, max: 100, value: 25, step: 1, translateX: 75});
setValueByClick(slider, input, 50);
checkInput(input, {min: 0, max: 100, value: 50, step: 1, translateX: 150});
setValueByClick(slider, input, 75);
checkInput(input, {min: 0, max: 100, value: 75, step: 1, translateX: 225});
setValueByClick(slider, input, 100);
checkInput(input, {min: 0, max: 100, value: 100, step: 1, translateX: 300});
}));
it('should update by slide', fakeAsync(() => {
slideToValue(slider, input, 25);
checkInput(input, {min: 0, max: 100, value: 25, step: 1, translateX: 75});
slideToValue(slider, input, 50);
checkInput(input, {min: 0, max: 100, value: 50, step: 1, translateX: 150});
slideToValue(slider, input, 75);
checkInput(input, {min: 0, max: 100, value: 75, step: 1, translateX: 225});
slideToValue(slider, input, 100);
checkInput(input, {min: 0, max: 100, value: 100, step: 1, translateX: 300});
}));
it('should not slide before the track', fakeAsync(() => {
slideToValue(slider, input, -10);
expect(input.value).toBe(0);
checkInput(input, {min: 0, max: 100, value: 0, step: 1, translateX: 0});
}));
it('should not slide past the track', fakeAsync(() => {
slideToValue(slider, input, 110);
expect(input.value).toBe(100);
checkInput(input, {min: 0, max: 100, value: 100, step: 1, translateX: 300});
}));
// TODO(wagnermaciel): Fix this test case (behavior works as intended in browser).
// it('should not break when the page layout changes', fakeAsync(async () => {
// slider._elementRef.nativeElement.style.marginLeft = '100px';
// tick(200);
// fixture.detectChanges();
// setValueByClick(slider, input, 25);
// checkInput(input, {min: 0, max: 100, value: 25, step: 1, translateX: 75});
// slider._elementRef.nativeElement.style.marginLeft = 'initial';
// }));
}); | {
"end_byte": 6498,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.spec.ts"
} |
components/src/material/slider/slider.spec.ts_6502_13563 | describe('standard range slider', () => {
let fixture: ComponentFixture<StandardRangeSlider>;
let slider: MatSlider;
let endInput: MatSliderRangeThumb;
let startInput: MatSliderRangeThumb;
beforeEach(waitForAsync(() => {
fixture = createComponent(StandardRangeSlider);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
endInput = slider._getInput(_MatThumb.END) as MatSliderRangeThumb;
startInput = slider._getInput(_MatThumb.START) as MatSliderRangeThumb;
}));
it('should set the default values', () => {
checkInput(startInput, {min: 0, max: 100, value: 0, step: 1, translateX: 0});
checkInput(endInput, {min: 0, max: 100, value: 100, step: 1, translateX: 300});
expect(slider.min).toBe(0);
expect(slider.max).toBe(100);
expect(slider.step).toBe(1);
});
it('should update by start input click', fakeAsync(() => {
setValueByClick(slider, startInput, 25);
checkInput(startInput, {min: 0, max: 100, value: 25, translateX: 75});
checkInput(endInput, {min: 25, max: 100, value: 100, translateX: 300});
}));
it('should update by end input click', fakeAsync(() => {
setValueByClick(slider, endInput, 75);
checkInput(startInput, {min: 0, max: 75, value: 0, translateX: 0});
checkInput(endInput, {min: 0, max: 100, value: 75, translateX: 225});
}));
it('should update by start thumb slide', fakeAsync(() => {
slideToValue(slider, startInput, 75);
checkInput(startInput, {min: 0, max: 100, value: 75, translateX: 225});
checkInput(endInput, {min: 75, max: 100, value: 100, translateX: 300});
}));
it('should update by end thumb slide', fakeAsync(() => {
slideToValue(slider, endInput, 25);
checkInput(startInput, {min: 0, max: 25, value: 0, translateX: 0});
checkInput(endInput, {min: 0, max: 100, value: 25, translateX: 75});
}));
it('should not allow start thumb to slide before the track', fakeAsync(() => {
slideToValue(slider, startInput, -10);
checkInput(startInput, {min: 0, max: 100, value: 0, translateX: 0});
checkInput(endInput, {min: 0, max: 100, value: 100, translateX: 300});
}));
it('should not allow end thumb to slide past the track', fakeAsync(() => {
slideToValue(slider, endInput, 110);
checkInput(startInput, {min: 0, max: 100, value: 0, translateX: 0});
checkInput(endInput, {min: 0, max: 100, value: 100, translateX: 300});
}));
it('should not allow start thumb to slide past the end thumb', fakeAsync(() => {
slideToValue(slider, endInput, 50);
slideToValue(slider, startInput, 55);
checkInput(startInput, {min: 0, max: 50, value: 50, translateX: 150});
checkInput(endInput, {min: 50, max: 100, value: 50, translateX: 150});
}));
it('should not allow end thumb to slide past the start thumb', fakeAsync(() => {
slideToValue(slider, startInput, 50);
slideToValue(slider, endInput, 45);
checkInput(startInput, {min: 0, max: 50, value: 50, translateX: 150});
checkInput(endInput, {min: 50, max: 100, value: 50, translateX: 150});
}));
// TODO(wagnermaciel): Fix this test case (behavior works as intended in browser).
// it('should not break when the page layout changes', fakeAsync(() => {
// slider._elementRef.nativeElement.style.marginLeft = '100px';
// setValueByClick(slider, startInput, 25);
// checkInput(startInput, {min: 0, max: 100, value: 25, translateX: 75});
// checkInput(endInput, {min: 25, max: 100, value: 100, translateX: 300});
// setValueByClick(slider, endInput, 75);
// checkInput(startInput, {min: 0, max: 75, value: 25, translateX: 75});
// checkInput(endInput, {min: 25, max: 100, value: 75, translateX: 225});
// slider._elementRef.nativeElement.style.marginLeft = 'initial';
// }));
});
describe('slider with min/max bindings', () => {
let fixture: ComponentFixture<SliderWithMinAndMax>;
let slider: MatSlider;
let input: MatSliderThumb;
beforeEach(waitForAsync(() => {
fixture = createComponent(SliderWithMinAndMax);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
input = slider._getInput(_MatThumb.END) as MatSliderThumb;
}));
it('should have the correct initial values', () => {
checkInput(input, {min: 25, max: 75, value: 25, translateX: 0});
});
it('should update the min when the bound value changes', () => {
fixture.componentInstance.min = 0;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(input, {min: 0, max: 75, value: 25, translateX: 100});
});
it('should update the max when the bound value changes', () => {
fixture.componentInstance.max = 90;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(input, {min: 25, max: 90, value: 25, translateX: 0});
});
it('should update the value if the min increases past it', () => {
fixture.componentInstance.min = 50;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(input, {min: 50, max: 75, value: 50, translateX: 0});
});
it('should update the value if the max decreases below it', () => {
input.value = 75;
fixture.componentInstance.max = 50;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(input, {min: 25, max: 50, value: 50, translateX: 300});
});
it('should allow the min increase above the max', () => {
fixture.componentInstance.min = 80;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(input, {min: 80, max: 75, value: 80, translateX: 0});
});
it('should allow the max to decrease below the min', () => {
fixture.componentInstance.max = -10;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(input, {min: 25, max: -10, value: 25, translateX: 0});
});
it('should update the thumb translateX when the min changes', () => {
checkInput(input, {min: 25, max: 75, value: 25, translateX: 0});
fixture.componentInstance.min = -25;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(input, {min: -25, max: 75, value: 25, translateX: 150});
});
it('should update the thumb translateX when the max changes', fakeAsync(() => {
setValueByClick(slider, input, 50);
checkInput(input, {min: 25, max: 75, value: 50, translateX: 150});
fixture.componentInstance.max = 125;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(input, {min: 25, max: 125, value: 50, translateX: 75});
}));
}); | {
"end_byte": 13563,
"start_byte": 6502,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.spec.ts"
} |
components/src/material/slider/slider.spec.ts_13567_17992 | describe('range slider with min/max bindings', () => {
let fixture: ComponentFixture<RangeSliderWithMinAndMax>;
let slider: MatSlider;
let endInput: MatSliderRangeThumb;
let startInput: MatSliderRangeThumb;
beforeEach(waitForAsync(() => {
fixture = createComponent(RangeSliderWithMinAndMax);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
endInput = slider._getInput(_MatThumb.END) as MatSliderRangeThumb;
startInput = slider._getInput(_MatThumb.START) as MatSliderRangeThumb;
}));
it('should have the correct initial values', () => {
checkInput(startInput, {min: 25, max: 75, value: 25, translateX: 0});
checkInput(endInput, {min: 25, max: 75, value: 75, translateX: 300});
});
describe('should handle min changes', () => {
it('that do not affect values', () => {
checkInput(startInput, {min: 25, max: 75, value: 25, translateX: 0});
checkInput(endInput, {min: 25, max: 75, value: 75, translateX: 300});
fixture.componentInstance.min = -25;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(startInput, {min: -25, max: 75, value: 25, translateX: 150});
checkInput(endInput, {min: 25, max: 75, value: 75, translateX: 300});
});
it('that affect the start value', () => {
fixture.componentInstance.min = 50;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(startInput, {min: 50, max: 75, value: 50, translateX: 0});
checkInput(endInput, {min: 50, max: 75, value: 75, translateX: 300});
});
it('that affect both values', () => {
endInput.value = 50;
fixture.componentInstance.min = 60;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(startInput, {min: 60, max: 60, value: 60, translateX: 0});
checkInput(endInput, {min: 60, max: 75, value: 60, translateX: 0});
});
it('where the new start tx is greater than the old end tx', fakeAsync(() => {
fixture.componentInstance.min = 0;
fixture.componentInstance.max = 100;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
slideToValue(slider, startInput, 10);
slideToValue(slider, endInput, 20);
checkInput(startInput, {min: 0, max: 20, value: 10, translateX: 30});
checkInput(endInput, {min: 10, max: 100, value: 20, translateX: 60});
fixture.componentInstance.min = -1000;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(startInput, {min: -1000, max: 20, value: 10, translateX: 275.5});
checkInput(endInput, {min: 10, max: 100, value: 20, translateX: 278});
}));
it('where the new end tx is less than the old start tx', fakeAsync(() => {
fixture.componentInstance.min = 0;
fixture.componentInstance.max = 100;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
slideToValue(slider, endInput, 92);
slideToValue(slider, startInput, 91);
checkInput(startInput, {min: 0, max: 92, value: 91, translateX: 273});
checkInput(endInput, {min: 91, max: 100, value: 92, translateX: 276});
fixture.componentInstance.min = 90;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(startInput, {min: 90, max: 92, value: 91, translateX: 30});
checkInput(endInput, {min: 91, max: 100, value: 92, translateX: 60});
}));
it('that make min and max equal', () => {
fixture.componentInstance.min = 75;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(startInput, {min: 75, max: 75, value: 75, translateX: 0});
checkInput(endInput, {min: 75, max: 75, value: 75, translateX: 0});
});
it('that increase above the max', () => {
fixture.componentInstance.min = 80;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(startInput, {min: 80, max: 75, value: 80, translateX: 0});
checkInput(endInput, {min: 80, max: 75, value: 80, translateX: 0});
});
}); | {
"end_byte": 17992,
"start_byte": 13567,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.spec.ts"
} |
components/src/material/slider/slider.spec.ts_17998_23592 | describe('should handle max changes', () => {
it('that do not affect values', () => {
checkInput(startInput, {min: 25, max: 75, value: 25, translateX: 0});
checkInput(endInput, {min: 25, max: 75, value: 75, translateX: 300});
fixture.componentInstance.max = 125;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(startInput, {min: 25, max: 75, value: 25, translateX: 0});
checkInput(endInput, {min: 25, max: 125, value: 75, translateX: 150});
});
it('that affect the end value', () => {
fixture.componentInstance.max = 50;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(endInput, {min: 25, max: 50, value: 50, translateX: 300});
checkInput(startInput, {min: 25, max: 50, value: 25, translateX: 0});
});
it('that affect both values', () => {
startInput.value = 60;
fixture.componentInstance.max = 50;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(endInput, {min: 50, max: 50, value: 50, translateX: 300});
checkInput(startInput, {min: 25, max: 50, value: 50, translateX: 300});
});
it('where the new start tx is greater than the old end tx', fakeAsync(() => {
fixture.componentInstance.min = 0;
fixture.componentInstance.max = 100;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
slideToValue(slider, startInput, 1);
slideToValue(slider, endInput, 2);
checkInput(startInput, {min: 0, max: 2, value: 1, translateX: 3});
checkInput(endInput, {min: 1, max: 100, value: 2, translateX: 6});
fixture.componentInstance.max = 10;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(startInput, {min: 0, max: 2, value: 1, translateX: 30});
checkInput(endInput, {min: 1, max: 10, value: 2, translateX: 60});
}));
it('where the new end tx is less than the old start tx', fakeAsync(() => {
fixture.componentInstance.min = 0;
fixture.componentInstance.max = 100;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
slideToValue(slider, endInput, 95);
slideToValue(slider, startInput, 90);
checkInput(startInput, {min: 0, max: 95, value: 90, translateX: 270});
checkInput(endInput, {min: 90, max: 100, value: 95, translateX: 285});
fixture.componentInstance.max = 1000;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(startInput, {min: 0, max: 95, value: 90, translateX: 27});
checkInput(endInput, {min: 90, max: 1000, value: 95, translateX: 28.5});
}));
it('that make min and max equal', () => {
fixture.componentInstance.max = 25;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(startInput, {min: 25, max: 25, value: 25, translateX: 0});
checkInput(endInput, {min: 25, max: 25, value: 25, translateX: 0});
});
it('that decrease below the min', () => {
fixture.componentInstance.max = 0;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// For some reason there was a bug with Safari 15.3.
// Manually testing on version 16.0 shows that this issue no longer exists.
if (!platform.SAFARI) {
checkInput(startInput, {min: 25, max: 0, value: 25, translateX: 0});
checkInput(endInput, {min: 25, max: 0, value: 25, translateX: 0});
}
});
});
});
describe('disabled slider', () => {
let slider: MatSlider;
let input: MatSliderThumb;
beforeEach(waitForAsync(() => {
const fixture = createComponent(DisabledSlider);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
input = slider._getInput(_MatThumb.END) as MatSliderThumb;
}));
it('should be disabled', () => {
expect(slider.disabled).toBeTrue();
});
it('should have the disabled class on the root element', () => {
expect(slider._elementRef.nativeElement.classList).toContain('mdc-slider--disabled');
});
it('should set the disabled attribute on the input element', () => {
expect(input._hostElement.disabled).toBeTrue();
});
});
describe('disabled range slider', () => {
let slider: MatSlider;
let startInput: MatSliderThumb;
let endInput: MatSliderThumb;
beforeEach(waitForAsync(() => {
const fixture = createComponent(DisabledRangeSlider);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
startInput = slider._getInput(_MatThumb.START) as MatSliderRangeThumb;
endInput = slider._getInput(_MatThumb.END) as MatSliderRangeThumb;
}));
it('should be disabled', () => {
expect(slider.disabled).toBeTrue();
});
it('should have the disabled class on the root element', () => {
expect(slider._elementRef.nativeElement.classList).toContain('mdc-slider--disabled');
});
it('should set the disabled attribute on the input elements', () => {
expect(startInput._hostElement.disabled).toBeTrue();
expect(endInput._hostElement.disabled).toBeTrue();
});
}); | {
"end_byte": 23592,
"start_byte": 17998,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.spec.ts"
} |
components/src/material/slider/slider.spec.ts_23596_31976 | describe('ripple states', () => {
let input: MatSliderThumb;
let thumbInstance: MatSliderVisualThumb;
let thumbElement: HTMLElement;
let thumbX: number;
let thumbY: number;
beforeEach(waitForAsync(() => {
const fixture = createComponent(StandardSlider);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
const slider = sliderDebugElement.componentInstance;
input = slider._getInput(_MatThumb.END) as MatSliderThumb;
thumbInstance = slider._getThumb(_MatThumb.END);
thumbElement = thumbInstance._hostElement;
const thumbDimensions = thumbElement.getBoundingClientRect();
thumbX = thumbDimensions.left + thumbDimensions.width / 2;
thumbY = thumbDimensions.top + thumbDimensions.height / 2;
}));
function isRippleVisible(selector: string) {
flushRippleTransitions();
return thumbElement.querySelector(`.mat-mdc-slider-${selector}-ripple`) !== null;
}
function flushRippleTransitions() {
thumbElement.querySelectorAll('.mat-ripple-element').forEach(el => {
dispatchFakeEvent(el, 'transitionend');
});
}
function blur() {
input._hostElement.blur();
}
function pointerenter() {
dispatchPointerEvent(input._hostElement, 'pointermove', thumbX, thumbY);
}
function pointerleave() {
dispatchPointerEvent(input._hostElement, 'pointermove', thumbX + 1000, thumbY);
}
function pointerdown() {
dispatchPointerEvent(input._hostElement, 'pointerdown', thumbX, thumbY);
input.focus();
}
function pointerup() {
dispatchPointerEvent(input._hostElement, 'pointerup', thumbX, thumbY);
}
it('should show the hover ripple on pointerenter', fakeAsync(() => {
// Doesn't make sense to test for pointerenter events on touch devices.
expect(isRippleVisible('hover')).toBeFalse();
pointerenter();
expect(isRippleVisible('hover')).toBeTrue();
}));
it('should hide the hover ripple on pointerleave', fakeAsync(() => {
// Doesn't make sense to test for pointerleave events on touch devices.
pointerenter();
pointerleave();
expect(isRippleVisible('hover')).toBeFalse();
}));
it('should show the focus ripple on pointerdown', fakeAsync(() => {
expect(isRippleVisible('focus')).toBeFalse();
pointerdown();
flush();
expect(isRippleVisible('focus')).toBeTrue();
}));
it('should continue to show the focus ripple on pointerup', fakeAsync(() => {
pointerdown();
pointerup();
flush();
// The slider immediately loses focus on pointerup for Safari.
if (platform.SAFARI) {
expect(isRippleVisible('hover')).toBeTrue();
} else {
expect(isRippleVisible('focus')).toBeTrue();
}
}));
it('should hide the focus ripple on blur', fakeAsync(() => {
pointerdown();
pointerup();
blur();
flush();
expect(isRippleVisible('focus')).toBeFalse();
}));
it('should show the active ripple on pointerdown', fakeAsync(() => {
expect(isRippleVisible('active')).toBeFalse();
pointerdown();
expect(isRippleVisible('active')).toBeTrue();
flush();
}));
it('should hide the active ripple on pointerup', fakeAsync(() => {
pointerdown();
pointerup();
flush();
expect(isRippleVisible('active')).toBeFalse();
}));
// Edge cases.
it('should not show the hover ripple if the thumb is already focused', fakeAsync(() => {
pointerdown();
pointerenter();
flush();
expect(isRippleVisible('hover')).toBeFalse();
}));
it('should hide the hover ripple if the thumb is focused', fakeAsync(() => {
pointerenter();
pointerdown();
flush();
expect(isRippleVisible('hover')).toBeFalse();
}));
it('should not hide the focus ripple if the thumb is pressed', fakeAsync(() => {
pointerdown();
blur();
flush();
expect(isRippleVisible('focus')).toBeTrue();
}));
it('should not hide the hover ripple on blur if the thumb is hovered', fakeAsync(() => {
pointerenter();
pointerdown();
pointerup();
blur();
flush();
expect(isRippleVisible('hover')).toBeTrue();
}));
it('should hide the focus ripple on drag end if the thumb already lost focus', fakeAsync(() => {
pointerdown();
blur();
pointerup();
flush();
expect(isRippleVisible('focus')).toBeFalse();
}));
});
describe('slider with set value', () => {
let slider: MatSlider;
let input: MatSliderThumb;
beforeEach(waitForAsync(() => {
const fixture = createComponent(SliderWithValue);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
input = slider._getInput(_MatThumb.END) as MatSliderThumb;
}));
it('should set the default value from the attribute', () => {
checkInput(input, {min: 0, max: 100, value: 50, translateX: 150});
});
it('should update the value', fakeAsync(() => {
slideToValue(slider, input, 75);
checkInput(input, {min: 0, max: 100, value: 75, translateX: 225});
}));
});
describe('range slider with set value', () => {
let slider: MatSlider;
let startInput: MatSliderThumb;
let endInput: MatSliderThumb;
beforeEach(waitForAsync(() => {
const fixture = createComponent(RangeSliderWithValue);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
startInput = slider._getInput(_MatThumb.START) as MatSliderRangeThumb;
endInput = slider._getInput(_MatThumb.END) as MatSliderRangeThumb;
}));
it('should set the correct initial values', fakeAsync(() => {
checkInput(startInput, {min: 0, max: 75, value: 25, translateX: 75});
checkInput(endInput, {min: 25, max: 100, value: 75, translateX: 225});
}));
it('should update the start value', fakeAsync(() => {
checkInput(startInput, {min: 0, max: 75, value: 25, translateX: 75});
checkInput(endInput, {min: 25, max: 100, value: 75, translateX: 225});
slideToValue(slider, startInput, 30);
checkInput(startInput, {min: 0, max: 75, value: 30, translateX: 90});
checkInput(endInput, {min: 30, max: 100, value: 75, translateX: 225});
}));
it('should update the end value', fakeAsync(() => {
slideToValue(slider, endInput, 77);
checkInput(startInput, {min: 0, max: 77, value: 25, translateX: 75});
checkInput(endInput, {min: 25, max: 100, value: 77, translateX: 231});
}));
});
describe('slider with set step', () => {
let fixture: ComponentFixture<SliderWithStep>;
let slider: MatSlider;
let input: MatSliderThumb;
beforeEach(waitForAsync(() => {
fixture = createComponent(SliderWithStep);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
input = slider._getInput(_MatThumb.END) as MatSliderThumb;
}));
it('should update to the value based on the step', fakeAsync(() => {
slideToValue(slider, input, 30);
expect(input.value).toBe(25);
}));
it('should not add decimals to the value if it is a whole number', fakeAsync(() => {
fixture.componentInstance.step = 0.1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
slideToValue(slider, input, 11);
expect(input.value).toBe(11);
}));
it('should truncate long decimal values when using a decimal step', fakeAsync(() => {
fixture.componentInstance.step = 0.5;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
slideToValue(slider, input, 55.555);
expect(input.value).toBe(55.5);
}));
it('should update the value on step change', fakeAsync(() => {
slideToValue(slider, input, 30);
fixture.componentInstance.step = 50;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(input.value).toBe(50);
}));
}); | {
"end_byte": 31976,
"start_byte": 23596,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.spec.ts"
} |
components/src/material/slider/slider.spec.ts_31980_40165 | describe('range slider with set step', () => {
let fixture: ComponentFixture<RangeSliderWithStep>;
let slider: MatSlider;
let startInput: MatSliderThumb;
let endInput: MatSliderThumb;
beforeEach(waitForAsync(() => {
fixture = createComponent(RangeSliderWithStep);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
startInput = slider._getInput(_MatThumb.START) as MatSliderRangeThumb;
endInput = slider._getInput(_MatThumb.END) as MatSliderRangeThumb;
}));
it('should set the correct start value on slide', fakeAsync(() => {
slideToValue(slider, startInput, 30);
expect(startInput.value).toBe(25);
}));
it('should set the correct end value on slide', fakeAsync(() => {
slideToValue(slider, endInput, 45);
expect(endInput.value).toBe(50);
}));
it('should not add decimals to the end value if it is a whole number', fakeAsync(() => {
fixture.componentInstance.step = 0.1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
slideToValue(slider, endInput, 11);
expect(endInput.value).toBe(11);
}));
it('should not add decimals to the start value if it is a whole number', fakeAsync(() => {
fixture.componentInstance.step = 0.1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
slideToValue(slider, startInput, 11);
expect(startInput.value).toBe(11);
}));
it('should truncate long decimal start values when using a decimal step', fakeAsync(() => {
fixture.componentInstance.step = 0.1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
slideToValue(slider, startInput, 33.666);
expect(startInput.value).toBe(33.7);
}));
it('should truncate long decimal end values when using a decimal step', fakeAsync(() => {
fixture.componentInstance.step = 0.1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
slideToValue(slider, endInput, 33.6666);
expect(endInput.value).toBe(33.7);
}));
describe('should handle step changes', () => {
it('where the new start tx is greater than the old end tx', fakeAsync(() => {
fixture.componentInstance.step = 0;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
slideToValue(slider, startInput, 45);
slideToValue(slider, endInput, 46);
checkInput(startInput, {min: 0, max: 46, value: 45, translateX: 135});
checkInput(endInput, {min: 45, max: 100, value: 46, translateX: 138});
fixture.componentInstance.step = 50;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(startInput, {min: 0, max: 50, value: 50, translateX: 150});
checkInput(endInput, {min: 50, max: 100, value: 50, translateX: 150});
}));
it('where the new end tx is less than the old start tx', fakeAsync(() => {
fixture.componentInstance.step = 0;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
slideToValue(slider, startInput, 21);
slideToValue(slider, endInput, 22);
checkInput(startInput, {min: 0, max: 22, value: 21, translateX: 63});
checkInput(endInput, {min: 21, max: 100, value: 22, translateX: 66});
fixture.componentInstance.step = 50;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
checkInput(startInput, {min: 0, max: 0, value: 0, translateX: 0});
checkInput(endInput, {min: 0, max: 100, value: 0, translateX: 0});
}));
});
});
describe('slider with custom thumb label formatting', () => {
let fixture: ComponentFixture<DiscreteSliderWithDisplayWith>;
let slider: MatSlider;
let input: MatSliderThumb;
let valueIndicatorTextElement: Element;
beforeEach(() => {
fixture = createComponent(DiscreteSliderWithDisplayWith);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!;
const sliderNativeElement = sliderDebugElement.nativeElement;
slider = sliderDebugElement.componentInstance;
valueIndicatorTextElement = sliderNativeElement.querySelector(
'.mdc-slider__value-indicator-text',
)!;
input = slider._getInput(_MatThumb.END) as MatSliderThumb;
});
it('should set the aria-valuetext attribute with the given `displayWith` function', fakeAsync(() => {
expect(input._hostElement.getAttribute('aria-valuetext')).toBe('$1');
setValueByClick(slider, input, 199);
fixture.detectChanges();
flush();
expect(input._hostElement.getAttribute('aria-valuetext')).toBe('$199');
}));
it('should invoke the passed-in `displayWith` function with the value', fakeAsync(() => {
spyOn(slider, 'displayWith').and.callThrough();
setValueByClick(slider, input, 199);
expect(slider.displayWith).toHaveBeenCalledWith(199);
}));
it('should format the thumb label based on the passed-in `displayWith` function', fakeAsync(() => {
setValueByClick(slider, input, 149);
fixture.detectChanges();
expect(valueIndicatorTextElement.textContent).toBe('$149');
}));
});
describe('range slider with custom thumb label formatting', () => {
let fixture: ComponentFixture<DiscreteRangeSliderWithDisplayWith>;
let slider: MatSlider;
let startValueIndicatorTextElement: Element;
let endValueIndicatorTextElement: Element;
let startInput: MatSliderThumb;
let endInput: MatSliderThumb;
beforeEach(() => {
fixture = createComponent(DiscreteRangeSliderWithDisplayWith);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!;
slider = sliderDebugElement.componentInstance;
startInput = slider._getInput(_MatThumb.START) as MatSliderRangeThumb;
endInput = slider._getInput(_MatThumb.END) as MatSliderRangeThumb;
const startThumbElement = slider._getThumb(_MatThumb.START)._hostElement;
const endThumbElement = slider._getThumb(_MatThumb.END)._hostElement;
startValueIndicatorTextElement = startThumbElement.querySelector(
'.mdc-slider__value-indicator-text',
)!;
endValueIndicatorTextElement = endThumbElement.querySelector(
'.mdc-slider__value-indicator-text',
)!;
});
it('should set the aria-valuetext attribute with the given `displayWith` function', fakeAsync(() => {
expect(startInput._hostElement.getAttribute('aria-valuetext')).toBe('$1');
expect(endInput._hostElement.getAttribute('aria-valuetext')).toBe('$200');
setValueByClick(slider, startInput, 25);
setValueByClick(slider, endInput, 81);
expect(startInput._hostElement.getAttribute('aria-valuetext')).toBe('$25');
expect(endInput._hostElement.getAttribute('aria-valuetext')).toBe('$81');
}));
it('should invoke the passed-in `displayWith` function with the start value', fakeAsync(() => {
spyOn(slider, 'displayWith').and.callThrough();
setValueByClick(slider, startInput, 197);
expect(slider.displayWith).toHaveBeenCalledWith(197);
}));
it('should invoke the passed-in `displayWith` function with the end value', fakeAsync(() => {
spyOn(slider, 'displayWith').and.callThrough();
setValueByClick(slider, endInput, 72);
expect(slider.displayWith).toHaveBeenCalledWith(72);
}));
it('should format the start thumb label based on the passed-in `displayWith` function', fakeAsync(() => {
setValueByClick(slider, startInput, 120);
fixture.detectChanges();
expect(startValueIndicatorTextElement.textContent).toBe('$120');
}));
it('should format the end thumb label based on the passed-in `displayWith` function', fakeAsync(() => {
setValueByClick(slider, endInput, 70);
fixture.detectChanges();
expect(endValueIndicatorTextElement.textContent).toBe('$70');
}));
}); | {
"end_byte": 40165,
"start_byte": 31980,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.spec.ts"
} |
components/src/material/slider/slider.spec.ts_40169_46879 | describe('slider with value property binding', () => {
let fixture: ComponentFixture<SliderWithOneWayBinding>;
let input: MatSliderThumb;
beforeEach(waitForAsync(() => {
fixture = createComponent(SliderWithOneWayBinding);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
const slider = sliderDebugElement.componentInstance;
input = slider._getInput(_MatThumb.END) as MatSliderThumb;
}));
it('should update when bound value changes', () => {
fixture.componentInstance.value = 75;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(input.value).toBe(75);
});
});
describe('range slider with value property binding', () => {
let fixture: ComponentFixture<RangeSliderWithOneWayBinding>;
let startInput: MatSliderThumb;
let endInput: MatSliderThumb;
beforeEach(waitForAsync(() => {
fixture = createComponent(RangeSliderWithOneWayBinding);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
const slider = sliderDebugElement.componentInstance;
startInput = slider._getInput(_MatThumb.START) as MatSliderRangeThumb;
endInput = slider._getInput(_MatThumb.END) as MatSliderRangeThumb;
}));
it('should update when bound start value changes', () => {
fixture.componentInstance.startValue = 30;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(startInput.value).toBe(30);
});
it('should update when bound end value changes', () => {
fixture.componentInstance.endValue = 70;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(endInput.value).toBe(70);
});
it('should update the input width when the start value changes', () => {
const startInputEl = startInput._elementRef.nativeElement;
const endInputEl = endInput._elementRef.nativeElement;
const startInputWidthBefore = startInputEl.getBoundingClientRect().width;
const endInputWidthBefore = endInputEl.getBoundingClientRect().width;
fixture.componentInstance.startValue = 10;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const startInputWidthAfter = startInputEl.getBoundingClientRect().width;
const endInputWidthAfter = endInputEl.getBoundingClientRect().width;
expect(startInputWidthBefore).not.toBe(startInputWidthAfter);
expect(endInputWidthBefore).not.toBe(endInputWidthAfter);
});
it('should update the input width when the end value changes', () => {
const startInputEl = startInput._elementRef.nativeElement;
const endInputEl = endInput._elementRef.nativeElement;
const startInputWidthBefore = startInputEl.getBoundingClientRect().width;
const endInputWidthBefore = endInputEl.getBoundingClientRect().width;
fixture.componentInstance.endValue = 90;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const startInputWidthAfter = startInputEl.getBoundingClientRect().width;
const endInputWidthAfter = endInputEl.getBoundingClientRect().width;
expect(startInputWidthBefore).not.toBe(startInputWidthAfter);
expect(endInputWidthBefore).not.toBe(endInputWidthAfter);
});
});
describe('slider with direction', () => {
let slider: MatSlider;
let input: MatSliderThumb;
beforeEach(waitForAsync(() => {
const fixture = createComponent(StandardSlider, [
{
provide: Directionality,
useValue: {value: 'rtl', change: of()},
},
]);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
input = slider._getInput(_MatThumb.END) as MatSliderThumb;
}));
it('works in RTL languages', fakeAsync(() => {
setValueByClick(slider, input, 25, true);
checkInput(input, {min: 0, max: 100, value: 75, translateX: 75});
}));
});
describe('range slider with direction', () => {
let slider: MatSlider;
let startInput: MatSliderThumb;
let endInput: MatSliderThumb;
beforeEach(waitForAsync(() => {
const fixture = createComponent(StandardRangeSlider, [
{
provide: Directionality,
useValue: {value: 'rtl', change: of()},
},
]);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
startInput = slider._getInput(_MatThumb.START) as MatSliderRangeThumb;
endInput = slider._getInput(_MatThumb.END) as MatSliderRangeThumb;
}));
it('works in RTL languages', fakeAsync(() => {
setValueByClick(slider, startInput, 90, true);
checkInput(startInput, {min: 0, max: 100, value: 10, translateX: 270});
setValueByClick(slider, endInput, 10, true);
checkInput(endInput, {min: 10, max: 100, value: 90, translateX: 30});
}));
});
describe('slider with ngModel', () => {
let fixture: ComponentFixture<SliderWithNgModel>;
let slider: MatSlider;
let input: MatSliderThumb;
beforeEach(waitForAsync(() => {
fixture = createComponent(SliderWithNgModel);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
input = slider._getInput(_MatThumb.END) as MatSliderThumb;
}));
it('should update the model', fakeAsync(() => {
slideToValue(slider, input, 19);
fixture.detectChanges();
expect(fixture.componentInstance.val).toBe(19);
checkInput(input, {min: 0, max: 100, value: 19, translateX: 57});
}));
it('should update the slider', fakeAsync(() => {
fixture.componentInstance.val = 20;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
checkInput(input, {min: 0, max: 100, value: 20, translateX: 60});
}));
it('should be able to reset a slider by setting the model back to undefined', fakeAsync(() => {
fixture.componentInstance.val = 5;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
checkInput(input, {min: 0, max: 100, value: 5, translateX: 15});
fixture.componentInstance.val = undefined;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
checkInput(input, {min: 0, max: 100, value: 0, translateX: 0});
}));
}); | {
"end_byte": 46879,
"start_byte": 40169,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.spec.ts"
} |
components/src/material/slider/slider.spec.ts_46883_52650 | describe('range slider with ngModel', () => {
let slider: MatSlider;
let fixture: ComponentFixture<RangeSliderWithNgModel>;
let startInput: MatSliderThumb;
let endInput: MatSliderThumb;
beforeEach(waitForAsync(() => {
fixture = createComponent(RangeSliderWithNgModel);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
startInput = slider._getInput(_MatThumb.START) as MatSliderRangeThumb;
endInput = slider._getInput(_MatThumb.END) as MatSliderRangeThumb;
}));
it('should update the models on input value changes', fakeAsync(() => {
slideToValue(slider, startInput, 25);
fixture.detectChanges();
flush();
checkInput(startInput, {min: 0, max: 100, value: 25, translateX: 75});
slideToValue(slider, endInput, 75);
fixture.detectChanges();
flush();
checkInput(endInput, {min: 25, max: 100, value: 75, translateX: 225});
}));
it('should update the thumbs on ngModel value change', fakeAsync(() => {
fixture.componentInstance.startVal = 50;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
checkInput(startInput, {min: 0, max: 100, value: 50, translateX: 150});
fixture.componentInstance.endVal = 75;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
checkInput(endInput, {min: 50, max: 100, value: 75, translateX: 225});
}));
it('should be able to reset a start input', fakeAsync(() => {
fixture.componentInstance.startVal = 5;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
checkInput(startInput, {min: 0, max: 100, value: 5, translateX: 15});
fixture.componentInstance.startVal = undefined;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
checkInput(startInput, {min: 0, max: 100, value: 0, translateX: 0});
}));
it('should be able to reset an end input', fakeAsync(() => {
fixture.componentInstance.endVal = 99;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
checkInput(endInput, {min: 0, max: 100, value: 99, translateX: 297});
fixture.componentInstance.endVal = undefined;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
checkInput(endInput, {min: 0, max: 100, value: 0, translateX: 0});
}));
});
describe('range slider w/ NgModel edge case', () => {
it('should initialize correctly despite NgModel `null` bug', fakeAsync(() => {
const fixture = createComponent(RangeSliderWithNgModelEdgeCase);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
const slider = sliderDebugElement.componentInstance;
const startInput = slider._getInput(_MatThumb.START) as MatSliderRangeThumb;
const endInput = slider._getInput(_MatThumb.END) as MatSliderRangeThumb;
flush();
checkInput(startInput, {min: -1, max: -0.3, value: -0.7, translateX: 90});
checkInput(endInput, {min: -0.7, max: 0, value: -0.3, translateX: 210});
}));
});
describe('slider as a custom form control', () => {
let fixture: ComponentFixture<SliderWithFormControl>;
let slider: MatSlider;
let input: MatSliderThumb;
beforeEach(waitForAsync(() => {
fixture = createComponent(SliderWithFormControl);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
input = slider._getInput(_MatThumb.END) as MatSliderThumb;
}));
it('should update the control on slide', fakeAsync(() => {
expect(fixture.componentInstance.control.value).toBe(0);
slideToValue(slider, input, 19);
expect(fixture.componentInstance.control.value).toBe(19);
}));
it('should update the value when the control is set', () => {
expect(input.value).toBe(0);
fixture.componentInstance.control.setValue(7);
checkInput(input, {min: 0, max: 100, value: 7, translateX: 21});
});
it('should update the disabled state when control is disabled', () => {
expect(slider.disabled).toBe(false);
fixture.componentInstance.control.disable();
expect(slider.disabled).toBe(true);
});
it('should update the disabled state when the control is enabled', () => {
slider.disabled = true;
fixture.componentInstance.control.enable();
expect(slider.disabled).toBe(false);
});
it('should have the correct control state initially and after interaction', fakeAsync(() => {
let sliderControl = fixture.componentInstance.control;
// The control should start off valid, pristine, and untouched.
expect(sliderControl.valid).toBe(true);
expect(sliderControl.pristine).toBe(true);
expect(sliderControl.touched).toBe(false);
// After changing the value, the control should become dirty (not pristine),
// but remain untouched.
setValueByClick(slider, input, 50);
expect(sliderControl.valid).toBe(true);
expect(sliderControl.pristine).toBe(false);
expect(sliderControl.touched).toBe(false);
// If the control has been visited due to interaction, the control should remain
// dirty and now also be touched.
input.blur();
fixture.detectChanges();
expect(sliderControl.valid).toBe(true);
expect(sliderControl.pristine).toBe(false);
expect(sliderControl.touched).toBe(true);
}));
}); | {
"end_byte": 52650,
"start_byte": 46883,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.spec.ts"
} |
components/src/material/slider/slider.spec.ts_52654_61233 | describe('slider as a custom form control', () => {
let fixture: ComponentFixture<RangeSliderWithFormControl>;
let slider: MatSlider;
let startInput: MatSliderThumb;
let endInput: MatSliderThumb;
beforeEach(waitForAsync(() => {
fixture = createComponent(RangeSliderWithFormControl);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
startInput = slider._getInput(_MatThumb.START) as MatSliderRangeThumb;
endInput = slider._getInput(_MatThumb.END) as MatSliderRangeThumb;
}));
it('should update the start input control on slide', fakeAsync(() => {
expect(fixture.componentInstance.startInputControl.value).toBe(0);
slideToValue(slider, startInput, 20);
expect(fixture.componentInstance.startInputControl.value).toBe(20);
}));
it('should update the end input control on slide', fakeAsync(() => {
expect(fixture.componentInstance.endInputControl.value).toBe(100);
slideToValue(slider, endInput, 80);
expect(fixture.componentInstance.endInputControl.value).toBe(80);
}));
it('should update the start input value when the start input control is set', () => {
expect(startInput.value).toBe(0);
fixture.componentInstance.startInputControl.setValue(10);
checkInput(startInput, {min: 0, max: 100, value: 10, translateX: 30});
});
it('should update the end input value when the end input control is set', () => {
expect(endInput.value).toBe(100);
fixture.componentInstance.endInputControl.setValue(90);
checkInput(endInput, {min: 0, max: 100, value: 90, translateX: 270});
});
it('should update the disabled state if the start input control is disabled', () => {
expect(slider.disabled).toBe(false);
fixture.componentInstance.startInputControl.disable();
expect(slider.disabled).toBe(true);
});
it('should update the disabled state if the end input control is disabled', () => {
expect(slider.disabled).toBe(false);
fixture.componentInstance.endInputControl.disable();
expect(slider.disabled).toBe(true);
});
it('should update the disabled state when both input controls are enabled', () => {
slider.disabled = true;
fixture.componentInstance.startInputControl.enable();
expect(slider.disabled).toBe(false);
fixture.componentInstance.endInputControl.enable();
expect(slider.disabled).toBe(false);
});
it('should have the correct start input control state initially and after interaction', fakeAsync(() => {
let sliderControl = fixture.componentInstance.startInputControl;
// The control should start off valid, pristine, and untouched.
expect(sliderControl.valid).toBe(true);
expect(sliderControl.pristine).toBe(true);
expect(sliderControl.touched).toBe(false);
// After changing the value, the control should become dirty (not pristine),
// but remain untouched.
setValueByClick(slider, startInput, 25);
expect(sliderControl.valid).toBe(true);
expect(sliderControl.pristine).toBe(false);
expect(sliderControl.touched).toBe(false);
// If the control has been visited due to interaction, the control should remain
// dirty and now also be touched.
startInput.blur();
fixture.detectChanges();
expect(sliderControl.valid).toBe(true);
expect(sliderControl.pristine).toBe(false);
expect(sliderControl.touched).toBe(true);
}));
it('should have the correct start input control state initially and after interaction', fakeAsync(() => {
let sliderControl = fixture.componentInstance.endInputControl;
// The control should start off valid, pristine, and untouched.
expect(sliderControl.valid).toBe(true);
expect(sliderControl.pristine).toBe(true);
expect(sliderControl.touched).toBe(false);
// After changing the value, the control should become dirty (not pristine),
// but remain untouched.
setValueByClick(slider, endInput, 75);
expect(sliderControl.valid).toBe(true);
expect(sliderControl.pristine).toBe(false);
expect(sliderControl.touched).toBe(false);
// If the control has been visited due to interaction, the control should remain
// dirty and now also be touched.
endInput.blur();
fixture.detectChanges();
expect(sliderControl.valid).toBe(true);
expect(sliderControl.pristine).toBe(false);
expect(sliderControl.touched).toBe(true);
}));
});
describe('slider with a two-way binding', () => {
let input: MatSliderThumb;
let slider: MatSlider;
let fixture: ComponentFixture<SliderWithTwoWayBinding>;
beforeEach(() => {
fixture = createComponent(SliderWithTwoWayBinding);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
input = slider._getInput(_MatThumb.END) as MatSliderThumb;
});
it('should sync the value binding in both directions', fakeAsync(() => {
checkInput(input, {min: 0, max: 100, value: 0, step: 1, translateX: 0});
slideToValue(slider, input, 10);
expect(fixture.componentInstance.value).toBe(10);
checkInput(input, {min: 0, max: 100, value: 10, step: 1, translateX: 30});
fixture.componentInstance.value = 20;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.value).toBe(20);
checkInput(input, {min: 0, max: 100, value: 20, step: 1, translateX: 60});
}));
});
describe('range slider with a two-way binding', () => {
let slider: MatSlider;
let startInput: MatSliderRangeThumb;
let endInput: MatSliderRangeThumb;
let fixture: ComponentFixture<RangeSliderWithTwoWayBinding>;
beforeEach(waitForAsync(() => {
fixture = createComponent(RangeSliderWithTwoWayBinding);
fixture.detectChanges();
const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider));
slider = sliderDebugElement.componentInstance;
endInput = slider._getInput(_MatThumb.END) as MatSliderRangeThumb;
startInput = slider._getInput(_MatThumb.START) as MatSliderRangeThumb;
}));
it('should sync the start value binding in both directions', fakeAsync(() => {
expect(fixture.componentInstance.startValue).toBe(0);
expect(startInput.value).toBe(0);
slideToValue(slider, startInput, 10);
expect(fixture.componentInstance.startValue).toBe(10);
expect(startInput.value).toBe(10);
fixture.componentInstance.startValue = 20;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.startValue).toBe(20);
expect(startInput.value).toBe(20);
}));
it('should sync the end value binding in both directions', fakeAsync(() => {
expect(fixture.componentInstance.endValue).toBe(100);
expect(endInput.value).toBe(100);
slideToValue(slider, endInput, 90);
expect(fixture.componentInstance.endValue).toBe(90);
expect(endInput.value).toBe(90);
fixture.componentInstance.endValue = 80;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.endValue).toBe(80);
expect(endInput.value).toBe(80);
}));
});
});
const SLIDER_STYLES = ['.mat-mdc-slider { width: 300px; }'];
@Component({
template: `
<mat-slider>
<input matSliderThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class StandardSlider {}
@Component({
template: `
<mat-slider>
<input matSliderStartThumb>
<input matSliderEndThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class StandardRangeSlider {}
@Component({
template: `
<mat-slider disabled>
<input matSliderThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class DisabledSlider {}
@Component({
template: `
<mat-slider disabled>
<input matSliderStartThumb>
<input matSliderEndThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class DisabledRangeSlider {}
@Component({
template: `
<mat-slider [min]="min" [max]="max">
<input matSliderThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class SliderWithMinAndMax {
min = 25;
max = 75;
} | {
"end_byte": 61233,
"start_byte": 52654,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.spec.ts"
} |
components/src/material/slider/slider.spec.ts_61235_67404 | @Component({
template: `
<mat-slider [min]="min" [max]="max">
<input matSliderStartThumb>
<input matSliderEndThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class RangeSliderWithMinAndMax {
min = 25;
max = 75;
}
@Component({
template: `
<mat-slider>
<input value="50" matSliderThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class SliderWithValue {}
@Component({
template: `
<mat-slider>
<input value="25" matSliderStartThumb>
<input value="75" matSliderEndThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class RangeSliderWithValue {}
@Component({
template: `
<mat-slider [step]="step">
<input matSliderThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class SliderWithStep {
step = 25;
}
@Component({
template: `
<mat-slider [step]="step">
<input matSliderStartThumb>
<input matSliderEndThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class RangeSliderWithStep {
step = 25;
}
@Component({
template: `
<mat-slider [displayWith]="displayWith" min="1" max="200" discrete>
<input matSliderThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class DiscreteSliderWithDisplayWith {
displayWith(v: number) {
return `$${v}`;
}
}
@Component({
template: `
<mat-slider [displayWith]="displayWith" min="1" max="200" discrete>
<input matSliderStartThumb>
<input matSliderEndThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class DiscreteRangeSliderWithDisplayWith {
displayWith(v: number) {
return `$${v}`;
}
}
@Component({
template: `
<mat-slider>
<input [value]="value" matSliderThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class SliderWithOneWayBinding {
value = 50;
}
@Component({
template: `
<mat-slider>
<input [value]="startValue" matSliderStartThumb>
<input [value]="endValue" matSliderEndThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class RangeSliderWithOneWayBinding {
startValue = 25;
endValue = 75;
}
@Component({
template: `
<mat-slider>
<input [(ngModel)]="val" matSliderThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class SliderWithNgModel {
@ViewChild(MatSlider) slider: MatSlider;
val: number | undefined = 0;
}
@Component({
template: `
<mat-slider>
<input [(ngModel)]="startVal" matSliderStartThumb>
<input [(ngModel)]="endVal" matSliderEndThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class RangeSliderWithNgModel {
@ViewChild(MatSlider) slider: MatSlider;
startVal: number | undefined = 0;
endVal: number | undefined = 100;
}
@Component({
template: `
<mat-slider min="-1" max="0" step="0.1">
<input [(ngModel)]="startValue" matSliderStartThumb />
<input [(ngModel)]="endValue" matSliderEndThumb />
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class RangeSliderWithNgModelEdgeCase {
@ViewChild(MatSlider) slider: MatSlider;
startValue: number = -0.7;
endValue: number = -0.3;
}
@Component({
template: `
<mat-slider>
<input [formControl]="control" matSliderThumb>
</mat-slider>`,
styles: SLIDER_STYLES,
standalone: false,
})
class SliderWithFormControl {
control = new FormControl(0);
}
@Component({
template: `
<mat-slider>
<input [formControl]="startInputControl" matSliderStartThumb>
<input [formControl]="endInputControl" matSliderEndThumb>
</mat-slider>`,
styles: SLIDER_STYLES,
standalone: false,
})
class RangeSliderWithFormControl {
startInputControl = new FormControl(0);
endInputControl = new FormControl(100);
}
@Component({
template: `
<mat-slider>
<input [(value)]="value" matSliderThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class SliderWithTwoWayBinding {
value = 0;
}
@Component({
template: `
<mat-slider>
<input [(value)]="startValue" matSliderStartThumb>
<input [(value)]="endValue" matSliderEndThumb>
</mat-slider>
`,
styles: SLIDER_STYLES,
standalone: false,
})
class RangeSliderWithTwoWayBinding {
@ViewChild(MatSlider) slider: MatSlider;
@ViewChildren(MatSliderThumb) sliderInputs: QueryList<MatSliderThumb>;
startValue = 0;
endValue = 100;
}
/** Clicks on the MatSlider at the coordinates corresponding to the given value. */
function setValueByClick(
slider: MatSlider,
input: MatSliderThumb,
value: number,
isRtl: boolean = false,
) {
const inputElement = input._elementRef.nativeElement;
const val = isRtl ? slider.max - value : value;
const {x, y} = getCoordsForValue(slider, value);
dispatchPointerEvent(inputElement, 'pointerdown', x, y);
input.value = val;
dispatchEvent(input._hostElement, new Event('input'));
input.focus();
dispatchPointerEvent(inputElement, 'pointerup', x, y);
dispatchEvent(input._hostElement, new Event('change'));
flush();
}
/** Slides the MatSlider's thumb to the given value. */
function slideToValue(slider: MatSlider, input: MatSliderThumb, value: number) {
const sliderElement = slider._elementRef.nativeElement;
const {x: startX, y: startY} = getCoordsForValue(slider, input.value);
const {x: endX, y: endY} = getCoordsForValue(slider, value);
dispatchPointerEvent(sliderElement, 'pointerdown', startX, startY);
input.focus();
dispatchPointerEvent(sliderElement, 'pointermove', endX, endY);
input._hostElement.value = `${value}`;
dispatchEvent(input._hostElement, new Event('input'));
dispatchPointerEvent(sliderElement, 'pointerup', endX, endY);
dispatchEvent(input._hostElement, new Event('change'));
tick(10);
}
/** Returns the x and y coordinates for the given slider value. */
function getCoordsForValue(slider: MatSlider, value: number): Point {
const {min, max} = slider;
const percent = (value - min) / (max - min);
const {top, left, width, height} = slider._elementRef.nativeElement.getBoundingClientRect();
const x = width * percent + left;
const y = top + height / 2;
return {x, y};
} | {
"end_byte": 67404,
"start_byte": 61235,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.spec.ts"
} |
components/src/material/slider/slider.html_0_1003 | <!-- Inputs -->
<ng-content></ng-content>
<!-- Track -->
<div class="mdc-slider__track">
<div class="mdc-slider__track--inactive"></div>
<div class="mdc-slider__track--active">
<div #trackActive class="mdc-slider__track--active_fill"></div>
</div>
@if (showTickMarks) {
<div class="mdc-slider__tick-marks" #tickMarkContainer>
@if (_cachedWidth) {
@for (tickMark of _tickMarks; track i; let i = $index) {
<div
[class]="tickMark === 0 ? 'mdc-slider__tick-mark--active' : 'mdc-slider__tick-mark--inactive'"
[style.transform]="_calcTickMarkTransform(i)"></div>
}
}
</div>
}
</div>
<!-- Thumbs -->
@if (_isRange) {
<mat-slider-visual-thumb
[discrete]="discrete"
[thumbPosition]="1"
[valueIndicatorText]="startValueIndicatorText">
</mat-slider-visual-thumb>
}
<mat-slider-visual-thumb
[discrete]="discrete"
[thumbPosition]="2"
[valueIndicatorText]="endValueIndicatorText">
</mat-slider-visual-thumb>
| {
"end_byte": 1003,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider.html"
} |
components/src/material/slider/BUILD.bazel_0_2064 | load("//src/e2e-app:test_suite.bzl", "e2e_test_suite")
load(
"//tools:defaults.bzl",
"extract_tokens",
"markdown_to_html",
"ng_e2e_test_library",
"ng_module",
"ng_test_library",
"ng_web_test_suite",
"sass_binary",
"sass_library",
)
package(default_visibility = ["//visibility:public"])
ng_module(
name = "slider",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = [
":slider_scss",
":slider_thumb_scss",
] + glob(["**/*.html"]),
deps = [
"//src/cdk/bidi",
"//src/cdk/platform",
"//src/material/core",
"@npm//@angular/forms",
],
)
sass_library(
name = "slider_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = [
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "slider_scss",
src = "slider.scss",
deps = [
"//src/cdk:sass_lib",
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "slider_thumb_scss",
src = "slider-thumb.scss",
)
markdown_to_html(
name = "overview",
srcs = [":slider.md"],
)
extract_tokens(
name = "tokens",
srcs = [":slider_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
###########
# Testing
###########
ng_test_library(
name = "slider_tests_lib",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":slider",
"//src/cdk/bidi",
"//src/cdk/keycodes",
"//src/cdk/platform",
"//src/cdk/testing/private",
"//src/material/core",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
"@npm//rxjs",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":slider_tests_lib",
],
)
ng_e2e_test_library(
name = "e2e_test_sources",
srcs = glob(["**/*.e2e.spec.ts"]),
deps = [
":slider",
],
)
e2e_test_suite(
name = "e2e_tests",
deps = [
":e2e_test_sources",
],
)
| {
"end_byte": 2064,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/BUILD.bazel"
} |
components/src/material/slider/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/slider/index.ts"
} |
components/src/material/slider/slider-interface.ts_0_7998 | /**
* @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, ChangeDetectorRef, WritableSignal} from '@angular/core';
import {MatRipple, RippleGlobalOptions} from '@angular/material/core';
/**
* Thumb types: range slider has two thumbs (START, END) whereas single point
* slider only has one thumb (END).
*/
export enum _MatThumb {
START = 1,
END = 2,
}
/** Tick mark enum, for discrete sliders. */
export enum _MatTickMark {
ACTIVE = 0,
INACTIVE = 1,
}
/**
* Injection token that can be used for a `MatSlider` to provide itself as a
* parent to the `MatSliderThumb` and `MatSliderRangeThumb`.
* Used primarily to avoid circular imports.
* @docs-private
*/
export const MAT_SLIDER = new InjectionToken<{}>('_MatSlider');
/**
* Injection token that can be used to query for a `MatSliderThumb`.
* Used primarily to avoid circular imports.
* @docs-private
*/
export const MAT_SLIDER_THUMB = new InjectionToken<{}>('_MatSliderThumb');
/**
* Injection token that can be used to query for a `MatSliderRangeThumb`.
* Used primarily to avoid circular imports.
* @docs-private
*/
export const MAT_SLIDER_RANGE_THUMB = new InjectionToken<{}>('_MatSliderRangeThumb');
/**
* Injection token that can be used to query for a `MatSliderVisualThumb`.
* Used primarily to avoid circular imports.
* @docs-private
*/
export const MAT_SLIDER_VISUAL_THUMB = new InjectionToken<{}>('_MatSliderVisualThumb');
/** Represents a drag event emitted by the MatSlider component. */
export interface MatSliderDragEvent {
/** The MatSliderThumb that was interacted with. */
source: _MatSliderThumb;
/** The MatSlider that was interacted with. */
parent: _MatSlider;
/** The current value of the slider. */
value: number;
}
/**
* A simple change event emitted by the MatSlider component.
* @deprecated Use event bindings directly on the MatSliderThumbs for `change` and `input` events. See https://v17.material.angular.io/guide/mdc-migration for information about migrating.
* @breaking-change 17.0.0
*/
export class MatSliderChange {
/** The MatSliderThumb that was interacted with. */
source: _MatSliderThumb;
/** The MatSlider that was interacted with. */
parent: _MatSlider;
/** The new value of the source slider. */
value: number;
}
export interface _MatSlider {
/** Whether the given pointer event occurred within the bounds of the slider pointer's DOM Rect. */
_isCursorOnSliderThumb(event: PointerEvent, rect: DOMRect): boolean;
/** Gets the slider thumb input of the given thumb position. */
_getInput(thumbPosition: _MatThumb): _MatSliderThumb | _MatSliderRangeThumb | undefined;
/** Gets the slider thumb HTML input element of the given thumb position. */
_getThumb(thumbPosition: _MatThumb): _MatSliderVisualThumb;
/** The minimum value that the slider can have. */
min: number;
/** The maximum value that the slider can have. */
max: number;
/** The amount that slider values can increment or decrement by. */
step: number;
/** Whether the slider is disabled. */
disabled: boolean;
/** Whether the slider is a range slider. */
_isRange: boolean;
/** Whether the slider is rtl. */
_isRtl: boolean;
/** The stored width of the host element's bounding client rect. */
_cachedWidth: number;
/** The stored width of the host element's bounding client rect. */
_cachedLeft: number;
/**
* The padding of the native slider input. This is added in order to make the region where the
* thumb ripple extends past the end of the slider track clickable.
*/
_inputPadding: number;
/** The radius of the visual slider's ripple. */
_rippleRadius: number;
/** The global configuration for `matRipple` instances. */
readonly _globalRippleOptions: RippleGlobalOptions | null;
/** Whether animations have been disabled. */
_noopAnimations: boolean;
/** Whether or not the slider should use animations. */
_hasAnimation: boolean;
/** Triggers UI updates that are needed after a slider input value has changed. */
_onValueChange: (source: _MatSliderThumb) => void;
/** Triggers UI updates that are needed after the slider thumb position has changed. */
_onTranslateXChange: (source: _MatSliderThumb) => void;
/** Updates the stored slider dimensions using the current bounding client rect. */
_updateDimensions: () => void;
/** Updates the scale on the active portion of the track. */
_updateTrackUI: (source: _MatSliderThumb) => void;
/** Used to set the transition duration for thumb and track animations. */
_setTransition: (withAnimation: boolean) => void;
_cdr: ChangeDetectorRef;
}
export interface _MatSliderThumb {
/** The minimum value that the slider can have. */
min: number;
/** The maximum value that the slider can have. */
max: number;
/** The amount that slider values can increment or decrement by. */
step: number;
/** The current value of this slider input. */
value: number;
/** The current translateX in px of the slider visual thumb. */
translateX: number;
/** Indicates whether this thumb is the start or end thumb. */
thumbPosition: _MatThumb;
/** Similar to percentage but calcualted using translateX relative to the total track width. */
fillPercentage: number;
/** Whether the slider is disabled. */
disabled: boolean;
/** The host native HTML input element. */
_hostElement: HTMLInputElement;
/** Whether the input is currently focused (either by tab or after clicking). */
_isFocused: boolean;
/** The aria-valuetext string representation of the input's value. */
_valuetext: WritableSignal<string>;
/**
* Indicates whether UI updates should be skipped.
*
* This flag is used to avoid flickering
* when correcting values on pointer up/down.
*/
_skipUIUpdate: boolean;
/** Handles the initialization of properties for the slider input. */
initProps: () => void;
/** Handles UI initialization controlled by this slider input. */
initUI: () => void;
/** Calculates the visual thumb's translateX based on the slider input's current value. */
_calcTranslateXByValue: () => number;
/** Updates the visual thumb based on the slider input's current value. */
_updateThumbUIByValue: () => void;
/**
* Sets the slider input to disproportionate dimensions to allow for touch
* events to be captured on touch devices.
*/
_updateWidthInactive: () => void;
/**
* Used to set the slider width to the correct
* dimensions while the user is dragging.
*/
_updateWidthActive: () => void;
}
export interface _MatSliderRangeThumb extends _MatSliderThumb {
/** Whether this slider corresponds to the input on the left hand side. */
_isLeftThumb: boolean;
/**
* Gets the sibling MatSliderRangeThumb.
* Returns undefined if it is too early in Angular's life cycle.
*/
getSibling: () => _MatSliderRangeThumb | undefined;
/** Used to cache whether this slider input corresponds to the visual left thumb. */
_setIsLeftThumb: () => void;
/** Updates the input styles to control whether it is pinned to the start or end of the mat-slider. */
_updateStaticStyles: () => void;
/** Updates the min and max properties of this slider input according to it's sibling. */
_updateMinMax: () => void;
}
export interface _MatSliderVisualThumb {
/** The MatRipple for this slider thumb. */
_ripple: MatRipple;
/** Whether the slider thumb is currently being pressed. */
_isActive: boolean;
/** The host native HTML input element. */
_hostElement: HTMLElement;
/** Shows the value indicator ui. */
_showValueIndicator: () => void;
/** Hides the value indicator ui. */
_hideValueIndicator: () => void;
/** Whether the slider visual thumb is currently showing any ripple. */
_isShowingAnyRipple: () => boolean;
}
| {
"end_byte": 7998,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/slider-interface.ts"
} |
components/src/material/slider/testing/slider-harness-filters.ts_0_939 | /**
* @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 positions of a slider thumb. */
export enum ThumbPosition {
START,
END,
}
/** A set of criteria that can be used to filter a list of `MatSliderHarness` instances. */
export interface SliderHarnessFilters extends BaseHarnessFilters {
/** Filters out only range/non-range sliders. */
isRange?: boolean;
/** Only find instances which match the given disabled state. */
disabled?: boolean;
}
/** A set of criteria that can be used to filter a list of `MatSliderThumbHarness` instances. */
export interface SliderThumbHarnessFilters extends BaseHarnessFilters {
/** Filters out slider thumbs with a particular position. */
position?: ThumbPosition;
}
| {
"end_byte": 939,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/testing/slider-harness-filters.ts"
} |
components/src/material/slider/testing/slider-thumb-harness.ts_0_4073 | /**
* @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 {coerceNumberProperty} from '@angular/cdk/coercion';
import {
ComponentHarness,
ComponentHarnessConstructor,
HarnessPredicate,
parallel,
} from '@angular/cdk/testing';
import {SliderThumbHarnessFilters, ThumbPosition} from './slider-harness-filters';
/** Harness for interacting with a thumb inside of a Material slider in tests. */
export class MatSliderThumbHarness extends ComponentHarness {
static hostSelector =
'input[matSliderThumb], input[matSliderStartThumb], input[matSliderEndThumb]';
/**
* Gets a `HarnessPredicate` that can be used to search for a slider thumb with specific attributes.
* @param options Options for filtering which thumb instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatSliderThumbHarness>(
this: ComponentHarnessConstructor<T>,
options: SliderThumbHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options).addOption(
'position',
options.position,
async (harness, value) => {
return (await harness.getPosition()) === value;
},
);
}
/** Gets the position of the thumb inside the slider. */
async getPosition(): Promise<ThumbPosition> {
// Meant to mimic MDC's logic where `matSliderThumb` is treated as END.
const isStart = (await (await this.host()).getAttribute('matSliderStartThumb')) != null;
return isStart ? ThumbPosition.START : ThumbPosition.END;
}
/** Gets the value of the thumb. */
async getValue(): Promise<number> {
return await (await this.host()).getProperty<number>('valueAsNumber');
}
/** Sets the value of the thumb. */
async setValue(newValue: number): Promise<void> {
const input = await this.host();
// Since this is a range input, we can't simulate the user interacting with it so we set the
// value directly and dispatch a couple of fake events to ensure that everything fires.
await input.setInputValue(newValue + '');
await input.dispatchEvent('input');
await input.dispatchEvent('change');
}
/** Gets the current percentage value of the slider. */
async getPercentage(): Promise<number> {
const [value, min, max] = await parallel(() => [
this.getValue(),
this.getMinValue(),
this.getMaxValue(),
]);
return (value - min) / (max - min);
}
/** Gets the maximum value of the thumb. */
async getMaxValue(): Promise<number> {
return coerceNumberProperty(await (await this.host()).getProperty<number>('max'));
}
/** Gets the minimum value of the thumb. */
async getMinValue(): Promise<number> {
return coerceNumberProperty(await (await this.host()).getProperty<number>('min'));
}
/** Gets the text representation of the slider's value. */
async getDisplayValue(): Promise<string> {
return (await (await this.host()).getAttribute('aria-valuetext')) || '';
}
/** Whether the thumb is disabled. */
async isDisabled(): Promise<boolean> {
return (await this.host()).getProperty<boolean>('disabled');
}
/** Gets the name of the thumb. */
async getName(): Promise<string> {
return await (await this.host()).getProperty<string>('name');
}
/** Gets the id of the thumb. */
async getId(): Promise<string> {
return await (await this.host()).getProperty<string>('id');
}
/**
* Focuses the thumb and returns a promise that indicates when the
* action is complete.
*/
async focus(): Promise<void> {
return (await this.host()).focus();
}
/**
* Blurs the thumb and returns a promise that indicates when the
* action is complete.
*/
async blur(): Promise<void> {
return (await this.host()).blur();
}
/** Whether the thumb is focused. */
async isFocused(): Promise<boolean> {
return (await this.host()).isFocused();
}
}
| {
"end_byte": 4073,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/testing/slider-thumb-harness.ts"
} |
components/src/material/slider/testing/public-api.ts_0_320 | /**
* @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 './slider-harness';
export * from './slider-thumb-harness';
export * from './slider-harness-filters';
| {
"end_byte": 320,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/testing/public-api.ts"
} |
components/src/material/slider/testing/slider-harness.spec.ts_0_8932 | /**
* @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 {Component, signal} from '@angular/core';
import {ComponentFixture, fakeAsync, TestBed} from '@angular/core/testing';
import {HarnessLoader, parallel} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {MatSliderModule} from '@angular/material/slider';
import {MatSliderHarness} from './slider-harness';
import {MatSliderThumbHarness} from './slider-thumb-harness';
import {ThumbPosition} from './slider-harness-filters';
describe('MatSliderHarness', () => {
let fixture: ComponentFixture<SliderHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatSliderModule, SliderHarnessTest],
});
fixture = TestBed.createComponent(SliderHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all slider harnesses', async () => {
const sliders = await loader.getAllHarnesses(MatSliderHarness);
expect(sliders.length).toBe(2);
});
it('should get whether is a range slider', async () => {
const sliders = await loader.getAllHarnesses(MatSliderHarness);
expect(await parallel(() => sliders.map(slider => slider.isRange()))).toEqual([false, true]);
});
it('should get whether a slider is disabled', async () => {
const slider = await loader.getHarness(MatSliderHarness);
expect(await slider.isDisabled()).toBe(false);
fixture.componentInstance.singleSliderDisabled.set(true);
expect(await slider.isDisabled()).toBe(true);
});
it('should filter by whether a slider is disabled', async () => {
let enabledSliders = await loader.getAllHarnesses(MatSliderHarness.with({disabled: false}));
let disabledSliders = await loader.getAllHarnesses(MatSliderHarness.with({disabled: true}));
expect(enabledSliders.length).toBe(2);
expect(disabledSliders.length).toBe(0);
fixture.componentInstance.singleSliderDisabled.set(true);
enabledSliders = await loader.getAllHarnesses(MatSliderHarness.with({disabled: false}));
disabledSliders = await loader.getAllHarnesses(MatSliderHarness.with({disabled: true}));
expect(enabledSliders.length).toBe(1);
expect(disabledSliders.length).toBe(1);
});
it('should get the min/max values of a single-thumb slider', async () => {
const slider = await loader.getHarness(MatSliderHarness);
const [min, max] = await parallel(() => [slider.getMinValue(), slider.getMaxValue()]);
expect(min).toBe(0);
expect(max).toBe(100);
});
it('should get the min/max values of a range slider', async () => {
const slider = await loader.getHarness(MatSliderHarness.with({isRange: true}));
const [min, max] = await parallel(() => [slider.getMinValue(), slider.getMaxValue()]);
expect(min).toBe(fixture.componentInstance.rangeSliderMin);
expect(max).toBe(fixture.componentInstance.rangeSliderMax);
});
it('should get the thumbs within a slider', async () => {
const sliders = await loader.getAllHarnesses(MatSliderHarness);
expect(await sliders[0].getEndThumb()).toBeTruthy();
expect(await sliders[1].getStartThumb()).toBeTruthy();
expect(await sliders[1].getEndThumb()).toBeTruthy();
});
it('should throw when trying to get the start thumb from a single point slider', async () => {
const slider = await loader.getHarness(MatSliderHarness.with({isRange: false}));
await expectAsync(slider.getStartThumb()).toBeRejectedWithError(
'`getStartThumb` is only applicable for range sliders. ' +
'Did you mean to use `getEndThumb`?',
);
});
it('should get the step of a slider', async () => {
const sliders = await loader.getAllHarnesses(MatSliderHarness);
expect(
await parallel(() => {
return sliders.map(slider => slider.getStep());
}),
).toEqual([1, fixture.componentInstance.rangeSliderStep]);
});
it('should get the position of a slider thumb in a range slider', async () => {
const slider = await loader.getHarness(MatSliderHarness.with({selector: '#range'}));
const [start, end] = await parallel(() => [slider.getStartThumb(), slider.getEndThumb()]);
expect(await start.getPosition()).toBe(ThumbPosition.START);
expect(await end.getPosition()).toBe(ThumbPosition.END);
});
it('should get the position of a slider thumb in a non-range slider', async () => {
const thumb = await loader.getHarness(MatSliderThumbHarness.with({ancestor: '#single'}));
expect(await thumb.getPosition()).toBe(ThumbPosition.END);
});
it('should get and set the value of a slider thumb', async () => {
const slider = await loader.getHarness(MatSliderHarness);
const thumb = await slider.getEndThumb();
expect(await thumb.getValue()).toBe(0);
await thumb.setValue(73);
expect(await thumb.getValue()).toBe(73);
});
it('should dispatch input and change events when setting the value', async () => {
const slider = await loader.getHarness(MatSliderHarness);
const thumb = await slider.getEndThumb();
const changeSpy = spyOn(fixture.componentInstance, 'changeListener');
const inputSpy = spyOn(fixture.componentInstance, 'inputListener');
await thumb.setValue(73);
expect(changeSpy).toHaveBeenCalledTimes(1);
expect(inputSpy).toHaveBeenCalledTimes(1);
expect(await thumb.getValue()).toBe(73);
});
it('should get the value of a thumb as a percentage', async () => {
const sliders = await loader.getAllHarnesses(MatSliderHarness);
expect(await (await sliders[0].getEndThumb()).getPercentage()).toBe(0);
expect(await (await sliders[1].getStartThumb()).getPercentage()).toBe(0.4);
expect(await (await sliders[1].getEndThumb()).getPercentage()).toBe(0.5);
});
it('should get the display value of a slider thumb', async () => {
const slider = await loader.getHarness(MatSliderHarness);
const thumb = await slider.getEndThumb();
fixture.componentInstance.displayFn.set(value => `#${value}`);
await thumb.setValue(73);
expect(await thumb.getDisplayValue()).toBe('#73');
});
it('should get the min/max values of a slider thumb', fakeAsync(async () => {
const instance = fixture.componentInstance;
const slider = await loader.getHarness(MatSliderHarness.with({selector: '#range'}));
const [start, end] = await parallel(() => [slider.getStartThumb(), slider.getEndThumb()]);
expect(await start.getMinValue()).toBe(instance.rangeSliderMin);
expect(await start.getMaxValue()).toBe(instance.rangeSliderEndValue);
expect(await end.getMinValue()).toBe(instance.rangeSliderStartValue);
expect(await end.getMaxValue()).toBe(instance.rangeSliderMax);
}));
it('should get the disabled state of a slider thumb', async () => {
const slider = await loader.getHarness(MatSliderHarness);
const thumb = await slider.getEndThumb();
expect(await thumb.isDisabled()).toBe(false);
fixture.componentInstance.singleSliderDisabled.set(true);
expect(await thumb.isDisabled()).toBe(true);
});
it('should get the name of a slider thumb', async () => {
const slider = await loader.getHarness(MatSliderHarness);
expect(await (await slider.getEndThumb()).getName()).toBe('price');
});
it('should get the id of a slider thumb', async () => {
const slider = await loader.getHarness(MatSliderHarness);
expect(await (await slider.getEndThumb()).getId()).toBe('price-input');
});
it('should be able to focus and blur a slider thumb', async () => {
const slider = await loader.getHarness(MatSliderHarness);
const thumb = await slider.getEndThumb();
expect(await thumb.isFocused()).toBe(false);
await thumb.focus();
expect(await thumb.isFocused()).toBe(true);
await thumb.blur();
expect(await thumb.isFocused()).toBe(false);
});
});
@Component({
template: `
<mat-slider id="single" [displayWith]="displayFn()" [disabled]="singleSliderDisabled()">
<input
name="price"
id="price-input"
matSliderThumb
(input)="inputListener()"
(change)="changeListener()">
</mat-slider>
<mat-slider id="range" [min]="rangeSliderMin" [max]="rangeSliderMax" [step]="rangeSliderStep">
<input [value]="rangeSliderStartValue" matSliderStartThumb>
<input [value]="rangeSliderEndValue" matSliderEndThumb>
</mat-slider>
`,
standalone: true,
imports: [MatSliderModule],
})
class SliderHarnessTest {
singleSliderDisabled = signal(false);
rangeSliderMin = 100;
rangeSliderMax = 500;
rangeSliderStep = 50;
rangeSliderStartValue = 200;
rangeSliderEndValue = 350;
displayFn = signal((value: number) => value + '');
inputListener() {}
changeListener() {}
}
| {
"end_byte": 8932,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/testing/slider-harness.spec.ts"
} |
components/src/material/slider/testing/slider-harness.ts_0_3101 | /**
* @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,
} from '@angular/cdk/testing';
import {coerceNumberProperty} from '@angular/cdk/coercion';
import {SliderHarnessFilters, ThumbPosition} from './slider-harness-filters';
import {MatSliderThumbHarness} from './slider-thumb-harness';
/** Harness for interacting with a MDC mat-slider in tests. */
export class MatSliderHarness extends ComponentHarness {
static hostSelector = '.mat-mdc-slider';
/**
* Gets a `HarnessPredicate` that can be used to search for a slider with specific attributes.
* @param options Options for filtering which input instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatSliderHarness>(
this: ComponentHarnessConstructor<T>,
options: SliderHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options)
.addOption('isRange', options.isRange, async (harness, value) => {
return (await harness.isRange()) === value;
})
.addOption('disabled', options.disabled, async (harness, disabled) => {
return (await harness.isDisabled()) === disabled;
});
}
/** Gets the start thumb of the slider (only applicable for range sliders). */
async getStartThumb(): Promise<MatSliderThumbHarness> {
if (!(await this.isRange())) {
throw Error(
'`getStartThumb` is only applicable for range sliders. ' +
'Did you mean to use `getEndThumb`?',
);
}
return this.locatorFor(MatSliderThumbHarness.with({position: ThumbPosition.START}))();
}
/** Gets the thumb (for single point sliders), or the end thumb (for range sliders). */
async getEndThumb(): Promise<MatSliderThumbHarness> {
return this.locatorFor(MatSliderThumbHarness.with({position: ThumbPosition.END}))();
}
/** Gets whether the slider is a range slider. */
async isRange(): Promise<boolean> {
return await (await this.host()).hasClass('mdc-slider--range');
}
/** Gets whether the slider is disabled. */
async isDisabled(): Promise<boolean> {
return await (await this.host()).hasClass('mdc-slider--disabled');
}
/** Gets the value step increments of the slider. */
async getStep(): Promise<number> {
// The same step value is forwarded to both thumbs.
const startHost = await (await this.getEndThumb()).host();
return coerceNumberProperty(await startHost.getProperty<string>('step'));
}
/** Gets the maximum value of the slider. */
async getMaxValue(): Promise<number> {
return (await this.getEndThumb()).getMaxValue();
}
/** Gets the minimum value of the slider. */
async getMinValue(): Promise<number> {
const startThumb = (await this.isRange())
? await this.getStartThumb()
: await this.getEndThumb();
return startThumb.getMinValue();
}
}
| {
"end_byte": 3101,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/testing/slider-harness.ts"
} |
components/src/material/slider/testing/BUILD.bazel_0_756 | 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/slider",
],
)
ng_test_library(
name = "unit_tests_lib",
srcs = glob(["**/*.spec.ts"]),
deps = [
":testing",
"//src/cdk/testing",
"//src/cdk/testing/testbed",
"//src/material/slider",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":unit_tests_lib",
],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 756,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slider/testing/BUILD.bazel"
} |
components/src/material/slider/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/slider/testing/index.ts"
} |
components/src/material/stepper/step-header.ts_0_4403 | /**
* @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 {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
Input,
OnDestroy,
ViewEncapsulation,
TemplateRef,
AfterViewInit,
inject,
} from '@angular/core';
import {Subscription} from 'rxjs';
import {MatStepLabel} from './step-label';
import {MatStepperIntl} from './stepper-intl';
import {MatStepperIconContext} from './stepper-icon';
import {CdkStepHeader, StepState} from '@angular/cdk/stepper';
import {_StructuralStylesLoader, MatRipple, ThemePalette} from '@angular/material/core';
import {MatIcon} from '@angular/material/icon';
import {NgTemplateOutlet} from '@angular/common';
import {_CdkPrivateStyleLoader, _VisuallyHiddenLoader} from '@angular/cdk/private';
@Component({
selector: 'mat-step-header',
templateUrl: 'step-header.html',
styleUrl: 'step-header.css',
host: {
'class': 'mat-step-header',
'[class]': '"mat-" + (color || "primary")',
'role': 'tab',
},
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [MatRipple, NgTemplateOutlet, MatIcon],
})
export class MatStepHeader extends CdkStepHeader implements AfterViewInit, OnDestroy {
_intl = inject(MatStepperIntl);
private _focusMonitor = inject(FocusMonitor);
private _intlSubscription: Subscription;
/** State of the given step. */
@Input() state: StepState;
/** Label of the given step. */
@Input() label: MatStepLabel | string;
/** Error message to display when there's an error. */
@Input() errorMessage: string;
/** Overrides for the header icons, passed in via the stepper. */
@Input() iconOverrides: {[key: string]: TemplateRef<MatStepperIconContext>};
/** Index of the given step. */
@Input() index: number;
/** Whether the given step is selected. */
@Input() selected: boolean;
/** Whether the given step label is active. */
@Input() active: boolean;
/** Whether the given step is optional. */
@Input() optional: boolean;
/** Whether the ripple should be disabled. */
@Input() disableRipple: boolean;
/**
* Theme color of the step header. 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;
constructor(...args: unknown[]);
constructor() {
super();
inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader);
inject(_CdkPrivateStyleLoader).load(_VisuallyHiddenLoader);
const changeDetectorRef = inject(ChangeDetectorRef);
this._intlSubscription = this._intl.changes.subscribe(() => changeDetectorRef.markForCheck());
}
ngAfterViewInit() {
this._focusMonitor.monitor(this._elementRef, true);
}
ngOnDestroy() {
this._intlSubscription.unsubscribe();
this._focusMonitor.stopMonitoring(this._elementRef);
}
/** Focuses the step header. */
override focus(origin?: FocusOrigin, options?: FocusOptions) {
if (origin) {
this._focusMonitor.focusVia(this._elementRef, origin, options);
} else {
this._elementRef.nativeElement.focus(options);
}
}
/** Returns string label of given step if it is a text label. */
_stringLabel(): string | null {
return this.label instanceof MatStepLabel ? null : this.label;
}
/** Returns MatStepLabel if the label of given step is a template label. */
_templateLabel(): MatStepLabel | null {
return this.label instanceof MatStepLabel ? this.label : null;
}
/** Returns the host HTML element. */
_getHostElement() {
return this._elementRef.nativeElement;
}
/** Template context variables that are exposed to the `matStepperIcon` instances. */
_getIconContext(): MatStepperIconContext {
return {
index: this.index,
active: this.active,
optional: this.optional,
};
}
_getDefaultTextForState(state: StepState): string {
if (state == 'number') {
return `${this.index + 1}`;
}
if (state == 'edit') {
return 'create';
}
if (state == 'error') {
return 'warning';
}
return state;
}
}
| {
"end_byte": 4403,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/stepper/step-header.ts"
} |
components/src/material/stepper/stepper-intl.ts_0_1319 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Injectable, Optional, SkipSelf} from '@angular/core';
import {Subject} from 'rxjs';
/** Stepper data that is required for internationalization. */
@Injectable({providedIn: 'root'})
export class MatStepperIntl {
/**
* Stream that emits whenever the labels here are changed. Use this to notify
* components if the labels have changed after initialization.
*/
readonly changes: Subject<void> = new Subject<void>();
/** Label that is rendered below optional steps. */
optionalLabel: string = 'Optional';
/** Label that is used to indicate step as completed to screen readers. */
completedLabel: string = 'Completed';
/** Label that is used to indicate step as editable to screen readers. */
editableLabel: string = 'Editable';
}
/** @docs-private */
export function MAT_STEPPER_INTL_PROVIDER_FACTORY(parentIntl: MatStepperIntl) {
return parentIntl || new MatStepperIntl();
}
/** @docs-private */
export const MAT_STEPPER_INTL_PROVIDER = {
provide: MatStepperIntl,
deps: [[new Optional(), new SkipSelf(), MatStepperIntl]],
useFactory: MAT_STEPPER_INTL_PROVIDER_FACTORY,
};
| {
"end_byte": 1319,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper-intl.ts"
} |
components/src/material/stepper/stepper-icon.ts_0_989 | /**
* @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, TemplateRef, inject} from '@angular/core';
import {StepState} from '@angular/cdk/stepper';
/** Template context available to an attached `matStepperIcon`. */
export interface MatStepperIconContext {
/** Index of the step. */
index: number;
/** Whether the step is currently active. */
active: boolean;
/** Whether the step is optional. */
optional: boolean;
}
/**
* Template to be used to override the icons inside the step header.
*/
@Directive({
selector: 'ng-template[matStepperIcon]',
})
export class MatStepperIcon {
templateRef = inject<TemplateRef<MatStepperIconContext>>(TemplateRef);
/** Name of the icon to be overridden. */
@Input('matStepperIcon') name: StepState;
constructor(...args: unknown[]);
constructor() {}
}
| {
"end_byte": 989,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper-icon.ts"
} |
components/src/material/stepper/stepper.html_0_3885 | <!--
We need to project the content somewhere to avoid hydration errors. Some observations:
1. This is only necessary on the server.
2. We get a hydration error if there aren't any nodes after the `ng-content`.
3. We get a hydration error if `ng-content` is wrapped in another element.
-->
@if (_isServer) {
<ng-content/>
}
@switch (orientation) {
@case ('horizontal') {
<div class="mat-horizontal-stepper-wrapper">
<div class="mat-horizontal-stepper-header-container">
@for (step of steps; track step; let i = $index, isLast = $last) {
<ng-container
[ngTemplateOutlet]="stepTemplate"
[ngTemplateOutletContext]="{step: step, i: i}"></ng-container>
@if (!isLast) {
<div class="mat-stepper-horizontal-line"></div>
}
}
</div>
<div class="mat-horizontal-content-container">
@for (step of steps; track step; let i = $index) {
<div class="mat-horizontal-stepper-content" role="tabpanel"
[@horizontalStepTransition]="{
'value': _getAnimationDirection(i),
'params': {'animationDuration': _getAnimationDuration()}
}"
(@horizontalStepTransition.done)="_animationDone.next($event)"
[id]="_getStepContentId(i)"
[attr.aria-labelledby]="_getStepLabelId(i)"
[class.mat-horizontal-stepper-content-inactive]="selectedIndex !== i">
<ng-container [ngTemplateOutlet]="step.content"></ng-container>
</div>
}
</div>
</div>
}
@case ('vertical') {
@for (step of steps; track step; let i = $index, isLast = $last) {
<div class="mat-step">
<ng-container
[ngTemplateOutlet]="stepTemplate"
[ngTemplateOutletContext]="{step: step, i: i}"></ng-container>
<div class="mat-vertical-content-container" [class.mat-stepper-vertical-line]="!isLast">
<div class="mat-vertical-stepper-content" role="tabpanel"
[@verticalStepTransition]="{
'value': _getAnimationDirection(i),
'params': {'animationDuration': _getAnimationDuration()}
}"
(@verticalStepTransition.done)="_animationDone.next($event)"
[id]="_getStepContentId(i)"
[attr.aria-labelledby]="_getStepLabelId(i)"
[class.mat-vertical-stepper-content-inactive]="selectedIndex !== i">
<div class="mat-vertical-content">
<ng-container [ngTemplateOutlet]="step.content"></ng-container>
</div>
</div>
</div>
</div>
}
}
}
<!-- Common step templating -->
<ng-template let-step="step" let-i="i" #stepTemplate>
<mat-step-header
[class.mat-horizontal-stepper-header]="orientation === 'horizontal'"
[class.mat-vertical-stepper-header]="orientation === 'vertical'"
(click)="step.select()"
(keydown)="_onKeydown($event)"
[tabIndex]="_getFocusIndex() === i ? 0 : -1"
[id]="_getStepLabelId(i)"
[attr.aria-posinset]="i + 1"
[attr.aria-setsize]="steps.length"
[attr.aria-controls]="_getStepContentId(i)"
[attr.aria-selected]="selectedIndex == i"
[attr.aria-label]="step.ariaLabel || null"
[attr.aria-labelledby]="(!step.ariaLabel && step.ariaLabelledby) ? step.ariaLabelledby : null"
[attr.aria-disabled]="_stepIsNavigable(i, step) ? null : true"
[index]="i"
[state]="_getIndicatorType(i, step.state)"
[label]="step.stepLabel || step.label"
[selected]="selectedIndex === i"
[active]="_stepIsNavigable(i, step)"
[optional]="step.optional"
[errorMessage]="step.errorMessage"
[iconOverrides]="_iconOverrides"
[disableRipple]="disableRipple || !_stepIsNavigable(i, step)"
[color]="step.color || color"></mat-step-header>
</ng-template>
| {
"end_byte": 3885,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.html"
} |
components/src/material/stepper/step-content.ts_0_532 | /**
* @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, TemplateRef, inject} from '@angular/core';
/**
* Content for a `mat-step` that will be rendered lazily.
*/
@Directive({
selector: 'ng-template[matStepContent]',
})
export class MatStepContent {
_template = inject<TemplateRef<any>>(TemplateRef);
constructor(...args: unknown[]);
constructor() {}
}
| {
"end_byte": 532,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/stepper/step-content.ts"
} |
components/src/material/stepper/step-header.scss_0_6533 | @use '@angular/cdk';
@use '../core/tokens/m2/mat/stepper' as tokens-mat-stepper;
@use '../core/tokens/token-utils';
@use '../core/style/layout-common';
@use './stepper-variables';
.mat-step-header {
overflow: hidden;
outline: none;
cursor: pointer;
position: relative;
box-sizing: content-box;
-webkit-tap-highlight-color: transparent;
// Stepper headers have the focus indicator as a descendant,
// because `::before` is used for other styling.
&:focus .mat-focus-indicator::before {
content: '';
}
&:hover[aria-disabled='true'] {
cursor: default;
}
@include token-utils.use-tokens(
tokens-mat-stepper.$prefix, tokens-mat-stepper.get-token-slots()) {
&:hover:not([aria-disabled]),
&:hover[aria-disabled='false'] {
@include token-utils.create-token-slot(background-color, header-hover-state-layer-color);
@include token-utils.create-token-slot(border-radius, header-hover-state-layer-shape);
}
&.cdk-keyboard-focused,
&.cdk-program-focused {
@include token-utils.create-token-slot(background-color, header-focus-state-layer-color);
@include token-utils.create-token-slot(border-radius, header-focus-state-layer-shape);
}
}
// On touch devices the :hover state will linger on the element after a tap.
// Reset it via `@media` after the declaration, because the media query isn't
// supported by all browsers yet.
@media (hover: none) {
&:hover {
background: none;
}
}
@include cdk.high-contrast {
outline: solid 1px;
&[aria-selected='true'] {
.mat-step-label {
text-decoration: underline;
}
}
// When a step header is disabled in high contrast mode, set the text color to the disabled
// color, which is (unintuitively) named "GrayText".
&[aria-disabled='true'] {
outline-color: GrayText;
.mat-step-label,
.mat-step-icon,
.mat-step-optional {
color: GrayText;
}
}
}
}
.mat-step-optional {
font-size: stepper-variables.$step-sub-label-font-size;
@include token-utils.use-tokens(
tokens-mat-stepper.$prefix, tokens-mat-stepper.get-token-slots()) {
@include token-utils.create-token-slot(color, header-optional-label-text-color);
}
}
.mat-step-sub-label-error {
font-size: stepper-variables.$step-sub-label-font-size;
font-weight: normal;
}
.mat-step-icon {
border-radius: 50%;
height: stepper-variables.$label-header-height;
width: stepper-variables.$label-header-height;
flex-shrink: 0;
position: relative;
@include token-utils.use-tokens(
tokens-mat-stepper.$prefix, tokens-mat-stepper.get-token-slots()) {
@include token-utils.create-token-slot(color, header-icon-foreground-color);
@include token-utils.create-token-slot(background-color, header-icon-background-color);
}
}
.mat-step-icon-content {
// Use absolute positioning to center the content, because it works better with text.
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
// We aren't using any flex features here, but using the `display: flex` prevents
// the browser from adding extra whitespace at the bottom of the element.
display: flex;
}
.mat-step-icon .mat-icon {
font-size: stepper-variables.$step-header-icon-size;
height: stepper-variables.$step-header-icon-size;
width: stepper-variables.$step-header-icon-size;
}
.mat-step-icon-state-error {
@include token-utils.use-tokens(
tokens-mat-stepper.$prefix, tokens-mat-stepper.get-token-slots()) {
@include token-utils.create-token-slot(background-color,
header-error-state-icon-background-color);
@include token-utils.create-token-slot(color,
header-error-state-icon-foreground-color);
}
.mat-icon {
font-size: stepper-variables.$step-header-icon-size + 8;
height: stepper-variables.$step-header-icon-size + 8;
width: stepper-variables.$step-header-icon-size + 8;
}
}
.mat-step-label {
display: inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
min-width: stepper-variables.$label-min-width;
vertical-align: middle;
@include token-utils.use-tokens(
tokens-mat-stepper.$prefix, tokens-mat-stepper.get-token-slots()) {
@include token-utils.create-token-slot(font-family, header-label-text-font);
@include token-utils.create-token-slot(font-size, header-label-text-size);
@include token-utils.create-token-slot(font-weight, header-label-text-weight);
@include token-utils.create-token-slot(color, header-label-text-color);
&.mat-step-label-active {
@include token-utils.create-token-slot(color, header-selected-state-label-text-color);
}
&.mat-step-label-error {
@include token-utils.create-token-slot(color, header-error-state-label-text-color);
@include token-utils.create-token-slot(font-size, header-error-state-label-text-size);
}
&.mat-step-label-selected {
@include token-utils.create-token-slot(font-size, header-selected-state-label-text-size);
@include token-utils.create-token-slot(font-weight, header-selected-state-label-text-weight);
}
}
}
.mat-step-text-label {
text-overflow: ellipsis;
overflow: hidden;
}
// Increase specificity because ripple styles are part of the `mat-core` mixin and can
// potentially overwrite the absolute position of the container.
.mat-step-header .mat-step-header-ripple {
@include layout-common.fill;
pointer-events: none;
}
.mat-step-icon-selected {
@include token-utils.use-tokens(
tokens-mat-stepper.$prefix, tokens-mat-stepper.get-token-slots()) {
@include token-utils.create-token-slot(background-color,
header-selected-state-icon-background-color);
@include token-utils.create-token-slot(color,
header-selected-state-icon-foreground-color);
}
}
.mat-step-icon-state-done {
@include token-utils.use-tokens(
tokens-mat-stepper.$prefix, tokens-mat-stepper.get-token-slots()) {
@include token-utils.create-token-slot(background-color,
header-done-state-icon-background-color);
@include token-utils.create-token-slot(color,
header-done-state-icon-foreground-color);
}
}
.mat-step-icon-state-edit {
@include token-utils.use-tokens(
tokens-mat-stepper.$prefix, tokens-mat-stepper.get-token-slots()) {
@include token-utils.create-token-slot(background-color,
header-edit-state-icon-background-color);
@include token-utils.create-token-slot(color,
header-edit-state-icon-foreground-color);
}
}
| {
"end_byte": 6533,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/stepper/step-header.scss"
} |
components/src/material/stepper/_stepper-theme.scss_0_4742 | @use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/typography/typography';
@use '../core/style/sass-utils';
@use '../core/tokens/token-utils';
@use '../core/tokens/m2/mat/stepper' as tokens-mat-stepper;
/// Outputs base theme styles (styles not dependent on the color, typography, or density settings)
/// for mat-stepper.
/// @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 {
}
}
/// Outputs color theme styles for mat-stepper.
/// @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 stepper: primary, secondary,
/// tertiary, or error (If not specified, primary color values 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 token-utils.create-token-values(
tokens-mat-stepper.$prefix,
tokens-mat-stepper.get-color-tokens($theme)
);
.mat-step-header.mat-accent {
@include token-utils.create-token-values(
tokens-mat-stepper.$prefix,
tokens-mat-stepper.private-get-color-palette-color-tokens($theme, accent)
);
}
.mat-step-header.mat-warn {
@include token-utils.create-token-values(
tokens-mat-stepper.$prefix,
tokens-mat-stepper.private-get-color-palette-color-tokens($theme, warn)
);
}
}
}
}
/// Outputs typography theme styles for mat-stepper.
/// @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-mat-stepper.$prefix,
tokens-mat-stepper.get-typography-tokens($theme)
);
}
}
}
/// Outputs density theme styles for mat-stepper.
/// @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-stepper.$prefix,
tokens-mat-stepper.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-stepper.$prefix,
tokens: tokens-mat-stepper.get-token-slots(),
),
);
}
/// 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 mat-stepper.
/// @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 stepper: primary, secondary,
/// tertiary, or error (If not specified, primary color values will be used).
@mixin theme($theme, $options...) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-stepper') {
@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 != ()) {
$mat-stepper-tokens: token-utils.get-tokens-for(
$tokens,
tokens-mat-stepper.$prefix,
$options...
);
@include token-utils.create-token-values(tokens-mat-stepper.$prefix, $mat-stepper-tokens);
}
}
| {
"end_byte": 4742,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/stepper/_stepper-theme.scss"
} |
components/src/material/stepper/public-api.ts_0_583 | /**
* @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 {StepperOrientation, StepState} from '@angular/cdk/stepper';
export * from './stepper-module';
export * from './step-label';
export * from './stepper';
export * from './stepper-button';
export * from './step-header';
export * from './stepper-intl';
export {matStepperAnimations} from './stepper-animations';
export * from './stepper-icon';
export * from './step-content';
| {
"end_byte": 583,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/stepper/public-api.ts"
} |
components/src/material/stepper/step-header.html_0_1805 | <div class="mat-step-header-ripple mat-focus-indicator" matRipple
[matRippleTrigger]="_getHostElement()"
[matRippleDisabled]="disableRipple"></div>
<div class="mat-step-icon-state-{{state}} mat-step-icon" [class.mat-step-icon-selected]="selected">
<div class="mat-step-icon-content">
@if (iconOverrides && iconOverrides[state]) {
<ng-container
[ngTemplateOutlet]="iconOverrides[state]"
[ngTemplateOutletContext]="_getIconContext()"></ng-container>
} @else {
@switch (state) {
@case ('number') {
<span aria-hidden="true">{{_getDefaultTextForState(state)}}</span>
}
@default {
@if (state === 'done') {
<span class="cdk-visually-hidden">{{_intl.completedLabel}}</span>
} @else if (state === 'edit') {
<span class="cdk-visually-hidden">{{_intl.editableLabel}}</span>
}
<mat-icon aria-hidden="true">{{_getDefaultTextForState(state)}}</mat-icon>
}
}
}
</div>
</div>
<div class="mat-step-label"
[class.mat-step-label-active]="active"
[class.mat-step-label-selected]="selected"
[class.mat-step-label-error]="state == 'error'">
@if (_templateLabel(); as templateLabel) {
<!-- If there is a label template, use it. -->
<div class="mat-step-text-label">
<ng-container [ngTemplateOutlet]="templateLabel.template"></ng-container>
</div>
} @else if (_stringLabel()) {
<!-- If there is no label template, fall back to the text label. -->
<div class="mat-step-text-label">{{label}}</div>
}
@if (optional && state != 'error') {
<div class="mat-step-optional">{{_intl.optionalLabel}}</div>
}
@if (state === 'error') {
<div class="mat-step-sub-label-error">{{errorMessage}}</div>
}
</div>
| {
"end_byte": 1805,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/stepper/step-header.html"
} |
components/src/material/stepper/stepper.scss_0_7991 | @use 'sass:math';
@use '@angular/cdk';
@use '../core/tokens/m2/mat/stepper' as tokens-mat-stepper;
@use '../core/tokens/token-utils';
@use './stepper-variables';
// Gets the `calc` expression for the vertical padding of the stepper header.
@function _get-vertical-padding-calc() {
$height: token-utils.get-token-variable(header-height);
@return calc(calc(#{$height} - #{stepper-variables.$label-header-height}) / 2);
}
.mat-stepper-vertical,
.mat-stepper-horizontal {
display: block;
@include token-utils.use-tokens(
tokens-mat-stepper.$prefix, tokens-mat-stepper.get-token-slots()) {
@include token-utils.create-token-slot(font-family, container-text-font);
@include token-utils.create-token-slot(background, container-color);
}
}
.mat-horizontal-stepper-header-container {
white-space: nowrap;
display: flex;
align-items: center;
.mat-stepper-label-position-bottom & {
align-items: flex-start;
}
.mat-stepper-header-position-bottom & {
order: 1;
}
}
.mat-stepper-horizontal-line {
border-top-width: stepper-variables.$line-width;
border-top-style: solid;
flex: auto;
height: 0;
margin: 0 stepper-variables.$line-gap - stepper-variables.$side-gap;
min-width: stepper-variables.$line-gap + stepper-variables.$side-gap;
@include token-utils.use-tokens(
tokens-mat-stepper.$prefix, tokens-mat-stepper.get-token-slots()) {
@include token-utils.create-token-slot(border-top-color, line-color);
.mat-stepper-label-position-bottom & {
$vertical-padding: _get-vertical-padding-calc();
margin: 0;
min-width: 0;
position: relative;
// Ensures that the horizontal line for the step content is aligned centered vertically.
top: calc(#{$vertical-padding} + #{math.div(stepper-variables.$label-header-height, 2)});
}
}
}
%mat-header-horizontal-line-label-position-bottom {
$half-side-gap: math.div(stepper-variables.$side-gap, 2);
border-top-width: stepper-variables.$line-width;
border-top-style: solid;
content: '';
display: inline-block;
height: 0;
position: absolute;
width: calc(50% - #{$half-side-gap + stepper-variables.$line-gap});
}
.mat-horizontal-stepper-header {
display: flex;
height: stepper-variables.$header-height;
overflow: hidden;
align-items: center;
padding: 0 stepper-variables.$side-gap;
@include token-utils.use-tokens(
tokens-mat-stepper.$prefix, tokens-mat-stepper.get-token-slots()) {
@include token-utils.create-token-slot(height, header-height);
}
.mat-step-icon {
margin-right: stepper-variables.$line-gap;
flex: none;
[dir='rtl'] & {
margin-right: 0;
margin-left: stepper-variables.$line-gap;
}
}
@include token-utils.use-tokens(
tokens-mat-stepper.$prefix, tokens-mat-stepper.get-token-slots()) {
$vertical-padding: _get-vertical-padding-calc();
&::before,
&::after {
@include token-utils.create-token-slot(border-top-color, line-color);
}
.mat-stepper-label-position-bottom & {
padding: #{$vertical-padding} stepper-variables.$side-gap;
&::before,
&::after {
// Ensures that the horizontal lines for the step header are centered vertically.
top: calc(#{$vertical-padding} + #{math.div(stepper-variables.$label-header-height, 2)});
}
}
}
.mat-stepper-label-position-bottom & {
box-sizing: border-box;
flex-direction: column;
// We use auto instead of fixed 104px (by spec) because when there is an optional step
// the height is greater than that
height: auto;
&:not(:last-child)::after,
[dir='rtl'] &:not(:first-child)::after {
@extend %mat-header-horizontal-line-label-position-bottom;
right: 0;
}
&:not(:first-child)::before,
[dir='rtl'] &:not(:last-child)::before {
@extend %mat-header-horizontal-line-label-position-bottom;
left: 0;
}
[dir='rtl'] &:last-child::before,
[dir='rtl'] &:first-child::after {
display: none;
}
& .mat-step-icon {
// Cleans margin both for ltr and rtl direction
margin-right: 0;
margin-left: 0;
}
& .mat-step-label {
padding: stepper-variables.$label-position-bottom-top-gap 0 0 0;
text-align: center;
width: 100%;
}
}
}
.mat-vertical-stepper-header {
display: flex;
align-items: center;
// We can't use `max-height` here, because it breaks the flexbox centering in IE.
height: stepper-variables.$label-header-height;
@include token-utils.use-tokens(
tokens-mat-stepper.$prefix, tokens-mat-stepper.get-token-slots()) {
padding: #{_get-vertical-padding-calc()} stepper-variables.$side-gap;
}
.mat-step-icon {
margin-right: stepper-variables.$vertical-stepper-content-margin - stepper-variables.$side-gap;
[dir='rtl'] & {
margin-right: 0;
margin-left: stepper-variables.$vertical-stepper-content-margin - stepper-variables.$side-gap;
}
}
}
.mat-horizontal-stepper-wrapper {
display: flex;
flex-direction: column;
}
.mat-horizontal-stepper-content {
outline: 0;
&.mat-horizontal-stepper-content-inactive {
height: 0;
overflow: hidden;
}
// Used to avoid an issue where when the stepper is nested inside a component that
// changes the `visibility` as a part of an Angular animation, the stepper's content
// stays hidden (see #25925). The value has to be `!important` to override the incorrect
// `visibility` from the animations package. This can also be solved using `visibility: visible`
// on `.mat-horizontal-stepper-content`, but it can allow tabbing into hidden content.
&:not(.mat-horizontal-stepper-content-inactive) {
visibility: inherit !important;
}
}
.mat-horizontal-content-container {
overflow: hidden;
padding: 0 stepper-variables.$side-gap stepper-variables.$side-gap stepper-variables.$side-gap;
@include cdk.high-contrast {
outline: solid 1px;
}
.mat-stepper-header-position-bottom & {
padding: stepper-variables.$side-gap stepper-variables.$side-gap 0 stepper-variables.$side-gap;
}
}
.mat-vertical-content-container {
margin-left: stepper-variables.$vertical-stepper-content-margin;
border: 0;
position: relative;
@include cdk.high-contrast {
outline: solid 1px;
}
[dir='rtl'] & {
margin-left: 0;
margin-right: stepper-variables.$vertical-stepper-content-margin;
}
}
.mat-stepper-vertical-line::before {
content: '';
position: absolute;
left: 0;
border-left-width: stepper-variables.$line-width;
border-left-style: solid;
@include token-utils.use-tokens(
tokens-mat-stepper.$prefix, tokens-mat-stepper.get-token-slots()) {
$vertical-padding: _get-vertical-padding-calc();
$vertical-offset: calc(#{stepper-variables.$line-gap} - #{$vertical-padding});
@include token-utils.create-token-slot(border-left-color, line-color);
// Ensures that the vertical lines for the step content exceed into the step
// headers with a given distance (`$mat-stepper-line-gap`) to the step icon.
top: $vertical-offset;
bottom: $vertical-offset;
}
[dir='rtl'] & {
left: auto;
right: 0;
}
}
.mat-vertical-stepper-content {
overflow: hidden;
outline: 0;
// Used to avoid an issue where when the stepper is nested inside a component that
// changes the `visibility` as a part of an Angular animation, the stepper's content
// stays hidden (see #25925). The value has to be `!important` to override the incorrect
// `visibility` from the animations package. This can also be solved using `visibility: visible`
// on `.mat-vertical-stepper-content`, but it can allow tabbing into hidden content.
&:not(.mat-vertical-stepper-content-inactive) {
visibility: inherit !important;
}
}
.mat-vertical-content {
padding: 0 stepper-variables.$side-gap stepper-variables.$side-gap stepper-variables.$side-gap;
}
.mat-step:last-child {
.mat-vertical-content-container {
border: none;
}
}
| {
"end_byte": 7991,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.scss"
} |
components/src/material/stepper/stepper-button.ts_0_826 | /**
* @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 {CdkStepperNext, CdkStepperPrevious} from '@angular/cdk/stepper';
import {Directive} from '@angular/core';
/** Button that moves to the next step in a stepper workflow. */
@Directive({
selector: 'button[matStepperNext]',
host: {
'class': 'mat-stepper-next',
'[type]': 'type',
},
})
export class MatStepperNext extends CdkStepperNext {}
/** Button that moves to the previous step in a stepper workflow. */
@Directive({
selector: 'button[matStepperPrevious]',
host: {
'class': 'mat-stepper-previous',
'[type]': 'type',
},
})
export class MatStepperPrevious extends CdkStepperPrevious {}
| {
"end_byte": 826,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper-button.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.