_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
components/src/material/tabs/testing/BUILD.bazel_0_803 | 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/private",
"//src/cdk/testing/testbed",
"//src/material/tabs",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":unit_tests_lib",
],
)
| {
"end_byte": 803,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/testing/BUILD.bazel"
} |
components/src/material/tabs/testing/tab-nav-bar-harness.ts_0_2927 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ComponentHarness,
ComponentHarnessConstructor,
HarnessPredicate,
parallel,
} from '@angular/cdk/testing';
import {
TabNavBarHarnessFilters,
TabNavPanelHarnessFilters,
TabLinkHarnessFilters,
} from './tab-harness-filters';
import {MatTabLinkHarness} from './tab-link-harness';
import {MatTabNavPanelHarness} from './tab-nav-panel-harness';
/** Harness for interacting with a mat-tab-nav-bar in tests. */
export class MatTabNavBarHarness extends ComponentHarness {
/** The selector for the host element of a `MatTabNavBar` instance. */
static hostSelector = '.mat-mdc-tab-nav-bar';
/**
* Gets a `HarnessPredicate` that can be used to search for a tab nav bar with specific
* attributes.
* @param options Options for filtering which tab nav bar instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatTabNavBarHarness>(
this: ComponentHarnessConstructor<T>,
options: TabNavBarHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options);
}
/**
* Gets the list of links in the nav bar.
* @param filter Optionally filters which links are included.
*/
async getLinks(filter: TabLinkHarnessFilters = {}): Promise<MatTabLinkHarness[]> {
return this.locatorForAll(MatTabLinkHarness.with(filter))();
}
/** Gets the active link in the nav bar. */
async getActiveLink(): Promise<MatTabLinkHarness> {
const links = await this.getLinks();
const isActive = await parallel(() => links.map(t => t.isActive()));
for (let i = 0; i < links.length; i++) {
if (isActive[i]) {
return links[i];
}
}
throw new Error('No active link could be found.');
}
/**
* Clicks a link inside the nav bar.
* @param filter An optional filter to apply to the child link. The first link matching the filter
* will be clicked.
*/
async clickLink(filter: TabLinkHarnessFilters = {}): Promise<void> {
const tabs = await this.getLinks(filter);
if (!tabs.length) {
throw Error(`Cannot find mat-tab-link matching filter ${JSON.stringify(filter)}`);
}
await tabs[0].click();
}
/** Gets the panel associated with the nav bar. */
async getPanel(): Promise<MatTabNavPanelHarness> {
const link = await this.getActiveLink();
const host = await link.host();
const panelId = await host.getAttribute('aria-controls');
if (!panelId) {
throw Error('No panel is controlled by the nav bar.');
}
const filter: TabNavPanelHarnessFilters = {selector: `#${panelId}`};
return await this.documentRootLocatorFactory().locatorFor(MatTabNavPanelHarness.with(filter))();
}
}
| {
"end_byte": 2927,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/testing/tab-nav-bar-harness.ts"
} |
components/src/material/tabs/testing/tab-link-harness.ts_0_1788 | /**
* @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 {TabLinkHarnessFilters} from './tab-harness-filters';
/** Harness for interacting with a Angular Material tab link in tests. */
export class MatTabLinkHarness extends ComponentHarness {
/** The selector for the host element of a `MatTabLink` instance. */
static hostSelector = '.mat-mdc-tab-link';
/**
* Gets a `HarnessPredicate` that can be used to search for a tab link with specific attributes.
* @param options Options for filtering which tab link instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatTabLinkHarness>(
this: ComponentHarnessConstructor<T>,
options: TabLinkHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options).addOption('label', options.label, (harness, label) =>
HarnessPredicate.stringMatches(harness.getLabel(), label),
);
}
/** Gets the label of the link. */
async getLabel(): Promise<string> {
return (await this.host()).text();
}
/** Whether the link is active. */
async isActive(): Promise<boolean> {
const host = await this.host();
return host.hasClass('mdc-tab--active');
}
/** Whether the link is disabled. */
async isDisabled(): Promise<boolean> {
const host = await this.host();
return host.hasClass('mat-mdc-tab-disabled');
}
/** Clicks on the link. */
async click(): Promise<void> {
await (await this.host()).click();
}
}
| {
"end_byte": 1788,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/testing/tab-link-harness.ts"
} |
components/src/material/tabs/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/tabs/testing/index.ts"
} |
components/src/material/tabs/testing/tab-nav-bar-harness.spec.ts_0_4597 | 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 {MatTabsModule} from '@angular/material/tabs';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatTabNavBarHarness} from './tab-nav-bar-harness';
describe('MatTabNavBarHarness', () => {
let fixture: ComponentFixture<TabNavBarHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatTabsModule, NoopAnimationsModule, TabNavBarHarnessTest],
});
fixture = TestBed.createComponent(TabNavBarHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load harness for tab nav bar', async () => {
const navBars = await loader.getAllHarnesses(MatTabNavBarHarness);
expect(navBars.length).toBe(1);
});
it('should be able to get links of nav bar', async () => {
const navBar = await loader.getHarness(MatTabNavBarHarness);
const links = await navBar.getLinks();
expect(links.length).toBe(3);
});
it('should be able to get filtered links', async () => {
const navBar = await loader.getHarness(MatTabNavBarHarness);
const links = await navBar.getLinks({label: 'Third'});
expect(links.length).toBe(1);
expect(await links[0].getLabel()).toBe('Third');
});
it('should be able to click tab from nav bar', async () => {
const navBar = await loader.getHarness(MatTabNavBarHarness);
expect(await (await navBar.getActiveLink()).getLabel()).toBe('First');
await navBar.clickLink({label: 'Second'});
expect(await (await navBar.getActiveLink()).getLabel()).toBe('Second');
});
it('should throw error when attempting to click invalid link', async () => {
const navBar = await loader.getHarness(MatTabNavBarHarness);
await expectAsync(navBar.clickLink({label: 'Fake'})).toBeRejectedWithError(
/Cannot find mat-tab-link matching filter {"label":"Fake"}/,
);
});
it('should be able to get label of links', async () => {
const navBar = await loader.getHarness(MatTabNavBarHarness);
const links = await navBar.getLinks();
expect(await links[0].getLabel()).toBe('First');
expect(await links[1].getLabel()).toBe('Second');
expect(await links[2].getLabel()).toBe('Third');
});
it('should be able to get disabled state of link', async () => {
const navBar = await loader.getHarness(MatTabNavBarHarness);
const links = await navBar.getLinks();
expect(await links[0].isDisabled()).toBe(false);
expect(await links[1].isDisabled()).toBe(false);
expect(await links[2].isDisabled()).toBe(false);
fixture.componentInstance.isDisabled.set(true);
fixture.detectChanges();
expect(await links[0].isDisabled()).toBe(false);
expect(await links[1].isDisabled()).toBe(false);
expect(await links[2].isDisabled()).toBe(true);
});
it('should be able to click specific link', async () => {
const navBar = await loader.getHarness(MatTabNavBarHarness);
const links = await navBar.getLinks();
expect(await links[0].isActive()).toBe(true);
expect(await links[1].isActive()).toBe(false);
expect(await links[2].isActive()).toBe(false);
await links[1].click();
expect(await links[0].isActive()).toBe(false);
expect(await links[1].isActive()).toBe(true);
expect(await links[2].isActive()).toBe(false);
});
it('should be able to get the associated tab panel', async () => {
const navBar = await loader.getHarness(MatTabNavBarHarness);
const navPanel = await navBar.getPanel();
expect(await navPanel.getTextContent()).toBe('Tab content');
});
});
@Component({
template: `
<nav mat-tab-nav-bar [tabPanel]="tabPanel">
<a href="#" (click)="select(0, $event)" [active]="activeLink === 0" matTabLink>First</a>
<a href="#" (click)="select(1, $event)" [active]="activeLink === 1" matTabLink>Second</a>
<a
href="#"
(click)="select(2, $event)"
[active]="activeLink === 2"
[disabled]="isDisabled()"
matTabLink>Third</a>
</nav>
<mat-tab-nav-panel #tabPanel id="tab-panel">
Tab content
</mat-tab-nav-panel>
`,
standalone: true,
imports: [MatTabsModule],
})
class TabNavBarHarnessTest {
activeLink = 0;
isDisabled = signal(false);
select(index: number, event: MouseEvent) {
this.activeLink = index;
event.preventDefault();
}
}
| {
"end_byte": 4597,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/testing/tab-nav-bar-harness.spec.ts"
} |
components/src/material/tabs/testing/tab-harness-filters.ts_0_1484 | /**
* @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 `MatTabHarness` instances. */
export interface TabHarnessFilters extends BaseHarnessFilters {
/** Only find instances whose label matches the given value. */
label?: string | RegExp;
/** Only find instances whose selected state matches the given value. */
selected?: boolean;
}
/** A set of criteria that can be used to filter a list of `MatTabGroupHarness` instances. */
export interface TabGroupHarnessFilters extends BaseHarnessFilters {
/** Only find instances whose selected tab label matches the given value. */
selectedTabLabel?: string | RegExp;
}
/** A set of criteria that can be used to filter a list of `MatTabLinkHarness` instances. */
export interface TabLinkHarnessFilters extends BaseHarnessFilters {
/** Only find instances whose label matches the given value. */
label?: string | RegExp;
}
/** A set of criteria that can be used to filter a list of `MatTabNavBarHarness` instances. */
export interface TabNavBarHarnessFilters extends BaseHarnessFilters {}
/** A set of criteria that can be used to filter a list of `MatTabNavPanelHarness` instances. */
export interface TabNavPanelHarnessFilters extends BaseHarnessFilters {}
| {
"end_byte": 1484,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/testing/tab-harness-filters.ts"
} |
components/src/material/tabs/testing/tab-group-harness.spec.ts_0_7191 | import {Component, signal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {ComponentHarness, HarnessLoader, parallel} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {MatTabsModule} from '@angular/material/tabs';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatTabGroupHarness} from './tab-group-harness';
import {MatTabHarness} from './tab-harness';
describe('MatTabGroupHarness', () => {
let fixture: ComponentFixture<TabGroupHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatTabsModule, NoopAnimationsModule, TabGroupHarnessTest],
});
fixture = TestBed.createComponent(TabGroupHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load harness for tab-group', async () => {
const tabGroups = await loader.getAllHarnesses(MatTabGroupHarness);
expect(tabGroups.length).toBe(1);
});
it('should load harness for tab-group with selected tab label', async () => {
const tabGroups = await loader.getAllHarnesses(
MatTabGroupHarness.with({
selectedTabLabel: 'First',
}),
);
expect(tabGroups.length).toBe(1);
});
it('should load harness for tab-group with matching tab label regex', async () => {
const tabGroups = await loader.getAllHarnesses(
MatTabGroupHarness.with({
selectedTabLabel: /f.*st/i,
}),
);
expect(tabGroups.length).toBe(1);
});
it('should be able to get tabs of tab-group', async () => {
const tabGroup = await loader.getHarness(MatTabGroupHarness);
const tabs = await tabGroup.getTabs();
expect(tabs.length).toBe(3);
});
it('should be able to get filtered tabs', async () => {
const tabGroup = await loader.getHarness(MatTabGroupHarness);
const tabs = await tabGroup.getTabs({label: 'Third'});
expect(tabs.length).toBe(1);
expect(await tabs[0].getLabel()).toBe('Third');
});
it('should be able to select tab from tab-group', async () => {
const tabGroup = await loader.getHarness(MatTabGroupHarness);
expect(await (await tabGroup.getSelectedTab()).getLabel()).toBe('First');
await tabGroup.selectTab({label: 'Second'});
expect(await (await tabGroup.getSelectedTab()).getLabel()).toBe('Second');
});
it('should throw error when attempting to select invalid tab', async () => {
const tabGroup = await loader.getHarness(MatTabGroupHarness);
await expectAsync(tabGroup.selectTab({label: 'Fake'})).toBeRejectedWithError(
/Cannot find mat-tab matching filter {"label":"Fake"}/,
);
});
it('should be able to get label of tabs', async () => {
const tabGroup = await loader.getHarness(MatTabGroupHarness);
const tabs = await tabGroup.getTabs();
expect(await tabs[0].getLabel()).toBe('First');
expect(await tabs[1].getLabel()).toBe('Second');
expect(await tabs[2].getLabel()).toBe('Third');
});
it('should be able to get aria-label of tabs', async () => {
const tabGroup = await loader.getHarness(MatTabGroupHarness);
const tabs = await tabGroup.getTabs();
expect(await tabs[0].getAriaLabel()).toBe('First tab');
expect(await tabs[1].getAriaLabel()).toBe('Second tab');
expect(await tabs[2].getAriaLabel()).toBe(null);
});
it('should be able to get aria-labelledby of tabs', async () => {
const tabGroup = await loader.getHarness(MatTabGroupHarness);
const tabs = await tabGroup.getTabs();
expect(await tabs[0].getAriaLabelledby()).toBe(null);
expect(await tabs[1].getAriaLabelledby()).toBe(null);
expect(await tabs[2].getAriaLabelledby()).toBe('tabLabelId');
});
it('should be able to get harness for content element of active tab', async () => {
const tabGroup = await loader.getHarness(MatTabGroupHarness);
const tabs = await tabGroup.getTabs();
expect(await tabs[0].getTextContent()).toBe('Content 1');
const tabContentHarness = await tabs[0].getHarness(TestTabContentHarness);
expect(await (await tabContentHarness.host()).text()).toBe('Content 1');
});
it('should be able to get disabled state of tab', async () => {
const tabGroup = await loader.getHarness(MatTabGroupHarness);
const tabs = await tabGroup.getTabs();
expect(await tabs[0].isDisabled()).toBe(false);
expect(await tabs[1].isDisabled()).toBe(false);
expect(await tabs[2].isDisabled()).toBe(false);
fixture.componentInstance.isDisabled.set(true);
fixture.detectChanges();
expect(await tabs[0].isDisabled()).toBe(false);
expect(await tabs[1].isDisabled()).toBe(false);
expect(await tabs[2].isDisabled()).toBe(true);
});
it('should be able to select specific tab', async () => {
const tabGroup = await loader.getHarness(MatTabGroupHarness);
const tabs = await tabGroup.getTabs();
expect(await tabs[0].isSelected()).toBe(true);
expect(await tabs[1].isSelected()).toBe(false);
expect(await tabs[2].isSelected()).toBe(false);
await tabs[1].select();
expect(await tabs[0].isSelected()).toBe(false);
expect(await tabs[1].isSelected()).toBe(true);
expect(await tabs[2].isSelected()).toBe(false);
// Should not be able to select third tab if disabled.
fixture.componentInstance.isDisabled.set(true);
fixture.detectChanges();
await tabs[2].select();
expect(await tabs[0].isSelected()).toBe(false);
expect(await tabs[1].isSelected()).toBe(true);
expect(await tabs[2].isSelected()).toBe(false);
// Should be able to select third tab if not disabled.
fixture.componentInstance.isDisabled.set(false);
fixture.detectChanges();
await tabs[2].select();
expect(await tabs[0].isSelected()).toBe(false);
expect(await tabs[1].isSelected()).toBe(false);
expect(await tabs[2].isSelected()).toBe(true);
});
it('should be able to get tabs by selected state', async () => {
const selectedTabs = await loader.getAllHarnesses(MatTabHarness.with({selected: true}));
const unselectedTabs = await loader.getAllHarnesses(MatTabHarness.with({selected: false}));
expect(await parallel(() => selectedTabs.map(t => t.getLabel()))).toEqual(['First']);
expect(await parallel(() => unselectedTabs.map(t => t.getLabel()))).toEqual([
'Second',
'Third',
]);
});
});
@Component({
template: `
<mat-tab-group>
<mat-tab label="First" aria-label="First tab">
<span class="test-tab-content">Content 1</span>
</mat-tab>
<mat-tab label="Second" aria-label="Second tab">
<span class="test-tab-content">Content 2</span>
</mat-tab>
<mat-tab label="Third" aria-labelledby="tabLabelId" [disabled]="isDisabled()">
<ng-template matTabLabel>Third</ng-template>
<span class="test-tab-content">Content 3</span>
</mat-tab>
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class TabGroupHarnessTest {
isDisabled = signal(false);
}
class TestTabContentHarness extends ComponentHarness {
static hostSelector = '.test-tab-content';
}
| {
"end_byte": 7191,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/testing/tab-group-harness.spec.ts"
} |
components/src/material/tree/padding.ts_0_1193 | /**
* @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 {CdkTreeNodePadding} from '@angular/cdk/tree';
import {Directive, Input, numberAttribute} from '@angular/core';
/**
* Wrapper for the CdkTree padding with Material design styles.
*/
@Directive({
selector: '[matTreeNodePadding]',
providers: [{provide: CdkTreeNodePadding, useExisting: MatTreeNodePadding}],
})
export class MatTreeNodePadding<T, K = T> extends CdkTreeNodePadding<T, K> {
/** The level of depth of the tree node. The padding will be `level * indent` pixels. */
@Input({alias: 'matTreeNodePadding', transform: numberAttribute})
override get level(): number {
return this._level;
}
override set level(value: number) {
this._setLevelInput(value);
}
/** The indent for each level. Default number 40px from material design menu sub-menu spec. */
@Input('matTreeNodePaddingIndent')
override get indent(): number | string {
return this._indent;
}
override set indent(indent: number | string) {
this._setIndentInput(indent);
}
}
| {
"end_byte": 1193,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/padding.ts"
} |
components/src/material/tree/node.ts_0_5942 | /**
* @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 {
CDK_TREE_NODE_OUTLET_NODE,
CdkNestedTreeNode,
CdkTreeNode,
CdkTreeNodeDef,
} from '@angular/cdk/tree';
import {
AfterContentInit,
Directive,
Input,
OnDestroy,
OnInit,
booleanAttribute,
numberAttribute,
inject,
HostAttributeToken,
} from '@angular/core';
import {NoopTreeKeyManager, TreeKeyManagerItem, TreeKeyManagerStrategy} from '@angular/cdk/a11y';
/**
* Determinte if argument TreeKeyManager is the NoopTreeKeyManager. This function is safe to use with SSR.
*/
function isNoopTreeKeyManager<T extends TreeKeyManagerItem>(
keyManager: TreeKeyManagerStrategy<T>,
): keyManager is NoopTreeKeyManager<T> {
return !!(keyManager as any)._isNoopTreeKeyManager;
}
/**
* Wrapper for the CdkTree node with Material design styles.
*/
@Directive({
selector: 'mat-tree-node',
exportAs: 'matTreeNode',
outputs: ['activation', 'expandedChange'],
providers: [{provide: CdkTreeNode, useExisting: MatTreeNode}],
host: {
'class': 'mat-tree-node',
'[attr.aria-expanded]': '_getAriaExpanded()',
'[attr.aria-level]': 'level + 1',
'[attr.aria-posinset]': '_getPositionInSet()',
'[attr.aria-setsize]': '_getSetSize()',
'(click)': '_focusItem()',
'[tabindex]': '_getTabindexAttribute()',
},
})
export class MatTreeNode<T, K = T> extends CdkTreeNode<T, K> implements OnInit, OnDestroy {
/**
* The tabindex of the tree node.
*
* @deprecated By default MatTreeNode manages focus using TreeKeyManager instead of tabIndex.
* Recommend to avoid setting tabIndex directly to prevent TreeKeyManager form getting into
* an unexpected state. Tabindex to be removed in a future version.
* @breaking-change 21.0.0 Remove this attribute.
*/
@Input({
transform: (value: unknown) => (value == null ? 0 : numberAttribute(value)),
alias: 'tabIndex',
})
get tabIndexInputBinding(): number {
return this._tabIndexInputBinding;
}
set tabIndexInputBinding(value: number) {
// If the specified tabIndex value is null or undefined, fall back to the default value.
this._tabIndexInputBinding = value;
}
private _tabIndexInputBinding: number;
/**
* The default tabindex of the tree node.
*
* @deprecated By default MatTreeNode manages focus using TreeKeyManager instead of tabIndex.
* Recommend to avoid setting tabIndex directly to prevent TreeKeyManager form getting into
* an unexpected state. Tabindex to be removed in a future version.
* @breaking-change 21.0.0 Remove this attribute.
*/
defaultTabIndex = 0;
protected _getTabindexAttribute() {
if (isNoopTreeKeyManager(this._tree._keyManager)) {
return this.tabIndexInputBinding;
}
return this._tabindex;
}
/**
* Whether the component is disabled.
*
* @deprecated This is an alias for `isDisabled`.
* @breaking-change 21.0.0 Remove this input
*/
@Input({transform: booleanAttribute})
get disabled(): boolean {
return this.isDisabled;
}
set disabled(value: boolean) {
this.isDisabled = value;
}
constructor(...args: unknown[]);
constructor() {
super();
const tabIndex = inject(new HostAttributeToken('tabindex'), {optional: true});
this.tabIndexInputBinding = Number(tabIndex) || this.defaultTabIndex;
}
// This is a workaround for https://github.com/angular/angular/issues/23091
// In aot mode, the lifecycle hooks from parent class are not called.
override ngOnInit() {
super.ngOnInit();
}
override ngOnDestroy() {
super.ngOnDestroy();
}
}
/**
* Wrapper for the CdkTree node definition with Material design styles.
* Captures the node's template and a when predicate that describes when this node should be used.
*/
@Directive({
selector: '[matTreeNodeDef]',
inputs: [{name: 'when', alias: 'matTreeNodeDefWhen'}],
providers: [{provide: CdkTreeNodeDef, useExisting: MatTreeNodeDef}],
})
export class MatTreeNodeDef<T> extends CdkTreeNodeDef<T> {
@Input('matTreeNode') data: T;
}
/**
* Wrapper for the CdkTree nested node with Material design styles.
*/
@Directive({
selector: 'mat-nested-tree-node',
exportAs: 'matNestedTreeNode',
outputs: ['activation', 'expandedChange'],
providers: [
{provide: CdkNestedTreeNode, useExisting: MatNestedTreeNode},
{provide: CdkTreeNode, useExisting: MatNestedTreeNode},
{provide: CDK_TREE_NODE_OUTLET_NODE, useExisting: MatNestedTreeNode},
],
host: {
'class': 'mat-nested-tree-node',
},
})
export class MatNestedTreeNode<T, K = T>
extends CdkNestedTreeNode<T, K>
implements AfterContentInit, OnDestroy, OnInit
{
@Input('matNestedTreeNode') node: T;
/**
* Whether the node is disabled.
*
* @deprecated This is an alias for `isDisabled`.
* @breaking-change 21.0.0 Remove this input
*/
@Input({transform: booleanAttribute})
get disabled(): boolean {
return this.isDisabled;
}
set disabled(value: boolean) {
this.isDisabled = value;
}
/** Tabindex of the node. */
@Input({
transform: (value: unknown) => (value == null ? 0 : numberAttribute(value)),
})
get tabIndex(): number {
return this.isDisabled ? -1 : this._tabIndex;
}
set tabIndex(value: number) {
// If the specified tabIndex value is null or undefined, fall back to the default value.
this._tabIndex = value;
}
private _tabIndex: number;
// This is a workaround for https://github.com/angular/angular/issues/19145
// In aot mode, the lifecycle hooks from parent class are not called.
// TODO(tinayuangao): Remove when the angular issue #19145 is fixed
override ngOnInit() {
super.ngOnInit();
}
override ngAfterContentInit() {
super.ngAfterContentInit();
}
override ngOnDestroy() {
super.ngOnDestroy();
}
}
| {
"end_byte": 5942,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/node.ts"
} |
components/src/material/tree/tree.scss_0_1219 | @use '../core/tokens/m2/mat/tree' as tokens-mat-tree;
@use '../core/tokens/token-utils';
.mat-tree {
display: block;
@include token-utils.use-tokens(tokens-mat-tree.$prefix, tokens-mat-tree.get-token-slots()) {
@include token-utils.create-token-slot(background-color, container-background-color);
}
}
.mat-tree-node,
.mat-nested-tree-node {
@include token-utils.use-tokens(tokens-mat-tree.$prefix, tokens-mat-tree.get-token-slots()) {
@include token-utils.create-token-slot(color, node-text-color);
@include token-utils.create-token-slot(font-family, node-text-font);
@include token-utils.create-token-slot(font-size, node-text-size);
@include token-utils.create-token-slot(font-weight, node-text-weight);
}
}
.mat-tree-node {
display: flex;
align-items: center;
flex: 1;
word-wrap: break-word;
@include token-utils.use-tokens(tokens-mat-tree.$prefix, tokens-mat-tree.get-token-slots()) {
// TODO: before tokens were introduced, the `min-height` only applied to the
// non-nested tree node. Should it apply to the nested one as well?
@include token-utils.create-token-slot(min-height, node-min-height);
}
}
.mat-nested-tree-node {
border-bottom-width: 0;
}
| {
"end_byte": 1219,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree.scss"
} |
components/src/material/tree/public-api.ts_0_460 | /**
* @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 './node';
export * from './padding';
export * from './tree';
export * from './tree-module';
export * from './toggle';
export * from './outlet';
export * from './data-source/flat-data-source';
export * from './data-source/nested-data-source';
| {
"end_byte": 460,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/public-api.ts"
} |
components/src/material/tree/tree-using-legacy-key-manager.spec.ts_0_4118 | import {Component, ElementRef, QueryList, ViewChild, ViewChildren} from '@angular/core';
import {of} from 'rxjs';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MatTreeModule} from './tree-module';
import {NOOP_TREE_KEY_MANAGER_FACTORY_PROVIDER} from '@angular/cdk/a11y';
import {DOWN_ARROW} from '@angular/cdk/keycodes';
import {createKeyboardEvent} from '@angular/cdk/testing/private';
describe('MatTree when provided LegacyTreeKeyManager', () => {
let fixture: ComponentFixture<SimpleMatTreeApp>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatTreeModule],
declarations: [SimpleMatTreeApp],
providers: [NOOP_TREE_KEY_MANAGER_FACTORY_PROVIDER],
});
fixture = TestBed.createComponent(SimpleMatTreeApp);
fixture.detectChanges();
});
describe('when nodes have default options', () => {
it('Should render tabindex attribute of 0', () => {
const treeItems = fixture.componentInstance.treeNodes;
expect(treeItems.map(x => `${x.nativeElement.getAttribute('tabindex')}`).join(', '))
.withContext('tabindex of tree nodes')
.toEqual('0, 0, 0');
});
});
describe('when nodes have TabIndex Input binding of 42', () => {
beforeEach(() => {
fixture.componentInstance.tabIndexInputBinding = 42;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
});
it('Should render tabindex attribute of 42.', () => {
const treeItems = fixture.componentInstance.treeNodes;
expect(treeItems.map(x => `${x.nativeElement.getAttribute('tabindex')}`).join(', '))
.withContext('tabindex of tree nodes')
.toEqual('42, 42, 42');
});
});
describe('when nodes have tabindex attribute binding of 2', () => {
beforeEach(() => {
fixture.componentInstance.tabindexAttributeBinding = '2';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
});
it('should render tabindex attribute of 2', () => {
const treeItems = fixture.componentInstance.treeNodes;
expect(treeItems.map(x => `${x.nativeElement.getAttribute('tabindex')}`).join(', '))
.withContext('tabindex of tree nodes')
.toEqual('2, 2, 2');
});
});
describe('when pressing down arrow key', () => {
beforeEach(() => {
const treeElement = fixture.componentInstance.tree.nativeElement;
treeElement.dispatchEvent(createKeyboardEvent('keydown', DOWN_ARROW, 'down'));
fixture.detectChanges();
});
it('should not change the active element', () => {
expect(document.activeElement).toEqual(document.body);
});
it('should not change the tabindex of tree nodes', () => {
const treeItems = fixture.componentInstance.treeNodes;
expect(treeItems.map(x => `${x.nativeElement.getAttribute('tabindex')}`).join(', '))
.withContext('tabindex of tree nodes')
.toEqual('0, 0, 0');
});
});
});
class MinimalTestData {
constructor(public name: string) {}
children: MinimalTestData[] = [];
}
@Component({
template: `
<mat-tree #tree [dataSource]="dataSource" [childrenAccessor]="getChildren">
<mat-tree-node #node *matTreeNodeDef="let node"
[tabIndex]="tabIndexInputBinding" tabindex="{{tabindexAttributeBinding}}">
{{node.name}}
</mat-tree-node>
</mat-tree>
`,
standalone: false,
})
class SimpleMatTreeApp {
isExpandable = (node: MinimalTestData) => node.children.length > 0;
getChildren = (node: MinimalTestData) => node.children;
dataSource = of([
new MinimalTestData('lettuce'),
new MinimalTestData('tomato'),
new MinimalTestData('onion'),
]);
/** Value passed to tabIndex Input binding of each tree node. Null by default. */
tabIndexInputBinding: number | null = null;
/** Value passed to tabindex attribute binding of each tree node. Null by default. */
tabindexAttributeBinding: string | null = null;
@ViewChild('tree', {read: ElementRef}) tree: ElementRef<HTMLElement>;
@ViewChildren('node') treeNodes: QueryList<ElementRef<HTMLElement>>;
}
| {
"end_byte": 4118,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree-using-legacy-key-manager.spec.ts"
} |
components/src/material/tree/outlet.ts_0_801 | /**
* @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 {CDK_TREE_NODE_OUTLET_NODE, CdkTreeNodeOutlet} from '@angular/cdk/tree';
import {Directive, ViewContainerRef, inject} from '@angular/core';
/**
* Outlet for nested CdkNode. Put `[matTreeNodeOutlet]` on a tag to place children dataNodes
* inside the outlet.
*/
@Directive({
selector: '[matTreeNodeOutlet]',
providers: [
{
provide: CdkTreeNodeOutlet,
useExisting: MatTreeNodeOutlet,
},
],
})
export class MatTreeNodeOutlet implements CdkTreeNodeOutlet {
viewContainer = inject(ViewContainerRef);
_node = inject(CDK_TREE_NODE_OUTLET_NODE, {optional: true});
}
| {
"end_byte": 801,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/outlet.ts"
} |
components/src/material/tree/_tree-theme.scss_0_3044 | @use 'sass:map';
@use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/typography/typography';
@use '../core/style/sass-utils';
@use '../core/tokens/token-utils';
@use '../core/tokens/m2/mat/tree' as tokens-mat-tree;
@mixin base($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, base));
} @else {
}
}
@mixin color($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, color));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-tree.$prefix,
tokens-mat-tree.get-color-tokens($theme)
);
}
}
}
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
// TODO(mmalerba): Stop calling this and resolve resulting screen diffs.
$theme: inspection.private-get-typography-back-compat-theme($theme);
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-tree.$prefix,
tokens-mat-tree.get-typography-tokens($theme)
);
}
}
}
@mixin density($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, density));
} @else {
$density-scale: inspection.get-theme-density($theme);
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-tree.$prefix,
tokens-mat-tree.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-tree.$prefix,
tokens: tokens-mat-tree.get-token-slots(),
),
);
}
@mixin overrides($tokens: ()) {
@include token-utils.batch-create-token-values($tokens, _define-overrides()...);
}
@mixin theme($theme) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-tree') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme));
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
@if ($tokens != ()) {
@include token-utils.create-token-values(
tokens-mat-tree.$prefix,
map.get($tokens, tokens-mat-tree.$prefix)
);
}
}
| {
"end_byte": 3044,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/_tree-theme.scss"
} |
components/src/material/tree/tree.spec.ts_0_484 | /**
* @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, ViewChild, Type} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {BehaviorSubject, Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {MatTree, MatTreeModule, MatTreeNestedDataSource} from './index'; | {
"end_byte": 484,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree.spec.ts"
} |
components/src/material/tree/tree.spec.ts_486_8982 | describe('MatTree', () => {
/** Represents an indent for expectNestedTreeToMatch */
const _ = {};
let treeElement: HTMLElement;
let underlyingDataSource: FakeDataSource;
function configureMatTreeTestingModule(declarations: Type<any>[]) {
TestBed.configureTestingModule({
imports: [MatTreeModule],
declarations: declarations,
});
}
describe('flat tree', () => {
describe('should initialize', () => {
let fixture: ComponentFixture<SimpleMatTreeApp>;
let component: SimpleMatTreeApp;
beforeEach(() => {
configureMatTreeTestingModule([SimpleMatTreeApp]);
fixture = TestBed.createComponent(SimpleMatTreeApp);
component = fixture.componentInstance;
underlyingDataSource = component.dataSource;
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('with rendered dataNodes', () => {
const nodes = getNodes(treeElement);
expect(nodes).withContext('Expect nodes to be defined').toBeDefined();
expect(nodes[0].classList).toContain('customNodeClass');
});
it('with the right accessibility roles', () => {
expect(treeElement.getAttribute('role')).toBe('tree');
getNodes(treeElement).forEach(node => {
expect(node.getAttribute('role')).toBe('treeitem');
});
});
it('with the right aria-level attrs', () => {
// add a child to the first node
const data = underlyingDataSource.data;
underlyingDataSource.addChild(data[2]);
component.tree.expandAll();
fixture.detectChanges();
const ariaLevels = getNodes(treeElement).map(n => n.getAttribute('aria-level'));
expect(ariaLevels).toEqual(['1', '1', '1', '2']);
});
it('with the right aria-expanded attrs', () => {
// add a child to the first node
const data = underlyingDataSource.data;
underlyingDataSource.addChild(data[2]);
fixture.detectChanges();
let ariaExpandedStates = getNodes(treeElement).map(n => n.getAttribute('aria-expanded'));
expect(ariaExpandedStates).toEqual([null, null, 'false']);
component.tree.expandAll();
fixture.detectChanges();
ariaExpandedStates = getNodes(treeElement).map(n => n.getAttribute('aria-expanded'));
expect(ariaExpandedStates).toEqual([null, null, 'true', null]);
});
it('with the right data', () => {
expect(underlyingDataSource.data.length).toBe(3);
const data = underlyingDataSource.data;
expectFlatTreeToMatch(
treeElement,
28,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
underlyingDataSource.addChild(data[2]);
fixture.detectChanges();
expectFlatTreeToMatch(
treeElement,
28,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
[`_, topping_4 - cheese_4 + base_4`],
);
});
});
describe('with toggle', () => {
let fixture: ComponentFixture<MatTreeAppWithToggle>;
let component: MatTreeAppWithToggle;
beforeEach(() => {
configureMatTreeTestingModule([MatTreeAppWithToggle]);
fixture = TestBed.createComponent(MatTreeAppWithToggle);
component = fixture.componentInstance;
underlyingDataSource = component.dataSource;
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('should expand/collapse the node', () => {
expect(underlyingDataSource.data.length).toBe(3);
let numExpandedNodes =
fixture.nativeElement.querySelectorAll('[aria-expanded="true"]').length;
expect(numExpandedNodes).withContext(`Expect no expanded node`).toBe(0);
component.toggleRecursively = false;
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[2]);
underlyingDataSource.addChild(child);
fixture.detectChanges();
expectFlatTreeToMatch(
treeElement,
40,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
(getNodes(treeElement)[2] as HTMLElement).click();
fixture.detectChanges();
numExpandedNodes = fixture.nativeElement.querySelectorAll('[aria-expanded="true"]').length;
expect(numExpandedNodes).toBe(1);
expectFlatTreeToMatch(
treeElement,
40,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
[_, `topping_4 - cheese_4 + base_4`],
);
(getNodes(treeElement)[3] as HTMLElement).click();
fixture.detectChanges();
numExpandedNodes = fixture.nativeElement.querySelectorAll('[aria-expanded="true"]').length;
expect(numExpandedNodes).withContext(`Expect node expanded`).toBe(2);
expectFlatTreeToMatch(
treeElement,
40,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
[_, `topping_4 - cheese_4 + base_4`],
[_, _, `topping_5 - cheese_5 + base_5`],
);
(getNodes(treeElement)[2] as HTMLElement).click();
fixture.detectChanges();
expectFlatTreeToMatch(
treeElement,
40,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
});
it('should expand/collapse the node recursively', () => {
expect(underlyingDataSource.data.length).toBe(3);
let numExpandedNodes =
fixture.nativeElement.querySelectorAll('[aria-expanded="true"]').length;
expect(numExpandedNodes).withContext(`Expect no expanded node`).toBe(0);
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[2]);
underlyingDataSource.addChild(child);
fixture.detectChanges();
expectFlatTreeToMatch(
treeElement,
40,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
(getNodes(treeElement)[2] as HTMLElement).click();
fixture.detectChanges();
numExpandedNodes = fixture.nativeElement.querySelectorAll('[aria-expanded="true"]').length;
expect(numExpandedNodes).withContext(`Expect nodes expanded`).toBe(2);
expectFlatTreeToMatch(
treeElement,
40,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
[_, `topping_4 - cheese_4 + base_4`],
[_, _, `topping_5 - cheese_5 + base_5`],
);
(getNodes(treeElement)[2] as HTMLElement).click();
fixture.detectChanges();
numExpandedNodes = fixture.nativeElement.querySelectorAll('[aria-expanded="true"]').length;
expect(numExpandedNodes).withContext(`Expect node collapsed`).toBe(0);
expectFlatTreeToMatch(
treeElement,
40,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
});
});
describe('with when node template', () => {
let fixture: ComponentFixture<WhenNodeMatTreeApp>;
let component: WhenNodeMatTreeApp;
beforeEach(() => {
configureMatTreeTestingModule([WhenNodeMatTreeApp]);
fixture = TestBed.createComponent(WhenNodeMatTreeApp);
component = fixture.componentInstance;
underlyingDataSource = component.dataSource;
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('with the right data', () => {
expectFlatTreeToMatch(
treeElement,
28,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
[`>>> topping_4 - cheese_4 + base_4`],
);
});
});
}); | {
"end_byte": 8982,
"start_byte": 486,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree.spec.ts"
} |
components/src/material/tree/tree.spec.ts_8986_14996 | describe('flat tree with undefined or null children', () => {
describe('should initialize', () => {
let fixture: ComponentFixture<MatTreeWithNullOrUndefinedChild>;
beforeEach(() => {
configureMatTreeTestingModule([MatTreeWithNullOrUndefinedChild]);
fixture = TestBed.createComponent(MatTreeWithNullOrUndefinedChild);
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('with rendered dataNodes', () => {
const nodes = getNodes(treeElement);
expect(nodes).withContext('Expect nodes to be defined').toBeDefined();
expect(nodes[0].classList).toContain('customNodeClass');
});
});
});
describe('nested tree with undefined or null children', () => {
describe('should initialize', () => {
let fixture: ComponentFixture<MatNestedTreeWithNullOrUndefinedChild>;
beforeEach(() => {
configureMatTreeTestingModule([MatNestedTreeWithNullOrUndefinedChild]);
fixture = TestBed.createComponent(MatNestedTreeWithNullOrUndefinedChild);
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('with rendered dataNodes', () => {
const nodes = getNodes(treeElement);
expect(nodes).withContext('Expect nodes to be defined').toBeDefined();
expect(nodes[0].classList).toContain('customNodeClass');
});
});
});
describe('nested tree', () => {
describe('should initialize', () => {
let fixture: ComponentFixture<NestedMatTreeApp>;
let component: NestedMatTreeApp;
beforeEach(() => {
configureMatTreeTestingModule([NestedMatTreeApp]);
fixture = TestBed.createComponent(NestedMatTreeApp);
component = fixture.componentInstance;
underlyingDataSource = component.underlyingDataSource;
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('with rendered dataNodes', () => {
const nodes = getNodes(treeElement);
expect(nodes).withContext('Expect nodes to be defined').toBeDefined();
expect(nodes[0].classList).toContain('customNodeClass');
});
it('with the right accessibility roles', () => {
expect(treeElement.getAttribute('role')).toBe('tree');
getNodes(treeElement).forEach(node => {
expect(node.getAttribute('role')).toBe('treeitem');
});
});
it('with the right data', () => {
expect(underlyingDataSource.data.length).toBe(3);
let data = underlyingDataSource.data;
expectNestedTreeToMatch(
treeElement,
[`${data[0].pizzaTopping} - ${data[0].pizzaCheese} + ${data[0].pizzaBase}`],
[`${data[1].pizzaTopping} - ${data[1].pizzaCheese} + ${data[1].pizzaBase}`],
[`${data[2].pizzaTopping} - ${data[2].pizzaCheese} + ${data[2].pizzaBase}`],
);
underlyingDataSource.addChild(data[1]);
fixture.detectChanges();
treeElement = fixture.nativeElement.querySelector('mat-tree');
data = underlyingDataSource.data;
expect(data.length).toBe(3);
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[_, `topping_4 - cheese_4 + base_4`],
[`topping_3 - cheese_3 + base_3`],
);
});
it('with nested child data', () => {
expect(underlyingDataSource.data.length).toBe(3);
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[1]);
underlyingDataSource.addChild(child);
fixture.detectChanges();
expect(data.length).toBe(3);
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[_, `topping_4 - cheese_4 + base_4`],
[_, _, `topping_5 - cheese_5 + base_5`],
[`topping_3 - cheese_3 + base_3`],
);
underlyingDataSource.addChild(child);
fixture.detectChanges();
expect(data.length).toBe(3);
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[_, `topping_4 - cheese_4 + base_4`],
[_, _, `topping_5 - cheese_5 + base_5`],
[_, _, `topping_6 - cheese_6 + base_6`],
[`topping_3 - cheese_3 + base_3`],
);
});
it('with correct aria-level on nodes', () => {
expect(
getNodes(treeElement).every(node => {
return node.getAttribute('aria-level') === '1';
}),
).toBe(true);
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[1]);
underlyingDataSource.addChild(child);
fixture.detectChanges();
const ariaLevels = getNodes(treeElement).map(n => n.getAttribute('aria-level'));
expect(ariaLevels).toEqual(['1', '1', '2', '3', '1']);
});
});
describe('with when node', () => {
let fixture: ComponentFixture<WhenNodeNestedMatTreeApp>;
let component: WhenNodeNestedMatTreeApp;
beforeEach(() => {
configureMatTreeTestingModule([WhenNodeNestedMatTreeApp]);
fixture = TestBed.createComponent(WhenNodeNestedMatTreeApp);
component = fixture.componentInstance;
underlyingDataSource = component.underlyingDataSource;
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('with the right data', () => {
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
[`>>> topping_4 - cheese_4 + base_4`],
);
});
}); | {
"end_byte": 14996,
"start_byte": 8986,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree.spec.ts"
} |
components/src/material/tree/tree.spec.ts_15002_19559 | describe('with toggle', () => {
let fixture: ComponentFixture<NestedMatTreeAppWithToggle>;
let component: NestedMatTreeAppWithToggle;
beforeEach(() => {
configureMatTreeTestingModule([NestedMatTreeAppWithToggle]);
fixture = TestBed.createComponent(NestedMatTreeAppWithToggle);
component = fixture.componentInstance;
underlyingDataSource = component.dataSource;
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('with the right aria-expanded attrs', () => {
expect(
getNodes(treeElement)
.map(x => `${x.getAttribute('aria-expanded')}`)
.join(', '),
).toEqual('null, null, null');
component.toggleRecursively = false;
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[1]);
underlyingDataSource.addChild(child);
fixture.detectChanges();
(getNodes(treeElement)[1] as HTMLElement).click();
fixture.detectChanges();
// Note: only four elements are present here; children are not present
// in DOM unless the parent node is expanded.
expect(
getNodes(treeElement)
.map(x => `${x.getAttribute('aria-expanded')}`)
.join(', '),
)
.withContext('aria-expanded attributes')
.toEqual('null, true, false, null');
});
it('should expand/collapse the node', () => {
component.toggleRecursively = false;
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[1]);
underlyingDataSource.addChild(child);
fixture.detectChanges();
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
fixture.detectChanges();
(getNodes(treeElement)[1] as HTMLElement).click();
fixture.detectChanges();
let numExpandedNodes =
fixture.nativeElement.querySelectorAll('[aria-expanded="true"]').length;
expect(numExpandedNodes).withContext(`Expect node expanded`).toBe(1);
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[_, `topping_4 - cheese_4 + base_4`],
[`topping_3 - cheese_3 + base_3`],
);
(getNodes(treeElement)[1] as HTMLElement).click();
fixture.detectChanges();
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
numExpandedNodes = fixture.nativeElement.querySelectorAll('[aria-expanded="true"]').length;
expect(numExpandedNodes).withContext(`Expect node collapsed`).toBe(0);
});
it('should expand/collapse the node recursively', () => {
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[1]);
underlyingDataSource.addChild(child);
fixture.detectChanges();
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
(getNodes(treeElement)[1] as HTMLElement).click();
fixture.detectChanges();
let numExpandedNodes =
fixture.nativeElement.querySelectorAll('[aria-expanded="true"]').length;
expect(numExpandedNodes).withContext(`Expect node expanded`).toBe(2);
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[_, `topping_4 - cheese_4 + base_4`],
[_, _, `topping_5 - cheese_5 + base_5`],
[`topping_3 - cheese_3 + base_3`],
);
(getNodes(treeElement)[1] as HTMLElement).click();
fixture.detectChanges();
numExpandedNodes = fixture.nativeElement.querySelectorAll('[aria-expanded="true"]').length;
expect(numExpandedNodes).withContext(`Expect node collapsed`).toBe(0);
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
});
});
}); | {
"end_byte": 19559,
"start_byte": 15002,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree.spec.ts"
} |
components/src/material/tree/tree.spec.ts_19563_27692 | describe('accessibility', () => {
let fixture: ComponentFixture<NestedMatTreeApp>;
let component: NestedMatTreeApp;
let nodes: HTMLElement[];
let tree: MatTree<TestData>;
beforeEach(() => {
configureMatTreeTestingModule([NestedMatTreeApp]);
fixture = TestBed.createComponent(NestedMatTreeApp);
fixture.detectChanges();
component = fixture.componentInstance;
underlyingDataSource = component.underlyingDataSource as FakeDataSource;
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[1], false);
underlyingDataSource.addChild(child, false);
underlyingDataSource.addChild(child, false);
fixture.detectChanges();
tree = component.tree;
treeElement = fixture.nativeElement.querySelector('mat-tree');
nodes = getNodes(treeElement);
});
describe('focus management', () => {
it('sets tabindex on the latest activated item, with all others "-1"', () => {
// activate the second child by clicking on it
nodes[1].click();
fixture.detectChanges();
expect(nodes.map(x => x.getAttribute('tabindex')).join(', ')).toEqual(
'-1, 0, -1, -1, -1, -1',
);
// activate the first child by clicking on it
nodes[0].click();
fixture.detectChanges();
expect(nodes.map(x => x.getAttribute('tabindex')).join(', ')).toEqual(
'0, -1, -1, -1, -1, -1',
);
});
it('maintains tabindex when component is blurred', () => {
// activate the second child by clicking on it
nodes[1].click();
nodes[1].focus();
fixture.detectChanges();
expect(nodes.map(x => x.getAttribute('tabindex')).join(', ')).toEqual(
'-1, 0, -1, -1, -1, -1',
);
expect(document.activeElement).toBe(nodes[1]);
// blur the currently active element (which we just checked is the above node)
nodes[1].blur();
fixture.detectChanges();
expect(nodes.map(x => x.getAttribute('tabindex')).join(', ')).toEqual(
'-1, 0, -1, -1, -1, -1',
);
});
it('ignores clicks on disabled items', () => {
underlyingDataSource.data[1].isDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// attempt to click on the first child
nodes[1].click();
fixture.detectChanges();
expect(nodes.map(x => x.getAttribute('tabindex')).join(', ')).toEqual(
'0, -1, -1, -1, -1, -1',
);
});
});
describe('tree role & attributes', () => {
it('sets the tree role on the tree element', () => {
expect(treeElement.getAttribute('role')).toBe('tree');
});
it('sets the treeitem role on all nodes', () => {
expect(nodes.map(x => x.getAttribute('role')).join(', ')).toEqual(
'treeitem, treeitem, treeitem, treeitem, treeitem, treeitem',
);
});
it('sets aria attributes for tree nodes', () => {
expect(nodes.map(x => x.getAttribute('aria-expanded')))
.withContext('aria-expanded attributes')
.toEqual([null, 'false', 'false', null, null, null]);
expect(nodes.map(x => x.getAttribute('aria-level')))
.withContext('aria-level attributes')
.toEqual(['1', '1', '2', '3', '3', '1']);
expect(nodes.map(x => x.getAttribute('aria-posinset')))
.withContext('aria-posinset attributes')
.toEqual(['1', '2', '1', '1', '2', '3']);
expect(nodes.map(x => x.getAttribute('aria-setsize')))
.withContext('aria-setsize attributes')
.toEqual(['3', '3', '1', '2', '2', '3']);
});
it('changes aria-expanded status when expanded or collapsed', () => {
tree.expand(underlyingDataSource.data[1]);
fixture.detectChanges();
expect(nodes.map(x => x.getAttribute('aria-expanded')))
.withContext('aria-expanded attributes')
.toEqual([null, 'true', 'false', null, null, null]);
tree.collapse(underlyingDataSource.data[1]);
fixture.detectChanges();
expect(nodes.map(x => x.getAttribute('aria-expanded')))
.withContext('aria-expanded attributes')
.toEqual([null, 'false', 'false', null, null, null]);
});
});
});
});
export class TestData {
pizzaTopping: string;
pizzaCheese: string;
pizzaBase: string;
level: number;
children: TestData[];
observableChildren: BehaviorSubject<TestData[]>;
isSpecial: boolean;
isDisabled?: boolean;
constructor(
pizzaTopping: string,
pizzaCheese: string,
pizzaBase: string,
children: TestData[] = [],
isSpecial: boolean = false,
) {
this.pizzaTopping = pizzaTopping;
this.pizzaCheese = pizzaCheese;
this.pizzaBase = pizzaBase;
this.isSpecial = isSpecial;
this.children = children;
this.observableChildren = new BehaviorSubject<TestData[]>(this.children);
}
}
class FakeDataSource {
dataIndex = 0;
_dataChange = new BehaviorSubject<TestData[]>([]);
get data() {
return this._dataChange.getValue();
}
set data(data: TestData[]) {
this._dataChange.next(data);
}
connect(): Observable<TestData[]> {
return this._dataChange;
}
disconnect() {}
constructor() {
for (let i = 0; i < 3; i++) {
this.addData();
}
}
addChild(parent: TestData, isSpecial: boolean = false) {
const nextIndex = ++this.dataIndex;
const child = new TestData(`topping_${nextIndex}`, `cheese_${nextIndex}`, `base_${nextIndex}`);
const index = this.data.indexOf(parent);
if (index > -1) {
parent = new TestData(
parent.pizzaTopping,
parent.pizzaCheese,
parent.pizzaBase,
parent.children,
isSpecial,
);
}
parent.children.push(child);
parent.observableChildren.next(parent.children);
let copiedData = this.data.slice();
if (index > -1) {
copiedData.splice(index, 1, parent);
}
this.data = copiedData;
return child;
}
addData(isSpecial: boolean = false) {
const nextIndex = ++this.dataIndex;
let copiedData = this.data.slice();
copiedData.push(
new TestData(
`topping_${nextIndex}`,
`cheese_${nextIndex}`,
`base_${nextIndex}`,
[],
isSpecial,
),
);
this.data = copiedData;
}
}
function getNodes(treeElement: Element): HTMLElement[] {
return [].slice.call(treeElement.querySelectorAll('.mat-tree-node, .mat-nested-tree-node'))!;
}
function expectFlatTreeToMatch(
treeElement: Element,
expectedPaddingIndent: number = 28,
...expectedTree: any[]
) {
const missedExpectations: string[] = [];
function checkNode(node: Element, expectedNode: any[]) {
const actualTextContent = node.textContent!.trim();
const expectedTextContent = expectedNode[expectedNode.length - 1];
if (actualTextContent !== expectedTextContent) {
missedExpectations.push(
`Expected node contents to be ${expectedTextContent} but was ${actualTextContent}`,
);
}
}
function checkLevel(node: Element, expectedNode: any[]) {
const rawLevel = (node as HTMLElement).style.paddingLeft;
// Some browsers return 0, while others return 0px.
const actualLevel = rawLevel === '0' ? '0px' : rawLevel;
if (expectedNode.length === 1) {
if (actualLevel !== `` && actualLevel !== '0px') {
missedExpectations.push(`Expected node level to be 0px but was ${actualLevel}`);
}
} else {
const expectedLevel = `${(expectedNode.length - 1) * expectedPaddingIndent}px`;
if (actualLevel != expectedLevel) {
missedExpectations.push(
`Expected node level to be ${expectedLevel} but was ${actualLevel}`,
);
}
}
}
getNodes(treeElement).forEach((node, index) => {
const expected = expectedTree ? expectedTree[index] : null;
checkLevel(node, expected);
checkNode(node, expected);
});
if (missedExpectations.length) {
fail(missedExpectations.join('\n'));
}
} | {
"end_byte": 27692,
"start_byte": 19563,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree.spec.ts"
} |
components/src/material/tree/tree.spec.ts_27694_36025 | function expectNestedTreeToMatch(treeElement: Element, ...expectedTree: any[]) {
const missedExpectations: string[] = [];
function checkNodeContent(node: Element, expectedNode: any[]) {
const expectedTextContent = expectedNode[expectedNode.length - 1];
const actualTextContent = node.childNodes.item(0).textContent!.trim();
if (actualTextContent !== expectedTextContent) {
missedExpectations.push(
`Expected node contents to be ${expectedTextContent} but was ${actualTextContent}`,
);
}
}
function checkNodeDescendants(node: Element, expectedNode: any[], currentIndex: number) {
let expectedDescendant = 0;
for (let i = currentIndex + 1; i < expectedTree.length; ++i) {
if (expectedTree[i].length > expectedNode.length) {
++expectedDescendant;
} else if (expectedTree[i].length === expectedNode.length) {
break;
}
}
const actualDescendant = getNodes(node).length;
if (actualDescendant !== expectedDescendant) {
missedExpectations.push(
`Expected node descendant num to be ${expectedDescendant} but was ${actualDescendant}`,
);
}
}
getNodes(treeElement).forEach((node, index) => {
const expected = expectedTree ? expectedTree[index] : null;
checkNodeDescendants(node, expected, index);
checkNodeContent(node, expected);
});
if (missedExpectations.length) {
fail(missedExpectations.join('\n'));
}
}
@Component({
template: `
<mat-tree [dataSource]="dataSource" [childrenAccessor]="getChildren">
<mat-tree-node *matTreeNodeDef="let node" class="customNodeClass"
matTreeNodePadding [matTreeNodePaddingIndent]="28"
matTreeNodeToggle
[isExpandable]="isExpandable(node)">
{{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
</mat-tree-node>
</mat-tree>
`,
standalone: false,
})
class SimpleMatTreeApp {
getLevel = (node: TestData) => node.level;
isExpandable = (node: TestData) => node.children.length > 0;
getChildren = (node: TestData) => node.observableChildren;
dataSource = new FakeDataSource();
@ViewChild(MatTree) tree: MatTree<TestData>;
}
interface FoodNode {
name: string;
children?: FoodNode[] | null;
}
/**
* Food data with nested structure.
* Each node has a name and an optiona list of children.
*/
const TREE_DATA: FoodNode[] = [
{
name: 'Fruit',
children: [{name: 'Apple'}, {name: 'Banana'}, {name: 'Fruit loops', children: null}],
},
{
name: 'Vegetables',
children: [
{
name: 'Green',
children: [{name: 'Broccoli'}, {name: 'Brussels sprouts'}],
},
{
name: 'Orange',
children: [{name: 'Pumpkins'}, {name: 'Carrots'}],
},
],
},
];
@Component({
template: `
<mat-tree [dataSource]="dataSource" [childrenAccessor]="childrenAccessor">
<mat-tree-node *matTreeNodeDef="let node" class="customNodeClass"
matTreeNodePadding matTreeNodeToggle>
{{node.name}}
</mat-tree-node>
</mat-tree>
`,
standalone: false,
})
class MatTreeWithNullOrUndefinedChild {
childrenAccessor = (node: FoodNode): FoodNode[] => node.children || [];
dataSource: MatTreeNestedDataSource<FoodNode>;
constructor() {
this.dataSource = new MatTreeNestedDataSource();
this.dataSource.data = TREE_DATA;
}
}
@Component({
template: `
<mat-tree [dataSource]="dataSource" [childrenAccessor]="childrenAccessor">
<mat-nested-tree-node *matTreeNodeDef="let node" class="customNodeClass">
{{node.name}}
<ng-template matTreeNodeOutlet></ng-template>
</mat-nested-tree-node>
</mat-tree>
`,
standalone: false,
})
class MatNestedTreeWithNullOrUndefinedChild {
childrenAccessor = (node: FoodNode): FoodNode[] => node.children || [];
dataSource: MatTreeNestedDataSource<FoodNode>;
constructor() {
this.dataSource = new MatTreeNestedDataSource();
this.dataSource.data = TREE_DATA;
}
}
@Component({
template: `
<mat-tree [dataSource]="dataSource" [childrenAccessor]="childrenAccessor">
<mat-nested-tree-node *matTreeNodeDef="let node" class="customNodeClass"
[isExpandable]="isExpandable(node) | async"
[isDisabled]="node.isDisabled">
{{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
<ng-template matTreeNodeOutlet></ng-template>
</mat-nested-tree-node>
</mat-tree>
`,
standalone: false,
})
class NestedMatTreeApp {
childrenAccessor = (node: TestData) => node.observableChildren;
isExpandable = (node: TestData) =>
node.observableChildren.pipe(map(children => children.length > 0));
dataSource = new MatTreeNestedDataSource();
underlyingDataSource = new FakeDataSource();
@ViewChild(MatTree) tree: MatTree<TestData>;
constructor() {
this.underlyingDataSource.connect().subscribe(data => {
this.dataSource.data = data;
});
}
}
@Component({
template: `
<mat-tree [dataSource]="dataSource" [childrenAccessor]="childrenAccessor">
<mat-nested-tree-node *matTreeNodeDef="let node">
{{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
<ng-template matTreeNodeOutlet></ng-template>
</mat-nested-tree-node>
<mat-nested-tree-node *matTreeNodeDef="let node; when: isSpecial"
matTreeNodeToggle>
>>> {{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
@if (isExpanded(node)) {
<div>
<ng-template matTreeNodeOutlet></ng-template>
</div>
}
</mat-nested-tree-node>
</mat-tree>
`,
standalone: false,
})
class WhenNodeNestedMatTreeApp {
isSpecial = (_: number, node: TestData) => node.isSpecial;
childrenAccessor = (node: TestData) => node.observableChildren;
isExpanded = (node: TestData) => {
return !!this.tree && this.tree.isExpanded(node);
};
dataSource = new MatTreeNestedDataSource();
underlyingDataSource = new FakeDataSource();
@ViewChild(MatTree) tree: MatTree<TestData>;
constructor() {
this.underlyingDataSource.connect().subscribe(data => {
this.dataSource.data = data;
});
}
}
@Component({
template: `
<mat-tree [dataSource]="dataSource" [childrenAccessor]="childrenAccessor">
<mat-tree-node *matTreeNodeDef="let node" class="customNodeClass"
[isExpandable]="isExpandable(node)"
[isDisabled]="node.isDisabled"
matTreeNodePadding
matTreeNodeToggle [matTreeNodeToggleRecursive]="toggleRecursively">
{{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
</mat-tree-node>
</mat-tree>
`,
standalone: false,
})
class MatTreeAppWithToggle {
toggleRecursively: boolean = true;
isExpandable = (node: TestData) => node.children.length > 0;
childrenAccessor = (node: TestData) => node.observableChildren;
dataSource: FakeDataSource = new FakeDataSource();
@ViewChild(MatTree) tree: MatTree<TestData>;
}
@Component({
template: `
<mat-tree [dataSource]="dataSource" [childrenAccessor]="childrenAccessor">
<mat-nested-tree-node *matTreeNodeDef="let node" class="customNodeClass"
[isExpandable]="isExpandable(node) | async"
matTreeNodeToggle
[matTreeNodeToggleRecursive]="toggleRecursively">
{{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
@if (isExpanded(node)) {
<div>
<ng-template matTreeNodeOutlet></ng-template>
</div>
}
</mat-nested-tree-node>
</mat-tree>
`,
standalone: false,
})
class NestedMatTreeAppWithToggle {
toggleRecursively: boolean = true;
childrenAccessor = (node: TestData) => node.observableChildren;
isExpandable = (node: TestData) =>
node.observableChildren.pipe(map(children => children.length > 0));
isExpanded = (node: TestData) => {
return !!this.tree && this.tree.isExpanded(node);
};
dataSource = new FakeDataSource();
@ViewChild(MatTree) tree: MatTree<TestData>;
} | {
"end_byte": 36025,
"start_byte": 27694,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree.spec.ts"
} |
components/src/material/tree/tree.spec.ts_36027_37093 | @Component({
template: `
<mat-tree [dataSource]="dataSource" [childrenAccessor]="childrenAccessor">
<mat-tree-node *matTreeNodeDef="let node" class="customNodeClass"
matTreeNodePadding [matTreeNodePaddingIndent]="28"
matTreeNodeToggle>
{{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
</mat-tree-node>
<mat-tree-node *matTreeNodeDef="let node; when: isSpecial" class="customNodeClass"
matTreeNodePadding [matTreeNodePaddingIndent]="28"
matTreeNodeToggle>
>>> {{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
</mat-tree-node>
</mat-tree>
`,
standalone: false,
})
class WhenNodeMatTreeApp {
isSpecial = (_: number, node: TestData) => node.isSpecial;
isExpandable = (node: TestData) => node.children.length > 0;
childrenAccessor = (node: TestData) => node.observableChildren;
dataSource = new FakeDataSource();
@ViewChild(MatTree) tree: MatTree<TestData>;
} | {
"end_byte": 37093,
"start_byte": 36027,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree.spec.ts"
} |
components/src/material/tree/BUILD.bazel_0_1433 | 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 = "tree",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = [":tree.css"] + glob(["**/*.html"]),
deps = [
"//src/cdk/collections",
"//src/cdk/tree",
"//src/material/core",
"@npm//@angular/core",
"@npm//rxjs",
],
)
sass_library(
name = "tree_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = [
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "tree_scss",
src = "tree.scss",
deps = [
":tree_scss_lib",
],
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":tree",
"//src/cdk/a11y",
"//src/cdk/keycodes",
"//src/cdk/testing/private",
"//src/cdk/tree",
"@npm//rxjs",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
markdown_to_html(
name = "overview",
srcs = [":tree.md"],
)
extract_tokens(
name = "tokens",
srcs = [":tree_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1433,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/BUILD.bazel"
} |
components/src/material/tree/tree-module.ts_0_916 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {CdkTreeModule} from '@angular/cdk/tree';
import {MatCommonModule} from '@angular/material/core';
import {MatNestedTreeNode, MatTreeNodeDef, MatTreeNode} from './node';
import {MatTree} from './tree';
import {MatTreeNodeToggle} from './toggle';
import {MatTreeNodeOutlet} from './outlet';
import {MatTreeNodePadding} from './padding';
const MAT_TREE_DIRECTIVES = [
MatNestedTreeNode,
MatTreeNodeDef,
MatTreeNodePadding,
MatTreeNodeToggle,
MatTree,
MatTreeNode,
MatTreeNodeOutlet,
];
@NgModule({
imports: [CdkTreeModule, MatCommonModule, ...MAT_TREE_DIRECTIVES],
exports: [MatCommonModule, MAT_TREE_DIRECTIVES],
})
export class MatTreeModule {}
| {
"end_byte": 916,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree-module.ts"
} |
components/src/material/tree/tree.md_0_8007 | The `mat-tree` provides a Material Design styled tree that can be used to display hierarchical
data.
This tree builds on the foundation of the CDK tree and uses a similar interface for its
data source input and template, except that its element and attribute selectors will be prefixed
with `mat-` instead of `cdk-`.
There are two types of trees: flat and nested. The DOM structures are different for these
two types of trees.
#### Flat tree
In a flat tree, the hierarchy is flattened; nodes are not rendered inside of each other,
but instead are rendered as siblings in sequence.
```html
<mat-tree>
<mat-tree-node> parent node </mat-tree-node>
<mat-tree-node> -- child node1 </mat-tree-node>
<mat-tree-node> -- child node2 </mat-tree-node>
</mat-tree>
```
<!-- example(tree-flat-child-accessor-overview) -->
Flat trees are generally easier to style and inspect. They are also more friendly to scrolling
variations, such as infinite or virtual scrolling.
#### Nested tree
In a nested tree, children nodes are placed inside their parent node in DOM. The parent node
contains a node outlet into which children are projected.
```html
<mat-tree>
<mat-nested-tree-node>
parent node
<mat-nested-tree-node> -- child node1 </mat-nested-tree-node>
<mat-nested-tree-node> -- child node2 </mat-nested-tree-node>
</mat-nested-tree-node>
</mat-tree>
```
<!-- example(tree-nested-child-accessor-overview) -->
Nested trees are easier to work with when hierarchical relationships are visually represented in
ways that would be difficult to accomplish with flat nodes.
### Usage
#### Writing your tree template
In order to use the tree, you must define a tree node template. There are two types of tree nodes,
`<mat-tree-node>` for flat tree and `<mat-nested-tree-node>` for nested tree. The tree node
template defines the look of the tree node, expansion/collapsing control and the structure for
nested children nodes.
A node definition is specified via any element with `matNodeDef`. This directive exports the node
data to be used in any bindings in the node template.
```html
<mat-tree-node *matNodeDef="let node">
{{node.key}}: {{node.value}}
</mat-tree-node>
```
##### Flat tree node template
Flat trees use the `level` of a node to both render and determine hierarchy of the nodes for screen
readers. This may be provided either via `levelAccessor`, or will be calculated by `MatTree` if
`childrenAccessor` is provided.
Spacing can be added either by applying the `matNodePadding` directive or by applying custom styles
based on the `aria-level` attribute.
##### Nested tree node template
When using nested tree nodes, the node template must contain a `matTreeNodeOutlet`, which marks
where the children of the node will be rendered.
```html
<mat-nested-tree-node *matNodeDef="let node">
{{node.value}}
<ng-container matTreeNodeOutlet></ng-container>
</mat-nested-tree-node>
```
#### Adding expand/collapse
The `matTreeNodeToggle` directive can be used to add expand/collapse functionality for tree nodes.
The toggle calls the expand/collapse functions in the `matTree` and is able to expand/collapse
a tree node recursively by setting `[matTreeNodeToggleRecursive]` to true.
`matTreeNodeToggle` should be attached to button elements, and will trigger upon click or keyboard
activation. For icon buttons, ensure that `aria-label` is provided.
```html
<mat-tree-node *matNodeDef="let node">
<button matTreeNodeToggle aria-label="toggle tree node" [matTreeNodeToggleRecursive]="true">
<mat-icon>expand</mat-icon>
</button>
{{node.value}}
</mat-tree-node>
```
### Toggle
A `matTreeNodeToggle` can be added in the tree node template to expand/collapse the tree node. The
toggle toggles the expand/collapse functions in `TreeControl` and is able to expand/collapse a
tree node recursively by setting `[matTreeNodeToggleRecursive]` to `true`.
The toggle can be placed anywhere in the tree node, and is only toggled by `click` action.
### Padding (Flat tree only)
The `matTreeNodePadding` can be placed in a flat tree's node template to display the `level`
information of a flat tree node.
```html
<mat-tree-node *matNodeDef="let node" matNodePadding>
{{node.value}}
</mat-tree-node>
```
This is unnecessary for a nested tree, since the hierarchical structure of the DOM allows for
padding to be added via CSS.
#### Conditional template
The tree may include multiple node templates, where a template is chosen
for a particular data node via the `when` predicate of the template.
```html
<mat-tree-node *matNodeDef="let node" matTreeNodePadding>
{{node.value}}
</mat-tree-node>
<mat-tree-node *matNodeDef="let node; when: isSpecial" matTreeNodePadding>
[ A special node {{node.value}} ]
</mat-tree-node>
```
### Data Source
#### Connecting the tree to a data source
Similar to `mat-table`, you can provide data to the tree through a `DataSource`. When the tree receives
a `DataSource` it will call its `connect()` method which returns an observable that emits an array
of data. Whenever the data source emits data to this stream, the tree will render an update.
Because the data source provides this stream, it bears the responsibility of toggling tree
updates. This can be based on anything: tree node expansion change, websocket connections, user
interaction, model updates, time-based intervals, etc.
There are two main methods of providing data to the tree:
* flattened data, combined with `levelAccessor`. This should be used if the data source already
flattens the nested data structure into a single array.
* only root data, combined with `childrenAccessor`. This should be used if the data source is
already provided as a nested data structure.
#### `levelAccessor`
`levelAccessor` is a function that when provided a datum, returns the level the data sits at in the
tree structure. If `levelAccessor` is provided, the data provided by `dataSource` should contain all
renderable nodes in a single array.
The data source is responsible for handling node expand/collapse events and providing an updated
array of renderable nodes, if applicable. This can be listened to via the `(expansionChange)` event
on `mat-tree-node` and `mat-nested-tree-node`.
#### `childrenAccessor`
`childrenAccessor` is a function that when provided a datum, returns the children of that particular
datum. If `childrenAccessor` is provided, the data provided by `dataSource` should _only_ contain
the root nodes of the tree.
#### `trackBy`
To improve performance, a `trackBy` function can be provided to the tree similar to Angular’s
[`ngFor` `trackBy`](https://angular.dev/api/common/NgForOf?tab=usage-notes). This informs the
tree how to uniquely identify nodes to track how the data changes with each update.
```html
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl" [trackBy]="trackByFn">
```
### Accessibility
The `<mat-tree>` implements the [`tree` widget](https://www.w3.org/WAI/ARIA/apg/patterns/treeview/),
including keyboard navigation and appropriate roles and ARIA attributes.
In order to use the new accessibility features, migrating to `levelAccessor` and `childrenAccessor`
is required. Trees using `treeControl` do not implement the correct accessibility features for
backwards compatibility.
#### isExpandable
In order for the tree to correctly determine whether or not a node is expandable, the `isExpandable`
property must be set on all `mat-tree-node` or `mat-tree-nested-node` that are expandable.
#### Activation actions
For trees with nodes that have actions upon activation or click, `<mat-tree-node>` will emit
`(activation)` events that can be listened to when the user activates a node via keyboard
interaction.
```html
<mat-tree-node
*matNodeDef="let node"
(click)="performAction(node)"
(activation)="performAction($event)">
</mat-tree-node>
```
In this example, `$event` contains the node's data and is equivalent to the implicit data passed in
the `matNodeDef` context.
| {
"end_byte": 8007,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree.md"
} |
components/src/material/tree/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/tree/index.ts"
} |
components/src/material/tree/tree.ts_0_1311 | /**
* @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 {CdkTree} from '@angular/cdk/tree';
import {ChangeDetectionStrategy, Component, ViewChild, ViewEncapsulation} from '@angular/core';
import {MatTreeNodeOutlet} from './outlet';
/**
* Wrapper for the CdkTable with Material design styles.
*/
@Component({
selector: 'mat-tree',
exportAs: 'matTree',
template: `<ng-container matTreeNodeOutlet></ng-container>`,
host: {
'class': 'mat-tree',
},
styleUrl: 'tree.css',
encapsulation: ViewEncapsulation.None,
// See note on CdkTree for explanation on why this uses the default change detection strategy.
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
providers: [{provide: CdkTree, useExisting: MatTree}],
imports: [MatTreeNodeOutlet],
})
export class MatTree<T, K = T> extends CdkTree<T, K> {
// Outlets within the tree's template where the dataNodes will be inserted.
// We need an initializer here to avoid a TS error. The value will be set in `ngAfterViewInit`.
@ViewChild(MatTreeNodeOutlet, {static: true}) override _nodeOutlet: MatTreeNodeOutlet =
undefined!;
}
| {
"end_byte": 1311,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree.ts"
} |
components/src/material/tree/tree-using-tree-control.spec.ts_0_621 | /**
* @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 {FlatTreeControl, NestedTreeControl, TreeControl} from '@angular/cdk/tree';
import {Component, ViewChild, Type} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {BehaviorSubject, Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {
MatTree,
MatTreeFlatDataSource,
MatTreeFlattener,
MatTreeModule,
MatTreeNestedDataSource,
} from './index'; | {
"end_byte": 621,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree-using-tree-control.spec.ts"
} |
components/src/material/tree/tree-using-tree-control.spec.ts_623_8929 | describe('MatTree', () => {
/** Represents an indent for expectNestedTreeToMatch */
const _ = {};
let treeElement: HTMLElement;
let underlyingDataSource: FakeDataSource;
function configureMatTreeTestingModule(declarations: Type<any>[]) {
TestBed.configureTestingModule({
imports: [MatTreeModule],
declarations: declarations,
});
}
describe('flat tree', () => {
describe('should initialize', () => {
let fixture: ComponentFixture<SimpleMatTreeApp>;
let component: SimpleMatTreeApp;
beforeEach(() => {
configureMatTreeTestingModule([SimpleMatTreeApp]);
fixture = TestBed.createComponent(SimpleMatTreeApp);
component = fixture.componentInstance;
underlyingDataSource = component.underlyingDataSource;
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('with rendered dataNodes', () => {
const nodes = getNodes(treeElement);
expect(nodes).withContext('Expect nodes to be defined').toBeDefined();
expect(nodes[0].classList).toContain('customNodeClass');
});
it('with the right accessibility roles', () => {
expect(treeElement.getAttribute('role')).toBe('tree');
getNodes(treeElement).forEach(node => {
expect(node.getAttribute('role')).toBe('treeitem');
});
});
it('with the right aria-level attrs', () => {
// add a child to the first node
const data = underlyingDataSource.data;
underlyingDataSource.addChild(data[2]);
component.treeControl.expandAll();
fixture.detectChanges();
const ariaLevels = getNodes(treeElement).map(n => n.getAttribute('aria-level'));
expect(ariaLevels).toEqual(['1', '1', '1', '2']);
});
it('with the right aria-expanded attrs', () => {
// add a child to the first node
const data = underlyingDataSource.data;
underlyingDataSource.addChild(data[2]);
fixture.detectChanges();
let ariaExpandedStates = getNodes(treeElement).map(n => n.getAttribute('aria-expanded'));
expect(ariaExpandedStates).toEqual([null, null, 'false']);
component.treeControl.expandAll();
fixture.detectChanges();
ariaExpandedStates = getNodes(treeElement).map(n => n.getAttribute('aria-expanded'));
expect(ariaExpandedStates).toEqual([null, null, 'true', null]);
});
it('with the right data', () => {
expect(underlyingDataSource.data.length).toBe(3);
const data = underlyingDataSource.data;
expectFlatTreeToMatch(
treeElement,
28,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
underlyingDataSource.addChild(data[2]);
fixture.detectChanges();
expectFlatTreeToMatch(
treeElement,
28,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
[`_, topping_4 - cheese_4 + base_4`],
);
});
});
describe('with toggle', () => {
let fixture: ComponentFixture<MatTreeAppWithToggle>;
let component: MatTreeAppWithToggle;
beforeEach(() => {
configureMatTreeTestingModule([MatTreeAppWithToggle]);
fixture = TestBed.createComponent(MatTreeAppWithToggle);
component = fixture.componentInstance;
underlyingDataSource = component.underlyingDataSource;
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('should expand/collapse the node', () => {
expect(underlyingDataSource.data.length).toBe(3);
expect(component.treeControl.expansionModel.selected.length)
.withContext(`Expect no expanded node`)
.toBe(0);
component.toggleRecursively = false;
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[2]);
underlyingDataSource.addChild(child);
fixture.detectChanges();
expectFlatTreeToMatch(
treeElement,
40,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
(getNodes(treeElement)[2] as HTMLElement).click();
fixture.detectChanges();
expect(component.treeControl.expansionModel.selected.length)
.withContext(`Expect node expanded one level`)
.toBe(1);
expectFlatTreeToMatch(
treeElement,
40,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
[_, `topping_4 - cheese_4 + base_4`],
);
(getNodes(treeElement)[3] as HTMLElement).click();
fixture.detectChanges();
expect(component.treeControl.expansionModel.selected.length)
.withContext(`Expect node expanded`)
.toBe(2);
expectFlatTreeToMatch(
treeElement,
40,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
[_, `topping_4 - cheese_4 + base_4`],
[_, _, `topping_5 - cheese_5 + base_5`],
);
(getNodes(treeElement)[2] as HTMLElement).click();
fixture.detectChanges();
expectFlatTreeToMatch(
treeElement,
40,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
});
it('should expand/collapse the node recursively', () => {
expect(underlyingDataSource.data.length).toBe(3);
expect(component.treeControl.expansionModel.selected.length)
.withContext(`Expect no expanded node`)
.toBe(0);
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[2]);
underlyingDataSource.addChild(child);
fixture.detectChanges();
expectFlatTreeToMatch(
treeElement,
40,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
(getNodes(treeElement)[2] as HTMLElement).click();
fixture.detectChanges();
expect(component.treeControl.expansionModel.selected.length)
.withContext(`Expect nodes expanded`)
.toBe(3);
expectFlatTreeToMatch(
treeElement,
40,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
[_, `topping_4 - cheese_4 + base_4`],
[_, _, `topping_5 - cheese_5 + base_5`],
);
(getNodes(treeElement)[2] as HTMLElement).click();
fixture.detectChanges();
expect(component.treeControl.expansionModel.selected.length)
.withContext(`Expect node collapsed`)
.toBe(0);
expectFlatTreeToMatch(
treeElement,
40,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
});
});
describe('with when node template', () => {
let fixture: ComponentFixture<WhenNodeMatTreeApp>;
let component: WhenNodeMatTreeApp;
beforeEach(() => {
configureMatTreeTestingModule([WhenNodeMatTreeApp]);
fixture = TestBed.createComponent(WhenNodeMatTreeApp);
component = fixture.componentInstance;
underlyingDataSource = component.underlyingDataSource;
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('with the right data', () => {
expectFlatTreeToMatch(
treeElement,
28,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
[`>>> topping_4 - cheese_4 + base_4`],
);
});
});
}); | {
"end_byte": 8929,
"start_byte": 623,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree-using-tree-control.spec.ts"
} |
components/src/material/tree/tree-using-tree-control.spec.ts_8933_10403 | describe('flat tree with undefined or null children', () => {
describe('should initialize', () => {
let fixture: ComponentFixture<MatTreeWithNullOrUndefinedChild>;
beforeEach(() => {
configureMatTreeTestingModule([MatTreeWithNullOrUndefinedChild]);
fixture = TestBed.createComponent(MatTreeWithNullOrUndefinedChild);
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('with rendered dataNodes', () => {
const nodes = getNodes(treeElement);
expect(nodes).withContext('Expect nodes to be defined').toBeDefined();
expect(nodes[0].classList).toContain('customNodeClass');
});
});
});
describe('nested tree with undefined or null children', () => {
describe('should initialize', () => {
let fixture: ComponentFixture<MatNestedTreeWithNullOrUndefinedChild>;
beforeEach(() => {
configureMatTreeTestingModule([MatNestedTreeWithNullOrUndefinedChild]);
fixture = TestBed.createComponent(MatNestedTreeWithNullOrUndefinedChild);
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('with rendered dataNodes', () => {
const nodes = getNodes(treeElement);
expect(nodes).withContext('Expect nodes to be defined').toBeDefined();
expect(nodes[0].classList).toContain('customNodeClass');
});
});
}); | {
"end_byte": 10403,
"start_byte": 8933,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree-using-tree-control.spec.ts"
} |
components/src/material/tree/tree-using-tree-control.spec.ts_10406_19232 | describe('nested tree', () => {
describe('should initialize', () => {
let fixture: ComponentFixture<NestedMatTreeApp>;
let component: NestedMatTreeApp;
beforeEach(() => {
configureMatTreeTestingModule([NestedMatTreeApp]);
fixture = TestBed.createComponent(NestedMatTreeApp);
component = fixture.componentInstance;
underlyingDataSource = component.underlyingDataSource;
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('with rendered dataNodes', () => {
const nodes = getNodes(treeElement);
expect(nodes).withContext('Expect nodes to be defined').toBeDefined();
expect(nodes[0].classList).toContain('customNodeClass');
});
it('with the right accessibility roles', () => {
expect(treeElement.getAttribute('role')).toBe('tree');
getNodes(treeElement).forEach(node => {
expect(node.getAttribute('role')).toBe('treeitem');
});
});
it('with the right data', () => {
expect(underlyingDataSource.data.length).toBe(3);
let data = underlyingDataSource.data;
expectNestedTreeToMatch(
treeElement,
[`${data[0].pizzaTopping} - ${data[0].pizzaCheese} + ${data[0].pizzaBase}`],
[`${data[1].pizzaTopping} - ${data[1].pizzaCheese} + ${data[1].pizzaBase}`],
[`${data[2].pizzaTopping} - ${data[2].pizzaCheese} + ${data[2].pizzaBase}`],
);
underlyingDataSource.addChild(data[1]);
fixture.detectChanges();
treeElement = fixture.nativeElement.querySelector('mat-tree');
data = underlyingDataSource.data;
expect(data.length).toBe(3);
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[_, `topping_4 - cheese_4 + base_4`],
[`topping_3 - cheese_3 + base_3`],
);
});
it('with nested child data', () => {
expect(underlyingDataSource.data.length).toBe(3);
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[1]);
underlyingDataSource.addChild(child);
fixture.detectChanges();
expect(data.length).toBe(3);
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[_, `topping_4 - cheese_4 + base_4`],
[_, _, `topping_5 - cheese_5 + base_5`],
[`topping_3 - cheese_3 + base_3`],
);
underlyingDataSource.addChild(child);
fixture.detectChanges();
expect(data.length).toBe(3);
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[_, `topping_4 - cheese_4 + base_4`],
[_, _, `topping_5 - cheese_5 + base_5`],
[_, _, `topping_6 - cheese_6 + base_6`],
[`topping_3 - cheese_3 + base_3`],
);
});
it('with correct aria-level on nodes', () => {
expect(
getNodes(treeElement).every(node => {
return node.getAttribute('aria-level') === '1';
}),
).toBe(true);
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[1]);
underlyingDataSource.addChild(child);
fixture.detectChanges();
const ariaLevels = getNodes(treeElement).map(n => n.getAttribute('aria-level'));
expect(ariaLevels).toEqual(['1', '1', '2', '3', '1']);
});
});
describe('with when node', () => {
let fixture: ComponentFixture<WhenNodeNestedMatTreeApp>;
let component: WhenNodeNestedMatTreeApp;
beforeEach(() => {
configureMatTreeTestingModule([WhenNodeNestedMatTreeApp]);
fixture = TestBed.createComponent(WhenNodeNestedMatTreeApp);
component = fixture.componentInstance;
underlyingDataSource = component.underlyingDataSource;
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('with the right data', () => {
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
[`>>> topping_4 - cheese_4 + base_4`],
);
});
});
describe('with toggle', () => {
let fixture: ComponentFixture<NestedMatTreeAppWithToggle>;
let component: NestedMatTreeAppWithToggle;
beforeEach(() => {
configureMatTreeTestingModule([NestedMatTreeAppWithToggle]);
fixture = TestBed.createComponent(NestedMatTreeAppWithToggle);
component = fixture.componentInstance;
underlyingDataSource = component.underlyingDataSource;
treeElement = fixture.nativeElement.querySelector('mat-tree');
fixture.detectChanges();
});
it('with the right aria-expanded attrs', () => {
let ariaExpandedStates = getNodes(treeElement).map(n => n.getAttribute('aria-expanded'));
expect(ariaExpandedStates).toEqual([null, null, null]);
component.toggleRecursively = false;
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[1]);
underlyingDataSource.addChild(child);
fixture.detectChanges();
(getNodes(treeElement)[1] as HTMLElement).click();
fixture.detectChanges();
// Note: only four elements are present here; children are not present
// in DOM unless the parent node is expanded.
const ariaExpanded = getNodes(treeElement).map(n => n.getAttribute('aria-expanded'));
expect(ariaExpanded).toEqual([null, 'true', 'false', null]);
});
it('should expand/collapse the node', () => {
component.toggleRecursively = false;
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[1]);
underlyingDataSource.addChild(child);
fixture.detectChanges();
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
fixture.detectChanges();
(getNodes(treeElement)[1] as HTMLElement).click();
fixture.detectChanges();
expect(component.treeControl.expansionModel.selected.length)
.withContext(`Expect node expanded`)
.toBe(1);
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[_, `topping_4 - cheese_4 + base_4`],
[`topping_3 - cheese_3 + base_3`],
);
(getNodes(treeElement)[1] as HTMLElement).click();
fixture.detectChanges();
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
expect(component.treeControl.expansionModel.selected.length)
.withContext(`Expect node collapsed`)
.toBe(0);
});
it('should expand/collapse the node recursively', () => {
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[1]);
underlyingDataSource.addChild(child);
fixture.detectChanges();
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
(getNodes(treeElement)[1] as HTMLElement).click();
fixture.detectChanges();
expect(component.treeControl.expansionModel.selected.length)
.withContext(`Expect node expanded`)
.toBe(3);
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[_, `topping_4 - cheese_4 + base_4`],
[_, _, `topping_5 - cheese_5 + base_5`],
[`topping_3 - cheese_3 + base_3`],
);
(getNodes(treeElement)[1] as HTMLElement).click();
fixture.detectChanges();
expect(component.treeControl.expansionModel.selected.length)
.withContext(`Expect node collapsed`)
.toBe(0);
expectNestedTreeToMatch(
treeElement,
[`topping_1 - cheese_1 + base_1`],
[`topping_2 - cheese_2 + base_2`],
[`topping_3 - cheese_3 + base_3`],
);
});
});
}); | {
"end_byte": 19232,
"start_byte": 10406,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree-using-tree-control.spec.ts"
} |
components/src/material/tree/tree-using-tree-control.spec.ts_19236_27287 | describe('accessibility', () => {
let fixture: ComponentFixture<NestedMatTreeApp>;
let component: NestedMatTreeApp;
let nodes: HTMLElement[];
let tree: MatTree<TestData>;
beforeEach(() => {
configureMatTreeTestingModule([NestedMatTreeApp]);
fixture = TestBed.createComponent(NestedMatTreeApp);
fixture.detectChanges();
component = fixture.componentInstance;
underlyingDataSource = component.underlyingDataSource as FakeDataSource;
const data = underlyingDataSource.data;
const child = underlyingDataSource.addChild(data[1], false);
underlyingDataSource.addChild(child, false);
underlyingDataSource.addChild(child, false);
fixture.detectChanges();
tree = component.tree;
treeElement = fixture.nativeElement.querySelector('mat-tree');
nodes = getNodes(treeElement);
});
describe('focus management', () => {
it('sets tabindex on the latest activated item, with all others "-1"', () => {
// activate the second child by clicking on it
nodes[1].click();
fixture.detectChanges();
expect(nodes.map(x => x.getAttribute('tabindex')).join(', ')).toEqual(
'-1, 0, -1, -1, -1, -1',
);
// activate the first child by clicking on it
nodes[0].click();
fixture.detectChanges();
expect(nodes.map(x => x.getAttribute('tabindex')).join(', ')).toEqual(
'0, -1, -1, -1, -1, -1',
);
});
it('maintains tabindex when component is blurred', () => {
// activate the second child by clicking on it
nodes[1].click();
nodes[1].focus();
fixture.detectChanges();
expect(document.activeElement).toBe(nodes[1]);
// blur the currently active element (which we just checked is the above node)
nodes[1].blur();
fixture.detectChanges();
expect(nodes.map(x => x.getAttribute('tabindex')).join(', ')).toEqual(
'-1, 0, -1, -1, -1, -1',
);
});
it('ignores clicks on disabled items', () => {
underlyingDataSource.data[1].isDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// attempt to click on the first child
nodes[1].click();
fixture.detectChanges();
expect(nodes.map(x => x.getAttribute('tabindex')).join(', ')).toEqual(
'0, -1, -1, -1, -1, -1',
);
});
});
describe('tree role & attributes', () => {
it('sets the tree role on the tree element', () => {
expect(treeElement.getAttribute('role')).toBe('tree');
});
it('sets the treeitem role on all nodes', () => {
expect(nodes.map(x => x.getAttribute('role')).join(', ')).toEqual(
'treeitem, treeitem, treeitem, treeitem, treeitem, treeitem',
);
});
it('sets aria attributes for tree nodes', () => {
expect(nodes.map(x => `${x.getAttribute('aria-expanded')}`).join(', '))
.withContext('aria-expanded attributes')
.toEqual('null, false, false, null, null, null');
expect(nodes.map(x => `${x.getAttribute('aria-level')}`).join(', '))
.withContext('aria-level attributes')
.toEqual('1, 1, 2, 3, 3, 1');
expect(nodes.map(x => `${x.getAttribute('aria-posinset')}`).join(', '))
.withContext('aria-posinset attributes')
.toEqual('1, 2, 1, 1, 2, 3');
expect(nodes.map(x => `${x.getAttribute('aria-setsize')}`).join(', '))
.withContext('aria-setsize attributes')
.toEqual('3, 3, 1, 2, 2, 3');
});
it('changes aria-expanded status when expanded or collapsed', () => {
tree.expand(underlyingDataSource.data[1]);
fixture.detectChanges();
expect(nodes.map(x => `${x.getAttribute('aria-expanded')}`).join(', '))
.withContext('aria-expanded attributes')
.toEqual('null, true, false, null, null, null');
tree.collapse(underlyingDataSource.data[1]);
fixture.detectChanges();
expect(nodes.map(x => `${x.getAttribute('aria-expanded')}`).join(', '))
.withContext('aria-expanded attributes')
.toEqual('null, false, false, null, null, null');
});
});
});
});
export class TestData {
pizzaTopping: string;
pizzaCheese: string;
pizzaBase: string;
level: number;
children: TestData[];
observableChildren: BehaviorSubject<TestData[]>;
isSpecial: boolean;
isDisabled?: boolean;
constructor(
pizzaTopping: string,
pizzaCheese: string,
pizzaBase: string,
children: TestData[] = [],
isSpecial: boolean = false,
) {
this.pizzaTopping = pizzaTopping;
this.pizzaCheese = pizzaCheese;
this.pizzaBase = pizzaBase;
this.isSpecial = isSpecial;
this.children = children;
this.observableChildren = new BehaviorSubject<TestData[]>(this.children);
}
}
class FakeDataSource {
dataIndex = 0;
_dataChange = new BehaviorSubject<TestData[]>([]);
get data() {
return this._dataChange.getValue();
}
set data(data: TestData[]) {
this._dataChange.next(data);
}
connect(): Observable<TestData[]> {
return this._dataChange;
}
disconnect() {}
constructor() {
for (let i = 0; i < 3; i++) {
this.addData();
}
}
addChild(parent: TestData, isSpecial: boolean = false) {
const nextIndex = ++this.dataIndex;
const child = new TestData(`topping_${nextIndex}`, `cheese_${nextIndex}`, `base_${nextIndex}`);
const index = this.data.indexOf(parent);
if (index > -1) {
parent = new TestData(
parent.pizzaTopping,
parent.pizzaCheese,
parent.pizzaBase,
parent.children,
isSpecial,
);
}
parent.children.push(child);
parent.observableChildren.next(parent.children);
let copiedData = this.data.slice();
if (index > -1) {
copiedData.splice(index, 1, parent);
}
this.data = copiedData;
return child;
}
addData(isSpecial: boolean = false) {
const nextIndex = ++this.dataIndex;
let copiedData = this.data.slice();
copiedData.push(
new TestData(
`topping_${nextIndex}`,
`cheese_${nextIndex}`,
`base_${nextIndex}`,
[],
isSpecial,
),
);
this.data = copiedData;
}
}
function getNodes(treeElement: Element): HTMLElement[] {
return [].slice.call(treeElement.querySelectorAll('.mat-tree-node, .mat-nested-tree-node'))!;
}
function expectFlatTreeToMatch(
treeElement: Element,
expectedPaddingIndent: number = 28,
...expectedTree: any[]
) {
const missedExpectations: string[] = [];
function checkNode(node: Element, expectedNode: any[]) {
const actualTextContent = node.textContent!.trim();
const expectedTextContent = expectedNode[expectedNode.length - 1];
if (actualTextContent !== expectedTextContent) {
missedExpectations.push(
`Expected node contents to be ${expectedTextContent} but was ${actualTextContent}`,
);
}
}
function checkLevel(node: Element, expectedNode: any[]) {
const rawLevel = (node as HTMLElement).style.paddingLeft;
// Some browsers return 0, while others return 0px.
const actualLevel = rawLevel === '0' ? '0px' : rawLevel;
if (expectedNode.length === 1) {
if (actualLevel !== `` && actualLevel !== '0px') {
missedExpectations.push(`Expected node level to be 0px but was ${actualLevel}`);
}
} else {
const expectedLevel = `${(expectedNode.length - 1) * expectedPaddingIndent}px`;
if (actualLevel != expectedLevel) {
missedExpectations.push(
`Expected node level to be ${expectedLevel} but was ${actualLevel}`,
);
}
}
}
getNodes(treeElement).forEach((node, index) => {
const expected = expectedTree ? expectedTree[index] : null;
checkLevel(node, expected);
checkNode(node, expected);
});
if (missedExpectations.length) {
fail(missedExpectations.join('\n'));
}
} | {
"end_byte": 27287,
"start_byte": 19236,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree-using-tree-control.spec.ts"
} |
components/src/material/tree/tree-using-tree-control.spec.ts_27289_34690 | function expectNestedTreeToMatch(treeElement: Element, ...expectedTree: any[]) {
const missedExpectations: string[] = [];
function checkNodeContent(node: Element, expectedNode: any[]) {
const expectedTextContent = expectedNode[expectedNode.length - 1];
const actualTextContent = node.childNodes.item(0).textContent!.trim();
if (actualTextContent !== expectedTextContent) {
missedExpectations.push(
`Expected node contents to be ${expectedTextContent} but was ${actualTextContent}`,
);
}
}
function checkNodeDescendants(node: Element, expectedNode: any[], currentIndex: number) {
let expectedDescendant = 0;
for (let i = currentIndex + 1; i < expectedTree.length; ++i) {
if (expectedTree[i].length > expectedNode.length) {
++expectedDescendant;
} else if (expectedTree[i].length === expectedNode.length) {
break;
}
}
const actualDescendant = getNodes(node).length;
if (actualDescendant !== expectedDescendant) {
missedExpectations.push(
`Expected node descendant num to be ${expectedDescendant} but was ${actualDescendant}`,
);
}
}
getNodes(treeElement).forEach((node, index) => {
const expected = expectedTree ? expectedTree[index] : null;
checkNodeDescendants(node, expected, index);
checkNodeContent(node, expected);
});
if (missedExpectations.length) {
fail(missedExpectations.join('\n'));
}
}
@Component({
template: `
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
<mat-tree-node *matTreeNodeDef="let node" class="customNodeClass"
matTreeNodePadding [matTreeNodePaddingIndent]="28"
matTreeNodeToggle>
{{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
</mat-tree-node>
</mat-tree>
`,
standalone: false,
})
class SimpleMatTreeApp {
getLevel = (node: TestData) => node.level;
isExpandable = (node: TestData) => node.children.length > 0;
getChildren = (node: TestData) => node.observableChildren;
transformer = (node: TestData, level: number) => {
node.level = level;
return node;
};
treeFlattener = new MatTreeFlattener<TestData, TestData>(
this.transformer,
this.getLevel,
this.isExpandable,
this.getChildren,
);
treeControl = new FlatTreeControl(this.getLevel, this.isExpandable);
dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
underlyingDataSource = new FakeDataSource();
@ViewChild(MatTree) tree: MatTree<TestData>;
constructor() {
this.underlyingDataSource.connect().subscribe(data => {
this.dataSource.data = data;
});
}
}
interface FoodNode {
name: string;
children?: FoodNode[] | null;
}
/** Flat node with expandable and level information */
interface ExampleFlatNode {
expandable: boolean;
name: string;
level: number;
}
/**
* Food data with nested structure.
* Each node has a name and an optiona list of children.
*/
const TREE_DATA: FoodNode[] = [
{
name: 'Fruit',
children: [{name: 'Apple'}, {name: 'Banana'}, {name: 'Fruit loops', children: null}],
},
{
name: 'Vegetables',
children: [
{
name: 'Green',
children: [{name: 'Broccoli'}, {name: 'Brussels sprouts'}],
},
{
name: 'Orange',
children: [{name: 'Pumpkins'}, {name: 'Carrots'}],
},
],
},
];
@Component({
template: `
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
<mat-tree-node *matTreeNodeDef="let node" class="customNodeClass"
matTreeNodePadding matTreeNodeToggle>
{{node.name}}
</mat-tree-node>
</mat-tree>
`,
standalone: false,
})
class MatTreeWithNullOrUndefinedChild {
private _transformer = (node: FoodNode, level: number) => {
return {
expandable: !!node.children,
name: node.name,
level: level,
};
};
treeControl = new FlatTreeControl<ExampleFlatNode>(
node => node.level,
node => node.expandable,
);
treeFlattener = new MatTreeFlattener(
this._transformer,
node => node.level,
node => node.expandable,
node => node.children,
);
dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener, TREE_DATA);
hasChild = (_: number, node: ExampleFlatNode) => node.expandable;
}
@Component({
template: `
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
<mat-nested-tree-node *matTreeNodeDef="let node" class="customNodeClass">
{{node.name}}
<ng-template matTreeNodeOutlet></ng-template>
</mat-nested-tree-node>
</mat-tree>
`,
standalone: false,
})
class MatNestedTreeWithNullOrUndefinedChild {
treeControl: NestedTreeControl<FoodNode>;
dataSource: MatTreeNestedDataSource<FoodNode>;
constructor() {
this.treeControl = new NestedTreeControl<FoodNode>(this._getChildren);
this.dataSource = new MatTreeNestedDataSource();
this.dataSource.data = TREE_DATA;
}
private _getChildren = (node: FoodNode) => node.children;
}
@Component({
template: `
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
<mat-nested-tree-node *matTreeNodeDef="let node" class="customNodeClass"
[isExpandable]="isExpandable(node) | async"
[isDisabled]="node.isDisabled">
{{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
<ng-template matTreeNodeOutlet></ng-template>
</mat-nested-tree-node>
</mat-tree>
`,
standalone: false,
})
class NestedMatTreeApp {
getChildren = (node: TestData) => node.observableChildren;
isExpandable = (node: TestData) =>
node.observableChildren.pipe(map(children => children.length > 0));
treeControl = new NestedTreeControl(this.getChildren);
dataSource = new MatTreeNestedDataSource();
underlyingDataSource = new FakeDataSource();
@ViewChild(MatTree) tree: MatTree<TestData>;
constructor() {
this.underlyingDataSource.connect().subscribe(data => {
this.dataSource.data = data;
});
}
}
@Component({
template: `
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
<mat-nested-tree-node *matTreeNodeDef="let node">
{{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
<ng-template matTreeNodeOutlet></ng-template>
</mat-nested-tree-node>
<mat-nested-tree-node *matTreeNodeDef="let node; when: isSpecial"
matTreeNodeToggle>
>>> {{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
<div *ngIf="treeControl.isExpanded(node)">
<ng-template matTreeNodeOutlet></ng-template>
</div>
</mat-nested-tree-node>
</mat-tree>
`,
standalone: false,
})
class WhenNodeNestedMatTreeApp {
isSpecial = (_: number, node: TestData) => node.isSpecial;
getChildren = (node: TestData) => node.observableChildren;
treeControl: TreeControl<TestData> = new NestedTreeControl(this.getChildren);
dataSource = new MatTreeNestedDataSource();
underlyingDataSource = new FakeDataSource();
@ViewChild(MatTree) tree: MatTree<TestData>;
constructor() {
this.underlyingDataSource.connect().subscribe(data => {
this.dataSource.data = data;
});
}
} | {
"end_byte": 34690,
"start_byte": 27289,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree-using-tree-control.spec.ts"
} |
components/src/material/tree/tree-using-tree-control.spec.ts_34692_38978 | @Component({
template: `
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
<mat-tree-node *matTreeNodeDef="let node" class="customNodeClass"
[isExpandable]="isExpandable(node)"
[isDisabled]="node.isDisabled"
matTreeNodePadding
matTreeNodeToggle [matTreeNodeToggleRecursive]="toggleRecursively">
{{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
</mat-tree-node>
</mat-tree>
`,
standalone: false,
})
class MatTreeAppWithToggle {
toggleRecursively: boolean = true;
getLevel = (node: TestData) => node.level;
isExpandable = (node: TestData) => node.children.length > 0;
getChildren = (node: TestData) => node.observableChildren;
transformer = (node: TestData, level: number) => {
node.level = level;
return node;
};
treeFlattener = new MatTreeFlattener<TestData, TestData>(
this.transformer,
this.getLevel,
this.isExpandable,
this.getChildren,
);
treeControl = new FlatTreeControl(this.getLevel, this.isExpandable);
dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
underlyingDataSource = new FakeDataSource();
@ViewChild(MatTree) tree: MatTree<TestData>;
constructor() {
this.underlyingDataSource.connect().subscribe(data => {
this.dataSource.data = data;
});
}
}
@Component({
template: `
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
<mat-nested-tree-node *matTreeNodeDef="let node" class="customNodeClass"
[isExpandable]="isExpandable(node) | async"
matTreeNodeToggle
[matTreeNodeToggleRecursive]="toggleRecursively">
{{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
<div *ngIf="treeControl.isExpanded(node)">
<ng-template matTreeNodeOutlet></ng-template>
</div>
</mat-nested-tree-node>
</mat-tree>
`,
standalone: false,
})
class NestedMatTreeAppWithToggle {
toggleRecursively: boolean = true;
getChildren = (node: TestData) => node.observableChildren;
isExpandable = (node: TestData) =>
node.observableChildren.pipe(map(children => children.length > 0));
treeControl = new NestedTreeControl(this.getChildren);
dataSource = new MatTreeNestedDataSource();
underlyingDataSource = new FakeDataSource();
@ViewChild(MatTree) tree: MatTree<TestData>;
constructor() {
this.underlyingDataSource.connect().subscribe(data => {
this.dataSource.data = data;
});
}
}
@Component({
template: `
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
<mat-tree-node *matTreeNodeDef="let node" class="customNodeClass"
matTreeNodePadding [matTreeNodePaddingIndent]="28"
matTreeNodeToggle>
{{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
</mat-tree-node>
<mat-tree-node *matTreeNodeDef="let node; when: isSpecial" class="customNodeClass"
matTreeNodePadding [matTreeNodePaddingIndent]="28"
matTreeNodeToggle>
>>> {{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}}
</mat-tree-node>
</mat-tree>
`,
standalone: false,
})
class WhenNodeMatTreeApp {
isSpecial = (_: number, node: TestData) => node.isSpecial;
getLevel = (node: TestData) => node.level;
isExpandable = (node: TestData) => node.children.length > 0;
getChildren = (node: TestData) => node.observableChildren;
transformer = (node: TestData, level: number) => {
node.level = level;
return node;
};
treeFlattener = new MatTreeFlattener<TestData, TestData>(
this.transformer,
this.getLevel,
this.isExpandable,
this.getChildren,
);
treeControl = new FlatTreeControl(this.getLevel, this.isExpandable);
dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
underlyingDataSource = new FakeDataSource();
@ViewChild(MatTree) tree: MatTree<TestData>;
constructor() {
this.underlyingDataSource.connect().subscribe(data => {
this.dataSource.data = data;
});
}
} | {
"end_byte": 38978,
"start_byte": 34692,
"url": "https://github.com/angular/components/blob/main/src/material/tree/tree-using-tree-control.spec.ts"
} |
components/src/material/tree/toggle.ts_0_646 | /**
* @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 {CdkTreeNodeToggle} from '@angular/cdk/tree';
import {Directive} from '@angular/core';
/**
* Wrapper for the CdkTree's toggle with Material design styles.
*/
@Directive({
selector: '[matTreeNodeToggle]',
providers: [{provide: CdkTreeNodeToggle, useExisting: MatTreeNodeToggle}],
inputs: [{name: 'recursive', alias: 'matTreeNodeToggleRecursive'}],
})
export class MatTreeNodeToggle<T, K = T> extends CdkTreeNodeToggle<T, K> {}
| {
"end_byte": 646,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/toggle.ts"
} |
components/src/material/tree/testing/tree-harness.ts_0_4789 | /**
* @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, HarnessPredicate, parallel} from '@angular/cdk/testing';
import {MatTreeNodeHarness} from './node-harness';
import {TreeHarnessFilters, TreeNodeHarnessFilters} from './tree-harness-filters';
export type TextTree = {
text?: string;
children?: TextTree[];
};
/** Harness for interacting with a standard mat-tree in tests. */
export class MatTreeHarness extends ComponentHarness {
/** The selector for the host element of a `MatTableHarness` instance. */
static hostSelector = '.mat-tree';
/**
* Gets a `HarnessPredicate` that can be used to search for a tree with specific attributes.
* @param options Options for narrowing the search
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: TreeHarnessFilters = {}): HarnessPredicate<MatTreeHarness> {
return new HarnessPredicate(MatTreeHarness, options);
}
/** Gets all of the nodes in the tree. */
async getNodes(filter: TreeNodeHarnessFilters = {}): Promise<MatTreeNodeHarness[]> {
return this.locatorForAll(MatTreeNodeHarness.with(filter))();
}
/**
* Gets an object representation for the visible tree structure
* If a node is under an unexpanded node it will not be included.
* Eg.
* Tree (all nodes expanded):
* `
* <mat-tree>
* <mat-tree-node>Node 1<mat-tree-node>
* <mat-nested-tree-node>
* Node 2
* <mat-nested-tree-node>
* Node 2.1
* <mat-tree-node>
* Node 2.1.1
* <mat-tree-node>
* <mat-nested-tree-node>
* <mat-tree-node>
* Node 2.2
* <mat-tree-node>
* <mat-nested-tree-node>
* </mat-tree>`
*
* Tree structure:
* {
* children: [
* {
* text: 'Node 1',
* children: [
* {
* text: 'Node 2',
* children: [
* {
* text: 'Node 2.1',
* children: [{text: 'Node 2.1.1'}]
* },
* {text: 'Node 2.2'}
* ]
* }
* ]
* }
* ]
* };
*/
async getTreeStructure(): Promise<TextTree> {
const nodes = await this.getNodes();
const nodeInformation = await parallel(() =>
nodes.map(node => {
return parallel(() => [node.getLevel(), node.getText(), node.isExpanded()]);
}),
);
return this._getTreeStructure(nodeInformation, 1, true);
}
/**
* Recursively collect the structured text of the tree nodes.
* @param nodes A list of tree nodes
* @param level The level of nodes that are being accounted for during this iteration
* @param parentExpanded Whether the parent of the first node in param nodes is expanded
*/
private _getTreeStructure(
nodes: [number, string, boolean][],
level: number,
parentExpanded: boolean,
): TextTree {
const result: TextTree = {};
for (let i = 0; i < nodes.length; i++) {
const [nodeLevel, text, expanded] = nodes[i];
const nextNodeLevel = nodes[i + 1]?.[0] ?? -1;
// Return the accumulated value for the current level once we reach a shallower level node
if (nodeLevel < level) {
return result;
}
// Skip deeper level nodes during this iteration, they will be picked up in a later iteration
if (nodeLevel > level) {
continue;
}
// Only add to representation if it is visible (parent is expanded)
if (parentExpanded) {
// Collect the data under this node according to the following rules:
// 1. If the next node in the list is a sibling of the current node add it to the child list
// 2. If the next node is a child of the current node, get the sub-tree structure for the
// child and add it under this node
// 3. If the next node has a shallower level, we've reached the end of the child nodes for
// the current parent.
if (nextNodeLevel === level) {
this._addChildToNode(result, {text});
} else if (nextNodeLevel > level) {
let children = this._getTreeStructure(
nodes.slice(i + 1),
nextNodeLevel,
expanded,
)?.children;
let child = children ? {text, children} : {text};
this._addChildToNode(result, child);
} else {
this._addChildToNode(result, {text});
return result;
}
}
}
return result;
}
private _addChildToNode(result: TextTree, child: TextTree) {
result.children ? result.children.push(child) : (result.children = [child]);
}
}
| {
"end_byte": 4789,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/testing/tree-harness.ts"
} |
components/src/material/tree/testing/tree-harness-filters.ts_0_944 | /**
* @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 tree harness instances */
export interface TreeHarnessFilters extends BaseHarnessFilters {}
/** A set of criteria that can be used to filter a list of node harness instances. */
export interface TreeNodeHarnessFilters extends BaseHarnessFilters {
/** Only find instances whose text matches the given value. */
text?: string | RegExp;
/** Only find instances whose disabled state matches the given value. */
disabled?: boolean;
/** Only find instances whose expansion state matches the given value. */
expanded?: boolean;
/** Only find instances whose level matches the given value. */
level?: number;
}
| {
"end_byte": 944,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/testing/tree-harness-filters.ts"
} |
components/src/material/tree/testing/public-api.ts_0_308 | /**
* @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 './node-harness';
export * from './tree-harness';
export * from './tree-harness-filters';
| {
"end_byte": 308,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/testing/public-api.ts"
} |
components/src/material/tree/testing/tree-harness.spec.ts_0_6714 | import {Component} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {FlatTreeControl, NestedTreeControl} from '@angular/cdk/tree';
import {
MatTreeFlatDataSource,
MatTreeFlattener,
MatTreeModule,
MatTreeNestedDataSource,
} from '@angular/material/tree';
import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {MatTreeHarness} from './tree-harness';
describe('MatTreeHarness', () => {
let fixture: ComponentFixture<TreeHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatTreeModule, TreeHarnessTest],
});
fixture = TestBed.createComponent(TreeHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load harness with 2 tress', async () => {
const trees = await loader.getAllHarnesses(MatTreeHarness);
expect(trees.length).toBe(2);
});
it('should get correct number of children and descendants', async () => {
const trees = await loader.getAllHarnesses(MatTreeHarness);
const flatTree = trees[0];
const nestedTree = trees[1];
const flatTreeDescendants = await flatTree.getNodes();
const nestedDescendants = await nestedTree.getNodes();
// flat nodes are not rendered until expanded
expect(flatTreeDescendants.length).toBe(2);
await flatTreeDescendants[0].expand();
expect((await flatTree.getNodes()).length).toBe(5);
expect(nestedDescendants.length).toBe(8);
});
it('should correctly get correct node with text (flat tree)', async () => {
const trees = await loader.getAllHarnesses(MatTreeHarness);
const flatTree = trees[0];
const flatTreeNodes = await flatTree.getNodes({text: /Flat Group/});
expect(flatTreeNodes.length).toBe(2);
const secondGroup = flatTreeNodes[0];
expect(await secondGroup.getText()).toBe('Flat Group 1');
expect(await secondGroup.getLevel()).toBe(1);
expect(await secondGroup.isDisabled()).toBe(false);
expect(await secondGroup.isExpanded()).toBe(false);
});
it('should correctly get correct node with text (nested tree)', async () => {
const trees = await loader.getAllHarnesses(MatTreeHarness);
const nestedTree = trees[1];
const nestedTreeNodes = await nestedTree.getNodes({text: /2./});
expect(nestedTreeNodes.length).toBe(3);
const thirdGroup = nestedTreeNodes[1];
expect(await thirdGroup.getText()).toBe('Nested Leaf 2.1.1');
expect(await thirdGroup.getLevel()).toBe(3);
expect(await thirdGroup.isDisabled()).toBe(false);
expect(await thirdGroup.isExpanded()).toBe(false);
});
it('should toggle expansion', async () => {
const trees = await loader.getAllHarnesses(MatTreeHarness);
const nestedTree = trees[1];
const nestedTreeNodes = await nestedTree.getNodes();
const firstGroup = nestedTreeNodes[0];
expect(await firstGroup.isExpanded()).toBe(false);
await firstGroup.expand();
expect(await firstGroup.isExpanded()).toBe(true);
await firstGroup.expand();
// no-op if already expanded
expect(await firstGroup.isExpanded()).toBe(true);
await firstGroup.collapse();
expect(await firstGroup.isExpanded()).toBe(false);
await firstGroup.collapse();
// no-op if already collapsed
expect(await firstGroup.isExpanded()).toBe(false);
});
it('should correctly get tree structure', async () => {
const trees = await loader.getAllHarnesses(MatTreeHarness);
const flatTree = trees[0];
expect(await flatTree.getTreeStructure()).toEqual({
children: [{text: 'Flat Group 1'}, {text: 'Flat Group 2'}],
});
const firstGroup = (await flatTree.getNodes({text: /Flat Group 1/}))[0];
await firstGroup.expand();
expect(await flatTree.getTreeStructure()).toEqual({
children: [
{
text: 'Flat Group 1',
children: [{text: 'Flat Leaf 1.1'}, {text: 'Flat Leaf 1.2'}, {text: 'Flat Leaf 1.3'}],
},
{text: 'Flat Group 2'},
],
});
const secondGroup = (await flatTree.getNodes({text: /Flat Group 2/}))[0];
await secondGroup.expand();
expect(await flatTree.getTreeStructure()).toEqual({
children: [
{
text: 'Flat Group 1',
children: [{text: 'Flat Leaf 1.1'}, {text: 'Flat Leaf 1.2'}, {text: 'Flat Leaf 1.3'}],
},
{
text: 'Flat Group 2',
children: [{text: 'Flat Group 2.1'}],
},
],
});
});
it('should correctly get tree structure', async () => {
const trees = await loader.getAllHarnesses(MatTreeHarness);
const nestedTree = trees[1];
expect(await nestedTree.getTreeStructure()).toEqual({
children: [{text: 'Nested Group 1'}, {text: 'Nested Group 2'}],
});
const firstGroup = (await nestedTree.getNodes({text: /Nested Group 1/}))[0];
await firstGroup.expand();
expect(await nestedTree.getTreeStructure()).toEqual({
children: [
{
text: 'Nested Group 1',
children: [
{text: 'Nested Leaf 1.1'},
{text: 'Nested Leaf 1.2'},
{text: 'Nested Leaf 1.3'},
],
},
{text: 'Nested Group 2'},
],
});
const secondGroup = (await nestedTree.getNodes({text: /Nested Group 2/}))[0];
await secondGroup.expand();
expect(await nestedTree.getTreeStructure()).toEqual({
children: [
{
text: 'Nested Group 1',
children: [
{text: 'Nested Leaf 1.1'},
{text: 'Nested Leaf 1.2'},
{text: 'Nested Leaf 1.3'},
],
},
{
text: 'Nested Group 2',
children: [{text: 'Nested Group 2.1'}],
},
],
});
});
});
interface Node {
name: string;
children?: Node[];
}
const FLAT_TREE_DATA: Node[] = [
{
name: 'Flat Group 1',
children: [{name: 'Flat Leaf 1.1'}, {name: 'Flat Leaf 1.2'}, {name: 'Flat Leaf 1.3'}],
},
{
name: 'Flat Group 2',
children: [
{
name: 'Flat Group 2.1',
children: [{name: 'Flat Leaf 2.1.1'}, {name: 'Flat Leaf 2.1.2'}, {name: 'Flat Leaf 2.1.3'}],
},
],
},
];
const NESTED_TREE_DATA: Node[] = [
{
name: 'Nested Group 1',
children: [{name: 'Nested Leaf 1.1'}, {name: 'Nested Leaf 1.2'}, {name: 'Nested Leaf 1.3'}],
},
{
name: 'Nested Group 2',
children: [
{
name: 'Nested Group 2.1',
children: [{name: 'Nested Leaf 2.1.1'}, {name: 'Nested Leaf 2.1.2'}],
},
],
},
];
interface ExampleFlatNode {
expandable: boolean;
name: string;
level: number;
} | {
"end_byte": 6714,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/testing/tree-harness.spec.ts"
} |
components/src/material/tree/testing/tree-harness.spec.ts_6716_9077 | @Component({
template: `
<mat-tree [dataSource]="flatTreeDataSource" [treeControl]="flatTreeControl">
<!-- This is the tree node template for leaf nodes -->
<mat-tree-node *matTreeNodeDef="let node" matTreeNodePadding>
{{node.name}}
</mat-tree-node>
<!-- This is the tree node template for expandable nodes -->
<mat-tree-node *matTreeNodeDef="let node;when: flatTreeHasChild" matTreeNodePadding isExpandable>
<button matTreeNodeToggle>
Toggle
</button>
{{node.name}}
</mat-tree-node>
</mat-tree>
<mat-tree [dataSource]="nestedTreeDataSource" [treeControl]="nestedTreeControl">
<!-- This is the tree node template for leaf nodes -->
<mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle>
{{node.name}}
</mat-tree-node>
<!-- This is the tree node template for expandable nodes -->
<mat-nested-tree-node *matTreeNodeDef="let node; when: nestedTreeHasChild" isExpandable>
<button matTreeNodeToggle>
Toggle
</button>
{{node.name}}
<ul [class.example-tree-invisible]="!nestedTreeControl.isExpanded(node)">
<ng-container matTreeNodeOutlet></ng-container>
</ul>
</mat-nested-tree-node>
</mat-tree>
`,
standalone: true,
imports: [MatTreeModule],
})
class TreeHarnessTest {
private _transformer = (node: Node, level: number) => {
return {
expandable: !!node.children && node.children.length > 0,
name: node.name,
level: level,
};
};
treeFlattener = new MatTreeFlattener(
this._transformer,
node => node.level,
node => node.expandable,
node => node.children,
);
flatTreeControl = new FlatTreeControl<ExampleFlatNode>(
node => node.level,
node => node.expandable,
);
flatTreeDataSource = new MatTreeFlatDataSource(this.flatTreeControl, this.treeFlattener);
nestedTreeControl = new NestedTreeControl<Node>(node => node.children);
nestedTreeDataSource = new MatTreeNestedDataSource<Node>();
constructor() {
this.flatTreeDataSource.data = FLAT_TREE_DATA;
this.nestedTreeDataSource.data = NESTED_TREE_DATA;
}
flatTreeHasChild = (_: number, node: ExampleFlatNode) => node.expandable;
nestedTreeHasChild = (_: number, node: Node) => !!node.children && node.children.length > 0;
} | {
"end_byte": 9077,
"start_byte": 6716,
"url": "https://github.com/angular/components/blob/main/src/material/tree/testing/tree-harness.spec.ts"
} |
components/src/material/tree/testing/BUILD.bazel_0_732 | 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/cdk/tree",
"//src/material/tree",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_tests_lib"],
)
| {
"end_byte": 732,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/testing/BUILD.bazel"
} |
components/src/material/tree/testing/node-harness.ts_0_3510 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ComponentHarnessConstructor,
ContentContainerComponentHarness,
HarnessPredicate,
} from '@angular/cdk/testing';
import {TreeNodeHarnessFilters} from './tree-harness-filters';
import {coerceBooleanProperty, coerceNumberProperty} from '@angular/cdk/coercion';
/** Harness for interacting with a standard Angular Material tree node. */
export class MatTreeNodeHarness extends ContentContainerComponentHarness<string> {
/** The selector of the host element of a `MatTreeNode` instance. */
static hostSelector = '.mat-tree-node, .mat-nested-tree-node';
_toggle = this.locatorForOptional('[matTreeNodeToggle]');
/**
* Gets a `HarnessPredicate` that can be used to search for a tree node with specific attributes.
* @param options Options for narrowing the search
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: TreeNodeHarnessFilters = {}): HarnessPredicate<MatTreeNodeHarness> {
return getNodePredicate(MatTreeNodeHarness, options);
}
/** Whether the tree node is expanded. */
async isExpanded(): Promise<boolean> {
return coerceBooleanProperty(await (await this.host()).getAttribute('aria-expanded'));
}
/** Whether the tree node is expandable. */
async isExpandable(): Promise<boolean> {
return (await (await this.host()).getAttribute('aria-expanded')) !== null;
}
/** Whether the tree node is disabled. */
async isDisabled(): Promise<boolean> {
return coerceBooleanProperty(await (await this.host()).getProperty('aria-disabled'));
}
/** Gets the level of the tree node. Note that this gets the aria-level and is 1 indexed. */
async getLevel(): Promise<number> {
return coerceNumberProperty(await (await this.host()).getAttribute('aria-level'));
}
/** Gets the tree node's text. */
async getText(): Promise<string> {
return (await this.host()).text({exclude: '.mat-tree-node, .mat-nested-tree-node, button'});
}
/** Toggles node between expanded/collapsed. Only works when node is not disabled. */
async toggle(): Promise<void> {
const toggle = await this._toggle();
if (toggle) {
return toggle.click();
}
}
/** Expands the node if it is collapsed. Only works when node is not disabled. */
async expand(): Promise<void> {
if (!(await this.isExpanded())) {
await this.toggle();
}
}
/** Collapses the node if it is expanded. Only works when node is not disabled. */
async collapse(): Promise<void> {
if (await this.isExpanded()) {
await this.toggle();
}
}
}
function getNodePredicate<T extends MatTreeNodeHarness>(
type: ComponentHarnessConstructor<T>,
options: TreeNodeHarnessFilters,
): HarnessPredicate<T> {
return new HarnessPredicate(type, options)
.addOption('text', options.text, (harness, text) =>
HarnessPredicate.stringMatches(harness.getText(), text),
)
.addOption(
'disabled',
options.disabled,
async (harness, disabled) => (await harness.isDisabled()) === disabled,
)
.addOption(
'expanded',
options.expanded,
async (harness, expanded) => (await harness.isExpanded()) === expanded,
)
.addOption(
'level',
options.level,
async (harness, level) => (await harness.getLevel()) === level,
);
}
| {
"end_byte": 3510,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/testing/node-harness.ts"
} |
components/src/material/tree/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/tree/testing/index.ts"
} |
components/src/material/tree/data-source/flat-data-source.ts_0_5455 | /**
* @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 {CollectionViewer, DataSource} from '@angular/cdk/collections';
import {FlatTreeControl, TreeControl} from '@angular/cdk/tree';
import {BehaviorSubject, merge, Observable} from 'rxjs';
import {map, take} from 'rxjs/operators';
/**
* Tree flattener to convert a normal type of node to node with children & level information.
* Transform nested nodes of type `T` to flattened nodes of type `F`.
*
* For example, the input data of type `T` is nested, and contains its children data:
* SomeNode: {
* key: 'Fruits',
* children: [
* NodeOne: {
* key: 'Apple',
* },
* NodeTwo: {
* key: 'Pear',
* }
* ]
* }
* After flattener flatten the tree, the structure will become
* SomeNode: {
* key: 'Fruits',
* expandable: true,
* level: 1
* },
* NodeOne: {
* key: 'Apple',
* expandable: false,
* level: 2
* },
* NodeTwo: {
* key: 'Pear',
* expandable: false,
* level: 2
* }
* and the output flattened type is `F` with additional information.
*
* @deprecated Use MatTree#childrenAccessor and MatTreeNode#isExpandable
* instead. To be removed in a future version.
* @breaking-change 21.0.0
*/
export class MatTreeFlattener<T, F, K = F> {
constructor(
public transformFunction: (node: T, level: number) => F,
public getLevel: (node: F) => number,
public isExpandable: (node: F) => boolean,
public getChildren: (node: T) => Observable<T[]> | T[] | undefined | null,
) {}
_flattenNode(node: T, level: number, resultNodes: F[], parentMap: boolean[]): F[] {
const flatNode = this.transformFunction(node, level);
resultNodes.push(flatNode);
if (this.isExpandable(flatNode)) {
const childrenNodes = this.getChildren(node);
if (childrenNodes) {
if (Array.isArray(childrenNodes)) {
this._flattenChildren(childrenNodes, level, resultNodes, parentMap);
} else {
childrenNodes.pipe(take(1)).subscribe(children => {
this._flattenChildren(children, level, resultNodes, parentMap);
});
}
}
}
return resultNodes;
}
_flattenChildren(children: T[], level: number, resultNodes: F[], parentMap: boolean[]): void {
children.forEach((child, index) => {
let childParentMap: boolean[] = parentMap.slice();
childParentMap.push(index != children.length - 1);
this._flattenNode(child, level + 1, resultNodes, childParentMap);
});
}
/**
* Flatten a list of node type T to flattened version of node F.
* Please note that type T may be nested, and the length of `structuredData` may be different
* from that of returned list `F[]`.
*/
flattenNodes(structuredData: T[]): F[] {
let resultNodes: F[] = [];
structuredData.forEach(node => this._flattenNode(node, 0, resultNodes, []));
return resultNodes;
}
/**
* Expand flattened node with current expansion status.
* The returned list may have different length.
*/
expandFlattenedNodes(nodes: F[], treeControl: TreeControl<F, K>): F[] {
let results: F[] = [];
let currentExpand: boolean[] = [];
currentExpand[0] = true;
nodes.forEach(node => {
let expand = true;
for (let i = 0; i <= this.getLevel(node); i++) {
expand = expand && currentExpand[i];
}
if (expand) {
results.push(node);
}
if (this.isExpandable(node)) {
currentExpand[this.getLevel(node) + 1] = treeControl.isExpanded(node);
}
});
return results;
}
}
/**
* Data source for flat tree.
* The data source need to handle expansion/collapsion of the tree node and change the data feed
* to `MatTree`.
* The nested tree nodes of type `T` are flattened through `MatTreeFlattener`, and converted
* to type `F` for `MatTree` to consume.
*
* @deprecated Use one of levelAccessor or childrenAccessor instead. To be removed in a future
* version.
* @breaking-change 21.0.0
*/
export class MatTreeFlatDataSource<T, F, K = F> extends DataSource<F> {
private readonly _flattenedData = new BehaviorSubject<F[]>([]);
private readonly _expandedData = new BehaviorSubject<F[]>([]);
get data() {
return this._data.value;
}
set data(value: T[]) {
this._data.next(value);
this._flattenedData.next(this._treeFlattener.flattenNodes(this.data));
this._treeControl.dataNodes = this._flattenedData.value;
}
private readonly _data = new BehaviorSubject<T[]>([]);
constructor(
private _treeControl: FlatTreeControl<F, K>,
private _treeFlattener: MatTreeFlattener<T, F, K>,
initialData?: T[],
) {
super();
if (initialData) {
// Assign the data through the constructor to ensure that all of the logic is executed.
this.data = initialData;
}
}
connect(collectionViewer: CollectionViewer): Observable<F[]> {
return merge(
collectionViewer.viewChange,
this._treeControl.expansionModel.changed,
this._flattenedData,
).pipe(
map(() => {
this._expandedData.next(
this._treeFlattener.expandFlattenedNodes(this._flattenedData.value, this._treeControl),
);
return this._expandedData.value;
}),
);
}
disconnect() {
// no op
}
}
| {
"end_byte": 5455,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/data-source/flat-data-source.ts"
} |
components/src/material/tree/data-source/nested-data-source.ts_0_1111 | /**
* @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 {CollectionViewer, DataSource} from '@angular/cdk/collections';
import {BehaviorSubject, merge, Observable} from 'rxjs';
import {map} from 'rxjs/operators';
/**
* Data source for nested tree.
*
* The data source for nested tree doesn't have to consider node flattener, or the way to expand
* or collapse. The expansion/collapsion will be handled by TreeControl and each non-leaf node.
*/
export class MatTreeNestedDataSource<T> extends DataSource<T> {
/**
* Data for the nested tree
*/
get data() {
return this._data.value;
}
set data(value: T[]) {
this._data.next(value);
}
private readonly _data = new BehaviorSubject<T[]>([]);
connect(collectionViewer: CollectionViewer): Observable<T[]> {
return merge(...([collectionViewer.viewChange, this._data] as Observable<unknown>[])).pipe(
map(() => this.data),
);
}
disconnect() {
// no op
}
}
| {
"end_byte": 1111,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tree/data-source/nested-data-source.ts"
} |
components/src/material/timepicker/_timepicker-theme.scss_0_4483 | @use 'sass:map';
@use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/typography/typography';
@use '../core/style/sass-utils';
@use '../core/tokens/m2/mat/timepicker' as tokens-mat-timepicker;
@use '../core/tokens/token-utils';
/// Outputs base theme styles (styles not dependent on the color, typography, or density settings)
/// for the mat-timepicker.
/// @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-mat-timepicker.$prefix,
tokens-mat-timepicker.get-unthemable-tokens()
);
}
}
}
/// Outputs color theme styles for the mat-timepicker.
/// @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 main selection: 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-mat-timepicker.$prefix,
tokens-mat-timepicker.get-color-tokens($theme)
);
}
}
}
/// Outputs typography theme styles for the mat-timepicker.
/// @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-timepicker.$prefix,
tokens-mat-timepicker.get-typography-tokens($theme)
);
}
}
}
/// Outputs density theme styles for the mat-timepicker.
/// @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-timepicker.$prefix,
tokens-mat-timepicker.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-timepicker.$prefix,
tokens: tokens-mat-timepicker.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-timepicker.
/// @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 main selection: primary, secondary, tertiary,
/// or error (If not specified, default primary color will be used).
@mixin theme($theme) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-timepicker') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme));
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
@if ($tokens != ()) {
@include token-utils.create-token-values(
tokens-mat-timepicker.$prefix,
map.get($tokens, tokens-mat-timepicker.$prefix)
);
}
}
| {
"end_byte": 4483,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/_timepicker-theme.scss"
} |
components/src/material/timepicker/timepicker-input.ts_0_2146 | /**
* @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,
computed,
Directive,
effect,
ElementRef,
inject,
input,
InputSignal,
InputSignalWithTransform,
model,
ModelSignal,
OnDestroy,
OutputRefSubscription,
Signal,
signal,
} from '@angular/core';
import {DateAdapter, MAT_DATE_FORMATS} from '@angular/material/core';
import {
AbstractControl,
ControlValueAccessor,
NG_VALIDATORS,
NG_VALUE_ACCESSOR,
ValidationErrors,
Validator,
ValidatorFn,
Validators,
} from '@angular/forms';
import {MAT_FORM_FIELD} from '@angular/material/form-field';
import {MatTimepicker} from './timepicker';
import {MAT_INPUT_VALUE_ACCESSOR} from '@angular/material/input';
import {Subscription} from 'rxjs';
import {DOWN_ARROW, ESCAPE, hasModifierKey, UP_ARROW} from '@angular/cdk/keycodes';
import {validateAdapter} from './util';
import {DOCUMENT} from '@angular/common';
/**
* Input that can be used to enter time and connect to a `mat-timepicker`.
*/
@Directive({
selector: 'input[matTimepicker]',
exportAs: 'matTimepickerInput',
host: {
'class': 'mat-timepicker-input',
'role': 'combobox',
'type': 'text',
'aria-haspopup': 'listbox',
'[attr.aria-activedescendant]': '_ariaActiveDescendant()',
'[attr.aria-expanded]': '_ariaExpanded()',
'[attr.aria-controls]': '_ariaControls()',
'[attr.mat-timepicker-id]': 'timepicker()?.panelId',
'[disabled]': 'disabled()',
'(blur)': '_handleBlur()',
'(input)': '_handleInput($event.target.value)',
'(keydown)': '_handleKeydown($event)',
},
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: MatTimepickerInput,
multi: true,
},
{
provide: NG_VALIDATORS,
useExisting: MatTimepickerInput,
multi: true,
},
{
provide: MAT_INPUT_VALUE_ACCESSOR,
useExisting: MatTimepickerInput,
},
],
})
export class MatTimepickerInput<D> implements ControlValueAccessor, Validator, OnDestroy | {
"end_byte": 2146,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker-input.ts"
} |
components/src/material/timepicker/timepicker-input.ts_2147_10514 | {
private _elementRef = inject<ElementRef<HTMLInputElement>>(ElementRef);
private _document = inject(DOCUMENT);
private _dateAdapter = inject<DateAdapter<D>>(DateAdapter, {optional: true})!;
private _dateFormats = inject(MAT_DATE_FORMATS, {optional: true})!;
private _formField = inject(MAT_FORM_FIELD, {optional: true});
private _onChange: ((value: any) => void) | undefined;
private _onTouched: (() => void) | undefined;
private _validatorOnChange: (() => void) | undefined;
private _accessorDisabled = signal(false);
private _localeSubscription: Subscription;
private _timepickerSubscription: OutputRefSubscription | undefined;
private _validator: ValidatorFn;
private _lastValueValid = false;
private _lastValidDate: D | null = null;
/** Value of the `aria-activedescendant` attribute. */
protected readonly _ariaActiveDescendant = computed(() => {
const timepicker = this.timepicker();
const isOpen = timepicker.isOpen();
const activeDescendant = timepicker.activeDescendant();
return isOpen && activeDescendant ? activeDescendant : null;
});
/** Value of the `aria-expanded` attribute. */
protected readonly _ariaExpanded = computed(() => this.timepicker().isOpen() + '');
/** Value of the `aria-controls` attribute. */
protected readonly _ariaControls = computed(() => {
const timepicker = this.timepicker();
return timepicker.isOpen() ? timepicker.panelId : null;
});
/** Current value of the input. */
readonly value: ModelSignal<D | null> = model<D | null>(null);
/** Timepicker that the input is associated with. */
readonly timepicker: InputSignal<MatTimepicker<D>> = input.required<MatTimepicker<D>>({
alias: 'matTimepicker',
});
/**
* Minimum time that can be selected or typed in. Can be either
* a date object (only time will be used) or a valid time string.
*/
readonly min: InputSignalWithTransform<D | null, unknown> = input(null, {
alias: 'matTimepickerMin',
transform: (value: unknown) => this._transformDateInput<D>(value),
});
/**
* Maximum time that can be selected or typed in. Can be either
* a date object (only time will be used) or a valid time string.
*/
readonly max: InputSignalWithTransform<D | null, unknown> = input(null, {
alias: 'matTimepickerMax',
transform: (value: unknown) => this._transformDateInput<D>(value),
});
/** Whether the input is disabled. */
readonly disabled: Signal<boolean> = computed(
() => this.disabledInput() || this._accessorDisabled(),
);
/** Whether the input should be disabled through the template. */
protected readonly disabledInput: InputSignalWithTransform<boolean, unknown> = input(false, {
transform: booleanAttribute,
alias: 'disabled',
});
constructor() {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
validateAdapter(this._dateAdapter, this._dateFormats);
}
this._validator = this._getValidator();
this._respondToValueChanges();
this._respondToMinMaxChanges();
this._registerTimepicker();
this._localeSubscription = this._dateAdapter.localeChanges.subscribe(() => {
if (!this._hasFocus()) {
this._formatValue(this.value());
}
});
// Bind the click listener manually to the overlay origin, because we want the entire
// form field to be clickable, if the timepicker is used in `mat-form-field`.
this.getOverlayOrigin().nativeElement.addEventListener('click', this._handleClick);
}
/**
* Implemented as a part of `ControlValueAccessor`.
* @docs-private
*/
writeValue(value: any): void {
this.value.set(this._dateAdapter.getValidDateOrNull(value));
}
/**
* Implemented as a part of `ControlValueAccessor`.
* @docs-private
*/
registerOnChange(fn: (value: any) => void): void {
this._onChange = fn;
}
/**
* Implemented as a part of `ControlValueAccessor`.
* @docs-private
*/
registerOnTouched(fn: () => void): void {
this._onTouched = fn;
}
/**
* Implemented as a part of `ControlValueAccessor`.
* @docs-private
*/
setDisabledState(isDisabled: boolean): void {
this._accessorDisabled.set(isDisabled);
}
/**
* Implemented as a part of `Validator`.
* @docs-private
*/
validate(control: AbstractControl): ValidationErrors | null {
return this._validator(control);
}
/**
* Implemented as a part of `Validator`.
* @docs-private
*/
registerOnValidatorChange(fn: () => void): void {
this._validatorOnChange = fn;
}
/** Gets the element to which the timepicker popup should be attached. */
getOverlayOrigin(): ElementRef<HTMLElement> {
return this._formField?.getConnectedOverlayOrigin() || this._elementRef;
}
/** Focuses the input. */
focus(): void {
this._elementRef.nativeElement.focus();
}
ngOnDestroy(): void {
this.getOverlayOrigin().nativeElement.removeEventListener('click', this._handleClick);
this._timepickerSubscription?.unsubscribe();
this._localeSubscription.unsubscribe();
}
/** Gets the ID of the input's label. */
_getLabelId(): string | null {
return this._formField?.getLabelId() || null;
}
/** Handles clicks on the input or the containing form field. */
private _handleClick = (): void => {
this.timepicker().open();
};
/** Handles the `input` event. */
protected _handleInput(value: string) {
const currentValue = this.value();
const date = this._dateAdapter.parseTime(value, this._dateFormats.parse.timeInput);
const hasChanged = !this._dateAdapter.sameTime(date, currentValue);
if (!date || hasChanged || !!(value && !currentValue)) {
// We need to fire the CVA change event for all nulls, otherwise the validators won't run.
this._assignUserSelection(date, true);
} else {
// Call the validator even if the value hasn't changed since
// some fields change depending on what the user has entered.
this._validatorOnChange?.();
}
}
/** Handles the `blur` event. */
protected _handleBlur() {
const value = this.value();
// Only reformat on blur so the value doesn't change while the user is interacting.
if (value && this._isValid(value)) {
this._formatValue(value);
}
this._onTouched?.();
}
/** Handles the `keydown` event. */
protected _handleKeydown(event: KeyboardEvent) {
// All keyboard events while open are handled through the timepicker.
if (this.timepicker().isOpen()) {
return;
}
if (event.keyCode === ESCAPE && !hasModifierKey(event) && this.value() !== null) {
event.preventDefault();
this.value.set(null);
this._formatValue(null);
} else if ((event.keyCode === DOWN_ARROW || event.keyCode === UP_ARROW) && !this.disabled()) {
event.preventDefault();
this.timepicker().open();
}
}
/** Sets up the code that watches for changes in the value and adjusts the input. */
private _respondToValueChanges(): void {
effect(() => {
const value = this._dateAdapter.deserialize(this.value());
const wasValid = this._lastValueValid;
this._lastValueValid = this._isValid(value);
// Reformat the value if it changes while the user isn't interacting.
if (!this._hasFocus()) {
this._formatValue(value);
}
if (value && this._lastValueValid) {
this._lastValidDate = value;
}
// Trigger the validator if the state changed.
if (wasValid !== this._lastValueValid) {
this._validatorOnChange?.();
}
});
}
/** Sets up the logic that registers the input with the timepicker. */
private _registerTimepicker(): void {
effect(() => {
const timepicker = this.timepicker();
timepicker.registerInput(this);
timepicker.closed.subscribe(() => this._onTouched?.());
timepicker.selected.subscribe(({value}) => {
if (!this._dateAdapter.sameTime(value, this.value())) {
this._assignUserSelection(value, true);
this._formatValue(value);
}
});
});
}
/** Sets up the logic that adjusts the input if the min/max changes. */
private _respondToMinMaxChanges(): void {
effect(() => {
// Read the min/max so the effect knows when to fire.
this.min();
this.max();
this._validatorOnChange?.();
});
} | {
"end_byte": 10514,
"start_byte": 2147,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker-input.ts"
} |
components/src/material/timepicker/timepicker-input.ts_10518_13904 | /**
* Assigns a value set by the user to the input's model.
* @param selection Time selected by the user that should be assigned.
* @param propagateToAccessor Whether the value should be propagated to the ControlValueAccessor.
*/
private _assignUserSelection(selection: D | null, propagateToAccessor: boolean) {
if (selection == null || !this._isValid(selection)) {
this.value.set(selection);
} else {
// If a datepicker and timepicker are writing to the same object and the user enters an
// invalid time into the timepicker, we may end up clearing their selection from the
// datepicker. If the user enters a valid time afterwards, the datepicker's selection will
// have been lost. This logic restores the previously-valid date and sets its time to
// the newly-selected time.
const adapter = this._dateAdapter;
const target = adapter.getValidDateOrNull(this._lastValidDate || this.value());
const hours = adapter.getHours(selection);
const minutes = adapter.getMinutes(selection);
const seconds = adapter.getSeconds(selection);
this.value.set(target ? adapter.setTime(target, hours, minutes, seconds) : selection);
}
if (propagateToAccessor) {
this._onChange?.(this.value());
}
}
/** Formats the current value and assigns it to the input. */
private _formatValue(value: D | null): void {
value = this._dateAdapter.getValidDateOrNull(value);
this._elementRef.nativeElement.value =
value == null ? '' : this._dateAdapter.format(value, this._dateFormats.display.timeInput);
}
/** Checks whether a value is valid. */
private _isValid(value: D | null): boolean {
return !value || this._dateAdapter.isValid(value);
}
/** Transforms an arbitrary value into a value that can be assigned to a date-based input. */
private _transformDateInput<D>(value: unknown): D | null {
const date =
typeof value === 'string'
? this._dateAdapter.parseTime(value, this._dateFormats.parse.timeInput)
: this._dateAdapter.deserialize(value);
return date && this._dateAdapter.isValid(date) ? (date as D) : null;
}
/** Whether the input is currently focused. */
private _hasFocus(): boolean {
return this._document.activeElement === this._elementRef.nativeElement;
}
/** Gets a function that can be used to validate the input. */
private _getValidator(): ValidatorFn {
return Validators.compose([
() =>
this._lastValueValid
? null
: {'matTimepickerParse': {'text': this._elementRef.nativeElement.value}},
control => {
const controlValue = this._dateAdapter.getValidDateOrNull(
this._dateAdapter.deserialize(control.value),
);
const min = this.min();
return !min || !controlValue || this._dateAdapter.compareTime(min, controlValue) <= 0
? null
: {'matTimepickerMin': {'min': min, 'actual': controlValue}};
},
control => {
const controlValue = this._dateAdapter.getValidDateOrNull(
this._dateAdapter.deserialize(control.value),
);
const max = this.max();
return !max || !controlValue || this._dateAdapter.compareTime(max, controlValue) >= 0
? null
: {'matTimepickerMax': {'max': max, 'actual': controlValue}};
},
])!;
}
} | {
"end_byte": 13904,
"start_byte": 10518,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker-input.ts"
} |
components/src/material/timepicker/timepicker.md_0_5 | TODO
| {
"end_byte": 5,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker.md"
} |
components/src/material/timepicker/timepicker.spec.ts_0_5040 | import {Component, Provider, signal, ViewChild} from '@angular/core';
import {ComponentFixture, fakeAsync, flush, TestBed} from '@angular/core/testing';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {DateAdapter, provideNativeDateAdapter} from '@angular/material/core';
import {
clearElement,
dispatchFakeEvent,
dispatchKeyboardEvent,
typeInElement,
} from '@angular/cdk/testing/private';
import {
DOWN_ARROW,
END,
ENTER,
ESCAPE,
HOME,
LEFT_ARROW,
PAGE_DOWN,
PAGE_UP,
RIGHT_ARROW,
TAB,
UP_ARROW,
} from '@angular/cdk/keycodes';
import {MatInput} from '@angular/material/input';
import {MatFormField, MatLabel, MatSuffix} from '@angular/material/form-field';
import {MatTimepickerInput} from './timepicker-input';
import {MatTimepicker} from './timepicker';
import {MatTimepickerToggle} from './timepicker-toggle';
import {MAT_TIMEPICKER_CONFIG, MatTimepickerOption} from './util';
import {FormControl, ReactiveFormsModule, Validators} from '@angular/forms';
describe('MatTimepicker', () => {
let adapter: DateAdapter<Date>;
beforeEach(() => configureTestingModule());
describe('value selection', () => {
it('should only change the time part of the selected date', fakeAsync(() => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.value.set(new Date(2024, 0, 15, 0, 0, 0));
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
getOptions()[3].click();
fixture.detectChanges();
flush();
const value = fixture.componentInstance.input.value()!;
expect(value).toBeTruthy();
expect(adapter.getYear(value)).toBe(2024);
expect(adapter.getMonth(value)).toBe(0);
expect(adapter.getDate(value)).toBe(15);
expect(adapter.getHours(value)).toBe(1);
expect(adapter.getMinutes(value)).toBe(30);
expect(adapter.getSeconds(value)).toBe(0);
}));
it('should accept the selected value and close the panel when clicking an option', fakeAsync(() => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
expect(input.value).toBe('');
expect(fixture.componentInstance.input.value()).toBe(null);
expect(fixture.componentInstance.selectedSpy).not.toHaveBeenCalled();
input.click();
fixture.detectChanges();
getOptions()[1].click();
fixture.detectChanges();
flush();
expect(getPanel()).toBeFalsy();
expect(input.value).toBe('12:30 AM');
expect(fixture.componentInstance.input.value()).toEqual(createTime(0, 30));
expect(fixture.componentInstance.selectedSpy).toHaveBeenCalledTimes(1);
expect(fixture.componentInstance.selectedSpy).toHaveBeenCalledWith(
jasmine.objectContaining({
source: fixture.componentInstance.timepicker,
value: jasmine.any(Date),
}),
);
}));
it('should support two-way binding on the `value` input', fakeAsync(() => {
const fixture = TestBed.createComponent(TimepickerTwoWayBinding);
const input = getInput(fixture);
fixture.detectChanges();
const inputInstance = fixture.componentInstance.input;
// Initial value
expect(fixture.componentInstance.value).toBeTruthy();
expect(inputInstance.value()).toEqual(fixture.componentInstance.value());
// Propagation from input back to host
clearElement(input);
typeInElement(input, '11:15 AM');
fixture.detectChanges();
let value = inputInstance.value()!;
expect(adapter.getHours(value)).toBe(11);
expect(adapter.getMinutes(value)).toBe(15);
expect(fixture.componentInstance.value()).toEqual(value);
// Propagation from host down to input
fixture.componentInstance.value.set(createTime(13, 37));
fixture.detectChanges();
flush();
value = inputInstance.value()!;
expect(adapter.getHours(value)).toBe(13);
expect(adapter.getMinutes(value)).toBe(37);
expect(value).toEqual(fixture.componentInstance.value());
}));
it('should emit the `selected` event if the option being clicked was selected already', fakeAsync(() => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.value.set(new Date(2024, 0, 15, 2, 30, 0));
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
expect(fixture.componentInstance.selectedSpy).not.toHaveBeenCalled();
getOptions()[getActiveOptionIndex()].click();
fixture.detectChanges();
flush();
expect(getPanel()).toBeFalsy();
expect(fixture.componentInstance.selectedSpy).toHaveBeenCalledTimes(1);
expect(fixture.componentInstance.selectedSpy).toHaveBeenCalledWith(
jasmine.objectContaining({
source: fixture.componentInstance.timepicker,
value: jasmine.any(Date),
}),
);
}));
}); | {
"end_byte": 5040,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker.spec.ts"
} |
components/src/material/timepicker/timepicker.spec.ts_5044_11447 | describe('input behavior', () => {
it('should reformat the input value when the model changes', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.componentInstance.value.set(createTime(13, 45));
fixture.detectChanges();
expect(input.value).toBe('1:45 PM');
fixture.componentInstance.value.set(createTime(9, 31));
fixture.detectChanges();
expect(input.value).toBe('9:31 AM');
});
it('should reformat the input value when the locale changes', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.componentInstance.value.set(createTime(13, 45));
fixture.detectChanges();
expect(input.value).toBe('1:45 PM');
adapter.setLocale('da-DK');
fixture.detectChanges();
expect(input.value).toBe('13.45');
});
it('should parse a valid time value entered by the user', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
expect(fixture.componentInstance.input.value()).toBe(null);
typeInElement(input, '13:37');
fixture.detectChanges();
// The user's value shouldn't be overwritten.
expect(input.value).toBe('13:37');
expect(fixture.componentInstance.input.value()).toEqual(createTime(13, 37));
});
it('should parse invalid time string', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.detectChanges();
const input = getInput(fixture);
fixture.componentInstance.input.value.set(createTime(10, 55));
typeInElement(input, 'not a valid time');
fixture.detectChanges();
expect(input.value).toBe('not a valid time');
expect(adapter.isValid(fixture.componentInstance.input.value()!)).toBe(false);
});
it('should format the entered value on blur', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
typeInElement(input, '13:37');
fixture.detectChanges();
expect(input.value).toBe('13:37');
dispatchFakeEvent(input, 'blur');
fixture.detectChanges();
expect(input.value).toBe('1:37 PM');
});
it('should not format invalid time string entered by the user', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
typeInElement(input, 'not a valid time');
fixture.detectChanges();
expect(input.value).toBe('not a valid time');
expect(adapter.isValid(fixture.componentInstance.input.value()!)).toBe(false);
dispatchFakeEvent(input, 'blur');
fixture.detectChanges();
expect(input.value).toBe('not a valid time');
expect(adapter.isValid(fixture.componentInstance.input.value()!)).toBe(false);
});
it('should not format invalid time set programmatically', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.value.set(adapter.invalid());
fixture.detectChanges();
expect(getInput(fixture).value).toBe('');
});
it('should set the disabled state of the input', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
expect(input.disabled).toBe(false);
fixture.componentInstance.disabled.set(true);
fixture.detectChanges();
expect(input.disabled).toBe(true);
});
it('should assign the last valid date with a new time if the user clears the time and re-enters it', () => {
const dateParts = [2024, 0, 15] as const;
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
const inputInstance = fixture.componentInstance.input;
inputInstance.value.set(new Date(...dateParts, 8, 15, 0));
fixture.detectChanges();
expect(input.value).toBe('8:15 AM');
clearElement(input);
fixture.detectChanges();
expect(input.value).toBe('');
expect(inputInstance.value()).toBe(null);
typeInElement(input, '2:10 PM');
fixture.detectChanges();
expect(input.value).toBe('2:10 PM');
expect(inputInstance.value()).toEqual(new Date(...dateParts, 14, 10, 0));
});
it('should not accept an invalid `min` value', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.min.set(createTime(13, 45));
fixture.detectChanges();
expect(fixture.componentInstance.input.min()).toEqual(createTime(13, 45));
fixture.componentInstance.min.set(adapter.invalid());
fixture.detectChanges();
expect(fixture.componentInstance.input.min()).toBe(null);
});
it('should not accept an invalid `max` value', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.max.set(createTime(13, 45));
fixture.detectChanges();
expect(fixture.componentInstance.input.max()).toEqual(createTime(13, 45));
fixture.componentInstance.max.set(adapter.invalid());
fixture.detectChanges();
expect(fixture.componentInstance.input.max()).toBe(null);
});
it('should accept a valid time string as the `min`', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.min.set('1:45 PM');
fixture.detectChanges();
expect(fixture.componentInstance.input.min()).toEqual(createTime(13, 45));
});
it('should accept a valid time string as the `max`', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.max.set('1:45 PM');
fixture.detectChanges();
expect(fixture.componentInstance.input.max()).toEqual(createTime(13, 45));
});
it('should throw if multiple inputs are associated with a timepicker', () => {
expect(() => {
const fixture = TestBed.createComponent(TimepickerWithMultipleInputs);
fixture.detectChanges();
}).toThrowError(/MatTimepicker can only be registered with one input at a time/);
});
}); | {
"end_byte": 11447,
"start_byte": 5044,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker.spec.ts"
} |
components/src/material/timepicker/timepicker.spec.ts_11451_16847 | describe('opening and closing', () => {
it('should open the timepicker on click', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
expect(getPanel()).toBeTruthy();
});
it('should open the timepicker on arrow press', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.detectChanges();
const event = dispatchKeyboardEvent(getInput(fixture), 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(getPanel()).toBeTruthy();
expect(event.defaultPrevented).toBe(true);
});
it('should not open the timepicker on focus', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.detectChanges();
getInput(fixture).focus();
fixture.detectChanges();
expect(getPanel()).toBeFalsy();
});
it('should close the timepicker when clicking outside', fakeAsync(() => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
expect(getPanel()).toBeTruthy();
document.body.click();
fixture.detectChanges();
flush();
expect(getPanel()).toBeFalsy();
}));
it('should close the timepicker when tabbing away from the input', fakeAsync(() => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
expect(getPanel()).toBeTruthy();
dispatchKeyboardEvent(getInput(fixture), 'keydown', TAB);
fixture.detectChanges();
flush();
expect(getPanel()).toBeFalsy();
}));
it('should close the timepicker when pressing escape', fakeAsync(() => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
expect(getPanel()).toBeTruthy();
const event = dispatchKeyboardEvent(document.body, 'keydown', ESCAPE);
fixture.detectChanges();
flush();
expect(getPanel()).toBeFalsy();
expect(event.defaultPrevented).toBe(true);
}));
it('should emit events on open/close', fakeAsync(() => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.detectChanges();
const {openedSpy, closedSpy} = fixture.componentInstance;
expect(openedSpy).not.toHaveBeenCalled();
expect(closedSpy).not.toHaveBeenCalled();
getInput(fixture).click();
fixture.detectChanges();
expect(openedSpy).toHaveBeenCalledTimes(1);
expect(closedSpy).not.toHaveBeenCalled();
document.body.click();
fixture.detectChanges();
flush();
expect(openedSpy).toHaveBeenCalledTimes(1);
expect(closedSpy).toHaveBeenCalledTimes(1);
}));
it('should clean up the overlay if it is open on destroy', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
expect(getPanel()).toBeTruthy();
fixture.destroy();
expect(getPanel()).toBeFalsy();
});
it('should be able to open and close the panel programmatically', fakeAsync(() => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.detectChanges();
fixture.componentInstance.timepicker.open();
fixture.detectChanges();
expect(getPanel()).toBeTruthy();
fixture.componentInstance.timepicker.close();
fixture.detectChanges();
flush();
expect(getPanel()).toBeFalsy();
}));
it('should focus the input when opened programmatically', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
fixture.componentInstance.timepicker.open();
fixture.detectChanges();
expect(input).toBeTruthy();
expect(document.activeElement).toBe(input);
});
it('should expose the current open state', fakeAsync(() => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.detectChanges();
const timepicker = fixture.componentInstance.timepicker;
expect(timepicker.isOpen()).toBe(false);
timepicker.open();
fixture.detectChanges();
expect(timepicker.isOpen()).toBe(true);
timepicker.close();
fixture.detectChanges();
flush();
expect(timepicker.isOpen()).toBe(false);
}));
// Note: this will be a type checking error, but we check it just in case for JIT mode.
it('should do nothing if trying to open a timepicker without an input', fakeAsync(() => {
const fixture = TestBed.createComponent(TimepickerWithoutInput);
fixture.detectChanges();
fixture.componentInstance.timepicker.open();
fixture.detectChanges();
expect(getPanel()).toBeFalsy();
expect(() => {
fixture.componentInstance.timepicker.close();
fixture.detectChanges();
flush();
}).not.toThrow();
}));
});
// Note: these tests intentionally don't cover the full option generation logic
// and interval parsing, because they are tested already in `util.spec.ts`. | {
"end_byte": 16847,
"start_byte": 11451,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker.spec.ts"
} |
components/src/material/timepicker/timepicker.spec.ts_16850_22931 | describe('panel options behavior', () => {
it('should set the selected state of the options based on the input value', () => {
const getStates = () => {
return getOptions().map(
o => `${o.textContent} - ${o.classList.contains('mdc-list-item--selected')}`,
);
};
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.componentInstance.min.set(createTime(12, 0));
fixture.componentInstance.max.set(createTime(14, 0));
fixture.detectChanges();
// Initial open with pre-entereted value.
typeInElement(input, '1:30 PM');
fixture.detectChanges();
input.click();
fixture.detectChanges();
expect(getStates()).toEqual([
'12:00 PM - false',
'12:30 PM - false',
'1:00 PM - false',
'1:30 PM - true',
'2:00 PM - false',
]);
// Clear the input while open.
clearElement(input);
fixture.detectChanges();
expect(getStates()).toEqual([
'12:00 PM - false',
'12:30 PM - false',
'1:00 PM - false',
'1:30 PM - false',
'2:00 PM - false',
]);
// Type new value while open.
typeInElement(input, '12:30 PM');
fixture.detectChanges();
expect(getStates()).toEqual([
'12:00 PM - false',
'12:30 PM - true',
'1:00 PM - false',
'1:30 PM - false',
'2:00 PM - false',
]);
// Type value that doesn't match anything.
clearElement(input);
typeInElement(input, '12:34 PM');
fixture.detectChanges();
expect(getStates()).toEqual([
'12:00 PM - false',
'12:30 PM - false',
'1:00 PM - false',
'1:30 PM - false',
'2:00 PM - false',
]);
});
it('should take the input min value into account when generating the options', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.min.set(createTime(18, 0));
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
expect(getOptions().map(o => o.textContent)).toEqual([
'6:00 PM',
'6:30 PM',
'7:00 PM',
'7:30 PM',
'8:00 PM',
'8:30 PM',
'9:00 PM',
'9:30 PM',
'10:00 PM',
'10:30 PM',
'11:00 PM',
'11:30 PM',
]);
});
it('should take the input max value into account when generating the options', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.max.set(createTime(4, 0));
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
expect(getOptions().map(o => o.textContent)).toEqual([
'12:00 AM',
'12:30 AM',
'1:00 AM',
'1:30 AM',
'2:00 AM',
'2:30 AM',
'3:00 AM',
'3:30 AM',
'4:00 AM',
]);
});
it('should take the interval into account when generating the options', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.interval.set('3.5h');
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
expect(getOptions().map(o => o.textContent)).toEqual([
'12:00 AM',
'3:30 AM',
'7:00 AM',
'10:30 AM',
'2:00 PM',
'5:30 PM',
'9:00 PM',
]);
});
it('should be able to pass a custom array of options', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.customOptions.set([
{label: 'Breakfast', value: createTime(8, 0)},
{label: 'Lunch', value: createTime(12, 0)},
{label: 'Dinner', value: createTime(20, 0)},
]);
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
expect(getOptions().map(o => o.textContent)).toEqual(['Breakfast', 'Lunch', 'Dinner']);
});
it('should throw if both an interval and custom options are passed in', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
expect(() => {
fixture.componentInstance.interval.set('3h');
fixture.componentInstance.customOptions.set([{label: 'Noon', value: createTime(12, 0)}]);
fixture.detectChanges();
}).toThrowError(/Cannot specify both the `options` and `interval` inputs at the same time/);
});
it('should throw if an empty array of custom options is passed in', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
expect(() => {
fixture.componentInstance.customOptions.set([]);
fixture.detectChanges();
}).toThrowError(/Value of `options` input cannot be an empty array/);
});
it('should interpret an invalid interval as null', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.interval.set('not a valid interval');
fixture.detectChanges();
expect(fixture.componentInstance.timepicker.interval()).toBe(null);
});
});
describe('mat-form-field integration', () => {
it('should open when clicking on the form field', () => {
const fixture = TestBed.createComponent(TimepickerInFormField);
fixture.detectChanges();
fixture.nativeElement.querySelector('mat-form-field').click();
fixture.detectChanges();
expect(getPanel()).toBeTruthy();
});
it('should default the aria-labelledby of the panel to the form field label', () => {
const fixture = TestBed.createComponent(TimepickerInFormField);
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
const panel = getPanel();
const labelId = fixture.nativeElement.querySelector('label').getAttribute('id');
expect(labelId).toBeTruthy();
expect(panel.getAttribute('aria-labelledby')).toBe(labelId);
});
}); | {
"end_byte": 22931,
"start_byte": 16850,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker.spec.ts"
} |
components/src/material/timepicker/timepicker.spec.ts_22935_31650 | describe('accessibility', () => {
it('should set the correct roles', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
input.click();
fixture.detectChanges();
const panel = getPanel();
const option = panel.querySelector('mat-option') as HTMLElement;
expect(input.getAttribute('role')).toBe('combobox');
expect(input.getAttribute('aria-haspopup')).toBe('listbox');
expect(panel.getAttribute('role')).toBe('listbox');
expect(option.getAttribute('role')).toBe('option');
});
it('should point the aria-controls attribute to the panel while open', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
expect(input.hasAttribute('aria-controls')).toBe(false);
input.click();
fixture.detectChanges();
const panelId = getPanel().getAttribute('id');
expect(panelId).toBeTruthy();
expect(input.getAttribute('aria-controls')).toBe(panelId);
});
it('should set aria-expanded based on whether the panel is open', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
expect(input.getAttribute('aria-expanded')).toBe('false');
input.click();
fixture.detectChanges();
expect(input.getAttribute('aria-expanded')).toBe('true');
document.body.click();
fixture.detectChanges();
expect(input.getAttribute('aria-expanded')).toBe('false');
});
it('should be able to set aria-label of the panel', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.ariaLabel.set('Pick a time');
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
expect(getPanel().getAttribute('aria-label')).toBe('Pick a time');
});
it('should be able to set aria-labelledby of the panel', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.ariaLabelledby.set('some-label');
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
expect(getPanel().getAttribute('aria-labelledby')).toBe('some-label');
});
it('should give precedence to aria-label over aria-labelledby', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.ariaLabel.set('Pick a time');
fixture.componentInstance.ariaLabelledby.set('some-label');
fixture.detectChanges();
getInput(fixture).click();
fixture.detectChanges();
const panel = getPanel();
expect(panel.getAttribute('aria-label')).toBe('Pick a time');
expect(panel.hasAttribute('aria-labelledby')).toBe(false);
});
it('should navigate up/down the list when pressing the arrow keys', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
input.click();
fixture.detectChanges();
expect(getActiveOptionIndex()).toBe(0);
// Navigate down
for (let i = 1; i < 6; i++) {
const event = dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(getActiveOptionIndex()).toBe(i);
expect(event.defaultPrevented).toBe(true);
}
// Navigate back up
for (let i = 4; i > -1; i--) {
const event = dispatchKeyboardEvent(input, 'keydown', UP_ARROW);
fixture.detectChanges();
expect(getActiveOptionIndex()).toBe(i);
expect(event.defaultPrevented).toBe(true);
}
});
it('should navigate to the first/last options when pressing home/end', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
input.click();
fixture.detectChanges();
expect(getActiveOptionIndex()).toBe(0);
let event = dispatchKeyboardEvent(input, 'keydown', END);
fixture.detectChanges();
expect(getActiveOptionIndex()).toBe(getOptions().length - 1);
expect(event.defaultPrevented).toBe(true);
event = dispatchKeyboardEvent(input, 'keydown', HOME);
fixture.detectChanges();
expect(getActiveOptionIndex()).toBe(0);
expect(event.defaultPrevented).toBe(true);
});
it('should navigate up/down the list using page up/down', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
input.click();
fixture.detectChanges();
expect(getActiveOptionIndex()).toBe(0);
let event = dispatchKeyboardEvent(input, 'keydown', PAGE_DOWN);
fixture.detectChanges();
expect(getActiveOptionIndex()).toBe(10);
expect(event.defaultPrevented).toBe(true);
event = dispatchKeyboardEvent(input, 'keydown', PAGE_UP);
fixture.detectChanges();
expect(getActiveOptionIndex()).toBe(0);
expect(event.defaultPrevented).toBe(true);
});
it('should select the active option and close when pressing enter', fakeAsync(() => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
input.click();
fixture.detectChanges();
for (let i = 0; i < 3; i++) {
dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW);
fixture.detectChanges();
}
expect(input.value).toBe('');
expect(fixture.componentInstance.input.value()).toBe(null);
expect(getPanel()).toBeTruthy();
expect(getActiveOptionIndex()).toBe(3);
expect(fixture.componentInstance.selectedSpy).not.toHaveBeenCalled();
const event = dispatchKeyboardEvent(input, 'keydown', ENTER);
fixture.detectChanges();
flush();
expect(input.value).toBe('1:30 AM');
expect(fixture.componentInstance.input.value()).toEqual(createTime(1, 30));
expect(getPanel()).toBeFalsy();
expect(event.defaultPrevented).toBeTrue();
expect(fixture.componentInstance.selectedSpy).toHaveBeenCalledTimes(1);
expect(fixture.componentInstance.selectedSpy).toHaveBeenCalledWith(
jasmine.objectContaining({
source: fixture.componentInstance.timepicker,
value: jasmine.any(Date),
}),
);
}));
it('should not navigate using the left/right arrow keys', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
input.click();
fixture.detectChanges();
expect(getActiveOptionIndex()).toBe(0);
let event = dispatchKeyboardEvent(input, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(event.defaultPrevented).toBe(false);
expect(getActiveOptionIndex()).toBe(0);
event = dispatchKeyboardEvent(input, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(event.defaultPrevented).toBe(false);
expect(getActiveOptionIndex()).toBe(0);
});
it('should set aria-activedescendant to the currently-active option', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const input = getInput(fixture);
fixture.detectChanges();
// Initial state
expect(input.hasAttribute('aria-activedescendant')).toBe(false);
// Once the panel is opened
input.click();
fixture.detectChanges();
const optionIds = getOptions().map(o => o.getAttribute('id'));
expect(optionIds.length).toBeGreaterThan(0);
expect(optionIds.every(o => o != null)).toBe(true);
expect(input.getAttribute('aria-activedescendant')).toBe(optionIds[0]);
// Navigate down once
dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(input.getAttribute('aria-activedescendant')).toBe(optionIds[1]);
// Navigate down again
dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(input.getAttribute('aria-activedescendant')).toBe(optionIds[2]);
// Navigate up once
dispatchKeyboardEvent(input, 'keydown', UP_ARROW);
fixture.detectChanges();
expect(input.getAttribute('aria-activedescendant')).toBe(optionIds[1]);
// Close
document.body.click();
fixture.detectChanges();
expect(input.hasAttribute('aria-activedescendant')).toBe(false);
});
}); | {
"end_byte": 31650,
"start_byte": 22935,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker.spec.ts"
} |
components/src/material/timepicker/timepicker.spec.ts_31654_40800 | describe('forms integration', () => {
it('should propagate value typed into the input to the form control', () => {
const fixture = TestBed.createComponent(TimepickerWithForms);
const input = getInput(fixture);
const control = fixture.componentInstance.control;
fixture.detectChanges();
expect(control.value).toBe(null);
expect(control.dirty).toBe(false);
typeInElement(input, '1:37 PM');
fixture.detectChanges();
expect(control.value).toEqual(createTime(13, 37));
expect(control.dirty).toBe(true);
expect(control.touched).toBe(false);
clearElement(input);
fixture.detectChanges();
expect(control.value).toBe(null);
expect(control.dirty).toBe(true);
});
it('should propagate value selected from the panel to the form control', () => {
const fixture = TestBed.createComponent(TimepickerWithForms);
const control = fixture.componentInstance.control;
fixture.detectChanges();
expect(control.value).toBe(null);
expect(control.dirty).toBe(false);
getInput(fixture).click();
fixture.detectChanges();
getOptions()[5].click();
fixture.detectChanges();
expect(control.value).toEqual(createTime(2, 30));
expect(control.dirty).toBe(true);
});
it('should format values assigned to the input through the form control', () => {
const fixture = TestBed.createComponent(TimepickerWithForms);
const input = getInput(fixture);
const control = fixture.componentInstance.control;
control.setValue(createTime(13, 37));
fixture.detectChanges();
expect(input.value).toBe('1:37 PM');
control.setValue(createTime(12, 15));
fixture.detectChanges();
expect(input.value).toBe('12:15 PM');
control.reset();
fixture.detectChanges();
expect(input.value).toBe('');
control.setValue(createTime(10, 10));
fixture.detectChanges();
expect(input.value).toBe('10:10 AM');
});
it('should not change the control if the same value is selected from the dropdown', () => {
const fixture = TestBed.createComponent(TimepickerWithForms);
const control = fixture.componentInstance.control;
control.setValue(createTime(2, 30));
fixture.detectChanges();
const spy = jasmine.createSpy('valueChanges');
const subscription = control.valueChanges.subscribe(spy);
expect(control.dirty).toBe(false);
expect(spy).not.toHaveBeenCalled();
getInput(fixture).click();
fixture.detectChanges();
getOptions()[5].click();
fixture.detectChanges();
expect(control.value).toEqual(createTime(2, 30));
expect(control.dirty).toBe(false);
expect(spy).not.toHaveBeenCalled();
subscription.unsubscribe();
});
it('should not propagate programmatic changes to the form control', () => {
const fixture = TestBed.createComponent(TimepickerWithForms);
const control = fixture.componentInstance.control;
control.setValue(createTime(13, 37));
fixture.detectChanges();
expect(control.dirty).toBe(false);
fixture.componentInstance.input.value.set(createTime(12, 0));
fixture.detectChanges();
expect(control.value).toEqual(createTime(13, 37));
expect(control.dirty).toBe(false);
});
it('should mark the control as touched on blur', () => {
const fixture = TestBed.createComponent(TimepickerWithForms);
fixture.detectChanges();
expect(fixture.componentInstance.control.touched).toBe(false);
dispatchFakeEvent(getInput(fixture), 'blur');
fixture.detectChanges();
expect(fixture.componentInstance.control.touched).toBe(true);
});
it('should mark the control as touched when the panel is closed', fakeAsync(() => {
const fixture = TestBed.createComponent(TimepickerWithForms);
fixture.detectChanges();
expect(fixture.componentInstance.control.touched).toBe(false);
getInput(fixture).click();
fixture.detectChanges();
expect(fixture.componentInstance.control.touched).toBe(false);
document.body.click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.control.touched).toBe(true);
}));
it('should not set the `required` error if there is no valid value in the input', () => {
const fixture = TestBed.createComponent(TimepickerWithForms);
const control = fixture.componentInstance.control;
const input = getInput(fixture);
fixture.detectChanges();
expect(control.errors?.['required']).toBeTruthy();
typeInElement(input, '10:10 AM');
fixture.detectChanges();
expect(control.errors?.['required']).toBeFalsy();
typeInElement(input, 'not a valid date');
fixture.detectChanges();
expect(control.errors?.['required']).toBeFalsy();
});
it('should set an error if the user enters an invalid time string', fakeAsync(() => {
const fixture = TestBed.createComponent(TimepickerWithForms);
const control = fixture.componentInstance.control;
const input = getInput(fixture);
fixture.detectChanges();
expect(control.errors?.['matTimepickerParse']).toBeFalsy();
expect(control.value).toBe(null);
typeInElement(input, '10:10 AM');
fixture.detectChanges();
expect(control.errors?.['matTimepickerParse']).toBeFalsy();
expect(control.value).toEqual(createTime(10, 10));
clearElement(input);
typeInElement(input, 'not a valid date');
fixture.detectChanges();
expect(control.errors?.['matTimepickerParse']).toEqual(
jasmine.objectContaining({
text: 'not a valid date',
}),
);
expect(control.value).toBeTruthy();
expect(adapter.isValid(control.value!)).toBe(false);
// Change from one invalid value to the other to make sure that the object stays in sync.
typeInElement(input, ' (changed)');
fixture.detectChanges();
expect(control.errors?.['matTimepickerParse']).toEqual(
jasmine.objectContaining({
text: 'not a valid date (changed)',
}),
);
expect(control.value).toBeTruthy();
expect(adapter.isValid(control.value!)).toBe(false);
clearElement(input);
fixture.detectChanges();
expect(control.errors?.['matTimepickerParse']).toBeFalsy();
expect(control.value).toBe(null);
typeInElement(input, '12:10 PM');
fixture.detectChanges();
expect(control.errors?.['matTimepickerParse']).toBeFalsy();
expect(control.value).toEqual(createTime(12, 10));
}));
it('should set an error if the user enters a time earlier than the minimum', fakeAsync(() => {
const fixture = TestBed.createComponent(TimepickerWithForms);
const control = fixture.componentInstance.control;
const input = getInput(fixture);
fixture.componentInstance.min.set(createTime(12, 0));
fixture.detectChanges();
// No value initially so no error either.
expect(control.errors?.['matTimepickerMin']).toBeFalsy();
expect(control.value).toBe(null);
// Entire a value that is before the minimum.
typeInElement(input, '11:59 AM');
fixture.detectChanges();
expect(control.errors?.['matTimepickerMin']).toBeTruthy();
expect(control.value).toEqual(createTime(11, 59));
// Change the minimum so the value becomes valid.
fixture.componentInstance.min.set(createTime(11, 0));
fixture.detectChanges();
expect(control.errors?.['matTimepickerMin']).toBeFalsy();
}));
it('should set an error if the user enters a time later than the maximum', fakeAsync(() => {
const fixture = TestBed.createComponent(TimepickerWithForms);
const control = fixture.componentInstance.control;
const input = getInput(fixture);
fixture.componentInstance.max.set(createTime(12, 0));
fixture.detectChanges();
// No value initially so no error either.
expect(control.errors?.['matTimepickerMax']).toBeFalsy();
expect(control.value).toBe(null);
// Entire a value that is after the maximum.
typeInElement(input, '12:01 PM');
fixture.detectChanges();
expect(control.errors?.['matTimepickerMax']).toBeTruthy();
expect(control.value).toEqual(createTime(12, 1));
// Change the maximum so the value becomes valid.
fixture.componentInstance.max.set(createTime(13, 0));
fixture.detectChanges();
expect(control.errors?.['matTimepickerMax']).toBeFalsy();
}));
it('should mark the input as disabled when the form control is disabled', () => {
const fixture = TestBed.createComponent(TimepickerWithForms);
const input = getInput(fixture);
fixture.detectChanges();
expect(input.disabled).toBe(false);
expect(fixture.componentInstance.input.disabled()).toBe(false);
fixture.componentInstance.control.disable();
fixture.detectChanges();
expect(input.disabled).toBe(true);
expect(fixture.componentInstance.input.disabled()).toBe(true);
});
}); | {
"end_byte": 40800,
"start_byte": 31654,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker.spec.ts"
} |
components/src/material/timepicker/timepicker.spec.ts_40804_49107 | describe('timepicker toggle', () => {
it('should open the timepicker when clicking the toggle', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.detectChanges();
expect(getPanel()).toBeFalsy();
getToggle(fixture).click();
fixture.detectChanges();
expect(getPanel()).toBeTruthy();
});
it('should set the correct ARIA attributes on the toggle', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const toggle = getToggle(fixture);
fixture.detectChanges();
expect(toggle.getAttribute('aria-haspopup')).toBe('listbox');
expect(toggle.getAttribute('aria-expanded')).toBe('false');
toggle.click();
fixture.detectChanges();
expect(toggle.getAttribute('aria-expanded')).toBe('true');
});
it('should be able to set aria-label on the button', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const toggle = getToggle(fixture);
fixture.detectChanges();
expect(toggle.hasAttribute('aria-label')).toBe(false);
fixture.componentInstance.toggleAriaLabel.set('Toggle the timepicker');
fixture.detectChanges();
expect(toggle.getAttribute('aria-label')).toBe('Toggle the timepicker');
});
it('should be able to set the tabindex on the toggle', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const toggle = getToggle(fixture);
fixture.detectChanges();
expect(toggle.getAttribute('tabindex')).toBe('0');
fixture.componentInstance.toggleTabIndex.set(1);
fixture.detectChanges();
expect(toggle.getAttribute('tabindex')).toBe('1');
});
it('should be able to set the disabled state on the toggle', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
const toggle = getToggle(fixture);
fixture.detectChanges();
expect(toggle.disabled).toBe(false);
expect(toggle.getAttribute('tabindex')).toBe('0');
fixture.componentInstance.toggleDisabled.set(true);
fixture.detectChanges();
expect(toggle.disabled).toBe(true);
expect(toggle.getAttribute('tabindex')).toBe('-1');
});
it('should not open the timepicker on click if the toggle is disabled', () => {
const fixture = TestBed.createComponent(StandaloneTimepicker);
fixture.componentInstance.toggleDisabled.set(true);
fixture.detectChanges();
getToggle(fixture).click();
fixture.detectChanges();
expect(getPanel()).toBeFalsy();
});
});
describe('global defaults', () => {
beforeEach(() => TestBed.resetTestingModule());
it('should be able to set the default inverval through DI', () => {
configureTestingModule([
{
provide: MAT_TIMEPICKER_CONFIG,
useValue: {interval: '9h'},
},
]);
const fixture = TestBed.createComponent(TimepickerInFormField);
fixture.detectChanges();
expect(fixture.componentInstance.timepicker.interval()).toBe(9 * 60 * 60);
});
it('should be able to set the default disableRipple value through DI', () => {
configureTestingModule([
{
provide: MAT_TIMEPICKER_CONFIG,
useValue: {disableRipple: true},
},
]);
const fixture = TestBed.createComponent(TimepickerInFormField);
fixture.detectChanges();
expect(fixture.componentInstance.timepicker.disableRipple()).toBe(true);
expect(fixture.componentInstance.toggle.disableRipple()).toBe(true);
});
});
function configureTestingModule(additionalProviders: Provider[] = []): void {
TestBed.configureTestingModule({
imports: [NoopAnimationsModule],
providers: [provideNativeDateAdapter(), ...additionalProviders],
});
adapter = TestBed.inject(DateAdapter);
adapter.setLocale('en-US');
}
function getInput(fixture: ComponentFixture<unknown>): HTMLInputElement {
return fixture.nativeElement.querySelector('.mat-timepicker-input');
}
function getPanel(): HTMLElement {
return document.querySelector('.mat-timepicker-panel')!;
}
function getOptions(): HTMLElement[] {
const panel = getPanel();
return panel ? Array.from(panel.querySelectorAll('mat-option')) : [];
}
function createTime(hours: number, minutes: number): Date {
return adapter.setTime(adapter.today(), hours, minutes, 0);
}
function getActiveOptionIndex(): number {
return getOptions().findIndex(o => o.classList.contains('mat-mdc-option-active'));
}
function getToggle(fixture: ComponentFixture<unknown>): HTMLButtonElement {
return fixture.nativeElement.querySelector('mat-timepicker-toggle button');
}
});
@Component({
template: `
<input
[matTimepicker]="picker"
[disabled]="disabled()"
[matTimepickerMin]="min()"
[matTimepickerMax]="max()"
[value]="value()"/>
<mat-timepicker
#picker
(opened)="openedSpy()"
(closed)="closedSpy()"
(selected)="selectedSpy($event)"
[interval]="interval()"
[options]="customOptions()"
[aria-label]="ariaLabel()"
[aria-labelledby]="ariaLabelledby()"/>
<mat-timepicker-toggle
[for]="picker"
[aria-label]="toggleAriaLabel()"
[disabled]="toggleDisabled()"
[tabIndex]="toggleTabIndex()"/>
`,
standalone: true,
imports: [MatTimepicker, MatTimepickerInput, MatTimepickerToggle],
})
class StandaloneTimepicker {
@ViewChild(MatTimepickerInput) input: MatTimepickerInput<Date>;
@ViewChild(MatTimepicker) timepicker: MatTimepicker<Date>;
readonly value = signal<Date | null>(null);
readonly disabled = signal(false);
readonly interval = signal<string | null>(null);
readonly min = signal<Date | string | null>(null);
readonly max = signal<Date | string | null>(null);
readonly ariaLabel = signal<string | null>(null);
readonly ariaLabelledby = signal<string | null>(null);
readonly toggleAriaLabel = signal<string | null>(null);
readonly toggleDisabled = signal<boolean>(false);
readonly toggleTabIndex = signal<number>(0);
readonly customOptions = signal<MatTimepickerOption<Date>[] | null>(null);
readonly openedSpy = jasmine.createSpy('opened');
readonly closedSpy = jasmine.createSpy('closed');
readonly selectedSpy = jasmine.createSpy('selected');
}
@Component({
template: `
<mat-form-field>
<mat-label>Pick a time</mat-label>
<input matInput [matTimepicker]="picker"/>
<mat-timepicker #picker/>
<mat-timepicker-toggle [for]="picker" matSuffix/>
</mat-form-field>
`,
standalone: true,
imports: [
MatTimepicker,
MatTimepickerInput,
MatTimepickerToggle,
MatInput,
MatLabel,
MatFormField,
MatSuffix,
],
})
class TimepickerInFormField {
@ViewChild(MatTimepicker) timepicker: MatTimepicker<Date>;
@ViewChild(MatTimepickerToggle) toggle: MatTimepickerToggle<Date>;
}
@Component({
template: `
<input [matTimepicker]="picker" [(value)]="value"/>
<mat-timepicker #picker/>
`,
standalone: true,
imports: [MatTimepicker, MatTimepickerInput],
})
class TimepickerTwoWayBinding {
@ViewChild(MatTimepickerInput) input: MatTimepickerInput<Date>;
readonly value = signal(new Date(2024, 0, 15, 10, 30, 0));
}
@Component({
template: `
<input
[formControl]="control"
[matTimepicker]="picker"
[matTimepickerMin]="min()"
[matTimepickerMax]="max()"/>
<mat-timepicker #picker/>
`,
standalone: true,
imports: [MatTimepicker, MatTimepickerInput, ReactiveFormsModule],
})
class TimepickerWithForms {
@ViewChild(MatTimepickerInput) input: MatTimepickerInput<Date>;
readonly control = new FormControl<Date | null>(null, [Validators.required]);
readonly min = signal<Date | null>(null);
readonly max = signal<Date | null>(null);
}
@Component({
template: `
<input [matTimepicker]="picker"/>
<input [matTimepicker]="picker"/>
<mat-timepicker #picker/>
`,
standalone: true,
imports: [MatTimepicker, MatTimepickerInput],
})
class TimepickerWithMultipleInputs {}
@Component({
template: '<mat-timepicker/>',
standalone: true,
imports: [MatTimepicker],
})
class TimepickerWithoutInput {
@ViewChild(MatTimepicker) timepicker: MatTimepicker<Date>;
} | {
"end_byte": 49107,
"start_byte": 40804,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker.spec.ts"
} |
components/src/material/timepicker/timepicker-toggle.ts_0_2623 | /**
* @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,
ChangeDetectionStrategy,
Component,
HostAttributeToken,
inject,
input,
InputSignal,
InputSignalWithTransform,
ViewEncapsulation,
} from '@angular/core';
import {MatIconButton} from '@angular/material/button';
import {MAT_TIMEPICKER_CONFIG} from './util';
import type {MatTimepicker} from './timepicker';
/** Button that can be used to open a `mat-timepicker`. */
@Component({
selector: 'mat-timepicker-toggle',
templateUrl: 'timepicker-toggle.html',
host: {
'class': 'mat-timepicker-toggle',
'[attr.tabindex]': 'null',
// Bind the `click` on the host, rather than the inner `button`, so that we can call
// `stopPropagation` on it without affecting the user's `click` handlers. We need to stop
// it so that the input doesn't get focused automatically by the form field (See #21836).
'(click)': '_open($event)',
},
exportAs: 'matTimepickerToggle',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [MatIconButton],
})
export class MatTimepickerToggle<D> {
private _defaultConfig = inject(MAT_TIMEPICKER_CONFIG, {optional: true});
private _defaultTabIndex = (() => {
const value = inject(new HostAttributeToken('tabindex'), {optional: true});
const parsed = Number(value);
return isNaN(parsed) ? null : parsed;
})();
/** Timepicker instance that the button will toggle. */
readonly timepicker: InputSignal<MatTimepicker<D>> = input.required<MatTimepicker<D>>({
alias: 'for',
});
/** Screen-reader label for the button. */
readonly ariaLabel = input<string | undefined>(undefined, {
alias: 'aria-label',
});
/** Whether the toggle button is disabled. */
readonly disabled: InputSignalWithTransform<boolean, unknown> = input(false, {
transform: booleanAttribute,
alias: 'disabled',
});
/** Tabindex for the toggle. */
readonly tabIndex: InputSignal<number | null> = input(this._defaultTabIndex);
/** Whether ripples on the toggle should be disabled. */
readonly disableRipple: InputSignalWithTransform<boolean, unknown> = input(
this._defaultConfig?.disableRipple ?? false,
{transform: booleanAttribute},
);
/** Opens the connected timepicker. */
protected _open(event: Event): void {
if (this.timepicker() && !this.disabled()) {
this.timepicker().open();
event.stopPropagation();
}
}
}
| {
"end_byte": 2623,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker-toggle.ts"
} |
components/src/material/timepicker/util.spec.ts_0_6251 | import {TestBed} from '@angular/core/testing';
import {
DateAdapter,
MAT_DATE_FORMATS,
MatDateFormats,
provideNativeDateAdapter,
} from '@angular/material/core';
import {generateOptions, parseInterval} from './util';
describe('timepicker utilities', () => {
describe('parseInterval', () => {
it('should parse null', () => {
expect(parseInterval(null)).toBe(null);
});
it('should parse a number', () => {
expect(parseInterval(75)).toBe(75);
});
it('should parse a number in a string', () => {
expect(parseInterval('75')).toBe(75);
expect(parseInterval('75.50')).toBe(75.5);
});
it('should handle invalid strings', () => {
expect(parseInterval('')).toBe(null);
expect(parseInterval(' ')).toBe(null);
expect(parseInterval('abc')).toBe(null);
expect(parseInterval('1a')).toBe(null);
expect(parseInterval('m1')).toBe(null);
expect(parseInterval('10.')).toBe(null);
});
it('should parse hours', () => {
expect(parseInterval('3h')).toBe(10_800);
expect(parseInterval('4.5h')).toBe(16_200);
expect(parseInterval('11h')).toBe(39_600);
});
it('should parse minutes', () => {
expect(parseInterval('3m')).toBe(180);
expect(parseInterval('7.5m')).toBe(450);
expect(parseInterval('90m')).toBe(5_400);
expect(parseInterval('100.5m')).toBe(6_030);
});
it('should parse seconds', () => {
expect(parseInterval('3s')).toBe(3);
expect(parseInterval('7.5s')).toBe(7.5);
expect(parseInterval('90s')).toBe(90);
expect(parseInterval('100.5s')).toBe(100.5);
});
it('should parse uppercase units', () => {
expect(parseInterval('3H')).toBe(10_800);
expect(parseInterval('3M')).toBe(180);
expect(parseInterval('3S')).toBe(3);
});
it('should parse interval with space', () => {
expect(parseInterval('3 h')).toBe(10_800);
expect(parseInterval('6 h')).toBe(21_600);
});
it('should handle long versions of units', () => {
expect(parseInterval('1 hour')).toBe(3600);
expect(parseInterval('3 hours')).toBe(10_800);
expect(parseInterval('1 minute')).toBe(60);
expect(parseInterval('3 min')).toBe(180);
expect(parseInterval('3 minutes')).toBe(180);
expect(parseInterval('1 second')).toBe(1);
expect(parseInterval('10 seconds')).toBe(10);
});
});
describe('generateOptions', () => {
let adapter: DateAdapter<Date>;
let formats: MatDateFormats;
beforeEach(() => {
TestBed.configureTestingModule({providers: [provideNativeDateAdapter()]});
adapter = TestBed.inject(DateAdapter);
formats = TestBed.inject(MAT_DATE_FORMATS);
adapter.setLocale('en-US');
});
it('should generate a list of options', () => {
const min = new Date(2024, 0, 1, 9, 0, 0, 0);
const max = new Date(2024, 0, 1, 22, 0, 0, 0);
const options = generateOptions(adapter, formats, min, max, 3600).map(o => o.label);
expect(options).toEqual([
'9:00 AM',
'10:00 AM',
'11:00 AM',
'12:00 PM',
'1:00 PM',
'2:00 PM',
'3:00 PM',
'4:00 PM',
'5:00 PM',
'6:00 PM',
'7:00 PM',
'8:00 PM',
'9:00 PM',
'10:00 PM',
]);
});
it('should generate a list of options with a sub-hour interval', () => {
const min = new Date(2024, 0, 1, 9, 0, 0, 0);
const max = new Date(2024, 0, 1, 22, 0, 0, 0);
const options = generateOptions(adapter, formats, min, max, 43 * 60).map(o => o.label);
expect(options).toEqual([
'9:00 AM',
'9:43 AM',
'10:26 AM',
'11:09 AM',
'11:52 AM',
'12:35 PM',
'1:18 PM',
'2:01 PM',
'2:44 PM',
'3:27 PM',
'4:10 PM',
'4:53 PM',
'5:36 PM',
'6:19 PM',
'7:02 PM',
'7:45 PM',
'8:28 PM',
'9:11 PM',
'9:54 PM',
]);
});
it('should generate a list of options with a minute interval', () => {
const min = new Date(2024, 0, 1, 9, 0, 0, 0);
const max = new Date(2024, 0, 1, 9, 16, 0, 0);
const options = generateOptions(adapter, formats, min, max, 60).map(o => o.label);
expect(options).toEqual([
'9:00 AM',
'9:01 AM',
'9:02 AM',
'9:03 AM',
'9:04 AM',
'9:05 AM',
'9:06 AM',
'9:07 AM',
'9:08 AM',
'9:09 AM',
'9:10 AM',
'9:11 AM',
'9:12 AM',
'9:13 AM',
'9:14 AM',
'9:15 AM',
'9:16 AM',
]);
});
it('should generate a list of options with a sub-minute interval', () => {
const previousFormat = formats.display.timeOptionLabel;
formats.display.timeOptionLabel = {hour: 'numeric', minute: 'numeric', second: 'numeric'};
const min = new Date(2024, 0, 1, 9, 0, 0, 0);
const max = new Date(2024, 0, 1, 9, 3, 0, 0);
const options = generateOptions(adapter, formats, min, max, 12).map(o => o.label);
expect(options).toEqual([
'9:00:00 AM',
'9:00:12 AM',
'9:00:24 AM',
'9:00:36 AM',
'9:00:48 AM',
'9:01:00 AM',
'9:01:12 AM',
'9:01:24 AM',
'9:01:36 AM',
'9:01:48 AM',
'9:02:00 AM',
'9:02:12 AM',
'9:02:24 AM',
'9:02:36 AM',
'9:02:48 AM',
'9:03:00 AM',
]);
formats.display.timeOptionLabel = previousFormat;
});
it('should generate at least one option if the interval is too large', () => {
const min = new Date(2024, 0, 1, 0, 0, 0, 0);
const max = new Date(2024, 0, 1, 23, 59, 0, 0);
const options = generateOptions(adapter, formats, min, max, 60 * 60 * 24).map(o => o.label);
expect(options).toEqual(['12:00 AM']);
});
it('should generate at least one option if the max is later than the min', () => {
const min = new Date(2024, 0, 1, 23, 0, 0, 0);
const max = new Date(2024, 0, 1, 13, 0, 0, 0);
const options = generateOptions(adapter, formats, min, max, 3600).map(o => o.label);
expect(options).toEqual(['1:00 PM']);
});
});
});
| {
"end_byte": 6251,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/util.spec.ts"
} |
components/src/material/timepicker/public-api.ts_0_432 | /**
* @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 './timepicker';
export * from './timepicker-input';
export * from './timepicker-toggle';
export * from './timepicker-module';
export {MatTimepickerOption, MAT_TIMEPICKER_CONFIG, MatTimepickerConfig} from './util';
| {
"end_byte": 432,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/public-api.ts"
} |
components/src/material/timepicker/timepicker.ts_0_2534 | /**
* @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 {
afterNextRender,
AfterRenderRef,
booleanAttribute,
ChangeDetectionStrategy,
Component,
effect,
ElementRef,
inject,
Injector,
input,
InputSignal,
InputSignalWithTransform,
OnDestroy,
output,
OutputEmitterRef,
Signal,
signal,
TemplateRef,
untracked,
viewChild,
viewChildren,
ViewContainerRef,
ViewEncapsulation,
} from '@angular/core';
import {animate, group, state, style, transition, trigger} from '@angular/animations';
import {
DateAdapter,
MAT_DATE_FORMATS,
MAT_OPTION_PARENT_COMPONENT,
MatOption,
MatOptionParentComponent,
} from '@angular/material/core';
import {Directionality} from '@angular/cdk/bidi';
import {Overlay, OverlayRef} from '@angular/cdk/overlay';
import {TemplatePortal} from '@angular/cdk/portal';
import {_getEventTarget} from '@angular/cdk/platform';
import {ENTER, ESCAPE, hasModifierKey, TAB} from '@angular/cdk/keycodes';
import {ActiveDescendantKeyManager} from '@angular/cdk/a11y';
import type {MatTimepickerInput} from './timepicker-input';
import {
generateOptions,
MAT_TIMEPICKER_CONFIG,
MatTimepickerOption,
parseInterval,
validateAdapter,
} from './util';
import {Subscription} from 'rxjs';
/** Counter used to generate unique IDs. */
let uniqueId = 0;
/** Event emitted when a value is selected in the timepicker. */
export interface MatTimepickerSelected<D> {
value: D;
source: MatTimepicker<D>;
}
/**
* Renders out a listbox that can be used to select a time of day.
* Intended to be used together with `MatTimepickerInput`.
*/
@Component({
selector: 'mat-timepicker',
exportAs: 'matTimepicker',
templateUrl: 'timepicker.html',
styleUrl: 'timepicker.css',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
imports: [MatOption],
providers: [
{
provide: MAT_OPTION_PARENT_COMPONENT,
useExisting: MatTimepicker,
},
],
animations: [
trigger('panel', [
state('void', style({opacity: 0, transform: 'scaleY(0.8)'})),
transition(':enter', [
group([
animate('0.03s linear', style({opacity: 1})),
animate('0.12s cubic-bezier(0, 0, 0.2, 1)', style({transform: 'scaleY(1)'})),
]),
]),
transition(':leave', [animate('0.075s linear', style({opacity: 0}))]),
]),
],
})
export | {
"end_byte": 2534,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker.ts"
} |
components/src/material/timepicker/timepicker.ts_2535_10441 | class MatTimepicker<D> implements OnDestroy, MatOptionParentComponent {
private _overlay = inject(Overlay);
private _dir = inject(Directionality, {optional: true});
private _viewContainerRef = inject(ViewContainerRef);
private _injector = inject(Injector);
private _defaultConfig = inject(MAT_TIMEPICKER_CONFIG, {optional: true});
private _dateAdapter = inject<DateAdapter<D>>(DateAdapter, {optional: true})!;
private _dateFormats = inject(MAT_DATE_FORMATS, {optional: true})!;
private _isOpen = signal(false);
private _activeDescendant = signal<string | null>(null);
private _input: MatTimepickerInput<D>;
private _overlayRef: OverlayRef | null = null;
private _portal: TemplatePortal<unknown> | null = null;
private _optionsCacheKey: string | null = null;
private _localeChanges: Subscription;
private _onOpenRender: AfterRenderRef | null = null;
protected _panelTemplate = viewChild.required<TemplateRef<unknown>>('panelTemplate');
protected _timeOptions: readonly MatTimepickerOption<D>[] = [];
protected _options = viewChildren(MatOption);
private _keyManager = new ActiveDescendantKeyManager(this._options, this._injector)
.withHomeAndEnd(true)
.withPageUpDown(true)
.withVerticalOrientation(true);
/**
* Interval between each option in the timepicker. The value can either be an amount of
* seconds (e.g. 90) or a number with a unit (e.g. 45m). Supported units are `s` for seconds,
* `m` for minutes or `h` for hours.
*/
readonly interval: InputSignalWithTransform<number | null, number | string | null> = input(
parseInterval(this._defaultConfig?.interval || null),
{transform: parseInterval},
);
/**
* Array of pre-defined options that the user can select from, as an alternative to using the
* `interval` input. An error will be thrown if both `options` and `interval` are specified.
*/
readonly options: InputSignal<readonly MatTimepickerOption<D>[] | null> = input<
readonly MatTimepickerOption<D>[] | null
>(null);
/** Whether the timepicker is open. */
readonly isOpen: Signal<boolean> = this._isOpen.asReadonly();
/** Emits when the user selects a time. */
readonly selected: OutputEmitterRef<MatTimepickerSelected<D>> = output();
/** Emits when the timepicker is opened. */
readonly opened: OutputEmitterRef<void> = output();
/** Emits when the timepicker is closed. */
readonly closed: OutputEmitterRef<void> = output();
/** ID of the active descendant option. */
readonly activeDescendant: Signal<string | null> = this._activeDescendant.asReadonly();
/** Unique ID of the timepicker's panel */
readonly panelId = `mat-timepicker-panel-${uniqueId++}`;
/** Whether ripples within the timepicker should be disabled. */
readonly disableRipple: InputSignalWithTransform<boolean, unknown> = input(
this._defaultConfig?.disableRipple ?? false,
{
transform: booleanAttribute,
},
);
/** ARIA label for the timepicker panel. */
readonly ariaLabel: InputSignal<string | null> = input<string | null>(null, {
alias: 'aria-label',
});
/** ID of the label element for the timepicker panel. */
readonly ariaLabelledby: InputSignal<string | null> = input<string | null>(null, {
alias: 'aria-labelledby',
});
constructor() {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
validateAdapter(this._dateAdapter, this._dateFormats);
effect(() => {
const options = this.options();
const interval = this.interval();
if (options !== null && interval !== null) {
throw new Error(
'Cannot specify both the `options` and `interval` inputs at the same time',
);
} else if (options?.length === 0) {
throw new Error('Value of `options` input cannot be an empty array');
}
});
}
// Since the panel ID is static, we can set it once without having to maintain a host binding.
const element = inject<ElementRef<HTMLElement>>(ElementRef);
element.nativeElement.setAttribute('mat-timepicker-panel-id', this.panelId);
this._handleLocaleChanges();
this._handleInputStateChanges();
this._keyManager.change.subscribe(() =>
this._activeDescendant.set(this._keyManager.activeItem?.id || null),
);
}
/** Opens the timepicker. */
open(): void {
if (!this._input) {
return;
}
// Focus should already be on the input, but this call is in case the timepicker is opened
// programmatically. We need to call this even if the timepicker is already open, because
// the user might be clicking the toggle.
this._input.focus();
if (this._isOpen()) {
return;
}
this._isOpen.set(true);
this._generateOptions();
const overlayRef = this._getOverlayRef();
overlayRef.updateSize({width: this._input.getOverlayOrigin().nativeElement.offsetWidth});
this._portal ??= new TemplatePortal(this._panelTemplate(), this._viewContainerRef);
overlayRef.attach(this._portal);
this._onOpenRender?.destroy();
this._onOpenRender = afterNextRender(
() => {
const options = this._options();
this._syncSelectedState(this._input.value(), options, options[0]);
this._onOpenRender = null;
},
{injector: this._injector},
);
this.opened.emit();
}
/** Closes the timepicker. */
close(): void {
if (this._isOpen()) {
this._isOpen.set(false);
this._overlayRef?.detach();
this.closed.emit();
}
}
/** Registers an input with the timepicker. */
registerInput(input: MatTimepickerInput<D>): void {
if (this._input && input !== this._input && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw new Error('MatTimepicker can only be registered with one input at a time');
}
this._input = input;
}
ngOnDestroy(): void {
this._keyManager.destroy();
this._localeChanges.unsubscribe();
this._onOpenRender?.destroy();
this._overlayRef?.dispose();
}
/** Selects a specific time value. */
protected _selectValue(value: D) {
this.close();
this.selected.emit({value, source: this});
this._input.focus();
}
/** Gets the value of the `aria-labelledby` attribute. */
protected _getAriaLabelledby(): string | null {
if (this.ariaLabel()) {
return null;
}
return this.ariaLabelledby() || this._input?._getLabelId() || null;
}
/** Creates an overlay reference for the timepicker panel. */
private _getOverlayRef(): OverlayRef {
if (this._overlayRef) {
return this._overlayRef;
}
const positionStrategy = this._overlay
.position()
.flexibleConnectedTo(this._input.getOverlayOrigin())
.withFlexibleDimensions(false)
.withPush(false)
.withTransformOriginOn('.mat-timepicker-panel')
.withPositions([
{
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'top',
},
{
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'bottom',
panelClass: 'mat-timepicker-above',
},
]);
this._overlayRef = this._overlay.create({
positionStrategy,
scrollStrategy: this._overlay.scrollStrategies.reposition(),
direction: this._dir || 'ltr',
hasBackdrop: false,
});
this._overlayRef.keydownEvents().subscribe(event => {
this._handleKeydown(event);
});
this._overlayRef.outsidePointerEvents().subscribe(event => {
const target = _getEventTarget(event) as HTMLElement;
const origin = this._input.getOverlayOrigin().nativeElement;
if (target && target !== origin && !origin.contains(target)) {
this.close();
}
});
return this._overlayRef;
}
/** Generates the list of options from which the user can select.. */ | {
"end_byte": 10441,
"start_byte": 2535,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker.ts"
} |
components/src/material/timepicker/timepicker.ts_10444_14437 | private _generateOptions(): void {
// Default the interval to 30 minutes.
const interval = this.interval() ?? 30 * 60;
const options = this.options();
if (options !== null) {
this._timeOptions = options;
} else {
const adapter = this._dateAdapter;
const timeFormat = this._dateFormats.display.timeInput;
const min = this._input.min() || adapter.setTime(adapter.today(), 0, 0, 0);
const max = this._input.max() || adapter.setTime(adapter.today(), 23, 59, 0);
const cacheKey =
interval + '/' + adapter.format(min, timeFormat) + '/' + adapter.format(max, timeFormat);
// Don't re-generate the options if the inputs haven't changed.
if (cacheKey !== this._optionsCacheKey) {
this._optionsCacheKey = cacheKey;
this._timeOptions = generateOptions(adapter, this._dateFormats, min, max, interval);
}
}
}
/**
* Synchronizes the internal state of the component based on a specific selected date.
* @param value Currently selected date.
* @param options Options rendered out in the timepicker.
* @param fallback Option to set as active if no option is selected.
*/
private _syncSelectedState(
value: D | null,
options: readonly MatOption[],
fallback: MatOption | null,
): void {
let hasSelected = false;
for (const option of options) {
if (value && this._dateAdapter.sameTime(option.value, value)) {
option.select(false);
scrollOptionIntoView(option, 'center');
untracked(() => this._keyManager.setActiveItem(option));
hasSelected = true;
} else {
option.deselect(false);
}
}
// If no option was selected, we need to reset the key manager since
// it might be holding onto an option that no longer exists.
if (!hasSelected) {
if (fallback) {
untracked(() => this._keyManager.setActiveItem(fallback));
scrollOptionIntoView(fallback, 'center');
} else {
untracked(() => this._keyManager.setActiveItem(-1));
}
}
}
/** Handles keyboard events while the overlay is open. */
private _handleKeydown(event: KeyboardEvent): void {
const keyCode = event.keyCode;
if (keyCode === TAB) {
this.close();
} else if (keyCode === ESCAPE && !hasModifierKey(event)) {
event.preventDefault();
this.close();
} else if (keyCode === ENTER) {
event.preventDefault();
if (this._keyManager.activeItem) {
this._selectValue(this._keyManager.activeItem.value);
} else {
this.close();
}
} else {
const previousActive = this._keyManager.activeItem;
this._keyManager.onKeydown(event);
const currentActive = this._keyManager.activeItem;
if (currentActive && currentActive !== previousActive) {
scrollOptionIntoView(currentActive, 'nearest');
}
}
}
/** Sets up the logic that updates the timepicker when the locale changes. */
private _handleLocaleChanges(): void {
// Re-generate the options list if the locale changes.
this._localeChanges = this._dateAdapter.localeChanges.subscribe(() => {
this._optionsCacheKey = null;
if (this.isOpen()) {
this._generateOptions();
}
});
}
/**
* Sets up the logic that updates the timepicker when the state of the connected input changes.
*/
private _handleInputStateChanges(): void {
effect(() => {
const value = this._input?.value();
const options = this._options();
if (this._isOpen()) {
this._syncSelectedState(value, options, null);
}
});
}
}
/**
* Scrolls an option into view.
* @param option Option to be scrolled into view.
* @param position Position to which to align the option relative to the scrollable container.
*/
function scrollOptionIntoView(option: MatOption, position: ScrollLogicalPosition) {
option._getHostElement().scrollIntoView({block: position, inline: position});
} | {
"end_byte": 14437,
"start_byte": 10444,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker.ts"
} |
components/src/material/timepicker/README.md_0_102 | Please see the official documentation at https://material.angular.dev/components/component/timepicker
| {
"end_byte": 102,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/README.md"
} |
components/src/material/timepicker/timepicker-module.ts_0_671 | /**
* @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 {CdkScrollableModule} from '@angular/cdk/scrolling';
import {MatTimepicker} from './timepicker';
import {MatTimepickerInput} from './timepicker-input';
import {MatTimepickerToggle} from './timepicker-toggle';
@NgModule({
imports: [MatTimepicker, MatTimepickerInput, MatTimepickerToggle],
exports: [CdkScrollableModule, MatTimepicker, MatTimepickerInput, MatTimepickerToggle],
})
export class MatTimepickerModule {}
| {
"end_byte": 671,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker-module.ts"
} |
components/src/material/timepicker/util.ts_0_4193 | /**
* @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 {DateAdapter, MatDateFormats} from '@angular/material/core';
/** Pattern that interval strings have to match. */
const INTERVAL_PATTERN = /^(\d*\.?\d+)\s*(h|hour|hours|m|min|minute|minutes|s|second|seconds)?$/i;
/**
* Object that can be used to configure the default options for the timepicker component.
*/
export interface MatTimepickerConfig {
/** Default interval for all time pickers. */
interval?: string | number;
/** Whether ripples inside the timepicker should be disabled by default. */
disableRipple?: boolean;
}
/**
* Injection token that can be used to configure the default options for the timepicker component.
*/
export const MAT_TIMEPICKER_CONFIG = new InjectionToken<MatTimepickerConfig>(
'MAT_TIMEPICKER_CONFIG',
);
/**
* Time selection option that can be displayed within a `mat-timepicker`.
*/
export interface MatTimepickerOption<D = unknown> {
/** Date value of the option. */
value: D;
/** Label to show to the user. */
label: string;
}
/** Parses an interval value into seconds. */
export function parseInterval(value: number | string | null): number | null {
let result: number;
if (value === null) {
return null;
} else if (typeof value === 'number') {
result = value;
} else {
if (value.trim().length === 0) {
return null;
}
const parsed = value.match(INTERVAL_PATTERN);
const amount = parsed ? parseFloat(parsed[1]) : null;
const unit = parsed?.[2]?.toLowerCase() || null;
if (!parsed || amount === null || isNaN(amount)) {
return null;
}
if (unit === 'h' || unit === 'hour' || unit === 'hours') {
result = amount * 3600;
} else if (unit === 'm' || unit === 'min' || unit === 'minute' || unit === 'minutes') {
result = amount * 60;
} else {
result = amount;
}
}
return result;
}
/**
* Generates the options to show in a timepicker.
* @param adapter Date adapter to be used to generate the options.
* @param formats Formatting config to use when displaying the options.
* @param min Time from which to start generating the options.
* @param max Time at which to stop generating the options.
* @param interval Amount of seconds between each option.
*/
export function generateOptions<D>(
adapter: DateAdapter<D>,
formats: MatDateFormats,
min: D,
max: D,
interval: number,
): MatTimepickerOption<D>[] {
const options: MatTimepickerOption<D>[] = [];
let current = adapter.compareTime(min, max) < 1 ? min : max;
while (
adapter.sameDate(current, min) &&
adapter.compareTime(current, max) < 1 &&
adapter.isValid(current)
) {
options.push({value: current, label: adapter.format(current, formats.display.timeOptionLabel)});
current = adapter.addSeconds(current, interval);
}
return options;
}
/** Checks whether a date adapter is set up correctly for use with the timepicker. */
export function validateAdapter(
adapter: DateAdapter<unknown> | null,
formats: MatDateFormats | null,
) {
function missingAdapterError(provider: string) {
return Error(
`MatTimepicker: No provider found for ${provider}. You must add one of the following ` +
`to your app config: provideNativeDateAdapter, provideDateFnsAdapter, ` +
`provideLuxonDateAdapter, provideMomentDateAdapter, or provide a custom implementation.`,
);
}
if (!adapter) {
throw missingAdapterError('DateAdapter');
}
if (!formats) {
throw missingAdapterError('MAT_DATE_FORMATS');
}
if (
formats.display.timeInput === undefined ||
formats.display.timeOptionLabel === undefined ||
formats.parse.timeInput === undefined
) {
throw new Error(
'MatTimepicker: Incomplete `MAT_DATE_FORMATS` has been provided. ' +
'`MAT_DATE_FORMATS` must provide `display.timeInput`, `display.timeOptionLabel` ' +
'and `parse.timeInput` formats in order to be compatible with MatTimepicker.',
);
}
}
| {
"end_byte": 4193,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/util.ts"
} |
components/src/material/timepicker/BUILD.bazel_0_1753 | 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 = "timepicker",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = [":timepicker.css"] + glob(["**/*.html"]),
deps = [
"//src:dev_mode_types",
"//src/cdk/bidi",
"//src/cdk/keycodes",
"//src/cdk/overlay",
"//src/cdk/platform",
"//src/cdk/portal",
"//src/cdk/scrolling",
"//src/material/button",
"//src/material/core",
"//src/material/input",
"@npm//@angular/core",
"@npm//@angular/forms",
],
)
sass_library(
name = "timepicker_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = ["//src/material/core:core_scss_lib"],
)
sass_binary(
name = "timepicker_scss",
src = "timepicker.scss",
deps = ["//src/material/core:core_scss_lib"],
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
),
deps = [
":timepicker",
"//src/cdk/keycodes",
"//src/cdk/testing/private",
"//src/material/core",
"//src/material/form-field",
"//src/material/input",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
markdown_to_html(
name = "overview",
srcs = [":timepicker.md"],
)
extract_tokens(
name = "tokens",
srcs = [":timepicker_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1753,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/BUILD.bazel"
} |
components/src/material/timepicker/timepicker.html_0_435 | <ng-template #panelTemplate>
<div
role="listbox"
class="mat-timepicker-panel"
[attr.aria-label]="ariaLabel() || null"
[attr.aria-labelledby]="_getAriaLabelledby()"
[id]="panelId"
@panel>
@for (option of _timeOptions; track option.value) {
<mat-option
[value]="option.value"
(onSelectionChange)="_selectValue(option.value)">{{option.label}}</mat-option>
}
</div>
</ng-template>
| {
"end_byte": 435,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker.html"
} |
components/src/material/timepicker/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/timepicker/index.ts"
} |
components/src/material/timepicker/timepicker-toggle.html_0_920 | <button
mat-icon-button
type="button"
aria-haspopup="listbox"
[attr.aria-label]="ariaLabel()"
[attr.aria-expanded]="timepicker().isOpen()"
[attr.tabindex]="disabled() ? -1 : tabIndex()"
[disabled]="disabled()"
[disableRipple]="disableRipple()">
<ng-content select="[matTimepickerToggleIcon]">
<svg
class="mat-timepicker-toggle-default-icon"
height="24px"
width="24px"
viewBox="0 -960 960 960"
fill="currentColor"
focusable="false"
aria-hidden="true">
<path d="m612-292 56-56-148-148v-184h-80v216l172 172ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 320q133 0 226.5-93.5T800-480q0-133-93.5-226.5T480-800q-133 0-226.5 93.5T160-480q0 133 93.5 226.5T480-160Z"/>
</svg>
</ng-content>
</button>
| {
"end_byte": 920,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker-toggle.html"
} |
components/src/material/timepicker/timepicker.scss_0_1665 | @use '@angular/cdk';
@use '../core/tokens/token-utils';
@use '../core/tokens/m2/mat/timepicker' as tokens-mat-timepicker;
mat-timepicker {
display: none;
}
.mat-timepicker-panel {
width: 100%;
max-height: 256px;
transform-origin: center top;
overflow: auto;
padding: 8px 0;
box-sizing: border-box;
@include token-utils.use-tokens(
tokens-mat-timepicker.$prefix, tokens-mat-timepicker.get-token-slots()) {
@include token-utils.create-token-slot(border-bottom-left-radius, container-shape);
@include token-utils.create-token-slot(border-bottom-right-radius, container-shape);
@include token-utils.create-token-slot(box-shadow, container-elevation-shadow);
@include token-utils.create-token-slot(background-color, container-background-color);
}
@include cdk.high-contrast {
outline: solid 1px;
}
.mat-timepicker-above & {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
@include token-utils.use-tokens(
tokens-mat-timepicker.$prefix, tokens-mat-timepicker.get-token-slots()) {
@include token-utils.create-token-slot(border-top-left-radius, container-shape);
@include token-utils.create-token-slot(border-top-right-radius, container-shape);
}
}
}
// stylelint-disable material/no-prefixes
.mat-timepicker-input:read-only {
cursor: pointer;
}
// stylelint-enable material/no-prefixes
@include cdk.high-contrast {
.mat-timepicker-toggle-default-icon {
// On Chromium-based browsers the icon doesn't appear to inherit the text color in high
// contrast mode so we have to set it explicitly. This is a no-op on IE and Firefox.
color: CanvasText;
}
}
| {
"end_byte": 1665,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/timepicker.scss"
} |
components/src/material/timepicker/testing/timepicker-input-harness.spec.ts_0_6791 | import {HarnessLoader, parallel} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component, signal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {DateAdapter, provideNativeDateAdapter} from '@angular/material/core';
import {MatTimepicker, MatTimepickerInput} from '@angular/material/timepicker';
import {MatTimepickerHarness} from './timepicker-harness';
import {MatTimepickerInputHarness} from './timepicker-input-harness';
describe('MatTimepickerInputHarness', () => {
let fixture: ComponentFixture<TimepickerInputHarnessTest>;
let loader: HarnessLoader;
let adapter: DateAdapter<Date>;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideNativeDateAdapter()],
imports: [NoopAnimationsModule, TimepickerInputHarnessTest],
});
adapter = TestBed.inject(DateAdapter);
adapter.setLocale('en-US');
fixture = TestBed.createComponent(TimepickerInputHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all timepicker input harnesses', async () => {
const inputs = await loader.getAllHarnesses(MatTimepickerInputHarness);
expect(inputs.length).toBe(2);
});
it('should filter inputs based on their value', async () => {
fixture.componentInstance.value.set(createTime(15, 10));
fixture.changeDetectorRef.markForCheck();
const inputs = await loader.getAllHarnesses(MatTimepickerInputHarness.with({value: /3:10/}));
expect(inputs.length).toBe(1);
});
it('should filter inputs based on their placeholder', async () => {
const inputs = await loader.getAllHarnesses(
MatTimepickerInputHarness.with({
placeholder: /^Pick/,
}),
);
expect(inputs.length).toBe(1);
});
it('should get whether the input is disabled', async () => {
const input = await loader.getHarness(MatTimepickerInputHarness.with({selector: '#bound'}));
expect(await input.isDisabled()).toBe(false);
fixture.componentInstance.disabled.set(true);
expect(await input.isDisabled()).toBe(true);
});
it('should get whether the input is required', async () => {
const input = await loader.getHarness(MatTimepickerInputHarness.with({selector: '#bound'}));
expect(await input.isRequired()).toBe(false);
fixture.componentInstance.required.set(true);
expect(await input.isRequired()).toBe(true);
});
it('should get the input value', async () => {
const input = await loader.getHarness(MatTimepickerInputHarness.with({selector: '#bound'}));
fixture.componentInstance.value.set(createTime(15, 10));
fixture.changeDetectorRef.markForCheck();
expect(await input.getValue()).toBe('3:10 PM');
});
it('should set the input value', async () => {
const input = await loader.getHarness(MatTimepickerInputHarness.with({selector: '#bound'}));
expect(await input.getValue()).toBeFalsy();
await input.setValue('3:10 PM');
expect(await input.getValue()).toBe('3:10 PM');
});
it('should set the input value based on date adapter validation and formatting', async () => {
const input = await loader.getHarness(MatTimepickerInputHarness.with({selector: '#bound'}));
const validValues: any[] = [createTime(15, 10), '', 0, false];
const invalidValues: any[] = [null, undefined];
spyOn(adapter, 'format').and.returnValue('FORMATTED_VALUE');
spyOn(adapter, 'isValid').and.callFake(value => validValues.includes(value));
spyOn(adapter, 'deserialize').and.callFake(value =>
validValues.includes(value) ? value : null,
);
spyOn(adapter, 'getValidDateOrNull').and.callFake((value: Date) =>
adapter.isValid(value) ? value : null,
);
for (let value of validValues) {
fixture.componentInstance.value.set(value);
fixture.changeDetectorRef.markForCheck();
expect(await input.getValue()).toBe('FORMATTED_VALUE');
}
for (let value of invalidValues) {
fixture.componentInstance.value.set(value);
fixture.changeDetectorRef.markForCheck();
expect(await input.getValue()).toBe('');
}
});
it('should get the input placeholder', async () => {
const inputs = await loader.getAllHarnesses(MatTimepickerInputHarness);
expect(await parallel(() => inputs.map(input => input.getPlaceholder()))).toEqual([
'Pick a time',
'Select a time',
]);
});
it('should be able to change the input focused state', async () => {
const input = await loader.getHarness(MatTimepickerInputHarness.with({selector: '#bound'}));
expect(await input.isFocused()).toBe(false);
await input.focus();
expect(await input.isFocused()).toBe(true);
await input.blur();
expect(await input.isFocused()).toBe(false);
});
it('should be able to open and close a timepicker', async () => {
const input = await loader.getHarness(MatTimepickerInputHarness.with({selector: '#bound'}));
expect(await input.isTimepickerOpen()).toBe(false);
await input.openTimepicker();
expect(await input.isTimepickerOpen()).toBe(true);
await input.closeTimepicker();
expect(await input.isTimepickerOpen()).toBe(false);
});
it('should be able to get the harness for the associated timepicker', async () => {
const input = await loader.getHarness(MatTimepickerInputHarness.with({selector: '#bound'}));
await input.openTimepicker();
expect(await input.getTimepicker()).toBeInstanceOf(MatTimepickerHarness);
});
it('should emit the `valueChange` event when the value is changed', async () => {
const input = await loader.getHarness(MatTimepickerInputHarness.with({selector: '#bound'}));
expect(fixture.componentInstance.changeCount).toBe(0);
await input.setValue('3:15 PM');
expect(fixture.componentInstance.changeCount).toBeGreaterThan(0);
});
function createTime(hours: number, minutes: number): Date {
return adapter.setTime(adapter.today(), hours, minutes, 0);
}
});
@Component({
template: `
<input
[matTimepicker]="boundPicker"
[value]="value()"
[disabled]="disabled()"
[required]="required()"
(valueChange)="changeCount = changeCount + 1"
placeholder="Pick a time"
id="bound">
<mat-timepicker #boundPicker/>
<input [matTimepicker]="basicPicker" id="basic" placeholder="Select a time">
<mat-timepicker #basicPicker/>
`,
standalone: true,
imports: [MatTimepickerInput, MatTimepicker],
})
class TimepickerInputHarnessTest {
readonly value = signal<Date | null>(null);
readonly disabled = signal(false);
readonly required = signal(false);
changeCount = 0;
}
| {
"end_byte": 6791,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/testing/timepicker-input-harness.spec.ts"
} |
components/src/material/timepicker/testing/public-api.ts_0_377 | /**
* @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 './timepicker-harness';
export * from './timepicker-harness-filters';
export * from './timepicker-input-harness';
export * from './timepicker-toggle-harness';
| {
"end_byte": 377,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/testing/public-api.ts"
} |
components/src/material/timepicker/testing/timepicker-harness-filters.ts_0_940 | /**
* @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 `MatTimepickerHarness` instances. */
export interface TimepickerHarnessFilters extends BaseHarnessFilters {}
/** A set of criteria that can be used to filter a list of timepicker input instances. */
export interface TimepickerInputHarnessFilters extends BaseHarnessFilters {
/** Filters based on the value of the input. */
value?: string | RegExp;
/** Filters based on the placeholder text of the input. */
placeholder?: string | RegExp;
}
/** A set of criteria that can be used to filter a list of timepicker toggle instances. */
export interface TimepickerToggleHarnessFilters extends BaseHarnessFilters {}
| {
"end_byte": 940,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/testing/timepicker-harness-filters.ts"
} |
components/src/material/timepicker/testing/timepicker-toggle-harness.spec.ts_0_2458 | import {Component, signal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {HarnessLoader} from '@angular/cdk/testing';
import {DateAdapter, provideNativeDateAdapter} from '@angular/material/core';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatTimepicker, MatTimepickerInput, MatTimepickerToggle} from '@angular/material/timepicker';
import {MatTimepickerToggleHarness} from './timepicker-toggle-harness';
describe('MatTimepickerToggleHarness', () => {
let fixture: ComponentFixture<TimepickerHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideNativeDateAdapter()],
imports: [NoopAnimationsModule, TimepickerHarnessTest],
});
const adapter = TestBed.inject(DateAdapter);
adapter.setLocale('en-US');
fixture = TestBed.createComponent(TimepickerHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.documentRootLoader(fixture);
});
it('should be able to load timepicker toggle harnesses', async () => {
const harnesses = await loader.getAllHarnesses(MatTimepickerToggleHarness);
expect(harnesses.length).toBe(2);
});
it('should get the open state of a timepicker toggle', async () => {
const toggle = await loader.getHarness(MatTimepickerToggleHarness.with({selector: '#one'}));
expect(await toggle.isTimepickerOpen()).toBe(false);
await toggle.openTimepicker();
expect(await toggle.isTimepickerOpen()).toBe(true);
});
it('should get the disabled state of a toggle', async () => {
const toggle = await loader.getHarness(MatTimepickerToggleHarness.with({selector: '#one'}));
expect(await toggle.isDisabled()).toBe(false);
fixture.componentInstance.disabled.set(true);
expect(await toggle.isDisabled()).toBe(true);
});
});
@Component({
template: `
<input [matTimepicker]="onePicker">
<mat-timepicker #onePicker/>
<mat-timepicker-toggle id="one" [for]="onePicker" [disabled]="disabled()"/>
<input [matTimepicker]="twoPicker">
<mat-timepicker #twoPicker/>
<mat-timepicker-toggle id="two" [for]="twoPicker" [disabled]="disabled()"/>
`,
standalone: true,
imports: [MatTimepickerInput, MatTimepicker, MatTimepickerToggle],
})
class TimepickerHarnessTest {
disabled = signal(false);
}
| {
"end_byte": 2458,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/testing/timepicker-toggle-harness.spec.ts"
} |
components/src/material/timepicker/testing/timepicker-toggle-harness.ts_0_1940 | /**
* @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, HarnessPredicate} from '@angular/cdk/testing';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {TimepickerToggleHarnessFilters} from './timepicker-harness-filters';
/** Harness for interacting with a standard Material timepicker toggle in tests. */
export class MatTimepickerToggleHarness extends ComponentHarness {
static hostSelector = '.mat-timepicker-toggle';
/** The clickable button inside the toggle. */
private _button = this.locatorFor('button');
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatTimepickerToggleHarness` that
* meets certain criteria.
* @param options Options for filtering which timepicker toggle instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(
options: TimepickerToggleHarnessFilters = {},
): HarnessPredicate<MatTimepickerToggleHarness> {
return new HarnessPredicate(MatTimepickerToggleHarness, options);
}
/** Opens the timepicker associated with the toggle. */
async openTimepicker(): Promise<void> {
const isOpen = await this.isTimepickerOpen();
if (!isOpen) {
const button = await this._button();
await button.click();
}
}
/** Gets whether the timepicker associated with the toggle is open. */
async isTimepickerOpen(): Promise<boolean> {
const button = await this._button();
const ariaExpanded = await button.getAttribute('aria-expanded');
return ariaExpanded === 'true';
}
/** Whether the toggle is disabled. */
async isDisabled(): Promise<boolean> {
const button = await this._button();
return coerceBooleanProperty(await button.getAttribute('disabled'));
}
}
| {
"end_byte": 1940,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/testing/timepicker-toggle-harness.ts"
} |
components/src/material/timepicker/testing/timepicker-harness.spec.ts_0_3323 | import {Component, signal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {HarnessLoader, parallel} from '@angular/cdk/testing';
import {DateAdapter, provideNativeDateAdapter} from '@angular/material/core';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatTimepicker, MatTimepickerInput} from '@angular/material/timepicker';
import {MatTimepickerHarness} from './timepicker-harness';
import {MatTimepickerInputHarness} from './timepicker-input-harness';
describe('MatTimepickerHarness', () => {
let fixture: ComponentFixture<TimepickerHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideNativeDateAdapter()],
imports: [NoopAnimationsModule, TimepickerHarnessTest],
});
const adapter = TestBed.inject(DateAdapter);
adapter.setLocale('en-US');
fixture = TestBed.createComponent(TimepickerHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.documentRootLoader(fixture);
});
it('should be able to load timepicker harnesses', async () => {
const harnesses = await loader.getAllHarnesses(MatTimepickerHarness);
expect(harnesses.length).toBe(2);
});
it('should get the open state of a timepicker', async () => {
const input = await loader.getHarness(MatTimepickerInputHarness.with({selector: '#one'}));
const timepicker = await input.getTimepicker();
expect(await timepicker.isOpen()).toBe(false);
await input.openTimepicker();
expect(await timepicker.isOpen()).toBe(true);
});
it('should throw when trying to get the options while closed', async () => {
const input = await loader.getHarness(MatTimepickerInputHarness.with({selector: '#one'}));
const timepicker = await input.getTimepicker();
await expectAsync(timepicker.getOptions()).toBeRejectedWithError(
/Unable to retrieve options for timepicker\. Timepicker panel is closed\./,
);
});
it('should get the options in a timepicker', async () => {
const input = await loader.getHarness(MatTimepickerInputHarness.with({selector: '#one'}));
const timepicker = await input.openTimepicker();
const options = await timepicker.getOptions();
const labels = await parallel(() => options.map(o => o.getText()));
expect(labels).toEqual(['12:00 AM', '4:00 AM', '8:00 AM', '12:00 PM', '4:00 PM', '8:00 PM']);
});
it('should be able to select an option', async () => {
const input = await loader.getHarness(MatTimepickerInputHarness.with({selector: '#one'}));
const timepicker = await input.openTimepicker();
expect(await input.getValue()).toBe('');
await timepicker.selectOption({text: '4:00 PM'});
expect(await input.getValue()).toBe('4:00 PM');
expect(await timepicker.isOpen()).toBe(false);
});
});
@Component({
template: `
<input id="one" [matTimepicker]="onePicker">
<mat-timepicker #onePicker [interval]="interval()"/>
<input id="two" [matTimepicker]="twoPicker">
<mat-timepicker #twoPicker [interval]="interval()"/>
`,
standalone: true,
imports: [MatTimepickerInput, MatTimepicker],
})
class TimepickerHarnessTest {
interval = signal('4h');
}
| {
"end_byte": 3323,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/testing/timepicker-harness.spec.ts"
} |
components/src/material/timepicker/testing/BUILD.bazel_0_899 | load("//tools:defaults.bzl", "ng_test_library", "ng_web_test_suite", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "testing",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
deps = [
"//src/cdk/coercion",
"//src/cdk/testing",
"//src/material/core/testing",
"//src/material/timepicker",
],
)
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/private",
"//src/cdk/testing/testbed",
"//src/material/core",
"//src/material/timepicker",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_tests_lib"],
)
| {
"end_byte": 899,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/testing/BUILD.bazel"
} |
components/src/material/timepicker/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/timepicker/testing/index.ts"
} |
components/src/material/timepicker/testing/timepicker-harness.ts_0_2445 | /**
* @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 {MatOptionHarness, OptionHarnessFilters} from '@angular/material/core/testing';
import {TimepickerHarnessFilters} from './timepicker-harness-filters';
export class MatTimepickerHarness extends ComponentHarness {
private _documentRootLocator = this.documentRootLocatorFactory();
static hostSelector = 'mat-timepicker';
/**
* Gets a `HarnessPredicate` that can be used to search for a timepicker with specific
* attributes.
* @param options Options for filtering which timepicker instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatTimepickerHarness>(
this: ComponentHarnessConstructor<T>,
options: TimepickerHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options);
}
/** Whether the timepicker is open. */
async isOpen(): Promise<boolean> {
const selector = await this._getPanelSelector();
const panel = await this._documentRootLocator.locatorForOptional(selector)();
return panel !== null;
}
/** Gets the options inside the timepicker panel. */
async getOptions(filters?: Omit<OptionHarnessFilters, 'ancestor'>): Promise<MatOptionHarness[]> {
if (!(await this.isOpen())) {
throw new Error('Unable to retrieve options for timepicker. Timepicker panel is closed.');
}
return this._documentRootLocator.locatorForAll(
MatOptionHarness.with({
...(filters || {}),
ancestor: await this._getPanelSelector(),
} as OptionHarnessFilters),
)();
}
/** Selects the first option matching the given filters. */
async selectOption(filters: OptionHarnessFilters): Promise<void> {
const options = await this.getOptions(filters);
if (!options.length) {
throw Error(`Could not find a mat-option matching ${JSON.stringify(filters)}`);
}
await options[0].click();
}
/** Gets the selector that can be used to find the timepicker's panel. */
protected async _getPanelSelector(): Promise<string> {
return `#${await (await this.host()).getAttribute('mat-timepicker-panel-id')}`;
}
}
| {
"end_byte": 2445,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/testing/timepicker-harness.ts"
} |
components/src/material/timepicker/testing/timepicker-input-harness.ts_0_4756 | /**
* @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,
TestKey,
} from '@angular/cdk/testing';
import {MatTimepickerHarness} from './timepicker-harness';
import {
TimepickerHarnessFilters,
TimepickerInputHarnessFilters,
} from './timepicker-harness-filters';
/** Harness for interacting with a standard Material timepicker inputs in tests. */
export class MatTimepickerInputHarness extends ComponentHarness {
private _documentRootLocator = this.documentRootLocatorFactory();
static hostSelector = '.mat-timepicker-input';
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatTimepickerInputHarness`
* that meets certain criteria.
* @param options Options for filtering which input instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatTimepickerInputHarness>(
this: ComponentHarnessConstructor<T>,
options: TimepickerInputHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options)
.addOption('value', options.value, (harness, value) => {
return HarnessPredicate.stringMatches(harness.getValue(), value);
})
.addOption('placeholder', options.placeholder, (harness, placeholder) => {
return HarnessPredicate.stringMatches(harness.getPlaceholder(), placeholder);
});
}
/** Gets whether the timepicker associated with the input is open. */
async isTimepickerOpen(): Promise<boolean> {
const host = await this.host();
return (await host.getAttribute('aria-expanded')) === 'true';
}
/** Opens the timepicker associated with the input and returns the timepicker instance. */
async openTimepicker(): Promise<MatTimepickerHarness> {
if (!(await this.isDisabled())) {
const host = await this.host();
await host.sendKeys(TestKey.DOWN_ARROW);
}
return this.getTimepicker();
}
/** Closes the timepicker associated with the input. */
async closeTimepicker(): Promise<void> {
await this._documentRootLocator.rootElement.click();
// This is necessary so that we wait for the closing animation.
await this.forceStabilize();
}
/**
* Gets the `MatTimepickerHarness` that is associated with the input.
* @param filter Optionally filters which timepicker is included.
*/
async getTimepicker(filter: TimepickerHarnessFilters = {}): Promise<MatTimepickerHarness> {
const host = await this.host();
const timepickerId = await host.getAttribute('mat-timepicker-id');
if (!timepickerId) {
throw Error('Element is not associated with a timepicker');
}
return this._documentRootLocator.locatorFor(
MatTimepickerHarness.with({
...filter,
selector: `[mat-timepicker-panel-id="${timepickerId}"]`,
}),
)();
}
/** Whether the input is disabled. */
async isDisabled(): Promise<boolean> {
return (await this.host()).getProperty<boolean>('disabled');
}
/** Whether the input is required. */
async isRequired(): Promise<boolean> {
return (await this.host()).getProperty<boolean>('required');
}
/** Gets the value of the input. */
async getValue(): Promise<string> {
// The "value" property of the native input is always defined.
return await (await this.host()).getProperty<string>('value');
}
/**
* Sets the value of the input. The value will be set by simulating
* keypresses that correspond to the given value.
*/
async setValue(newValue: string): Promise<void> {
const inputEl = await this.host();
await inputEl.clear();
// We don't want to send keys for the value if the value is an empty
// string in order to clear the value. Sending keys with an empty string
// still results in unnecessary focus events.
if (newValue) {
await inputEl.sendKeys(newValue);
}
}
/** Gets the placeholder of the input. */
async getPlaceholder(): Promise<string> {
return await (await this.host()).getProperty<string>('placeholder');
}
/**
* Focuses the input and returns a promise that indicates when the
* action is complete.
*/
async focus(): Promise<void> {
return (await this.host()).focus();
}
/**
* Blurs the input and returns a promise that indicates when the
* action is complete.
*/
async blur(): Promise<void> {
return (await this.host()).blur();
}
/** Whether the input is focused. */
async isFocused(): Promise<boolean> {
return (await this.host()).isFocused();
}
}
| {
"end_byte": 4756,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/timepicker/testing/timepicker-input-harness.ts"
} |
components/src/material/tooltip/module.ts_0_847 | /**
* @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 {A11yModule} from '@angular/cdk/a11y';
import {OverlayModule} from '@angular/cdk/overlay';
import {CdkScrollableModule} from '@angular/cdk/scrolling';
import {MatCommonModule} from '@angular/material/core';
import {
MatTooltip,
TooltipComponent,
MAT_TOOLTIP_SCROLL_STRATEGY_FACTORY_PROVIDER,
} from './tooltip';
@NgModule({
imports: [A11yModule, OverlayModule, MatCommonModule, MatTooltip, TooltipComponent],
exports: [MatTooltip, TooltipComponent, MatCommonModule, CdkScrollableModule],
providers: [MAT_TOOLTIP_SCROLL_STRATEGY_FACTORY_PROVIDER],
})
export class MatTooltipModule {}
| {
"end_byte": 847,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/module.ts"
} |
components/src/material/tooltip/_tooltip-theme.scss_0_3247 | @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/plain-tooltip' as tokens-mdc-plain-tooltip;
@mixin base($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, base));
} @else {
// Add default values for tokens not related to color, typography, or density.
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mdc-plain-tooltip.$prefix,
tokens-mdc-plain-tooltip.get-unthemable-tokens()
);
}
}
}
@mixin color($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, color));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mdc-plain-tooltip.$prefix,
tokens-mdc-plain-tooltip.get-color-tokens($theme)
);
}
}
}
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mdc-plain-tooltip.$prefix,
tokens-mdc-plain-tooltip.get-typography-tokens($theme)
);
}
}
}
@mixin density($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, density));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mdc-plain-tooltip.$prefix,
tokens-mdc-plain-tooltip.get-density-tokens($theme)
);
}
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
@return (
(
namespace: tokens-mdc-plain-tooltip.$prefix,
tokens: tokens-mdc-plain-tooltip.get-token-slots(),
),
);
}
@mixin overrides($tokens: ()) {
@include token-utils.batch-create-token-values($tokens, _define-overrides()...);
}
@mixin theme($theme) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-tooltip') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme));
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
@if $tokens != () {
$tokens: token-utils.get-tokens-for($tokens, tokens-mdc-plain-tooltip.$prefix);
@include token-utils.create-token-values(tokens-mdc-plain-tooltip.$prefix, $tokens);
}
}
| {
"end_byte": 3247,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/_tooltip-theme.scss"
} |
components/src/material/tooltip/public-api.ts_0_295 | /**
* @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 './tooltip';
export * from './tooltip-animations';
export * from './module';
| {
"end_byte": 295,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/public-api.ts"
} |
components/src/material/tooltip/tooltip-animations.ts_0_1003 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
animate,
AnimationTriggerMetadata,
state,
style,
transition,
trigger,
} from '@angular/animations';
/**
* Animations used by MatTooltip.
* @docs-private
*/
export const matTooltipAnimations: {
readonly tooltipState: AnimationTriggerMetadata;
} = {
/** Animation that transitions a tooltip in and out. */
tooltipState: trigger('state', [
// TODO(crisbeto): these values are based on MDC's CSS.
// We should be able to use their styles directly once we land #19432.
state('initial, void, hidden', style({opacity: 0, transform: 'scale(0.8)'})),
state('visible', style({transform: 'scale(1)'})),
transition('* => visible', animate('150ms cubic-bezier(0, 0, 0.2, 1)')),
transition('* => hidden', animate('75ms cubic-bezier(0.4, 0, 1, 1)')),
]),
};
| {
"end_byte": 1003,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip-animations.ts"
} |
components/src/material/tooltip/tooltip.scss_0_3401 | @use '../core/tokens/m2/mdc/plain-tooltip' as tokens-mdc-plain-tooltip;
@use '../core/tokens/token-utils';
.mat-mdc-tooltip {
// We don't use MDC's positioning so this has to be relative.
position: relative;
transform: scale(0);
display: inline-flex;
// Increases the area of the tooltip so the user's pointer can go from the trigger directly to it.
&::before {
$offset: -8px;
content: '';
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: -1;
position: absolute;
// Only set the offset on the side closest to the panel so we
// don't accidentally cover more content than we need to.
.mat-mdc-tooltip-panel-below & {
top: $offset;
}
.mat-mdc-tooltip-panel-above & {
bottom: $offset;
}
// Note that here we use left/right instead of before/after
// so that we don't have to add extra styles for RTL.
.mat-mdc-tooltip-panel-right & {
left: $offset;
}
.mat-mdc-tooltip-panel-left & {
right: $offset;
}
}
&._mat-animation-noopable {
animation: none;
transform: scale(1);
}
}
.mat-mdc-tooltip-surface {
word-break: normal;
overflow-wrap: anywhere;
padding: 4px 8px;
min-width: 40px;
max-width: 200px;
min-height: 24px;
max-height: 40vh;
box-sizing: border-box;
overflow: hidden;
text-align: center;
// TODO(crisbeto): these styles aren't necessary, but they were present in
// MDC and removing them is likely to cause screenshot differences.
will-change: transform, opacity;
@include token-utils.use-tokens(
tokens-mdc-plain-tooltip.$prefix,
tokens-mdc-plain-tooltip.get-token-slots()
) {
@include token-utils.create-token-slot(background-color, container-color);
@include token-utils.create-token-slot(color, supporting-text-color);
@include token-utils.create-token-slot(border-radius, container-shape);
@include token-utils.create-token-slot(font-family, supporting-text-font);
@include token-utils.create-token-slot(font-size, supporting-text-size);
@include token-utils.create-token-slot(font-weight, supporting-text-weight);
@include token-utils.create-token-slot(line-height, supporting-text-line-height);
@include token-utils.create-token-slot(letter-spacing, supporting-text-tracking);
}
// Renders an outline in high contrast mode.
&::before {
position: absolute;
box-sizing: border-box;
width: 100%;
height: 100%;
top: 0;
left: 0;
border: 1px solid transparent;
border-radius: inherit;
content: '';
pointer-events: none;
}
.mdc-tooltip--multiline & {
text-align: left;
}
[dir='rtl'] .mdc-tooltip--multiline & {
text-align: right;
}
}
// We need the additional specificity here, because it can be overridden by `.cdk-overlay-panel`.
.mat-mdc-tooltip-panel.mat-mdc-tooltip-panel-non-interactive {
pointer-events: none;
}
@keyframes mat-mdc-tooltip-show {
0% {
opacity: 0;
transform: scale(0.8);
}
100% {
opacity: 1;
transform: scale(1);
}
}
@keyframes mat-mdc-tooltip-hide {
0% {
opacity: 1;
transform: scale(1);
}
100% {
opacity: 0;
transform: scale(0.8);
}
}
.mat-mdc-tooltip-show {
animation: mat-mdc-tooltip-show 150ms cubic-bezier(0, 0, 0.2, 1) forwards;
}
.mat-mdc-tooltip-hide {
animation: mat-mdc-tooltip-hide 75ms cubic-bezier(0.4, 0, 1, 1) forwards;
}
| {
"end_byte": 3401,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.scss"
} |
components/src/material/tooltip/README.md_0_98 | Please see the official documentation at https://material.angular.io/components/component/tooltip
| {
"end_byte": 98,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/README.md"
} |
components/src/material/tooltip/tooltip.ts_0_5752 | /**
* @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 {takeUntil} from 'rxjs/operators';
import {
BooleanInput,
coerceBooleanProperty,
coerceNumberProperty,
NumberInput,
} from '@angular/cdk/coercion';
import {ESCAPE, hasModifierKey} from '@angular/cdk/keycodes';
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
Directive,
ElementRef,
InjectionToken,
Input,
NgZone,
OnDestroy,
ViewChild,
ViewContainerRef,
ViewEncapsulation,
inject,
ANIMATION_MODULE_TYPE,
afterNextRender,
Injector,
} from '@angular/core';
import {DOCUMENT, NgClass} from '@angular/common';
import {normalizePassiveListenerOptions, Platform} from '@angular/cdk/platform';
import {AriaDescriber, FocusMonitor} from '@angular/cdk/a11y';
import {Directionality} from '@angular/cdk/bidi';
import {
ConnectedPosition,
ConnectionPositionPair,
FlexibleConnectedPositionStrategy,
HorizontalConnectionPos,
OriginConnectionPosition,
Overlay,
OverlayConnectionPosition,
OverlayRef,
ScrollDispatcher,
ScrollStrategy,
VerticalConnectionPos,
} from '@angular/cdk/overlay';
import {ComponentPortal} from '@angular/cdk/portal';
import {Observable, Subject} from 'rxjs';
/** Possible positions for a tooltip. */
export type TooltipPosition = 'left' | 'right' | 'above' | 'below' | 'before' | 'after';
/**
* Options for how the tooltip trigger should handle touch gestures.
* See `MatTooltip.touchGestures` for more information.
*/
export type TooltipTouchGestures = 'auto' | 'on' | 'off';
/** Possible visibility states of a tooltip. */
export type TooltipVisibility = 'initial' | 'visible' | 'hidden';
/** Time in ms to throttle repositioning after scroll events. */
export const SCROLL_THROTTLE_MS = 20;
/**
* Creates an error to be thrown if the user supplied an invalid tooltip position.
* @docs-private
*/
export function getMatTooltipInvalidPositionError(position: string) {
return Error(`Tooltip position "${position}" is invalid.`);
}
/** Injection token that determines the scroll handling while a tooltip is visible. */
export const MAT_TOOLTIP_SCROLL_STRATEGY = new InjectionToken<() => ScrollStrategy>(
'mat-tooltip-scroll-strategy',
{
providedIn: 'root',
factory: () => {
const overlay = inject(Overlay);
return () => overlay.scrollStrategies.reposition({scrollThrottle: SCROLL_THROTTLE_MS});
},
},
);
/** @docs-private */
export function MAT_TOOLTIP_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy {
return () => overlay.scrollStrategies.reposition({scrollThrottle: SCROLL_THROTTLE_MS});
}
/** @docs-private */
export const MAT_TOOLTIP_SCROLL_STRATEGY_FACTORY_PROVIDER = {
provide: MAT_TOOLTIP_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: MAT_TOOLTIP_SCROLL_STRATEGY_FACTORY,
};
/** @docs-private */
export function MAT_TOOLTIP_DEFAULT_OPTIONS_FACTORY(): MatTooltipDefaultOptions {
return {
showDelay: 0,
hideDelay: 0,
touchendHideDelay: 1500,
};
}
/** Injection token to be used to override the default options for `matTooltip`. */
export const MAT_TOOLTIP_DEFAULT_OPTIONS = new InjectionToken<MatTooltipDefaultOptions>(
'mat-tooltip-default-options',
{
providedIn: 'root',
factory: MAT_TOOLTIP_DEFAULT_OPTIONS_FACTORY,
},
);
/** Default `matTooltip` options that can be overridden. */
export interface MatTooltipDefaultOptions {
/** Default delay when the tooltip is shown. */
showDelay: number;
/** Default delay when the tooltip is hidden. */
hideDelay: number;
/** Default delay when hiding the tooltip on a touch device. */
touchendHideDelay: number;
/** Time between the user putting the pointer on a tooltip trigger and the long press event being fired on a touch device. */
touchLongPressShowDelay?: number;
/** Default touch gesture handling for tooltips. */
touchGestures?: TooltipTouchGestures;
/** Default position for tooltips. */
position?: TooltipPosition;
/**
* Default value for whether tooltips should be positioned near the click or touch origin
* instead of outside the element bounding box.
*/
positionAtOrigin?: boolean;
/** Disables the ability for the user to interact with the tooltip element. */
disableTooltipInteractivity?: boolean;
/**
* Default classes to be applied to the tooltip. These default classes will not be applied if
* `tooltipClass` is defined directly on the tooltip element, as it will override the default.
*/
tooltipClass?: string | string[];
}
/**
* CSS class that will be attached to the overlay panel.
* @deprecated
* @breaking-change 13.0.0 remove this variable
*/
export const TOOLTIP_PANEL_CLASS = 'mat-mdc-tooltip-panel';
const PANEL_CLASS = 'tooltip-panel';
/** Options used to bind passive event listeners. */
const passiveListenerOptions = normalizePassiveListenerOptions({passive: true});
// These constants were taken from MDC's `numbers` object. We can't import them from MDC,
// because they have some top-level references to `window` which break during SSR.
const MIN_VIEWPORT_TOOLTIP_THRESHOLD = 8;
const UNBOUNDED_ANCHOR_GAP = 8;
const MIN_HEIGHT = 24;
const MAX_WIDTH = 200;
/**
* Directive that attaches a material design tooltip to the host element. Animates the showing and
* hiding of a tooltip provided position (defaults to below the element).
*
* https://material.io/design/components/tooltips.html
*/
@Directive({
selector: '[matTooltip]',
exportAs: 'matTooltip',
host: {
'class': 'mat-mdc-tooltip-trigger',
'[class.mat-mdc-tooltip-disabled]': 'disabled',
},
})
export | {
"end_byte": 5752,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.ts"
} |
components/src/material/tooltip/tooltip.ts_5753_14359 | class MatTooltip implements OnDestroy, AfterViewInit {
private _overlay = inject(Overlay);
private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private _scrollDispatcher = inject(ScrollDispatcher);
private _viewContainerRef = inject(ViewContainerRef);
private _ngZone = inject(NgZone);
private _platform = inject(Platform);
private _ariaDescriber = inject(AriaDescriber);
private _focusMonitor = inject(FocusMonitor);
protected _dir = inject(Directionality);
private _injector = inject(Injector);
private _defaultOptions = inject<MatTooltipDefaultOptions>(MAT_TOOLTIP_DEFAULT_OPTIONS, {
optional: true,
});
_overlayRef: OverlayRef | null;
_tooltipInstance: TooltipComponent | null;
private _portal: ComponentPortal<TooltipComponent>;
private _position: TooltipPosition = 'below';
private _positionAtOrigin: boolean = false;
private _disabled: boolean = false;
private _tooltipClass: string | string[] | Set<string> | {[key: string]: any};
private _scrollStrategy = inject(MAT_TOOLTIP_SCROLL_STRATEGY);
private _viewInitialized = false;
private _pointerExitEventsInitialized = false;
private readonly _tooltipComponent = TooltipComponent;
private _viewportMargin = 8;
private _currentPosition: TooltipPosition;
private readonly _cssClassPrefix: string = 'mat-mdc';
private _ariaDescriptionPending: boolean;
/** Allows the user to define the position of the tooltip relative to the parent element */
@Input('matTooltipPosition')
get position(): TooltipPosition {
return this._position;
}
set position(value: TooltipPosition) {
if (value !== this._position) {
this._position = value;
if (this._overlayRef) {
this._updatePosition(this._overlayRef);
this._tooltipInstance?.show(0);
this._overlayRef.updatePosition();
}
}
}
/**
* Whether tooltip should be relative to the click or touch origin
* instead of outside the element bounding box.
*/
@Input('matTooltipPositionAtOrigin')
get positionAtOrigin(): boolean {
return this._positionAtOrigin;
}
set positionAtOrigin(value: BooleanInput) {
this._positionAtOrigin = coerceBooleanProperty(value);
this._detach();
this._overlayRef = null;
}
/** Disables the display of the tooltip. */
@Input('matTooltipDisabled')
get disabled(): boolean {
return this._disabled;
}
set disabled(value: BooleanInput) {
const isDisabled = coerceBooleanProperty(value);
if (this._disabled !== isDisabled) {
this._disabled = isDisabled;
// If tooltip is disabled, hide immediately.
if (isDisabled) {
this.hide(0);
} else {
this._setupPointerEnterEventsIfNeeded();
}
this._syncAriaDescription(this.message);
}
}
/** The default delay in ms before showing the tooltip after show is called */
@Input('matTooltipShowDelay')
get showDelay(): number {
return this._showDelay;
}
set showDelay(value: NumberInput) {
this._showDelay = coerceNumberProperty(value);
}
private _showDelay: number;
/** The default delay in ms before hiding the tooltip after hide is called */
@Input('matTooltipHideDelay')
get hideDelay(): number {
return this._hideDelay;
}
set hideDelay(value: NumberInput) {
this._hideDelay = coerceNumberProperty(value);
if (this._tooltipInstance) {
this._tooltipInstance._mouseLeaveHideDelay = this._hideDelay;
}
}
private _hideDelay: number;
/**
* How touch gestures should be handled by the tooltip. On touch devices the tooltip directive
* uses a long press gesture to show and hide, however it can conflict with the native browser
* gestures. To work around the conflict, Angular Material disables native gestures on the
* trigger, but that might not be desirable on particular elements (e.g. inputs and draggable
* elements). The different values for this option configure the touch event handling as follows:
* - `auto` - Enables touch gestures for all elements, but tries to avoid conflicts with native
* browser gestures on particular elements. In particular, it allows text selection on inputs
* and textareas, and preserves the native browser dragging on elements marked as `draggable`.
* - `on` - Enables touch gestures for all elements and disables native
* browser gestures with no exceptions.
* - `off` - Disables touch gestures. Note that this will prevent the tooltip from
* showing on touch devices.
*/
@Input('matTooltipTouchGestures') touchGestures: TooltipTouchGestures = 'auto';
/** The message to be displayed in the tooltip */
@Input('matTooltip')
get message(): string {
return this._message;
}
set message(value: string | null | undefined) {
const oldMessage = this._message;
// If the message is not a string (e.g. number), convert it to a string and trim it.
// Must convert with `String(value)`, not `${value}`, otherwise Closure Compiler optimises
// away the string-conversion: https://github.com/angular/components/issues/20684
this._message = value != null ? String(value).trim() : '';
if (!this._message && this._isTooltipVisible()) {
this.hide(0);
} else {
this._setupPointerEnterEventsIfNeeded();
this._updateTooltipMessage();
}
this._syncAriaDescription(oldMessage);
}
private _message = '';
/** Classes to be passed to the tooltip. Supports the same syntax as `ngClass`. */
@Input('matTooltipClass')
get tooltipClass() {
return this._tooltipClass;
}
set tooltipClass(value: string | string[] | Set<string> | {[key: string]: any}) {
this._tooltipClass = value;
if (this._tooltipInstance) {
this._setTooltipClass(this._tooltipClass);
}
}
/** Manually-bound passive event listeners. */
private readonly _passiveListeners: (readonly [string, EventListenerOrEventListenerObject])[] =
[];
/** Reference to the current document. */
private _document = inject(DOCUMENT);
/** Timer started at the last `touchstart` event. */
private _touchstartTimeout: null | ReturnType<typeof setTimeout> = null;
/** Emits when the component is destroyed. */
private readonly _destroyed = new Subject<void>();
constructor(...args: unknown[]);
constructor() {
const defaultOptions = this._defaultOptions;
if (defaultOptions) {
this._showDelay = defaultOptions.showDelay;
this._hideDelay = defaultOptions.hideDelay;
if (defaultOptions.position) {
this.position = defaultOptions.position;
}
if (defaultOptions.positionAtOrigin) {
this.positionAtOrigin = defaultOptions.positionAtOrigin;
}
if (defaultOptions.touchGestures) {
this.touchGestures = defaultOptions.touchGestures;
}
if (defaultOptions.tooltipClass) {
this.tooltipClass = defaultOptions.tooltipClass;
}
}
this._dir.change.pipe(takeUntil(this._destroyed)).subscribe(() => {
if (this._overlayRef) {
this._updatePosition(this._overlayRef);
}
});
this._viewportMargin = MIN_VIEWPORT_TOOLTIP_THRESHOLD;
}
ngAfterViewInit() {
// This needs to happen after view init so the initial values for all inputs have been set.
this._viewInitialized = true;
this._setupPointerEnterEventsIfNeeded();
this._focusMonitor
.monitor(this._elementRef)
.pipe(takeUntil(this._destroyed))
.subscribe(origin => {
// Note that the focus monitor runs outside the Angular zone.
if (!origin) {
this._ngZone.run(() => this.hide(0));
} else if (origin === 'keyboard') {
this._ngZone.run(() => this.show());
}
});
}
/**
* Dispose the tooltip when destroyed.
*/
ngOnDestroy() {
const nativeElement = this._elementRef.nativeElement;
// Optimization: Do not call clearTimeout unless there is an active timer.
if (this._touchstartTimeout) {
clearTimeout(this._touchstartTimeout);
}
if (this._overlayRef) {
this._overlayRef.dispose();
this._tooltipInstance = null;
}
// Clean up the event listeners set in the constructor
this._passiveListeners.forEach(([event, listener]) => {
nativeElement.removeEventListener(event, listener, passiveListenerOptions);
});
this._passiveListeners.length = 0;
this._destroyed.next();
this._destroyed.complete();
this._ariaDescriber.removeDescription(nativeElement, this.message, 'tooltip');
this._focusMonitor.stopMonitoring(nativeElement);
} | {
"end_byte": 14359,
"start_byte": 5753,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.ts"
} |
components/src/material/tooltip/tooltip.ts_14363_22552 | /** Shows the tooltip after the delay in ms, defaults to tooltip-delay-show or 0ms if no input */
show(delay: number = this.showDelay, origin?: {x: number; y: number}): void {
if (this.disabled || !this.message || this._isTooltipVisible()) {
this._tooltipInstance?._cancelPendingAnimations();
return;
}
const overlayRef = this._createOverlay(origin);
this._detach();
this._portal =
this._portal || new ComponentPortal(this._tooltipComponent, this._viewContainerRef);
const instance = (this._tooltipInstance = overlayRef.attach(this._portal).instance);
instance._triggerElement = this._elementRef.nativeElement;
instance._mouseLeaveHideDelay = this._hideDelay;
instance
.afterHidden()
.pipe(takeUntil(this._destroyed))
.subscribe(() => this._detach());
this._setTooltipClass(this._tooltipClass);
this._updateTooltipMessage();
instance.show(delay);
}
/** Hides the tooltip after the delay in ms, defaults to tooltip-delay-hide or 0ms if no input */
hide(delay: number = this.hideDelay): void {
const instance = this._tooltipInstance;
if (instance) {
if (instance.isVisible()) {
instance.hide(delay);
} else {
instance._cancelPendingAnimations();
this._detach();
}
}
}
/** Shows/hides the tooltip */
toggle(origin?: {x: number; y: number}): void {
this._isTooltipVisible() ? this.hide() : this.show(undefined, origin);
}
/** Returns true if the tooltip is currently visible to the user */
_isTooltipVisible(): boolean {
return !!this._tooltipInstance && this._tooltipInstance.isVisible();
}
/** Create the overlay config and position strategy */
private _createOverlay(origin?: {x: number; y: number}): OverlayRef {
if (this._overlayRef) {
const existingStrategy = this._overlayRef.getConfig()
.positionStrategy as FlexibleConnectedPositionStrategy;
if ((!this.positionAtOrigin || !origin) && existingStrategy._origin instanceof ElementRef) {
return this._overlayRef;
}
this._detach();
}
const scrollableAncestors = this._scrollDispatcher.getAncestorScrollContainers(
this._elementRef,
);
// Create connected position strategy that listens for scroll events to reposition.
const strategy = this._overlay
.position()
.flexibleConnectedTo(this.positionAtOrigin ? origin || this._elementRef : this._elementRef)
.withTransformOriginOn(`.${this._cssClassPrefix}-tooltip`)
.withFlexibleDimensions(false)
.withViewportMargin(this._viewportMargin)
.withScrollableContainers(scrollableAncestors);
strategy.positionChanges.pipe(takeUntil(this._destroyed)).subscribe(change => {
this._updateCurrentPositionClass(change.connectionPair);
if (this._tooltipInstance) {
if (change.scrollableViewProperties.isOverlayClipped && this._tooltipInstance.isVisible()) {
// After position changes occur and the overlay is clipped by
// a parent scrollable then close the tooltip.
this._ngZone.run(() => this.hide(0));
}
}
});
this._overlayRef = this._overlay.create({
direction: this._dir,
positionStrategy: strategy,
panelClass: `${this._cssClassPrefix}-${PANEL_CLASS}`,
scrollStrategy: this._scrollStrategy(),
});
this._updatePosition(this._overlayRef);
this._overlayRef
.detachments()
.pipe(takeUntil(this._destroyed))
.subscribe(() => this._detach());
this._overlayRef
.outsidePointerEvents()
.pipe(takeUntil(this._destroyed))
.subscribe(() => this._tooltipInstance?._handleBodyInteraction());
this._overlayRef
.keydownEvents()
.pipe(takeUntil(this._destroyed))
.subscribe(event => {
if (this._isTooltipVisible() && event.keyCode === ESCAPE && !hasModifierKey(event)) {
event.preventDefault();
event.stopPropagation();
this._ngZone.run(() => this.hide(0));
}
});
if (this._defaultOptions?.disableTooltipInteractivity) {
this._overlayRef.addPanelClass(`${this._cssClassPrefix}-tooltip-panel-non-interactive`);
}
return this._overlayRef;
}
/** Detaches the currently-attached tooltip. */
private _detach() {
if (this._overlayRef && this._overlayRef.hasAttached()) {
this._overlayRef.detach();
}
this._tooltipInstance = null;
}
/** Updates the position of the current tooltip. */
private _updatePosition(overlayRef: OverlayRef) {
const position = overlayRef.getConfig().positionStrategy as FlexibleConnectedPositionStrategy;
const origin = this._getOrigin();
const overlay = this._getOverlayPosition();
position.withPositions([
this._addOffset({...origin.main, ...overlay.main}),
this._addOffset({...origin.fallback, ...overlay.fallback}),
]);
}
/** Adds the configured offset to a position. Used as a hook for child classes. */
protected _addOffset(position: ConnectedPosition): ConnectedPosition {
const offset = UNBOUNDED_ANCHOR_GAP;
const isLtr = !this._dir || this._dir.value == 'ltr';
if (position.originY === 'top') {
position.offsetY = -offset;
} else if (position.originY === 'bottom') {
position.offsetY = offset;
} else if (position.originX === 'start') {
position.offsetX = isLtr ? -offset : offset;
} else if (position.originX === 'end') {
position.offsetX = isLtr ? offset : -offset;
}
return position;
}
/**
* Returns the origin position and a fallback position based on the user's position preference.
* The fallback position is the inverse of the origin (e.g. `'below' -> 'above'`).
*/
_getOrigin(): {main: OriginConnectionPosition; fallback: OriginConnectionPosition} {
const isLtr = !this._dir || this._dir.value == 'ltr';
const position = this.position;
let originPosition: OriginConnectionPosition;
if (position == 'above' || position == 'below') {
originPosition = {originX: 'center', originY: position == 'above' ? 'top' : 'bottom'};
} else if (
position == 'before' ||
(position == 'left' && isLtr) ||
(position == 'right' && !isLtr)
) {
originPosition = {originX: 'start', originY: 'center'};
} else if (
position == 'after' ||
(position == 'right' && isLtr) ||
(position == 'left' && !isLtr)
) {
originPosition = {originX: 'end', originY: 'center'};
} else if (typeof ngDevMode === 'undefined' || ngDevMode) {
throw getMatTooltipInvalidPositionError(position);
}
const {x, y} = this._invertPosition(originPosition!.originX, originPosition!.originY);
return {
main: originPosition!,
fallback: {originX: x, originY: y},
};
}
/** Returns the overlay position and a fallback position based on the user's preference */
_getOverlayPosition(): {main: OverlayConnectionPosition; fallback: OverlayConnectionPosition} {
const isLtr = !this._dir || this._dir.value == 'ltr';
const position = this.position;
let overlayPosition: OverlayConnectionPosition;
if (position == 'above') {
overlayPosition = {overlayX: 'center', overlayY: 'bottom'};
} else if (position == 'below') {
overlayPosition = {overlayX: 'center', overlayY: 'top'};
} else if (
position == 'before' ||
(position == 'left' && isLtr) ||
(position == 'right' && !isLtr)
) {
overlayPosition = {overlayX: 'end', overlayY: 'center'};
} else if (
position == 'after' ||
(position == 'right' && isLtr) ||
(position == 'left' && !isLtr)
) {
overlayPosition = {overlayX: 'start', overlayY: 'center'};
} else if (typeof ngDevMode === 'undefined' || ngDevMode) {
throw getMatTooltipInvalidPositionError(position);
}
const {x, y} = this._invertPosition(overlayPosition!.overlayX, overlayPosition!.overlayY);
return {
main: overlayPosition!,
fallback: {overlayX: x, overlayY: y},
};
}
/** Updates the tooltip message and repositions the overlay according to the new message length */ | {
"end_byte": 22552,
"start_byte": 14363,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.ts"
} |
components/src/material/tooltip/tooltip.ts_22555_30582 | private _updateTooltipMessage() {
// Must wait for the message to be painted to the tooltip so that the overlay can properly
// calculate the correct positioning based on the size of the text.
if (this._tooltipInstance) {
this._tooltipInstance.message = this.message;
this._tooltipInstance._markForCheck();
afterNextRender(
() => {
if (this._tooltipInstance) {
this._overlayRef!.updatePosition();
}
},
{
injector: this._injector,
},
);
}
}
/** Updates the tooltip class */
private _setTooltipClass(tooltipClass: string | string[] | Set<string> | {[key: string]: any}) {
if (this._tooltipInstance) {
this._tooltipInstance.tooltipClass = tooltipClass;
this._tooltipInstance._markForCheck();
}
}
/** Inverts an overlay position. */
private _invertPosition(x: HorizontalConnectionPos, y: VerticalConnectionPos) {
if (this.position === 'above' || this.position === 'below') {
if (y === 'top') {
y = 'bottom';
} else if (y === 'bottom') {
y = 'top';
}
} else {
if (x === 'end') {
x = 'start';
} else if (x === 'start') {
x = 'end';
}
}
return {x, y};
}
/** Updates the class on the overlay panel based on the current position of the tooltip. */
private _updateCurrentPositionClass(connectionPair: ConnectionPositionPair): void {
const {overlayY, originX, originY} = connectionPair;
let newPosition: TooltipPosition;
// If the overlay is in the middle along the Y axis,
// it means that it's either before or after.
if (overlayY === 'center') {
// Note that since this information is used for styling, we want to
// resolve `start` and `end` to their real values, otherwise consumers
// would have to remember to do it themselves on each consumption.
if (this._dir && this._dir.value === 'rtl') {
newPosition = originX === 'end' ? 'left' : 'right';
} else {
newPosition = originX === 'start' ? 'left' : 'right';
}
} else {
newPosition = overlayY === 'bottom' && originY === 'top' ? 'above' : 'below';
}
if (newPosition !== this._currentPosition) {
const overlayRef = this._overlayRef;
if (overlayRef) {
const classPrefix = `${this._cssClassPrefix}-${PANEL_CLASS}-`;
overlayRef.removePanelClass(classPrefix + this._currentPosition);
overlayRef.addPanelClass(classPrefix + newPosition);
}
this._currentPosition = newPosition;
}
}
/** Binds the pointer events to the tooltip trigger. */
private _setupPointerEnterEventsIfNeeded() {
// Optimization: Defer hooking up events if there's no message or the tooltip is disabled.
if (
this._disabled ||
!this.message ||
!this._viewInitialized ||
this._passiveListeners.length
) {
return;
}
// The mouse events shouldn't be bound on mobile devices, because they can prevent the
// first tap from firing its click event or can cause the tooltip to open for clicks.
if (this._platformSupportsMouseEvents()) {
this._passiveListeners.push([
'mouseenter',
event => {
this._setupPointerExitEventsIfNeeded();
let point = undefined;
if ((event as MouseEvent).x !== undefined && (event as MouseEvent).y !== undefined) {
point = event as MouseEvent;
}
this.show(undefined, point);
},
]);
} else if (this.touchGestures !== 'off') {
this._disableNativeGesturesIfNecessary();
this._passiveListeners.push([
'touchstart',
event => {
const touch = (event as TouchEvent).targetTouches?.[0];
const origin = touch ? {x: touch.clientX, y: touch.clientY} : undefined;
// Note that it's important that we don't `preventDefault` here,
// because it can prevent click events from firing on the element.
this._setupPointerExitEventsIfNeeded();
if (this._touchstartTimeout) {
clearTimeout(this._touchstartTimeout);
}
const DEFAULT_LONGPRESS_DELAY = 500;
this._touchstartTimeout = setTimeout(() => {
this._touchstartTimeout = null;
this.show(undefined, origin);
}, this._defaultOptions?.touchLongPressShowDelay ?? DEFAULT_LONGPRESS_DELAY);
},
]);
}
this._addListeners(this._passiveListeners);
}
private _setupPointerExitEventsIfNeeded() {
if (this._pointerExitEventsInitialized) {
return;
}
this._pointerExitEventsInitialized = true;
const exitListeners: (readonly [string, EventListenerOrEventListenerObject])[] = [];
if (this._platformSupportsMouseEvents()) {
exitListeners.push(
[
'mouseleave',
event => {
const newTarget = (event as MouseEvent).relatedTarget as Node | null;
if (!newTarget || !this._overlayRef?.overlayElement.contains(newTarget)) {
this.hide();
}
},
],
['wheel', event => this._wheelListener(event as WheelEvent)],
);
} else if (this.touchGestures !== 'off') {
this._disableNativeGesturesIfNecessary();
const touchendListener = () => {
if (this._touchstartTimeout) {
clearTimeout(this._touchstartTimeout);
}
this.hide(this._defaultOptions?.touchendHideDelay);
};
exitListeners.push(['touchend', touchendListener], ['touchcancel', touchendListener]);
}
this._addListeners(exitListeners);
this._passiveListeners.push(...exitListeners);
}
private _addListeners(listeners: (readonly [string, EventListenerOrEventListenerObject])[]) {
listeners.forEach(([event, listener]) => {
this._elementRef.nativeElement.addEventListener(event, listener, passiveListenerOptions);
});
}
private _platformSupportsMouseEvents() {
return !this._platform.IOS && !this._platform.ANDROID;
}
/** Listener for the `wheel` event on the element. */
private _wheelListener(event: WheelEvent) {
if (this._isTooltipVisible()) {
const elementUnderPointer = this._document.elementFromPoint(event.clientX, event.clientY);
const element = this._elementRef.nativeElement;
// On non-touch devices we depend on the `mouseleave` event to close the tooltip, but it
// won't fire if the user scrolls away using the wheel without moving their cursor. We
// work around it by finding the element under the user's cursor and closing the tooltip
// if it's not the trigger.
if (elementUnderPointer !== element && !element.contains(elementUnderPointer)) {
this.hide();
}
}
}
/** Disables the native browser gestures, based on how the tooltip has been configured. */
private _disableNativeGesturesIfNecessary() {
const gestures = this.touchGestures;
if (gestures !== 'off') {
const element = this._elementRef.nativeElement;
const style = element.style;
// If gestures are set to `auto`, we don't disable text selection on inputs and
// textareas, because it prevents the user from typing into them on iOS Safari.
if (gestures === 'on' || (element.nodeName !== 'INPUT' && element.nodeName !== 'TEXTAREA')) {
style.userSelect =
(style as any).msUserSelect =
style.webkitUserSelect =
(style as any).MozUserSelect =
'none';
}
// If we have `auto` gestures and the element uses native HTML dragging,
// we don't set `-webkit-user-drag` because it prevents the native behavior.
if (gestures === 'on' || !element.draggable) {
(style as any).webkitUserDrag = 'none';
}
style.touchAction = 'none';
(style as any).webkitTapHighlightColor = 'transparent';
}
}
/** Updates the tooltip's ARIA description based on it current state. */ | {
"end_byte": 30582,
"start_byte": 22555,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.ts"
} |
components/src/material/tooltip/tooltip.ts_30585_39185 | private _syncAriaDescription(oldMessage: string): void {
if (this._ariaDescriptionPending) {
return;
}
this._ariaDescriptionPending = true;
this._ariaDescriber.removeDescription(this._elementRef.nativeElement, oldMessage, 'tooltip');
this._ngZone.runOutsideAngular(() => {
// The `AriaDescriber` has some functionality that avoids adding a description if it's the
// same as the `aria-label` of an element, however we can't know whether the tooltip trigger
// has a data-bound `aria-label` or when it'll be set for the first time. We can avoid the
// issue by deferring the description by a tick so Angular has time to set the `aria-label`.
Promise.resolve().then(() => {
this._ariaDescriptionPending = false;
if (this.message && !this.disabled) {
this._ariaDescriber.describe(this._elementRef.nativeElement, this.message, 'tooltip');
}
});
});
}
}
/**
* Internal component that wraps the tooltip's content.
* @docs-private
*/
@Component({
selector: 'mat-tooltip-component',
templateUrl: 'tooltip.html',
styleUrl: 'tooltip.css',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'(mouseleave)': '_handleMouseLeave($event)',
'aria-hidden': 'true',
},
imports: [NgClass],
})
export class TooltipComponent implements OnDestroy {
private _changeDetectorRef = inject(ChangeDetectorRef);
protected _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
/* Whether the tooltip text overflows to multiple lines */
_isMultiline = false;
/** Message to display in the tooltip */
message: string;
/** Classes to be added to the tooltip. Supports the same syntax as `ngClass`. */
tooltipClass: string | string[] | Set<string> | {[key: string]: any};
/** The timeout ID of any current timer set to show the tooltip */
private _showTimeoutId: ReturnType<typeof setTimeout> | undefined;
/** The timeout ID of any current timer set to hide the tooltip */
private _hideTimeoutId: ReturnType<typeof setTimeout> | undefined;
/** Element that caused the tooltip to open. */
_triggerElement: HTMLElement;
/** Amount of milliseconds to delay the closing sequence. */
_mouseLeaveHideDelay: number;
/** Whether animations are currently disabled. */
private _animationsDisabled: boolean;
/** Reference to the internal tooltip element. */
@ViewChild('tooltip', {
// Use a static query here since we interact directly with
// the DOM which can happen before `ngAfterViewInit`.
static: true,
})
_tooltip: ElementRef<HTMLElement>;
/** Whether interactions on the page should close the tooltip */
private _closeOnInteraction = false;
/** Whether the tooltip is currently visible. */
private _isVisible = false;
/** Subject for notifying that the tooltip has been hidden from the view */
private readonly _onHide: Subject<void> = new Subject();
/** Name of the show animation and the class that toggles it. */
private readonly _showAnimation = 'mat-mdc-tooltip-show';
/** Name of the hide animation and the class that toggles it. */
private readonly _hideAnimation = 'mat-mdc-tooltip-hide';
constructor(...args: unknown[]);
constructor() {
const animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true});
this._animationsDisabled = animationMode === 'NoopAnimations';
}
/**
* Shows the tooltip with an animation originating from the provided origin
* @param delay Amount of milliseconds to the delay showing the tooltip.
*/
show(delay: number): void {
// Cancel the delayed hide if it is scheduled
if (this._hideTimeoutId != null) {
clearTimeout(this._hideTimeoutId);
}
this._showTimeoutId = setTimeout(() => {
this._toggleVisibility(true);
this._showTimeoutId = undefined;
}, delay);
}
/**
* Begins the animation to hide the tooltip after the provided delay in ms.
* @param delay Amount of milliseconds to delay showing the tooltip.
*/
hide(delay: number): void {
// Cancel the delayed show if it is scheduled
if (this._showTimeoutId != null) {
clearTimeout(this._showTimeoutId);
}
this._hideTimeoutId = setTimeout(() => {
this._toggleVisibility(false);
this._hideTimeoutId = undefined;
}, delay);
}
/** Returns an observable that notifies when the tooltip has been hidden from view. */
afterHidden(): Observable<void> {
return this._onHide;
}
/** Whether the tooltip is being displayed. */
isVisible(): boolean {
return this._isVisible;
}
ngOnDestroy() {
this._cancelPendingAnimations();
this._onHide.complete();
this._triggerElement = null!;
}
/**
* Interactions on the HTML body should close the tooltip immediately as defined in the
* material design spec.
* https://material.io/design/components/tooltips.html#behavior
*/
_handleBodyInteraction(): void {
if (this._closeOnInteraction) {
this.hide(0);
}
}
/**
* Marks that the tooltip needs to be checked in the next change detection run.
* Mainly used for rendering the initial text before positioning a tooltip, which
* can be problematic in components with OnPush change detection.
*/
_markForCheck(): void {
this._changeDetectorRef.markForCheck();
}
_handleMouseLeave({relatedTarget}: MouseEvent) {
if (!relatedTarget || !this._triggerElement.contains(relatedTarget as Node)) {
if (this.isVisible()) {
this.hide(this._mouseLeaveHideDelay);
} else {
this._finalizeAnimation(false);
}
}
}
/**
* Callback for when the timeout in this.show() gets completed.
* This method is only needed by the mdc-tooltip, and so it is only implemented
* in the mdc-tooltip, not here.
*/
protected _onShow(): void {
this._isMultiline = this._isTooltipMultiline();
this._markForCheck();
}
/** Whether the tooltip text has overflown to the next line */
private _isTooltipMultiline() {
const rect = this._elementRef.nativeElement.getBoundingClientRect();
return rect.height > MIN_HEIGHT && rect.width >= MAX_WIDTH;
}
/** Event listener dispatched when an animation on the tooltip finishes. */
_handleAnimationEnd({animationName}: AnimationEvent) {
if (animationName === this._showAnimation || animationName === this._hideAnimation) {
this._finalizeAnimation(animationName === this._showAnimation);
}
}
/** Cancels any pending animation sequences. */
_cancelPendingAnimations() {
if (this._showTimeoutId != null) {
clearTimeout(this._showTimeoutId);
}
if (this._hideTimeoutId != null) {
clearTimeout(this._hideTimeoutId);
}
this._showTimeoutId = this._hideTimeoutId = undefined;
}
/** Handles the cleanup after an animation has finished. */
private _finalizeAnimation(toVisible: boolean) {
if (toVisible) {
this._closeOnInteraction = true;
} else if (!this.isVisible()) {
this._onHide.next();
}
}
/** Toggles the visibility of the tooltip element. */
private _toggleVisibility(isVisible: boolean) {
// We set the classes directly here ourselves so that toggling the tooltip state
// isn't bound by change detection. This allows us to hide it even if the
// view ref has been detached from the CD tree.
const tooltip = this._tooltip.nativeElement;
const showClass = this._showAnimation;
const hideClass = this._hideAnimation;
tooltip.classList.remove(isVisible ? hideClass : showClass);
tooltip.classList.add(isVisible ? showClass : hideClass);
if (this._isVisible !== isVisible) {
this._isVisible = isVisible;
this._changeDetectorRef.markForCheck();
}
// It's common for internal apps to disable animations using `* { animation: none !important }`
// which can break the opening sequence. Try to detect such cases and work around them.
if (isVisible && !this._animationsDisabled && typeof getComputedStyle === 'function') {
const styles = getComputedStyle(tooltip);
// Use `getPropertyValue` to avoid issues with property renaming.
if (
styles.getPropertyValue('animation-duration') === '0s' ||
styles.getPropertyValue('animation-name') === 'none'
) {
this._animationsDisabled = true;
}
}
if (isVisible) {
this._onShow();
}
if (this._animationsDisabled) {
tooltip.classList.add('_mat-animation-noopable');
this._finalizeAnimation(isVisible);
}
}
} | {
"end_byte": 39185,
"start_byte": 30585,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.ts"
} |
components/src/material/tooltip/tooltip.zone.spec.ts_0_3129 | import {Directionality} from '@angular/cdk/bidi';
import {CdkScrollable, OverlayModule} from '@angular/cdk/overlay';
import {dispatchFakeEvent} from '@angular/cdk/testing/private';
import {
Component,
DebugElement,
NgZone,
ViewChild,
provideZoneChangeDetection,
} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, tick, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {Subject} from 'rxjs';
import {MatTooltipModule} from './module';
import {MatTooltip} from './tooltip';
const initialTooltipMessage = 'initial tooltip message';
describe('MatTooltip Zone.js integration', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatTooltipModule, OverlayModule, ScrollableTooltipDemo],
providers: [
provideZoneChangeDetection(),
{
provide: Directionality,
useFactory: () => ({value: 'ltr', change: new Subject()}),
},
],
});
}));
describe('scrollable usage', () => {
let fixture: ComponentFixture<ScrollableTooltipDemo>;
let buttonDebugElement: DebugElement;
let tooltipDirective: MatTooltip;
beforeEach(() => {
fixture = TestBed.createComponent(ScrollableTooltipDemo);
fixture.detectChanges();
buttonDebugElement = fixture.debugElement.query(By.css('button'))!;
tooltipDirective = buttonDebugElement.injector.get<MatTooltip>(MatTooltip);
});
it('should execute the `hide` call, after scrolling away, inside the NgZone', fakeAsync(() => {
const inZoneSpy = jasmine.createSpy('in zone spy');
tooltipDirective.show();
fixture.detectChanges();
tick(0);
spyOn(tooltipDirective._tooltipInstance!, 'hide').and.callFake(() => {
inZoneSpy(NgZone.isInAngularZone());
});
fixture.componentInstance.scrollDown();
tick(100);
fixture.detectChanges();
expect(inZoneSpy).toHaveBeenCalled();
expect(inZoneSpy).toHaveBeenCalledWith(true);
}));
});
});
@Component({
selector: 'app',
template: `
<div cdkScrollable style="padding: 100px; margin: 300px;
height: 200px; width: 200px; overflow: auto;">
@if (showButton) {
<button style="margin-bottom: 600px"
[matTooltip]="message"
[matTooltipPosition]="position">Button</button>
}
</div>`,
standalone: true,
imports: [MatTooltipModule, OverlayModule],
})
class ScrollableTooltipDemo {
position: string = 'below';
message: string = initialTooltipMessage;
showButton: boolean = true;
@ViewChild(CdkScrollable) scrollingContainer: CdkScrollable;
scrollDown() {
const scrollingContainerEl = this.scrollingContainer.getElementRef().nativeElement;
scrollingContainerEl.scrollTop = 250;
// Emit a scroll event from the scrolling element in our component.
// This event should be picked up by the scrollable directive and notify.
// The notification should be picked up by the service.
dispatchFakeEvent(scrollingContainerEl, 'scroll');
}
}
| {
"end_byte": 3129,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.zone.spec.ts"
} |
components/src/material/tooltip/tooltip.spec.ts_0_1113 | import {FocusMonitor} from '@angular/cdk/a11y';
import {Direction, Directionality} from '@angular/cdk/bidi';
import {ESCAPE} from '@angular/cdk/keycodes';
import {CdkScrollable, OverlayContainer, OverlayModule} from '@angular/cdk/overlay';
import {Platform} from '@angular/cdk/platform';
import {
createFakeEvent,
createKeyboardEvent,
createMouseEvent,
dispatchEvent,
dispatchFakeEvent,
dispatchKeyboardEvent,
dispatchMouseEvent,
patchElementFocus,
} from '@angular/cdk/testing/private';
import {
ChangeDetectionStrategy,
Component,
DebugElement,
ElementRef,
ViewChild,
} from '@angular/core';
import {
ComponentFixture,
TestBed,
fakeAsync,
flush,
inject,
tick,
waitForAsync,
} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {Subject} from 'rxjs';
import {
MAT_TOOLTIP_DEFAULT_OPTIONS,
MatTooltip,
MatTooltipModule,
SCROLL_THROTTLE_MS,
TooltipPosition,
TooltipTouchGestures,
} from './index';
const initialTooltipMessage = 'initial tooltip message'; | {
"end_byte": 1113,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.spec.ts"
} |
components/src/material/tooltip/tooltip.spec.ts_1115_10896 | describe('MatTooltip', () => {
let overlayContainerElement: HTMLElement;
let dir: {value: Direction; change: Subject<Direction>};
let platform: Platform;
let focusMonitor: FocusMonitor;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
MatTooltipModule,
OverlayModule,
BasicTooltipDemo,
ScrollableTooltipDemo,
OnPushTooltipDemo,
DynamicTooltipsDemo,
TooltipOnTextFields,
TooltipOnDraggableElement,
DataBoundAriaLabelTooltip,
],
providers: [
{
provide: Directionality,
useFactory: () => {
return (dir = {value: 'ltr', change: new Subject()});
},
},
],
});
inject(
[OverlayContainer, FocusMonitor, Platform],
(oc: OverlayContainer, fm: FocusMonitor, pl: Platform) => {
overlayContainerElement = oc.getContainerElement();
focusMonitor = fm;
platform = pl;
},
)();
}));
describe('basic usage', () => {
let fixture: ComponentFixture<BasicTooltipDemo>;
let buttonDebugElement: DebugElement;
let buttonElement: HTMLButtonElement;
let tooltipDirective: MatTooltip;
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(BasicTooltipDemo);
fixture.detectChanges();
tick();
buttonDebugElement = fixture.debugElement.query(By.css('button'))!;
buttonElement = buttonDebugElement.nativeElement;
tooltipDirective = buttonDebugElement.injector.get<MatTooltip>(MatTooltip);
}));
it('should show and hide the tooltip', fakeAsync(() => {
assertTooltipInstance(tooltipDirective, false);
tooltipDirective.show();
tick(0); // Tick for the show delay (default is 0)
expect(tooltipDirective._isTooltipVisible()).toBe(true);
fixture.detectChanges();
// Wait until animation has finished
finishCurrentTooltipAnimation(overlayContainerElement, true);
// Make sure tooltip is shown to the user and animation has finished.
const tooltipElement = overlayContainerElement.querySelector(
'.mat-mdc-tooltip',
) as HTMLElement;
expect(tooltipElement instanceof HTMLElement).toBe(true);
expect(tooltipElement.classList).toContain('mat-mdc-tooltip-show');
expect(overlayContainerElement.textContent).toContain(initialTooltipMessage);
// After hide is called, a timeout delay is created that will to hide the tooltip.
const tooltipDelay = 1000;
tooltipDirective.hide(tooltipDelay);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
// After the tooltip delay elapses, expect that the tooltip is not visible.
tick(tooltipDelay);
fixture.detectChanges();
expect(tooltipDirective._isTooltipVisible()).toBe(false);
// On animation complete, should expect that the tooltip has been detached.
finishCurrentTooltipAnimation(overlayContainerElement, false);
assertTooltipInstance(tooltipDirective, false);
flush();
}));
it('should be able to re-open a tooltip if it was closed by detaching the overlay', fakeAsync(() => {
tooltipDirective.show();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, true);
tooltipDirective._overlayRef!.detach();
tick(0);
fixture.detectChanges();
expect(tooltipDirective._isTooltipVisible()).toBe(false);
assertTooltipInstance(tooltipDirective, false);
tooltipDirective.show();
tick(0);
finishCurrentTooltipAnimation(overlayContainerElement, true);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
flush();
}));
it('should show with delay', fakeAsync(() => {
assertTooltipInstance(tooltipDirective, false);
const tooltipDelay = 1000;
tooltipDirective.show(tooltipDelay);
expect(tooltipDirective._isTooltipVisible()).toBe(false);
fixture.detectChanges();
expect(overlayContainerElement.textContent).toContain('');
tick(tooltipDelay);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
expect(overlayContainerElement.textContent).toContain(initialTooltipMessage);
}));
it('should be able to override the default show and hide delays', fakeAsync(() => {
TestBed.resetTestingModule().configureTestingModule({
imports: [MatTooltipModule, OverlayModule, BasicTooltipDemo],
providers: [
{
provide: MAT_TOOLTIP_DEFAULT_OPTIONS,
useValue: {showDelay: 1337, hideDelay: 7331},
},
],
});
fixture = TestBed.createComponent(BasicTooltipDemo);
fixture.detectChanges();
tooltipDirective = fixture.debugElement
.query(By.css('button'))!
.injector.get<MatTooltip>(MatTooltip);
tooltipDirective.show();
fixture.detectChanges();
tick();
expect(tooltipDirective._isTooltipVisible()).toBe(false);
tick(1337);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
tooltipDirective.hide();
fixture.detectChanges();
tick();
expect(tooltipDirective._isTooltipVisible()).toBe(true);
tick(7331);
expect(tooltipDirective._isTooltipVisible()).toBe(false);
flush();
}));
it('should be able to override the default position', fakeAsync(() => {
TestBed.resetTestingModule().configureTestingModule({
imports: [MatTooltipModule, OverlayModule],
declarations: [TooltipDemoWithoutPositionBinding],
providers: [
{
provide: MAT_TOOLTIP_DEFAULT_OPTIONS,
useValue: {position: 'right'},
},
],
});
const newFixture = TestBed.createComponent(TooltipDemoWithoutPositionBinding);
newFixture.detectChanges();
tooltipDirective = newFixture.debugElement
.query(By.css('button'))!
.injector.get<MatTooltip>(MatTooltip);
tooltipDirective.show();
newFixture.detectChanges();
tick();
expect(tooltipDirective.position).toBe('right');
expect(tooltipDirective._getOverlayPosition().main.overlayX).toBe('start');
expect(tooltipDirective._getOverlayPosition().fallback.overlayX).toBe('end');
}));
it('should be able to define a default (global) tooltip class', fakeAsync(() => {
TestBed.resetTestingModule().configureTestingModule({
declarations: [TooltipDemoWithoutTooltipClassBinding],
imports: [MatTooltipModule, OverlayModule],
providers: [
{
provide: MAT_TOOLTIP_DEFAULT_OPTIONS,
useValue: {tooltipClass: 'my-default-tooltip-class'},
},
],
});
const fixture = TestBed.createComponent(TooltipDemoWithoutTooltipClassBinding);
fixture.detectChanges();
tooltipDirective = fixture.componentInstance.tooltip;
tooltipDirective.show();
fixture.detectChanges();
tick();
const overlayRef = tooltipDirective._overlayRef!;
const tooltipElement = overlayRef.overlayElement.querySelector(
'.mat-mdc-tooltip',
) as HTMLElement;
expect(tooltipDirective.tooltipClass).toBe('my-default-tooltip-class');
expect(tooltipElement.classList).toContain('my-default-tooltip-class');
}));
it('should be able to provide tooltip class over the custom default one', fakeAsync(() => {
TestBed.resetTestingModule().configureTestingModule({
declarations: [TooltipDemoWithTooltipClassBinding],
imports: [MatTooltipModule, OverlayModule],
providers: [
{
provide: MAT_TOOLTIP_DEFAULT_OPTIONS,
useValue: {tooltipClass: 'my-default-tooltip-class'},
},
],
});
const fixture = TestBed.createComponent(TooltipDemoWithTooltipClassBinding);
fixture.detectChanges();
tooltipDirective = fixture.componentInstance.tooltip;
tooltipDirective.show();
fixture.detectChanges();
tick();
const overlayRef = tooltipDirective._overlayRef!;
const tooltipElement = overlayRef.overlayElement.querySelector(
'.mat-mdc-tooltip',
) as HTMLElement;
expect(tooltipDirective.tooltipClass).not.toBe('my-default-tooltip-class');
expect(tooltipElement.classList).not.toContain('my-default-tooltip-class');
expect(tooltipElement.classList).toContain('fixed-tooltip-class');
}));
it('should position on the bottom-left by default', fakeAsync(() => {
// We don't bind mouse events on mobile devices.
if (platform.IOS || platform.ANDROID) {
return;
}
TestBed.resetTestingModule().configureTestingModule({
imports: [MatTooltipModule, OverlayModule],
declarations: [WideTooltipDemo],
});
const wideFixture = TestBed.createComponent(WideTooltipDemo);
wideFixture.detectChanges();
tooltipDirective = wideFixture.debugElement
.query(By.css('button'))!
.injector.get<MatTooltip>(MatTooltip);
const button: HTMLButtonElement = wideFixture.nativeElement.querySelector('button');
const triggerRect = button.getBoundingClientRect();
dispatchMouseEvent(button, 'mouseenter', triggerRect.right - 100, triggerRect.top + 100);
wideFixture.detectChanges();
tick();
expect(tooltipDirective._isTooltipVisible()).toBe(true);
expect(tooltipDirective._overlayRef!.overlayElement.offsetLeft).toBeLessThan(
triggerRect.right - 250,
);
expect(tooltipDirective._overlayRef!.overlayElement.offsetTop).toBeGreaterThanOrEqual(
triggerRect.bottom,
);
})); | {
"end_byte": 10896,
"start_byte": 1115,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.spec.ts"
} |
components/src/material/tooltip/tooltip.spec.ts_10902_19685 | it('should be able to override the default positionAtOrigin', async () => {
// We don't bind mouse events on mobile devices.
if (platform.IOS || platform.ANDROID) {
return;
}
TestBed.resetTestingModule().configureTestingModule({
imports: [MatTooltipModule, OverlayModule],
declarations: [WideTooltipDemo],
providers: [
{
provide: MAT_TOOLTIP_DEFAULT_OPTIONS,
useValue: {positionAtOrigin: true},
},
],
});
const wideFixture = TestBed.createComponent(WideTooltipDemo);
wideFixture.detectChanges();
tooltipDirective = wideFixture.debugElement
.query(By.css('button'))!
.injector.get<MatTooltip>(MatTooltip);
const button: HTMLButtonElement = wideFixture.nativeElement.querySelector('button');
const triggerRect = button.getBoundingClientRect();
dispatchMouseEvent(button, 'mouseenter', triggerRect.right - 100, triggerRect.top + 100);
wideFixture.detectChanges();
await new Promise<void>(resolve => setTimeout(resolve));
expect(tooltipDirective._isTooltipVisible()).toBe(true);
const actualOffsetLeft = tooltipDirective._overlayRef!.overlayElement.offsetLeft;
const expectedOffsetLeft = triggerRect.right - 100 - 20;
expect(actualOffsetLeft).toBeLessThanOrEqual(expectedOffsetLeft + 1);
expect(actualOffsetLeft).toBeGreaterThanOrEqual(expectedOffsetLeft - 1);
expect(tooltipDirective._overlayRef!.overlayElement.offsetTop).toBe(triggerRect.top + 100);
});
it('should be able to disable tooltip interactivity', fakeAsync(() => {
TestBed.resetTestingModule().configureTestingModule({
imports: [MatTooltipModule, OverlayModule, NoopAnimationsModule],
declarations: [TooltipDemoWithoutPositionBinding],
providers: [
{
provide: MAT_TOOLTIP_DEFAULT_OPTIONS,
useValue: {disableTooltipInteractivity: true},
},
],
});
const newFixture = TestBed.createComponent(TooltipDemoWithoutPositionBinding);
newFixture.detectChanges();
tooltipDirective = newFixture.debugElement
.query(By.css('button'))!
.injector.get<MatTooltip>(MatTooltip);
tooltipDirective.show();
newFixture.detectChanges();
tick();
expect(tooltipDirective._overlayRef?.overlayElement.classList).toContain(
'mat-mdc-tooltip-panel-non-interactive',
);
}));
it('should set a css class on the overlay panel element', fakeAsync(() => {
tooltipDirective.show();
fixture.detectChanges();
tick(0);
const overlayRef = tooltipDirective._overlayRef;
expect(!!overlayRef).toBeTruthy();
expect(overlayRef!.overlayElement.classList)
.withContext('Expected the overlay panel element to have the tooltip panel class set.')
.toContain('mat-mdc-tooltip-panel');
}));
it('should not show if disabled', fakeAsync(() => {
// Test that disabling the tooltip will not set the tooltip visible
tooltipDirective.disabled = true;
fixture.changeDetectorRef.markForCheck();
tooltipDirective.show();
fixture.detectChanges();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(false);
// Test to make sure setting disabled to false will show the tooltip
// Sanity check to make sure everything was correct before (detectChanges, tick)
tooltipDirective.disabled = false;
fixture.changeDetectorRef.markForCheck();
tooltipDirective.show();
fixture.detectChanges();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
}));
it('should hide if disabled while visible', fakeAsync(() => {
// Display the tooltip with a timeout before hiding.
tooltipDirective.hideDelay = 1000;
tooltipDirective.show();
fixture.detectChanges();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
// Set tooltip to be disabled and verify that the tooltip hides.
tooltipDirective.disabled = true;
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(false);
}));
it('should hide if the message is cleared while the tooltip is open', fakeAsync(() => {
tooltipDirective.show();
fixture.detectChanges();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
fixture.componentInstance.message = '';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(false);
}));
it('should not show if hide is called before delay finishes', waitForAsync(() => {
assertTooltipInstance(tooltipDirective, false);
const tooltipDelay = 1000;
tooltipDirective.show(tooltipDelay);
expect(tooltipDirective._isTooltipVisible()).toBe(false);
fixture.detectChanges();
expect(overlayContainerElement.textContent).toContain('');
tooltipDirective.hide();
fixture.whenStable().then(() => {
expect(tooltipDirective._isTooltipVisible()).toBe(false);
});
}));
it('should not show tooltip if message is not present or empty', () => {
assertTooltipInstance(tooltipDirective, false);
tooltipDirective.message = undefined;
fixture.detectChanges();
tooltipDirective.show();
assertTooltipInstance(tooltipDirective, false);
tooltipDirective.message = null;
fixture.detectChanges();
tooltipDirective.show();
assertTooltipInstance(tooltipDirective, false);
tooltipDirective.message = '';
fixture.detectChanges();
tooltipDirective.show();
assertTooltipInstance(tooltipDirective, false);
tooltipDirective.message = ' ';
fixture.detectChanges();
tooltipDirective.show();
assertTooltipInstance(tooltipDirective, false);
});
it('should not follow through with hide if show is called after', fakeAsync(() => {
tooltipDirective.show();
tick(0); // Tick for the show delay (default is 0)
expect(tooltipDirective._isTooltipVisible()).toBe(true);
// After hide called, a timeout delay is created that will to hide the tooltip.
const tooltipDelay = 1000;
tooltipDirective.hide(tooltipDelay);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
// Before delay time has passed, call show which should cancel intent to hide tooltip.
tooltipDirective.show();
tick(tooltipDelay);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
}));
it('should be able to update the tooltip position while open', fakeAsync(() => {
tooltipDirective.position = 'below';
tooltipDirective.show();
tick();
assertTooltipInstance(tooltipDirective, true);
spyOn(tooltipDirective._overlayRef!, 'updatePosition').and.callThrough();
tooltipDirective.position = 'above';
fixture.detectChanges();
tick();
assertTooltipInstance(tooltipDirective, true);
expect(tooltipDirective._overlayRef!.updatePosition).toHaveBeenCalled();
}));
it('should update the tooltip position when the directionality changes', fakeAsync(() => {
tooltipDirective.position = 'right';
tooltipDirective.show();
tick();
assertTooltipInstance(tooltipDirective, true);
const spy = spyOn(tooltipDirective as any, '_updatePosition').and.callThrough();
dir.change.next('rtl');
assertTooltipInstance(tooltipDirective, true);
expect(spy).toHaveBeenCalled();
}));
it('should not throw when updating the position for a closed tooltip', fakeAsync(() => {
tooltipDirective.position = 'left';
tooltipDirective.show(0);
fixture.detectChanges();
tick();
tooltipDirective.hide(0);
fixture.detectChanges();
tick();
finishCurrentTooltipAnimation(overlayContainerElement, false);
expect(() => {
tooltipDirective.position = 'right';
fixture.detectChanges();
tick();
}).not.toThrow();
}));
it('should be able to modify the tooltip message', fakeAsync(() => {
assertTooltipInstance(tooltipDirective, false);
tooltipDirective.show();
tick(0); // Tick for the show delay (default is 0)
expect(tooltipDirective._tooltipInstance!.isVisible()).toBe(true);
fixture.detectChanges();
expect(overlayContainerElement.textContent).toContain(initialTooltipMessage);
const newMessage = 'new tooltip message';
tooltipDirective.message = newMessage;
fixture.detectChanges();
expect(overlayContainerElement.textContent).toContain(newMessage);
})); | {
"end_byte": 19685,
"start_byte": 10902,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.spec.ts"
} |
components/src/material/tooltip/tooltip.spec.ts_19691_29239 | it('should allow extra classes to be set on the tooltip', fakeAsync(() => {
assertTooltipInstance(tooltipDirective, false);
tooltipDirective.show();
tick(0); // Tick for the show delay (default is 0)
fixture.detectChanges();
// Make sure classes aren't prematurely added
let tooltipElement = overlayContainerElement.querySelector('.mat-mdc-tooltip') as HTMLElement;
expect(tooltipElement.classList).not.toContain(
'custom-one',
'Expected to not have the class before enabling matTooltipClass',
);
expect(tooltipElement.classList).not.toContain(
'custom-two',
'Expected to not have the class before enabling matTooltipClass',
);
// Enable the classes via ngClass syntax
fixture.componentInstance.showTooltipClass = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Make sure classes are correctly added
tooltipElement = overlayContainerElement.querySelector('.mat-mdc-tooltip') as HTMLElement;
expect(tooltipElement.classList)
.withContext('Expected to have the class after enabling matTooltipClass')
.toContain('custom-one');
expect(tooltipElement.classList)
.withContext('Expected to have the class after enabling matTooltipClass')
.toContain('custom-two');
}));
it('should be removed after parent destroyed', fakeAsync(() => {
tooltipDirective.show();
tick(0); // Tick for the show delay (default is 0)
expect(tooltipDirective._isTooltipVisible()).toBe(true);
fixture.destroy();
expect(overlayContainerElement.childNodes.length).toBe(0);
expect(overlayContainerElement.textContent).toBe('');
flush();
}));
it('should have an aria-describedby element with the tooltip message', fakeAsync(() => {
const dynamicTooltipsDemoFixture = TestBed.createComponent(DynamicTooltipsDemo);
const dynamicTooltipsComponent = dynamicTooltipsDemoFixture.componentInstance;
dynamicTooltipsComponent.tooltips = ['Tooltip One', 'Tooltip Two'];
dynamicTooltipsDemoFixture.detectChanges();
tick();
const buttons = dynamicTooltipsDemoFixture.nativeElement.querySelectorAll('button');
const firstButtonAria = buttons[0].getAttribute('aria-describedby');
expect(document.querySelector(`#${firstButtonAria}`)!.textContent).toBe('Tooltip One');
const secondButtonAria = buttons[1].getAttribute('aria-describedby');
expect(document.querySelector(`#${secondButtonAria}`)!.textContent).toBe('Tooltip Two');
}));
it('should not add an ARIA description for elements that have the same text as a data-bound aria-label', fakeAsync(() => {
const ariaLabelFixture = TestBed.createComponent(DataBoundAriaLabelTooltip);
ariaLabelFixture.detectChanges();
tick();
const button = ariaLabelFixture.nativeElement.querySelector('button');
expect(button.getAttribute('aria-describedby')).toBeFalsy();
}));
it('should toggle aria-describedby depending on whether the tooltip is disabled', fakeAsync(() => {
expect(buttonElement.getAttribute('aria-describedby')).toBeTruthy();
fixture.componentInstance.tooltipDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(buttonElement.hasAttribute('aria-describedby')).toBe(false);
fixture.componentInstance.tooltipDisabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(buttonElement.getAttribute('aria-describedby')).toBeTruthy();
}));
it('should not try to dispose the tooltip when destroyed and done hiding', fakeAsync(() => {
tooltipDirective.show();
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, true);
const tooltipDelay = 1000;
tooltipDirective.hide();
tick(tooltipDelay); // Change the tooltip state to hidden and trigger animation start
fixture.componentInstance.showButton = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
}));
it('should complete the afterHidden stream when tooltip is destroyed', fakeAsync(() => {
tooltipDirective.show();
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, true);
const spy = jasmine.createSpy('complete spy');
const subscription = tooltipDirective
._tooltipInstance!.afterHidden()
.subscribe({complete: spy});
tooltipDirective.hide(0);
tick(0);
fixture.detectChanges();
expect(spy).toHaveBeenCalled();
subscription.unsubscribe();
}));
it('should consistently position before and after overlay origin in ltr and rtl dir', () => {
tooltipDirective.position = 'left';
const leftOrigin = tooltipDirective._getOrigin().main;
tooltipDirective.position = 'right';
const rightOrigin = tooltipDirective._getOrigin().main;
// Test expectations in LTR
tooltipDirective.position = 'before';
expect(tooltipDirective._getOrigin().main).toEqual(leftOrigin);
tooltipDirective.position = 'after';
expect(tooltipDirective._getOrigin().main).toEqual(rightOrigin);
// Test expectations in RTL
dir.value = 'rtl';
tooltipDirective.position = 'before';
expect(tooltipDirective._getOrigin().main).toEqual(leftOrigin);
tooltipDirective.position = 'after';
expect(tooltipDirective._getOrigin().main).toEqual(rightOrigin);
});
it('should consistently position before and after overlay position in ltr and rtl dir', () => {
tooltipDirective.position = 'left';
const leftOverlayPosition = tooltipDirective._getOverlayPosition().main;
tooltipDirective.position = 'right';
const rightOverlayPosition = tooltipDirective._getOverlayPosition().main;
// Test expectations in LTR
tooltipDirective.position = 'before';
expect(tooltipDirective._getOverlayPosition().main).toEqual(leftOverlayPosition);
tooltipDirective.position = 'after';
expect(tooltipDirective._getOverlayPosition().main).toEqual(rightOverlayPosition);
// Test expectations in RTL
dir.value = 'rtl';
tooltipDirective.position = 'before';
expect(tooltipDirective._getOverlayPosition().main).toEqual(leftOverlayPosition);
tooltipDirective.position = 'after';
expect(tooltipDirective._getOverlayPosition().main).toEqual(rightOverlayPosition);
});
it('should throw when trying to assign an invalid position', () => {
expect(() => {
fixture.componentInstance.position = 'everywhere';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tooltipDirective.show();
}).toThrowError('Tooltip position "everywhere" is invalid.');
});
it('should pass the layout direction to the tooltip', fakeAsync(() => {
dir.value = 'rtl';
tooltipDirective.show();
tick(0);
fixture.detectChanges();
const tooltipWrapper = overlayContainerElement.querySelector(
'.cdk-overlay-connected-position-bounding-box',
)!;
expect(tooltipWrapper).withContext('Expected tooltip to be shown.').toBeTruthy();
expect(tooltipWrapper.getAttribute('dir'))
.withContext('Expected tooltip to be in RTL mode.')
.toBe('rtl');
}));
it('should keep the overlay direction in sync with the trigger direction', fakeAsync(() => {
dir.value = 'rtl';
tooltipDirective.show();
tick(0);
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, true);
let tooltipWrapper = overlayContainerElement.querySelector(
'.cdk-overlay-connected-position-bounding-box',
)!;
expect(tooltipWrapper.getAttribute('dir'))
.withContext('Expected tooltip to be in RTL.')
.toBe('rtl');
tooltipDirective.hide(0);
tick(0);
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, false);
dir.value = 'ltr';
tooltipDirective.show();
tick(0);
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, true);
tooltipWrapper = overlayContainerElement.querySelector(
'.cdk-overlay-connected-position-bounding-box',
)!;
expect(tooltipWrapper.getAttribute('dir'))
.withContext('Expected tooltip to be in LTR.')
.toBe('ltr');
flush();
}));
it('should be able to set the tooltip message as a number', fakeAsync(() => {
fixture.componentInstance.message = 100;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tooltipDirective.message).toBe('100');
}));
it('should hide when clicking away', fakeAsync(() => {
tooltipDirective.show();
tick(0);
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, true);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
expect(overlayContainerElement.textContent).toContain(initialTooltipMessage);
document.body.click();
tick(0);
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, false);
fixture.detectChanges();
expect(tooltipDirective._isTooltipVisible()).toBe(false);
expect(overlayContainerElement.textContent).toBe('');
})); | {
"end_byte": 29239,
"start_byte": 19691,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.spec.ts"
} |
components/src/material/tooltip/tooltip.spec.ts_29245_39096 | it('should hide when clicking away with an auxilliary button', fakeAsync(() => {
tooltipDirective.show();
tick(0);
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, true);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
expect(overlayContainerElement.textContent).toContain(initialTooltipMessage);
dispatchFakeEvent(document.body, 'auxclick');
tick(0);
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, false);
fixture.detectChanges();
expect(tooltipDirective._isTooltipVisible()).toBe(false);
expect(overlayContainerElement.textContent).toBe('');
}));
it('should not hide immediately if a click fires while animating', fakeAsync(() => {
tooltipDirective.show();
tick(0);
fixture.detectChanges();
document.body.click();
fixture.detectChanges();
tick(500);
finishCurrentTooltipAnimation(overlayContainerElement, true);
expect(overlayContainerElement.textContent).toContain(initialTooltipMessage);
flush();
}));
it('should hide when pressing escape', fakeAsync(() => {
tooltipDirective.show();
tick(0);
fixture.detectChanges();
tick(500);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
expect(overlayContainerElement.textContent).toContain(initialTooltipMessage);
dispatchKeyboardEvent(document.body, 'keydown', ESCAPE);
tick(0);
fixture.detectChanges();
tick(500);
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, false);
expect(tooltipDirective._isTooltipVisible()).toBe(false);
expect(overlayContainerElement.textContent).toBe('');
flush();
}));
it('should not throw when pressing ESCAPE', fakeAsync(() => {
expect(() => {
dispatchKeyboardEvent(document.body, 'keydown', ESCAPE);
fixture.detectChanges();
}).not.toThrow();
// Flush due to the additional tick that is necessary for the FocusMonitor.
flush();
}));
it('should preventDefault when pressing ESCAPE', fakeAsync(() => {
tooltipDirective.show();
tick(0);
fixture.detectChanges();
const event = dispatchKeyboardEvent(document.body, 'keydown', ESCAPE);
fixture.detectChanges();
flush();
expect(event.defaultPrevented).toBe(true);
}));
it('should not preventDefault when pressing ESCAPE with a modifier', fakeAsync(() => {
tooltipDirective.show();
tick(0);
fixture.detectChanges();
const event = createKeyboardEvent('keydown', ESCAPE, undefined, {alt: true});
dispatchEvent(document.body, event);
fixture.detectChanges();
flush();
expect(event.defaultPrevented).toBe(false);
}));
it('should not show the tooltip on programmatic focus', fakeAsync(() => {
patchElementFocus(buttonElement);
assertTooltipInstance(tooltipDirective, false);
focusMonitor.focusVia(buttonElement, 'program');
tick(0);
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.querySelector('.mat-mdc-tooltip')).toBeNull();
}));
it('should not show the tooltip on mouse focus', fakeAsync(() => {
patchElementFocus(buttonElement);
assertTooltipInstance(tooltipDirective, false);
focusMonitor.focusVia(buttonElement, 'mouse');
tick(0);
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.querySelector('.mat-mdc-tooltip')).toBeNull();
}));
it('should not show the tooltip on touch focus', fakeAsync(() => {
patchElementFocus(buttonElement);
assertTooltipInstance(tooltipDirective, false);
focusMonitor.focusVia(buttonElement, 'touch');
tick(0);
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.querySelector('.mat-mdc-tooltip')).toBeNull();
}));
it('should not hide the tooltip when calling `show` twice in a row', fakeAsync(() => {
tooltipDirective.show();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, true);
const overlayRef = tooltipDirective._overlayRef!;
spyOn(overlayRef, 'detach').and.callThrough();
tooltipDirective.show();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, true);
expect(overlayRef.detach).not.toHaveBeenCalled();
flush();
}));
it('should set a class on the overlay panel that reflects the position', fakeAsync(() => {
// Move the element so that the primary position is always used.
buttonElement.style.position = 'fixed';
buttonElement.style.top = buttonElement.style.left = '200px';
fixture.componentInstance.message = 'hi';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
setPositionAndShow('below');
const classList = tooltipDirective._overlayRef!.overlayElement.classList;
expect(classList).toContain('mat-mdc-tooltip-panel-below');
setPositionAndShow('above');
expect(classList).not.toContain('mat-mdc-tooltip-panel-below');
expect(classList).toContain('mat-mdc-tooltip-panel-above');
setPositionAndShow('left');
expect(classList).not.toContain('mat-mdc-tooltip-panel-above');
expect(classList).toContain('mat-mdc-tooltip-panel-left');
setPositionAndShow('right');
expect(classList).not.toContain('mat-mdc-tooltip-panel-left');
expect(classList).toContain('mat-mdc-tooltip-panel-right');
function setPositionAndShow(position: TooltipPosition) {
tooltipDirective.hide(0);
fixture.detectChanges();
tick(0);
tooltipDirective.position = position;
tooltipDirective.show(0);
fixture.detectChanges();
tick(0);
fixture.detectChanges();
tick(500);
}
}));
it('should account for RTL when setting the tooltip position class', fakeAsync(() => {
// Move the element so that the primary position is always used.
buttonElement.style.position = 'fixed';
buttonElement.style.top = buttonElement.style.left = '200px';
fixture.componentInstance.message = 'hi';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dir.value = 'ltr';
tooltipDirective.position = 'after';
fixture.changeDetectorRef.markForCheck();
tooltipDirective.show(0);
fixture.detectChanges();
tick(0);
fixture.detectChanges();
tick(500);
const classList = tooltipDirective._overlayRef!.overlayElement.classList;
expect(classList).not.toContain('mat-mdc-tooltip-panel-after');
expect(classList).not.toContain('mat-mdc-tooltip-panel-before');
expect(classList).not.toContain('mat-mdc-tooltip-panel-left');
expect(classList).toContain('mat-mdc-tooltip-panel-right');
tooltipDirective.hide(0);
fixture.detectChanges();
tick(0);
dir.value = 'rtl';
tooltipDirective.show(0);
fixture.detectChanges();
tick(0);
fixture.detectChanges();
tick(500);
expect(classList).not.toContain('mat-mdc-tooltip-panel-after');
expect(classList).not.toContain('mat-mdc-tooltip-panel-before');
expect(classList).not.toContain('mat-mdc-tooltip-panel-right');
expect(classList).toContain('mat-mdc-tooltip-panel-left');
}));
it('should clear the show timeout on destroy', fakeAsync(() => {
assertTooltipInstance(tooltipDirective, false);
tooltipDirective.show(1000);
fixture.detectChanges();
// Note that we aren't asserting anything, but `fakeAsync` will
// throw if we have any timers by the end of the test.
fixture.destroy();
flush();
}));
it('should clear the hide timeout on destroy', fakeAsync(() => {
assertTooltipInstance(tooltipDirective, false);
tooltipDirective.show();
tick(0);
fixture.detectChanges();
tick(500);
tooltipDirective.hide(1000);
fixture.detectChanges();
// Note that we aren't asserting anything, but `fakeAsync` will
// throw if we have any timers by the end of the test.
fixture.destroy();
flush();
}));
it('should set the multiline class on tooltips with messages that overflow', fakeAsync(() => {
fixture.componentInstance.message =
'This is a very long message that should cause the' +
'tooltip message body to overflow onto a new line.';
tooltipDirective.show();
fixture.detectChanges();
tick();
// Need to detect changes again to wait for the multiline class to be applied.
fixture.detectChanges();
const tooltipElement = overlayContainerElement.querySelector(
'.mat-mdc-tooltip',
) as HTMLElement;
expect(tooltipElement.classList).toContain('mdc-tooltip--multiline');
expect(tooltipDirective._tooltipInstance?._isMultiline).toBeTrue();
}));
it('should hide on mouseleave on the trigger', fakeAsync(() => {
// We don't bind mouse events on mobile devices.
if (platform.IOS || platform.ANDROID) {
return;
}
dispatchMouseEvent(fixture.componentInstance.button.nativeElement, 'mouseenter');
fixture.detectChanges();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
dispatchMouseEvent(fixture.componentInstance.button.nativeElement, 'mouseleave');
fixture.detectChanges();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(false);
})); | {
"end_byte": 39096,
"start_byte": 29245,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.spec.ts"
} |
components/src/material/tooltip/tooltip.spec.ts_39102_47668 | it('should not hide on mouseleave if the pointer goes from the trigger to the tooltip', fakeAsync(() => {
// We don't bind mouse events on mobile devices.
if (platform.IOS || platform.ANDROID) {
return;
}
dispatchMouseEvent(fixture.componentInstance.button.nativeElement, 'mouseenter');
fixture.detectChanges();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
const tooltipElement = overlayContainerElement.querySelector(
'.mat-mdc-tooltip',
) as HTMLElement;
const event = createMouseEvent('mouseleave');
Object.defineProperty(event, 'relatedTarget', {value: tooltipElement});
dispatchEvent(fixture.componentInstance.button.nativeElement, event);
fixture.detectChanges();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
}));
it('should hide on mouseleave on the tooltip', fakeAsync(() => {
// We don't bind mouse events on mobile devices.
if (platform.IOS || platform.ANDROID) {
return;
}
dispatchMouseEvent(fixture.componentInstance.button.nativeElement, 'mouseenter');
fixture.detectChanges();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
const tooltipElement = overlayContainerElement.querySelector(
'.mat-mdc-tooltip',
) as HTMLElement;
dispatchMouseEvent(tooltipElement, 'mouseleave');
fixture.detectChanges();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(false);
}));
it('should not hide on mouseleave if the pointer goes from the tooltip to the trigger', fakeAsync(() => {
// We don't bind mouse events on mobile devices.
if (platform.IOS || platform.ANDROID) {
return;
}
dispatchMouseEvent(fixture.componentInstance.button.nativeElement, 'mouseenter');
fixture.detectChanges();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
const tooltipElement = overlayContainerElement.querySelector(
'.mat-mdc-tooltip',
) as HTMLElement;
const event = createMouseEvent('mouseleave');
Object.defineProperty(event, 'relatedTarget', {
value: fixture.componentInstance.button.nativeElement,
});
dispatchEvent(tooltipElement, event);
fixture.detectChanges();
tick(0);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
}));
});
describe('fallback positions', () => {
let fixture: ComponentFixture<BasicTooltipDemo>;
let tooltip: MatTooltip;
beforeEach(() => {
fixture = TestBed.createComponent(BasicTooltipDemo);
fixture.detectChanges();
tooltip = fixture.debugElement.query(By.css('button'))!.injector.get<MatTooltip>(MatTooltip);
});
it('should set a fallback origin position by inverting the main origin position', () => {
tooltip.position = 'left';
expect(tooltip._getOrigin().main.originX).toBe('start');
expect(tooltip._getOrigin().fallback.originX).toBe('end');
tooltip.position = 'right';
expect(tooltip._getOrigin().main.originX).toBe('end');
expect(tooltip._getOrigin().fallback.originX).toBe('start');
tooltip.position = 'above';
expect(tooltip._getOrigin().main.originY).toBe('top');
expect(tooltip._getOrigin().fallback.originY).toBe('bottom');
tooltip.position = 'below';
expect(tooltip._getOrigin().main.originY).toBe('bottom');
expect(tooltip._getOrigin().fallback.originY).toBe('top');
});
it('should set a fallback overlay position by inverting the main overlay position', () => {
tooltip.position = 'left';
expect(tooltip._getOverlayPosition().main.overlayX).toBe('end');
expect(tooltip._getOverlayPosition().fallback.overlayX).toBe('start');
tooltip.position = 'right';
expect(tooltip._getOverlayPosition().main.overlayX).toBe('start');
expect(tooltip._getOverlayPosition().fallback.overlayX).toBe('end');
tooltip.position = 'above';
expect(tooltip._getOverlayPosition().main.overlayY).toBe('bottom');
expect(tooltip._getOverlayPosition().fallback.overlayY).toBe('top');
tooltip.position = 'below';
expect(tooltip._getOverlayPosition().main.overlayY).toBe('top');
expect(tooltip._getOverlayPosition().fallback.overlayY).toBe('bottom');
});
});
describe('scrollable usage', () => {
let fixture: ComponentFixture<ScrollableTooltipDemo>;
let buttonDebugElement: DebugElement;
let tooltipDirective: MatTooltip;
beforeEach(() => {
fixture = TestBed.createComponent(ScrollableTooltipDemo);
fixture.detectChanges();
buttonDebugElement = fixture.debugElement.query(By.css('button'))!;
tooltipDirective = buttonDebugElement.injector.get<MatTooltip>(MatTooltip);
});
it('should hide tooltip if clipped after changing positions', fakeAsync(() => {
assertTooltipInstance(tooltipDirective, false);
// Show the tooltip and tick for the show delay (default is 0)
tooltipDirective.show();
fixture.detectChanges();
tick(0);
// Expect that the tooltip is displayed
// Expect that the tooltip is displayed
expect(tooltipDirective._isTooltipVisible())
.withContext('Expected tooltip to be initially visible')
.toBe(true);
// Scroll the page but tick just before the default throttle should update.
fixture.componentInstance.scrollDown();
tick(SCROLL_THROTTLE_MS - 1);
expect(tooltipDirective._isTooltipVisible())
.withContext('Expected tooltip to be visible when scrolling, before throttle limit')
.toBe(true);
// Finish ticking to the throttle's limit and check that the scroll event notified the
// tooltip and it was hidden.
tick(100);
fixture.detectChanges();
expect(tooltipDirective._isTooltipVisible())
.withContext('Expected tooltip hidden when scrolled out of view, after throttle limit')
.toBe(false);
}));
});
describe('with OnPush', () => {
let fixture: ComponentFixture<OnPushTooltipDemo>;
let buttonDebugElement: DebugElement;
let buttonElement: HTMLButtonElement;
let tooltipDirective: MatTooltip;
beforeEach(() => {
fixture = TestBed.createComponent(OnPushTooltipDemo);
fixture.detectChanges();
buttonDebugElement = fixture.debugElement.query(By.css('button'))!;
buttonElement = <HTMLButtonElement>buttonDebugElement.nativeElement;
tooltipDirective = buttonDebugElement.injector.get<MatTooltip>(MatTooltip);
});
it('should show and hide the tooltip', fakeAsync(() => {
assertTooltipInstance(tooltipDirective, false);
tooltipDirective.show();
tick(0); // Tick for the show delay (default is 0)
expect(tooltipDirective._isTooltipVisible()).toBe(true);
fixture.detectChanges();
// wait until animation has finished
finishCurrentTooltipAnimation(overlayContainerElement, true);
// Make sure tooltip is shown to the user and animation has finished
const tooltipElement = overlayContainerElement.querySelector(
'.mat-mdc-tooltip',
) as HTMLElement;
expect(tooltipElement instanceof HTMLElement).toBe(true);
expect(tooltipElement.classList).toContain('mat-mdc-tooltip-show');
// After hide called, a timeout delay is created that will to hide the tooltip.
const tooltipDelay = 1000;
tooltipDirective.hide(tooltipDelay);
expect(tooltipDirective._isTooltipVisible()).toBe(true);
// After the tooltip delay elapses, expect that the tooltip is not visible.
tick(tooltipDelay);
fixture.detectChanges();
expect(tooltipDirective._isTooltipVisible()).toBe(false);
// On animation complete, should expect that the tooltip has been detached.
finishCurrentTooltipAnimation(overlayContainerElement, false);
assertTooltipInstance(tooltipDirective, false);
flush();
}));
it('should have rendered the tooltip text on init', fakeAsync(() => {
// We don't bind mouse events on mobile devices.
if (platform.IOS || platform.ANDROID) {
return;
}
dispatchFakeEvent(buttonElement, 'mouseenter');
fixture.detectChanges();
tick(0);
const tooltipElement = overlayContainerElement.querySelector(
'.mat-mdc-tooltip',
) as HTMLElement;
expect(tooltipElement.textContent).toContain('initial tooltip message');
}));
}); | {
"end_byte": 47668,
"start_byte": 39102,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.spec.ts"
} |
components/src/material/tooltip/tooltip.spec.ts_47672_55550 | describe('touch gestures', () => {
beforeEach(() => {
platform.ANDROID = true;
});
it('should have a delay when showing on touchstart', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicTooltipDemo);
fixture.detectChanges();
const button: HTMLButtonElement = fixture.nativeElement.querySelector('button');
dispatchFakeEvent(button, 'touchstart');
fixture.detectChanges();
tick(250); // Halfway through the delay.
assertTooltipInstance(fixture.componentInstance.tooltip, false);
tick(500); // Finish the delay.
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, true); // Finish the animation.
assertTooltipInstance(fixture.componentInstance.tooltip, true);
flush();
}));
it('should be able to disable opening on touch', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicTooltipDemo);
fixture.componentInstance.touchGestures = 'off';
fixture.detectChanges();
const button: HTMLButtonElement = fixture.nativeElement.querySelector('button');
dispatchFakeEvent(button, 'touchstart');
fixture.detectChanges();
tick(500); // Finish the delay.
fixture.detectChanges();
tick(500); // Finish the animation.
assertTooltipInstance(fixture.componentInstance.tooltip, false);
}));
it('should not prevent the default action on touchstart', () => {
const fixture = TestBed.createComponent(BasicTooltipDemo);
fixture.detectChanges();
const button: HTMLButtonElement = fixture.nativeElement.querySelector('button');
const event = dispatchFakeEvent(button, 'touchstart');
fixture.detectChanges();
expect(event.defaultPrevented).toBe(false);
});
it('should close on touchend with a delay', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicTooltipDemo);
fixture.detectChanges();
const button: HTMLButtonElement = fixture.nativeElement.querySelector('button');
dispatchFakeEvent(button, 'touchstart');
fixture.detectChanges();
tick(500); // Finish the open delay.
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, true); // Finish the animation.
assertTooltipInstance(fixture.componentInstance.tooltip, true);
dispatchFakeEvent(button, 'touchend');
fixture.detectChanges();
tick(1000); // 2/3 through the delay
assertTooltipInstance(fixture.componentInstance.tooltip, true);
tick(500); // Finish the delay.
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, false); // Finish the exit animation.
assertTooltipInstance(fixture.componentInstance.tooltip, false);
flush();
}));
it('should close on touchcancel with a delay', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicTooltipDemo);
fixture.detectChanges();
const button: HTMLButtonElement = fixture.nativeElement.querySelector('button');
dispatchFakeEvent(button, 'touchstart');
fixture.detectChanges();
tick(500); // Finish the open delay.
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, true); // Finish the animation.
assertTooltipInstance(fixture.componentInstance.tooltip, true);
dispatchFakeEvent(button, 'touchcancel');
fixture.detectChanges();
tick(1000); // 2/3 through the delay
assertTooltipInstance(fixture.componentInstance.tooltip, true);
tick(500); // Finish the delay.
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, false); // Finish the exit animation.
assertTooltipInstance(fixture.componentInstance.tooltip, false);
flush();
}));
it('should disable native touch interactions', () => {
const fixture = TestBed.createComponent(BasicTooltipDemo);
fixture.detectChanges();
const styles = fixture.nativeElement.querySelector('button').style;
expect(styles.touchAction || (styles as any).webkitUserDrag).toBe('none');
});
it('should allow native touch interactions if touch gestures are turned off', () => {
const fixture = TestBed.createComponent(BasicTooltipDemo);
fixture.componentInstance.touchGestures = 'off';
fixture.detectChanges();
const styles = fixture.nativeElement.querySelector('button').style;
expect(styles.touchAction || (styles as any).webkitUserDrag).toBeFalsy();
});
it('should allow text selection on inputs when gestures are set to auto', () => {
const fixture = TestBed.createComponent(TooltipOnTextFields);
fixture.detectChanges();
const inputStyle = fixture.componentInstance.input.nativeElement.style;
const textareaStyle = fixture.componentInstance.textarea.nativeElement.style;
expect(inputStyle.userSelect).toBeFalsy();
expect(inputStyle.webkitUserSelect).toBeFalsy();
expect((inputStyle as any).msUserSelect).toBeFalsy();
expect((inputStyle as any).MozUserSelect).toBeFalsy();
expect(textareaStyle.userSelect).toBeFalsy();
expect(textareaStyle.webkitUserSelect).toBeFalsy();
expect((textareaStyle as any).msUserSelect).toBeFalsy();
expect((textareaStyle as any).MozUserSelect).toBeFalsy();
});
it('should disable text selection on inputs when gestures are set to on', () => {
const fixture = TestBed.createComponent(TooltipOnTextFields);
fixture.componentInstance.touchGestures = 'on';
fixture.detectChanges();
const inputStyle = fixture.componentInstance.input.nativeElement.style;
const inputUserSelect =
inputStyle.userSelect ||
inputStyle.webkitUserSelect ||
(inputStyle as any).msUserSelect ||
(inputStyle as any).MozUserSelect;
const textareaStyle = fixture.componentInstance.textarea.nativeElement.style;
const textareaUserSelect =
textareaStyle.userSelect ||
textareaStyle.webkitUserSelect ||
(textareaStyle as any).msUserSelect ||
(textareaStyle as any).MozUserSelect;
expect(inputUserSelect).toBe('none');
expect(textareaUserSelect).toBe('none');
});
it('should allow native dragging on draggable elements when gestures are set to auto', () => {
const fixture = TestBed.createComponent(TooltipOnDraggableElement);
fixture.detectChanges();
expect(fixture.componentInstance.button.nativeElement.style.webkitUserDrag).toBeFalsy();
});
it('should disable native dragging on draggable elements when gestures are set to on', () => {
const fixture = TestBed.createComponent(TooltipOnDraggableElement);
fixture.componentInstance.touchGestures = 'on';
fixture.detectChanges();
const styles = fixture.componentInstance.button.nativeElement.style;
if ('webkitUserDrag' in styles) {
expect(styles.webkitUserDrag).toBe('none');
}
});
it('should not open on `mouseenter` on iOS', () => {
platform.IOS = true;
platform.ANDROID = false;
const fixture = TestBed.createComponent(BasicTooltipDemo);
fixture.detectChanges();
dispatchMouseEvent(fixture.componentInstance.button.nativeElement, 'mouseenter');
fixture.detectChanges();
assertTooltipInstance(fixture.componentInstance.tooltip, false);
});
it('should not open on `mouseenter` on Android', () => {
platform.ANDROID = true;
platform.IOS = false;
const fixture = TestBed.createComponent(BasicTooltipDemo);
fixture.detectChanges();
dispatchMouseEvent(fixture.componentInstance.button.nativeElement, 'mouseenter');
fixture.detectChanges();
assertTooltipInstance(fixture.componentInstance.tooltip, false);
});
}); | {
"end_byte": 55550,
"start_byte": 47672,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.spec.ts"
} |
components/src/material/tooltip/tooltip.spec.ts_55554_64016 | describe('mouse wheel handling', () => {
it('should close when a wheel event causes the cursor to leave the trigger', fakeAsync(() => {
// We don't bind wheel events on mobile devices.
if (platform.IOS || platform.ANDROID) {
return;
}
const fixture = TestBed.createComponent(BasicTooltipDemo);
fixture.detectChanges();
const button: HTMLButtonElement = fixture.nativeElement.querySelector('button');
dispatchFakeEvent(button, 'mouseenter');
fixture.detectChanges();
tick(500); // Finish the open delay.
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, true);
assertTooltipInstance(fixture.componentInstance.tooltip, true);
// Simulate the pointer at the bottom/right of the page.
const wheelEvent = createFakeEvent('wheel');
Object.defineProperties(wheelEvent, {
clientX: {get: () => window.innerWidth},
clientY: {get: () => window.innerHeight},
});
dispatchEvent(button, wheelEvent);
fixture.detectChanges();
tick(1500); // Finish the delay.
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, false);
assertTooltipInstance(fixture.componentInstance.tooltip, false);
flush();
}));
it('should not close if the cursor is over the trigger after a wheel event', fakeAsync(() => {
// We don't bind wheel events on mobile devices.
if (platform.IOS || platform.ANDROID) {
return;
}
const fixture = TestBed.createComponent(BasicTooltipDemo);
fixture.detectChanges();
const button: HTMLButtonElement = fixture.nativeElement.querySelector('button');
dispatchFakeEvent(button, 'mouseenter');
fixture.detectChanges();
tick(500); // Finish the open delay.
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, true);
assertTooltipInstance(fixture.componentInstance.tooltip, true);
// Simulate the pointer over the trigger.
const triggerRect = button.getBoundingClientRect();
const wheelEvent = createFakeEvent('wheel');
Object.defineProperties(wheelEvent, {
clientX: {get: () => triggerRect.left + 1},
clientY: {get: () => triggerRect.top + 1},
});
dispatchEvent(button, wheelEvent);
fixture.detectChanges();
tick(1500); // Finish the delay.
fixture.detectChanges();
finishCurrentTooltipAnimation(overlayContainerElement, false);
assertTooltipInstance(fixture.componentInstance.tooltip, true);
flush();
}));
});
});
@Component({
selector: 'app',
template: `
@if (showButton) {
<button #button
[matTooltip]="message"
[matTooltipPosition]="position"
[matTooltipClass]="{'custom-one': showTooltipClass, 'custom-two': showTooltipClass}"
[matTooltipTouchGestures]="touchGestures"
[matTooltipDisabled]="tooltipDisabled">Button</button>
}`,
standalone: true,
imports: [MatTooltipModule, OverlayModule],
})
class BasicTooltipDemo {
position = 'below';
message: any = initialTooltipMessage;
showButton = true;
showTooltipClass = false;
tooltipDisabled = false;
touchGestures: TooltipTouchGestures = 'auto';
@ViewChild(MatTooltip) tooltip: MatTooltip;
@ViewChild('button') button: ElementRef<HTMLButtonElement>;
}
@Component({
selector: 'app',
template: `
<div cdkScrollable style="padding: 100px; margin: 300px;
height: 200px; width: 200px; overflow: auto;">
@if (showButton) {
<button style="margin-bottom: 600px"
[matTooltip]="message"
[matTooltipPosition]="position">Button</button>
}
</div>`,
standalone: true,
imports: [MatTooltipModule, OverlayModule],
})
class ScrollableTooltipDemo {
position: string = 'below';
message: string = initialTooltipMessage;
showButton: boolean = true;
@ViewChild(CdkScrollable) scrollingContainer: CdkScrollable;
scrollDown() {
const scrollingContainerEl = this.scrollingContainer.getElementRef().nativeElement;
scrollingContainerEl.scrollTop = 250;
// Emit a scroll event from the scrolling element in our component.
// This event should be picked up by the scrollable directive and notify.
// The notification should be picked up by the service.
dispatchFakeEvent(scrollingContainerEl, 'scroll');
}
}
@Component({
selector: 'app',
template: `
<button [matTooltip]="message"
[matTooltipPosition]="position">
Button
</button>`,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [MatTooltipModule, OverlayModule],
})
class OnPushTooltipDemo {
position: string = 'below';
message: string = initialTooltipMessage;
}
@Component({
selector: 'app',
template: `
@for (tooltip of tooltips; track tooltip) {
<button [matTooltip]="tooltip">Button {{tooltip}}</button>
}
`,
standalone: true,
imports: [MatTooltipModule, OverlayModule],
})
class DynamicTooltipsDemo {
tooltips: string[] = [];
}
@Component({
template: `<button [matTooltip]="message" [attr.aria-label]="message">Click me</button>`,
standalone: true,
imports: [MatTooltipModule, OverlayModule],
})
class DataBoundAriaLabelTooltip {
message = 'Hello there';
}
@Component({
template: `
<input
#input
matTooltip="Something"
[matTooltipTouchGestures]="touchGestures">
<textarea
#textarea
matTooltip="Another thing"
[matTooltipTouchGestures]="touchGestures"></textarea>
`,
standalone: true,
imports: [MatTooltipModule, OverlayModule],
})
class TooltipOnTextFields {
@ViewChild('input') input: ElementRef<HTMLInputElement>;
@ViewChild('textarea') textarea: ElementRef<HTMLTextAreaElement>;
touchGestures: TooltipTouchGestures = 'auto';
}
@Component({
template: `
<button
#button
draggable="true"
matTooltip="Drag me"
[matTooltipTouchGestures]="touchGestures"></button>
`,
standalone: true,
imports: [MatTooltipModule, OverlayModule],
})
class TooltipOnDraggableElement {
@ViewChild('button') button: ElementRef;
touchGestures: TooltipTouchGestures = 'auto';
}
@Component({
selector: 'app',
template: `<button #button [matTooltip]="message">Button</button>`,
standalone: false,
})
class TooltipDemoWithoutPositionBinding {
message: any = initialTooltipMessage;
@ViewChild(MatTooltip) tooltip: MatTooltip;
@ViewChild('button') button: ElementRef<HTMLButtonElement>;
}
@Component({
selector: 'app',
template: `<button #button [matTooltip]="message">Button</button>`,
standalone: false,
})
class TooltipDemoWithoutTooltipClassBinding {
message = initialTooltipMessage;
@ViewChild(MatTooltip) tooltip: MatTooltip;
@ViewChild('button') button: ElementRef<HTMLButtonElement>;
}
@Component({
selector: 'app',
template: `
<button #button matTooltipClass="fixed-tooltip-class" [matTooltip]="message">Button</button>
`,
standalone: false,
})
class TooltipDemoWithTooltipClassBinding {
message: any = initialTooltipMessage;
@ViewChild(MatTooltip) tooltip: MatTooltip;
@ViewChild('button') button: ElementRef<HTMLButtonElement>;
}
@Component({
selector: 'app',
styles: `button { width: 500px; height: 500px; }`,
template: `<button #button [matTooltip]="message">Button</button>`,
standalone: false,
})
class WideTooltipDemo {
message = 'Test';
@ViewChild(MatTooltip) tooltip: MatTooltip;
@ViewChild('button') button: ElementRef<HTMLButtonElement>;
}
/** Asserts whether a tooltip directive has a tooltip instance. */
function assertTooltipInstance(tooltip: MatTooltip, shouldExist: boolean): void {
// Note that we have to cast this to a boolean, because Jasmine will go into an infinite loop
// if it tries to stringify the `_tooltipInstance` when an assertion fails. The infinite loop
// happens due to the `_tooltipInstance` having a circular structure.
expect(!!tooltip._tooltipInstance).toBe(shouldExist);
}
function finishCurrentTooltipAnimation(overlayContainer: HTMLElement, isVisible: boolean) {
const tooltip = overlayContainer.querySelector('.mat-mdc-tooltip')!;
const event = createFakeEvent('animationend');
Object.defineProperty(event, 'animationName', {
get: () => `mat-mdc-tooltip-${isVisible ? 'show' : 'hide'}`,
});
dispatchEvent(tooltip, event);
} | {
"end_byte": 64016,
"start_byte": 55554,
"url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.