_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
components/src/dev-app/focus-trap/focus-trap-demo.html_0_6403 | <div>
<mat-card class="demo-mat-card">
<mat-toolbar color="primary">Basic</mat-toolbar>
<mat-card-content class="demo-mat-card-content">
<button mat-raised-button (click)="toggleFocus(basicFocusTrap)">
{{basicFocusTrap && basicFocusTrap.enabled ? "Disable" : "Enable"}} FocusTrap
</button>
<div
class="demo-focus-trap-region"
cdkTrapFocus
#basicFocusTrap="cdkTrapFocus"
[class.demo-focus-trap-enabled]="basicFocusTrap && basicFocusTrap.enabled">
<textarea class="demo-focus-trap-element" placeholder="One"></textarea>
<textarea class="demo-focus-trap-element" placeholder="Two"></textarea>
</div>
</mat-card-content>
</mat-card>
<mat-card class="demo-mat-card">
<mat-toolbar color="primary">Nested</mat-toolbar>
<mat-card-content class="demo-mat-card-content">
<button mat-raised-button (click)="toggleFocus(nestedOuterFocusTrap)">
{{nestedOuterFocusTrap && nestedOuterFocusTrap.enabled ? "Disable" : "Enable"}} outer FocusTrap
</button>
<div class="demo-focus-trap-region"
cdkTrapFocus
#nestedOuterFocusTrap="cdkTrapFocus"
[class.demo-focus-trap-enabled]="nestedOuterFocusTrap && nestedOuterFocusTrap.enabled">
<textarea class="demo-focus-trap-element" placeholder="One"></textarea>
<textarea class="demo-focus-trap-element" placeholder="Two"></textarea>
<button mat-raised-button class="demo-focus-trap-element"
(click)="toggleFocus(nestedInnerFocusTrap)">
{{nestedInnerFocusTrap && nestedInnerFocusTrap.enabled ? "Disable" : "Enable"}} inner FocusTrap
</button>
<div class="demo-focus-trap-region"
cdkTrapFocus
#nestedInnerFocusTrap="cdkTrapFocus"
[class.demo-focus-trap-enabled]="nestedInnerFocusTrap && nestedInnerFocusTrap.enabled">
<textarea class="demo-focus-trap-element" placeholder="Three"></textarea>
<textarea class="demo-focus-trap-element" placeholder="Four"></textarea>
</div>
</div>
</mat-card-content>
</mat-card>
<mat-card class="demo-mat-card">
<mat-toolbar color="primary">Tabindex > 0</mat-toolbar>
<mat-card-content class="demo-mat-card-content">
<button mat-raised-button (click)="toggleFocus(tabIndexFocusTrap)">
{{tabIndexFocusTrap && tabIndexFocusTrap.enabled ? "Disable" : "Enable"}} FocusTrap
</button>
<div class="demo-focus-trap-region"
cdkTrapFocus
#tabIndexFocusTrap="cdkTrapFocus"
[class.demo-focus-trap-enabled]="tabIndexFocusTrap && tabIndexFocusTrap.enabled">
<textarea class="demo-focus-trap-element" tabindex="1"
placeholder="I have tabindex 1"></textarea>
<textarea class="demo-focus-trap-element" placeholder="One"></textarea>
<textarea class="demo-focus-trap-element" placeholder="Two"></textarea>
</div>
<textarea class="demo-focus-trap-element" tabindex="1"
placeholder="I have tabindex 1"></textarea>
</mat-card-content>
</mat-card>
<mat-card class="demo-mat-card">
<mat-toolbar color="primary">Shadow DOMs</mat-toolbar>
<mat-card-content class="demo-mat-card-content">
@if (_supportsShadowDom) {
<button mat-raised-button (click)="toggleFocus(shadowDomFocusTrap)">
{{shadowDomFocusTrap && shadowDomFocusTrap.enabled ? "Disable" : "Enable"}} FocusTrap
</button>
<div class="demo-focus-trap-region"
cdkTrapFocus
#shadowDomFocusTrap="cdkTrapFocus"
[class.demo-focus-trap-enabled]="shadowDomFocusTrap && shadowDomFocusTrap.enabled">
<shadow-dom-demo>
<textarea placeholder="I am in a shadow DOM"></textarea>
</shadow-dom-demo>
<textarea class="demo-focus-trap-element" placeholder="One"></textarea>
<textarea class="demo-focus-trap-element" placeholder="Two"></textarea>
</div>
<shadow-dom-demo>
<textarea class="demo-focus-trap-element" placeholder="I am in a shadow DOM"></textarea>
</shadow-dom-demo>
} @else {
Shadow DOM not supported
}
</mat-card-content>
</mat-card>
<mat-card class="demo-mat-card">
<mat-toolbar color="primary">iframes</mat-toolbar>
<mat-card-content class="demo-mat-card-content">
<button mat-raised-button (click)="toggleFocus(iframeFocusTrap)">
{{iframeFocusTrap && iframeFocusTrap.enabled ? "Disable" : "Enable"}} FocusTrap
</button>
<div class="demo-focus-trap-region"
cdkTrapFocus
#iframeFocusTrap="cdkTrapFocus"
[class.demo-focus-trap-enabled]="iframeFocusTrap && iframeFocusTrap.enabled">
<iframe class="demo-focus-trap-element"
srcdoc="<textarea placeholder='I am in an iframe'></textarea>">
</iframe>
<textarea class="demo-focus-trap-element" placeholder="One"></textarea>
<textarea class="demo-focus-trap-element" placeholder="Two"></textarea>
</div>
<iframe srcdoc="<textarea placeholder='I am in an iframe'></textarea>"></iframe>
</mat-card-content>
</mat-card>
<mat-card class="demo-mat-card">
<mat-toolbar color="primary">Dynamic page content</mat-toolbar>
<mat-card-content class="demo-mat-card-content">
<button mat-raised-button (click)="toggleFocus(dynamicFocusTrap)">
{{dynamicFocusTrap && dynamicFocusTrap.enabled ? "Disable" : "Enable"}} FocusTrap
</button>
<div class="demo-focus-trap-region"
cdkTrapFocus
#dynamicFocusTrap="cdkTrapFocus"
[class.demo-focus-trap-enabled]="dynamicFocusTrap && dynamicFocusTrap.enabled">
<textarea class="demo-focus-trap-element" placeholder="One"></textarea>
<textarea class="demo-focus-trap-element" placeholder="Two"></textarea>
<button mat-raised-button class="demo-focus-trap-element" (click)="addNewElement()">
Click to add more focusable elements to the page
</button>
</div>
<div #newElements></div>
</mat-card-content>
</mat-card>
<mat-card class="demo-mat-card">
<mat-toolbar color="primary">Dialog-on-dialog</mat-toolbar>
<mat-card-content class="demo-mat-card-content">
<button mat-raised-button (click)="openDialog()">Open dialog</button>
</mat-card-content>
</mat-card>
</div>
| {
"end_byte": 6403,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/focus-trap/focus-trap-demo.html"
} |
components/src/dev-app/focus-trap/focus-trap-demo.scss_0_517 | .demo-focus-trap-region {
outline: 2px dashed lightgray;
padding: 4px;
margin: 12px 0;
&.demo-focus-trap-enabled {
outline: 2px solid red;
}
.demo-focus-trap-element, .demo-focus-trap-shadow-root {
display: block;
margin: 4px;
}
.demo-focus-trap-region {
margin: 12px 4px;
}
}
.demo-focus-trap-shadow-root {
display: block;
padding: 4px;
background-color: lightgrey;
}
.demo-mat-card {
padding: 0;
margin: 16px;
& .demo-mat-card-content {
padding: 24px;
}
}
| {
"end_byte": 517,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/focus-trap/focus-trap-demo.scss"
} |
components/src/dev-app/focus-trap/focus-trap-dialog-demo.scss_0_59 | .demo-dialog-textarea {
display: block;
margin: 4px;
}
| {
"end_byte": 59,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/focus-trap/focus-trap-dialog-demo.scss"
} |
components/src/dev-app/focus-trap/focus-trap-dialog-demo.html_0_434 | <h2 mat-dialog-title>Dialog {{id}}</h2>
<mat-dialog-content>
<textarea class="demo-dialog-textarea" placeholder="One"></textarea>
<textarea class="demo-dialog-textarea" placeholder="Two"></textarea>
</mat-dialog-content>
<mat-dialog-actions>
<button mat-raised-button mat-dialog-close>
Close
</button>
<button mat-raised-button (click)="openAnotherDialog()">
Open another dialog
</button>
</mat-dialog-actions>
| {
"end_byte": 434,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/focus-trap/focus-trap-dialog-demo.html"
} |
components/src/dev-app/focus-trap/BUILD.bazel_0_738 | load("//tools:defaults.bzl", "ng_module", "sass_binary")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "focus-trap",
srcs = glob(["**/*.ts"]),
assets = [
"focus-trap-demo.html",
"focus-trap-dialog-demo.html",
":focus_trap_demo_scss",
":focus_trap_dialog_demo_scss",
],
deps = [
"//src/cdk/a11y",
"//src/cdk/platform",
"//src/material/button",
"//src/material/card",
"//src/material/dialog",
"//src/material/toolbar",
],
)
sass_binary(
name = "focus_trap_demo_scss",
src = "focus-trap-demo.scss",
)
sass_binary(
name = "focus_trap_dialog_demo_scss",
src = "focus-trap-dialog-demo.scss",
)
| {
"end_byte": 738,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/focus-trap/BUILD.bazel"
} |
components/src/dev-app/focus-trap/focus-trap-demo.ts_0_2956 | /**
* @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 {A11yModule, CdkTrapFocus} from '@angular/cdk/a11y';
import {_supportsShadowDom} from '@angular/cdk/platform';
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
QueryList,
ViewChild,
ViewChildren,
ViewEncapsulation,
inject,
} from '@angular/core';
import {MatButtonModule} from '@angular/material/button';
import {MatCardModule} from '@angular/material/card';
import {
MatDialog,
MatDialogActions,
MatDialogClose,
MatDialogContent,
MatDialogTitle,
} from '@angular/material/dialog';
import {MatToolbarModule} from '@angular/material/toolbar';
@Component({
selector: 'shadow-dom-demo',
template: '<ng-content></ng-content>',
host: {'class': 'demo-focus-trap-shadow-root'},
encapsulation: ViewEncapsulation.ShadowDom,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FocusTrapShadowDomDemo {}
@Component({
selector: 'focus-trap-demo',
templateUrl: 'focus-trap-demo.html',
styleUrl: 'focus-trap-demo.css',
imports: [A11yModule, MatButtonModule, MatCardModule, MatToolbarModule, FocusTrapShadowDomDemo],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FocusTrapDemo implements AfterViewInit {
dialog = inject(MatDialog);
@ViewChild('newElements')
private _newElements: ElementRef<HTMLElement>;
@ViewChildren(CdkTrapFocus)
private _focusTraps: QueryList<CdkTrapFocus>;
_supportsShadowDom = _supportsShadowDom();
readonly cdr = inject(ChangeDetectorRef);
ngAfterViewInit() {
// We want all the traps to be disabled by default, but doing so while using the value in
// the view will result in "changed after checked" errors so we defer it to the next tick.
setTimeout(() => {
this._focusTraps.forEach(trap => (trap.enabled = false));
this.cdr.markForCheck();
});
}
toggleFocus(instance: CdkTrapFocus) {
instance.enabled = !instance.enabled;
if (instance.enabled) {
instance.focusTrap.focusInitialElementWhenReady();
}
}
addNewElement() {
const textarea = document.createElement('textarea');
textarea.setAttribute('placeholder', 'I am a new element!');
this._newElements.nativeElement.appendChild(textarea);
}
openDialog() {
this.dialog.open(FocusTrapDialogDemo);
}
}
let dialogCount = 0;
@Component({
selector: 'focus-trap-dialog-demo',
styleUrl: 'focus-trap-dialog-demo.css',
templateUrl: 'focus-trap-dialog-demo.html',
imports: [MatDialogTitle, MatDialogContent, MatDialogClose, MatDialogActions],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FocusTrapDialogDemo {
dialog = inject(MatDialog);
id = dialogCount++;
openAnotherDialog() {
this.dialog.open(FocusTrapDialogDemo);
}
}
| {
"end_byte": 2956,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/focus-trap/focus-trap-demo.ts"
} |
components/src/dev-app/focus-origin/focus-origin-demo.ts_0_605 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ChangeDetectionStrategy, Component, inject} from '@angular/core';
import {A11yModule, FocusMonitor} from '@angular/cdk/a11y';
@Component({
selector: 'focus-origin-demo',
templateUrl: 'focus-origin-demo.html',
styleUrl: 'focus-origin-demo.css',
imports: [A11yModule],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FocusOriginDemo {
fom = inject(FocusMonitor);
}
| {
"end_byte": 605,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/focus-origin/focus-origin-demo.ts"
} |
components/src/dev-app/focus-origin/BUILD.bazel_0_409 | load("//tools:defaults.bzl", "ng_module", "sass_binary")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "focus-origin",
srcs = glob(["**/*.ts"]),
assets = [
"focus-origin-demo.html",
":focus_origin_demo_scss",
],
deps = [
"//src/cdk/a11y",
],
)
sass_binary(
name = "focus_origin_demo_scss",
src = "focus-origin-demo.scss",
)
| {
"end_byte": 409,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/focus-origin/BUILD.bazel"
} |
components/src/dev-app/focus-origin/focus-origin-demo.scss_0_357 | .demo-focusable {
border: 2px solid transparent;
}
.demo-focusable.cdk-focused {
border: 2px solid red;
}
.demo-focusable.cdk-mouse-focused {
background: green;
}
.demo-focusable.cdk-keyboard-focused {
background: yellow;
}
.demo-focusable.cdk-program-focused {
background: blue;
}
.demo-focusable.cdk-touch-focused {
background: purple;
}
| {
"end_byte": 357,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/focus-origin/focus-origin-demo.scss"
} |
components/src/dev-app/focus-origin/focus-origin-demo.html_0_994 | <button #b class="demo-focusable" cdkMonitorElementFocus>focus me!</button>
<button (click)="b.focus()">focus programmatically</button>
<button (click)="fom.focusVia(b, 'mouse')">focusVia: mouse</button>
<button (click)="fom.focusVia(b, 'touch')">focusVia: touch</button>
<button (click)="fom.focusVia(b, 'keyboard')">focusVia: keyboard</button>
<button (click)="fom.focusVia(b, 'program')">focusVia: program</button>
<div>Active classes: {{b.classList}}</div>
<br>
<div class="demo-focusable" tabindex="0" cdkMonitorElementFocus>
<p>div with element focus monitored</p>
<button>1</button><button>2</button>
</div>
<div class="demo-focusable" tabindex="0" cdkMonitorSubtreeFocus>
<p>div with subtree focus monitored</p>
<button>1</button><button>2</button>
</div>
<div class="demo-focusable" cdkMonitorSubtreeFocus>
<p>Parent div should get same focus origin as button when button is focused:</p>
<button class="demo-focusable" cdkMonitorElementFocus>focus me</button>
</div>
| {
"end_byte": 994,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/focus-origin/focus-origin-demo.html"
} |
components/src/dev-app/badge/badge-demo.scss_0_144 | .demo-badge {
margin-bottom: 25px;
}
.mat-badge {
margin-right: 22px;
[dir='rtl'] & {
margin-right: 0;
margin-left: 22px;
}
}
| {
"end_byte": 144,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/badge/badge-demo.scss"
} |
components/src/dev-app/badge/badge-demo.ts_0_781 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ChangeDetectionStrategy, Component} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {MatBadgeModule} from '@angular/material/badge';
import {MatButtonModule} from '@angular/material/button';
import {MatIconModule} from '@angular/material/icon';
@Component({
selector: 'badge-demo',
templateUrl: 'badge-demo.html',
styleUrl: 'badge-demo.css',
imports: [FormsModule, MatBadgeModule, MatButtonModule, MatIconModule],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BadgeDemo {
visible = true;
badgeContent = '0';
}
| {
"end_byte": 781,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/badge/badge-demo.ts"
} |
components/src/dev-app/badge/badge-demo.html_0_2299 | <div>
<div class="demo-badge">
<h3>Buttons</h3>
<button mat-stroked-button matBadge="7" matBadgeDescription="7 unread messages">
Inbox
</button>
<button mat-stroked-button matBadge="7" matBadgePosition="below after"
matBadgeDescription="7 unread messages">
Inbox
</button>
<button mat-stroked-button matBadge="7" disabled matBadgeDisabled
matBadgeDescription="7 unread messages">
Inbox
</button>
<button mat-stroked-button matBadge="7" matBadgeColor="accent"
matBadgeDescription="7 unread messages">
Inbox
</button>
</div>
<div class="demo-badge">
<h3>Icons</h3>
<mat-icon [matBadge]="badgeContent" matBadgeDescription="This is a home indicator">
home
</mat-icon>
<mat-icon color="primary" matBadge="22" matBadgePosition="below after" matBadgeColor="accent">
home
</mat-icon>
<mat-icon color="primary" matBadge="22" matBadgePosition="above before" matBadgeColor="warn">
home
</mat-icon>
<mat-icon color="primary" matBadge="22" matBadgePosition="below before">
home
</mat-icon>
</div>
<div class="demo-badge">
<h3>Size</h3>
<mat-icon [matBadge]="badgeContent" matBadgeSize="small">
home
</mat-icon>
<mat-icon [matBadge]="badgeContent" matBadgeSize="large">
home
</mat-icon>
</div>
<div class="demo-badge">
<h3>Text</h3>
@if (visible) {
<span [matBadge]="badgeContent" matBadgeOverlap="false">Hello</span>
}
<span matBadge="11111" matBadgeOverlap="false">
Hello
</span>
<span matBadge="22" matBadgeOverlap="false" matBadgePosition="below after" matBadgeColor="accent">
Hello
</span>
<span matBadge="22" matBadgeOverlap="false" matBadgePosition="above before" matBadgeColor="warn">
Hello
</span>
<span matBadge="⚡️" matBadgeOverlap="false" matBadgePosition="below before">
Hello
</span>
<span [matBadge]="badgeContent" matBadgeDescription="I've got {{badgeContent}} problems">
Aria
</span>
<span [matBadge]="badgeContent" matBadgeHidden="true">
Hidden
</span>
<input type="text" [(ngModel)]="badgeContent" />
<button (click)="visible = !visible">Toggle</button>
</div>
</div>
| {
"end_byte": 2299,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/badge/badge-demo.html"
} |
components/src/dev-app/badge/BUILD.bazel_0_476 | load("//tools:defaults.bzl", "ng_module", "sass_binary")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "badge",
srcs = glob(["**/*.ts"]),
assets = [
"badge-demo.html",
":badge_demo_scss",
],
deps = [
"//src/material/badge",
"//src/material/button",
"//src/material/icon",
"@npm//@angular/forms",
],
)
sass_binary(
name = "badge_demo_scss",
src = "badge-demo.scss",
)
| {
"end_byte": 476,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/badge/BUILD.bazel"
} |
components/src/dev-app/clipboard/clipboard-demo.html_0_652 | <section>
<label for="example-textarea">Text to be copied</label>
<textarea id="example-textarea" cols="30" rows="10" [(ngModel)]="value"></textarea>
</section>
<section>
<label for="example-attempts-input">Copy attempts</label>
<input id="example-attempts-input" type="number" [(ngModel)]="attempts"/>
</section>
<button (click)="copyViaService()">Copy to clipboard via service</button>
<button
[cdkCopyToClipboard]="value"
[cdkCopyToClipboardAttempts]="attempts">Copy to clipboard via directive</button>
<section>
<label for="testing-area">Testing area</label>
<textarea id="testing-area" cols="30" rows="5"></textarea>
</section>
| {
"end_byte": 652,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/clipboard/clipboard-demo.html"
} |
components/src/dev-app/clipboard/clipboard-demo.scss_0_59 | label {
display: block;
}
section {
margin: 8px 0;
}
| {
"end_byte": 59,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/clipboard/clipboard-demo.scss"
} |
components/src/dev-app/clipboard/clipboard-demo.ts_0_1590 | /**
* @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 {Clipboard, ClipboardModule} from '@angular/cdk/clipboard';
import {ChangeDetectionStrategy, Component, inject} from '@angular/core';
import {FormsModule} from '@angular/forms';
@Component({
selector: 'clipboard-demo',
styleUrl: 'clipboard-demo.css',
templateUrl: 'clipboard-demo.html',
imports: [ClipboardModule, FormsModule],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ClipboardDemo {
private _clipboard = inject(Clipboard);
attempts = 3;
value =
`Did you ever hear the tragedy of Darth Plagueis The Wise? I thought not. It's not ` +
`a story the Jedi would tell you. It's a Sith legend. Darth Plagueis was a Dark Lord ` +
`of the Sith, so powerful and so wise he could use the Force to influence the ` +
`midichlorians to create life… He had such a knowledge of the dark side that he could ` +
`even keep the ones he cared about from dying. The dark side of the Force is a pathway ` +
`to many abilities some consider to be unnatural. He became so powerful… the only ` +
`thing he was afraid of was losing his power, which eventually, of course, he did. ` +
`Unfortunately, he taught his apprentice everything he knew, then his apprentice ` +
`killed him in his sleep. Ironic. He could save others from death, but not himself.`;
copyViaService() {
this._clipboard.copy(this.value);
}
}
| {
"end_byte": 1590,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/clipboard/clipboard-demo.ts"
} |
components/src/dev-app/clipboard/BUILD.bazel_0_431 | load("//tools:defaults.bzl", "ng_module", "sass_binary")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "clipboard",
srcs = glob(["**/*.ts"]),
assets = [
":clipboard_demo_scss",
"clipboard-demo.html",
],
deps = [
"//src/cdk/clipboard",
"@npm//@angular/forms",
],
)
sass_binary(
name = "clipboard_demo_scss",
src = "clipboard-demo.scss",
)
| {
"end_byte": 431,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/dev-app/clipboard/BUILD.bazel"
} |
components/src/universal-app/main.ts_0_432 | import {bootstrapApplication, provideClientHydration} from '@angular/platform-browser';
import {provideAnimations} from '@angular/platform-browser/animations';
import {AUTOMATED_KITCHEN_SINK, KitchenSink} from './kitchen-sink/kitchen-sink';
bootstrapApplication(KitchenSink, {
providers: [
provideAnimations(),
provideClientHydration(),
{
provide: AUTOMATED_KITCHEN_SINK,
useValue: false,
},
],
});
| {
"end_byte": 432,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/universal-app/main.ts"
} |
components/src/universal-app/styles.scss_0_707 | @use '@angular/material' as mat;
@include mat.app-background();
$theme: mat.define-theme((
color: (
theme-type: light,
primary: mat.$azure-palette,
tertiary: mat.$blue-palette,
),
density: (
scale: 0,
)
));
html {
@include mat.all-component-themes($theme);
}
@include mat.typography-hierarchy($theme);
body.test-automated {
// Make sure bottom sheet doesn't obscure components.
padding-bottom: 80px;
// Hide the overlay so hover styles can be tested,
// but show a message so we can see that the overlay is there.
.cdk-overlay-backdrop {
bottom: 100vh !important;
}
.cdk-overlay-backdrop::after {
content: 'OVERLAY ACTIVE';
background: lime;
}
}
| {
"end_byte": 707,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/universal-app/styles.scss"
} |
components/src/universal-app/prerender.ts_0_2076 | import 'reflect-metadata';
import 'zone.js';
import {ErrorHandler} from '@angular/core';
import {bootstrapApplication, provideClientHydration} from '@angular/platform-browser';
import {provideServerRendering, renderApplication} from '@angular/platform-server';
import {provideNoopAnimations} from '@angular/platform-browser/animations';
import {runfiles} from '@bazel/runfiles';
import {readFileSync, writeFileSync} from 'fs';
import {AUTOMATED_KITCHEN_SINK, KitchenSink} from './kitchen-sink/kitchen-sink';
const outputPath = process.argv[2];
const indexPath = runfiles.resolvePackageRelative('./index-source.html');
// Debug mode disables some automated interactions to make it easier to debug components locally.
const isDebugMode = process.argv.includes('--debug');
if (!outputPath) {
throw new Error('Cannot determine output path for prerendered content');
}
// Do not enable production mode, because otherwise the `MatCommonModule` won't execute
// the browser related checks that could cause NodeJS issues.
renderApplication(bootstrap, {
document: readFileSync(indexPath, 'utf-8'),
})
.then(content => writeFileSync(outputPath, content))
.catch(error => {
// If rendering fails, print the error and exit the process with a non-zero exit code.
console.error(error);
process.exit(1);
});
function bootstrap() {
return bootstrapApplication(KitchenSink, {
providers: [
provideNoopAnimations(),
provideServerRendering(),
provideClientHydration(),
{
provide: AUTOMATED_KITCHEN_SINK,
useValue: !isDebugMode,
},
{
// If an error is thrown asynchronously during server-side rendering
// it'll get logged to stderr, but it won't cause the build to fail.
// We still want to catch these errors so we provide an ErrorHandler
// that rethrows the error and causes the process to exit correctly.
provide: ErrorHandler,
useValue: {
handleError: (error: Error) => {
throw error;
},
},
},
],
});
}
| {
"end_byte": 2076,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/universal-app/prerender.ts"
} |
components/src/universal-app/README.md_0_518 | ### Server-side debugging app
Application that renders all components on the server and hydrates them on the client. Common tasks:
* Run `yarn universal-app` to start a local server. **Does not support live reload**
* To inspect the server-side-generated HTML, run `yarn universal-app`, visit the local server and
use either the dev tools or "View source" to see the `index.html` provided by the server.
* To test if all components would render on the server, run `yarn bazel test src/universal-app:prerender_test`.
| {
"end_byte": 518,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/universal-app/README.md"
} |
components/src/universal-app/hydration.e2e.spec.ts_0_1208 | import {browser, by, element, ExpectedConditions} from 'protractor';
describe('hydration e2e', () => {
beforeEach(async () => {
await browser.waitForAngularEnabled(false);
await browser.get('/');
await browser.wait(ExpectedConditions.presenceOf(element(by.css('.render-marker'))), 5000);
});
it('should enable hydration', async () => {
const hydrationState = await getHydrationState();
const logs = await browser.manage().logs().get('browser');
expect(hydrationState.hydratedComponents).toBeGreaterThan(0);
expect(logs.map(log => log.message).filter(msg => msg.includes('NG0500'))).toEqual([]);
});
it('should not skip hydration on any components', async () => {
const hydrationState = await getHydrationState();
expect(hydrationState.componentsSkippedHydration).toBe(0);
});
});
/** Gets the hydration state from the current app. */
async function getHydrationState() {
return browser.executeScript<{
hydratedComponents: number;
componentsSkippedHydration: number;
}>(() => ({
hydratedComponents: (window as any).ngDevMode.hydratedComponents,
componentsSkippedHydration: (window as any).ngDevMode.componentsSkippedHydration,
}));
}
| {
"end_byte": 1208,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/universal-app/hydration.e2e.spec.ts"
} |
components/src/universal-app/start-devserver.js_0_1016 | const protractor = require('protractor');
// Note: We need to specify an explicit file extension here because otherwise
// the Bazel-patched NodeJS module resolution would resolve to the `.mjs` file
// in non-sandbox environments (as usually with Bazel and Windows).
const utils = require('@bazel/protractor/protractor-utils.js');
/**
* Called by Protractor before starting any tests. This is script is responsible for
* starting up the devserver and updating the Protractor base URL to the proper port.
*/
module.exports = async function (config) {
const {port} = await utils.runServer(config.workspace, config.server, '--port', []);
const baseUrl = `http://localhost:${port}`;
const processedConfig = await protractor.browser.getProcessedConfig();
// Update the protractor "baseUrl" to match the new random TCP port. We need random TCP ports
// because otherwise Bazel could not execute protractor tests concurrently.
protractor.browser.baseUrl = baseUrl;
processedConfig.baseUrl = baseUrl;
};
| {
"end_byte": 1016,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/universal-app/start-devserver.js"
} |
components/src/universal-app/protractor.conf.js_0_365 | exports.config = {
useAllAngular2AppRoots: true,
allScriptsTimeout: 120000,
getPageTimeout: 120000,
jasmineNodeOpts: {
defaultTimeoutInterval: 120000,
},
// Since we want to use async/await we don't want to mix up with selenium's promise
// manager. In order to enforce this, we disable the promise manager.
SELENIUM_PROMISE_MANAGER: false,
};
| {
"end_byte": 365,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/universal-app/protractor.conf.js"
} |
components/src/universal-app/BUILD.bazel_0_4295 | load("@bazel_skylib//rules:build_test.bzl", "build_test")
load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_binary", "npm_package_bin")
load("//src/cdk:config.bzl", "CDK_TARGETS")
load("//src/cdk-experimental:config.bzl", "CDK_EXPERIMENTAL_TARGETS")
load("//src/components-examples:config.bzl", "ALL_EXAMPLES")
load("//src/material:config.bzl", "MATERIAL_TARGETS")
load("//src/material-experimental:config.bzl", "MATERIAL_EXPERIMENTAL_TARGETS")
load("//tools:defaults.bzl", "devmode_esbuild", "http_server", "ng_e2e_test_library", "ng_module", "protractor_web_test_suite", "sass_binary", "ts_library")
load("//tools/angular:index.bzl", "LINKER_PROCESSED_FW_PACKAGES")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "kitchen-sink",
srcs = [
"kitchen-sink/kitchen-sink.ts",
],
assets = [
"kitchen-sink/kitchen-sink.html",
],
deps = [
"//src/google-maps",
"//src/youtube-player",
"@npm//@angular/platform-server",
] + CDK_TARGETS + CDK_EXPERIMENTAL_TARGETS + MATERIAL_TARGETS + MATERIAL_EXPERIMENTAL_TARGETS + ALL_EXAMPLES,
)
ts_library(
name = "client_lib",
srcs = [
"main.ts",
],
deps = [
":kitchen-sink",
"@npm//@angular/platform-browser",
],
)
ts_library(
name = "prerender_lib",
srcs = [
"prerender.ts",
],
deps = [
":kitchen-sink",
"@npm//@angular/core",
"@npm//@angular/platform-browser",
"@npm//@angular/platform-server",
"@npm//@bazel/runfiles",
"@npm//@types/node",
"@npm//reflect-metadata",
"@npm//zone.js",
],
)
sass_binary(
name = "styles_scss",
src = "styles.scss",
deps = [
"//src/material:sass_lib",
"//src/material-experimental:sass_lib",
],
)
nodejs_binary(
name = "prerender",
data = [
"index-source.html",
":prerender_bundle",
":styles_scss",
],
entry_point = ":prerender_bundle.js",
templated_args = [
# TODO(josephperrott): update dependency usages to no longer need bazel patch module resolver
# See: https://github.com/bazelbuild/rules_nodejs/wiki#--bazel_patch_module_resolver-now-defaults-to-false-2324
"--bazel_patch_module_resolver",
],
)
devmode_esbuild(
name = "client_bundle",
entry_points = [":main.ts"],
platform = "browser",
target = "es2016",
deps = LINKER_PROCESSED_FW_PACKAGES + [
":client_lib",
],
)
devmode_esbuild(
name = "prerender_bundle",
entry_point = ":prerender.ts",
platform = "node",
# We cannot use `ES2017` or higher as that would result in `async/await` not being downleveled.
# ZoneJS needs to be able to intercept these as otherwise change detection would not work properly.
target = "es2016",
# Note: We add all linker-processed FW packages as dependencies here so that ESBuild will
# map all framework packages to their linker-processed bundles from `tools/angular`.
deps = LINKER_PROCESSED_FW_PACKAGES + [
":prerender_lib",
],
)
npm_package_bin(
name = "prerender_test_bin",
outs = ["index-prerendered.html"],
args = ["$@"],
tool = ":prerender",
)
npm_package_bin(
name = "debug_prerender_bin",
# Note: the file needs to be called `index.html` specifically so the server can pick it up.
outs = ["index.html"],
args = [
"$@",
"--debug", # Disables some testing behavior that can be annoying while debugging.
],
tool = ":prerender",
)
build_test(
name = "prerender_test",
targets = [
":prerender_test_bin",
],
)
http_server(
name = "server",
srcs = [
":debug_prerender_bin",
"@npm//zone.js",
],
additional_root_paths = [
"npm/node_modules",
],
tags = ["manual"],
deps = [
":client_bundle",
":styles_scss",
],
)
ng_e2e_test_library(
name = "hydration_e2e_tests_sources",
srcs = ["hydration.e2e.spec.ts"],
)
protractor_web_test_suite(
name = "hydration_e2e_tests",
configuration = ":protractor.conf.js",
on_prepare = ":start-devserver.js",
server = ":server",
tags = ["e2e"],
deps = [
":hydration_e2e_tests_sources",
],
)
| {
"end_byte": 4295,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/universal-app/BUILD.bazel"
} |
components/src/universal-app/index-source.html_0_939 | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Angular Material Universal Kitchen Sink Test</title>
<link href="styles.css" rel="stylesheet">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<base href="/">
</head>
<body class="mat-app-background mat-typography">
<kitchen-sink>Loading...</kitchen-sink>
<script src="zone.js/bundles/zone.umd.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=visualization"></script>
<script src="https://unpkg.com/@googlemaps/markerclustererplus/dist/index.min.js"></script>
<script src="client_bundle/main.js" type="module"></script>
</body>
</html>
| {
"end_byte": 939,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/universal-app/index-source.html"
} |
components/src/universal-app/kitchen-sink/kitchen-sink.ts_0_8024 | import {ScrollingModule as ExperimentalScrollingModule} from '@angular/cdk-experimental/scrolling';
import {A11yModule, FocusMonitor} from '@angular/cdk/a11y';
import {DragDropModule} from '@angular/cdk/drag-drop';
import {CdkListboxModule} from '@angular/cdk/listbox';
import {ScrollingModule, ViewportRuler} from '@angular/cdk/scrolling';
import {CdkTableModule, DataSource} from '@angular/cdk/table';
import {DOCUMENT} from '@angular/common';
import {CdkPopoverEditCdkTableExample} from '@angular/components-examples/cdk-experimental/popover-edit';
import {Component, ElementRef, InjectionToken, inject} from '@angular/core';
import {
GoogleMap,
MapBicyclingLayer,
MapCircle,
MapGroundOverlay,
MapHeatmapLayer,
MapInfoWindow,
MapKmlLayer,
MapMarker,
DeprecatedMapMarkerClusterer,
MapPolygon,
MapPolyline,
MapRectangle,
MapTrafficLayer,
MapTransitLayer,
MapAdvancedMarker,
} from '@angular/google-maps';
import {MatAutocompleteModule} from '@angular/material/autocomplete';
import {MatBadgeModule} from '@angular/material/badge';
import {MatBottomSheet, MatBottomSheetModule} from '@angular/material/bottom-sheet';
import {MatButtonModule} from '@angular/material/button';
import {MatButtonToggleModule} from '@angular/material/button-toggle';
import {MatCardModule} from '@angular/material/card';
import {MatCheckboxModule} from '@angular/material/checkbox';
import {MatChipsModule} from '@angular/material/chips';
import {MatRippleModule, provideNativeDateAdapter} from '@angular/material/core';
import {MatDatepickerModule} from '@angular/material/datepicker';
import {MatDialog} from '@angular/material/dialog';
import {MatDividerModule} from '@angular/material/divider';
import {MatExpansionModule} from '@angular/material/expansion';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatGridListModule} from '@angular/material/grid-list';
import {MatIconModule} from '@angular/material/icon';
import {MatInputModule} from '@angular/material/input';
import {MatListModule} from '@angular/material/list';
import {MatMenuModule} from '@angular/material/menu';
import {MatPaginatorModule} from '@angular/material/paginator';
import {MatProgressBarModule} from '@angular/material/progress-bar';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import {MatRadioModule} from '@angular/material/radio';
import {MatSelectModule} from '@angular/material/select';
import {MatSidenavModule} from '@angular/material/sidenav';
import {MatSlideToggleModule} from '@angular/material/slide-toggle';
import {MatSliderModule} from '@angular/material/slider';
import {MatSnackBar} from '@angular/material/snack-bar';
import {MatSortModule} from '@angular/material/sort';
import {MatStepperModule} from '@angular/material/stepper';
import {MatTableModule} from '@angular/material/table';
import {MatTabsModule} from '@angular/material/tabs';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatTooltipModule} from '@angular/material/tooltip';
import {YouTubePlayer} from '@angular/youtube-player';
import {Observable, of as observableOf} from 'rxjs';
export class TableDataSource extends DataSource<any> {
connect(): Observable<any> {
return observableOf([
{position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
{position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
{position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
{position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
{position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
{position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
{position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
{position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
{position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
]);
}
disconnect() {}
}
export const AUTOMATED_KITCHEN_SINK = new InjectionToken<boolean>('AUTOMATED_KITCHEN_SINK');
@Component({
template: `<button>Do the thing</button>`,
})
export class TestEntryComponent {}
@Component({
selector: 'kitchen-sink',
templateUrl: './kitchen-sink.html',
providers: [provideNativeDateAdapter()],
styles: `
.universal-viewport {
height: 100px;
border: 1px solid black;
}
.test-cdk-listbox {
display: block;
width: 100%;
> label {
display: block;
padding: 5px;
}
> ul {
list-style: none;
padding: 0;
margin: 0;
> li {
position: relative;
padding: 5px 5px 5px 25px;
&:focus {
background: rgba(0, 0, 0, 0.2);
}
&[aria-selected='true']::before {
content: "✔";
position: absolute;
left: 2px;
}
}
}
}
.test-cdk-table {
display: table;
width: 100%;
}
.test-cdk-table .cdk-row,
.test-cdk-table .cdk-header-row {
display: table-row;
}
.test-cdk-table .cdk-cell,
.test-cdk-table .cdk-header-cell {
display: table-cell;
}
`,
imports: [
MatAutocompleteModule,
MatBadgeModule,
MatBottomSheetModule,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatCheckboxModule,
MatChipsModule,
MatDatepickerModule,
MatDividerModule,
MatFormFieldModule,
MatGridListModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatPaginatorModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatRadioModule,
MatRippleModule,
MatSelectModule,
MatSidenavModule,
MatSliderModule,
MatSlideToggleModule,
MatTabsModule,
MatToolbarModule,
MatTooltipModule,
MatExpansionModule,
MatSortModule,
MatTableModule,
MatStepperModule,
ScrollingModule,
ExperimentalScrollingModule,
// CDK Modules
CdkListboxModule,
CdkTableModule,
DragDropModule,
A11yModule,
// Other modules
YouTubePlayer,
GoogleMap,
MapBicyclingLayer,
MapCircle,
MapGroundOverlay,
MapHeatmapLayer,
MapInfoWindow,
MapKmlLayer,
MapMarker,
MapAdvancedMarker,
DeprecatedMapMarkerClusterer,
MapPolygon,
MapPolyline,
MapRectangle,
MapTrafficLayer,
MapTransitLayer,
// Examples
CdkPopoverEditCdkTableExample,
],
})
export class KitchenSink {
private _snackBar = inject(MatSnackBar);
private _dialog = inject(MatDialog);
private _bottomSheet = inject(MatBottomSheet);
/** List of columns for the CDK and Material table. */
tableColumns = ['position', 'name', 'weight', 'symbol'];
/** Data source for the CDK and Material table. */
tableDataSource = new TableDataSource();
/** Data used to render a virtual scrolling list. */
virtualScrollData = Array(10000).fill(50);
/** Whether the kitchen sink is running as a part of an automated test or for local debugging. */
isAutomated: boolean;
constructor() {
const viewportRuler = inject(ViewportRuler);
const focusMonitor = inject(FocusMonitor);
const elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
this.isAutomated = inject(AUTOMATED_KITCHEN_SINK, {optional: true}) ?? true;
focusMonitor.focusVia(elementRef, 'program');
// Do a sanity check on the viewport ruler.
viewportRuler.getViewportRect();
viewportRuler.getViewportSize();
viewportRuler.getViewportScrollPosition();
// Only open overlays when automation is enabled since they can prevent debugging.
if (this.isAutomated) {
inject(DOCUMENT).body.classList.add('test-automated');
this.openSnackbar();
this.openDialog();
this.openBottomSheet();
}
}
openSnackbar() {
this._snackBar.open('Hello there');
}
openDialog() {
this._dialog.open(TestEntryComponent);
}
openBottomSheet() {
this._bottomSheet.open(TestEntryComponent);
}
}
| {
"end_byte": 8024,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/universal-app/kitchen-sink/kitchen-sink.ts"
} |
components/src/universal-app/kitchen-sink/kitchen-sink.html_0_6801 | <h2>Autocomplete</h2>
<mat-form-field>
<mat-label>Computer scientists</mat-label>
<input matInput [matAutocomplete]="autocomplete" />
</mat-form-field>
<mat-autocomplete #autocomplete>
<mat-option value="Grace Hopper">Grace Hopper</mat-option>
<mat-option value="Anita Borg">Anita Borg</mat-option>
<mat-option value="Ada Lovelace">Ada Lovelace</mat-option>
</mat-autocomplete>
<h2>Bottom sheet</h2>
<button mat-raised-button (click)="openBottomSheet()">Open bottom sheet</button>
<h2>Button</h2>
<button mat-button>go</button>
<button mat-icon-button><mat-icon>search</mat-icon></button>
<button mat-raised-button>go</button>
<button mat-fab><mat-icon>home</mat-icon></button>
<button mat-mini-fab><mat-icon>favorite</mat-icon></button>
<a mat-button href="https://google.com">Google</a>
<a mat-icon-button href="https://google.com"><mat-icon>search</mat-icon></a>
<a mat-raised-button href="https://google.com">Google</a>
<a mat-fab href="https://google.com"><mat-icon>home</mat-icon></a>
<a mat-mini-fab href="https://google.com"><mat-icon>favorite</mat-icon></a>
<h2>Button toggle</h2>
<h3>Single selection</h3>
<mat-button-toggle-group>
<mat-button-toggle>Ketchup</mat-button-toggle>
<mat-button-toggle>Mustard</mat-button-toggle>
<mat-button-toggle>Mayo</mat-button-toggle>
</mat-button-toggle-group>
<h3>Multi selection</h3>
<mat-button-toggle-group multiple>
<mat-button-toggle>Ketchup</mat-button-toggle>
<mat-button-toggle>Mustard</mat-button-toggle>
<mat-button-toggle>Mayo</mat-button-toggle>
</mat-button-toggle-group>
<h3>Standalone</h3>
<mat-button-toggle>Hyperspinner enabled</mat-button-toggle>
<h3>Card</h3>
<mat-card> Simple card </mat-card>
<mat-card>
<mat-card-title>Complicated card</mat-card-title>
<mat-card-subtitle>Subtitle</mat-card-subtitle>
<mat-card-content>
<p>This is some stuff</p>
<p>And more stuff</p>
</mat-card-content>
<mat-card-actions>
<button mat-button>LIKE</button>
<button mat-button>SHARE</button>
</mat-card-actions>
<mat-card-footer> Hurray </mat-card-footer>
</mat-card>
<h2>Checkbox</h2>
<mat-checkbox></mat-checkbox>
<mat-checkbox checked></mat-checkbox>
<mat-checkbox checked disabled></mat-checkbox>
<mat-checkbox indeterminate></mat-checkbox>
<mat-checkbox>with a label</mat-checkbox>
<h2>Chips</h2>
<mat-chip-set>
<mat-basic-chip>Basic Chip 1</mat-basic-chip>
<mat-basic-chip>Basic Chip 2</mat-basic-chip>
<mat-basic-chip>Basic Chip 3</mat-basic-chip>
</mat-chip-set>
<mat-chip-listbox multiple>
<mat-chip-option>Extra Small</mat-chip-option>
<mat-chip-option selected>Small</mat-chip-option>
<mat-chip-option selected disabled>Medium</mat-chip-option>
<mat-chip-option>Large</mat-chip-option>
</mat-chip-listbox>
<h2>Datepicker</h2>
<mat-form-field>
<input type="text" matInput [matDatepicker]="birthday" placeholder="Birthday" />
<mat-datepicker-toggle matSuffix [for]="birthday"></mat-datepicker-toggle>
<mat-datepicker #birthday></mat-datepicker>
</mat-form-field>
<h3>Disabled datepicker</h3>
<mat-form-field>
<input
type="text"
disabled
matInput
[matDatepicker]="departureDate"
placeholder="Departure date"
/>
<mat-datepicker-toggle matSuffix [for]="departureDate"></mat-datepicker-toggle>
<mat-datepicker #departureDate></mat-datepicker>
</mat-form-field>
<h2>Dialog</h2>
<button mat-raised-button (click)="openDialog()">Open dialog</button>
<h2>Grid list</h2>
<mat-grid-list cols="4">
<mat-grid-tile>Fry</mat-grid-tile>
<mat-grid-tile>Leela</mat-grid-tile>
<mat-grid-tile>Amy</mat-grid-tile>
<mat-grid-tile>Bender</mat-grid-tile>
</mat-grid-list>
<h2>Icon</h2>
<mat-icon>grade</mat-icon>
<h2>Input</h2>
<mat-form-field>
<mat-label>Label</mat-label>
<input matInput value="Initial value" />
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Placeholder" />
</mat-form-field>
<mat-form-field floatLabel="always">
<mat-label>Always floating</mat-label>
<input matInput />
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Label</mat-label>
<input matInput />
</mat-form-field>
<mat-form-field>
<mat-label>Label</mat-label>
<textarea matInput></textarea>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Label</mat-label>
<textarea matInput></textarea>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Label</mat-label>
<input matInput value="Initial" />
</mat-form-field>
<h3>Prefix and Suffix</h3>
<mat-form-field appearance="outline">
<span matPrefix>+123 </span>
<mat-label>Phone Number</mat-label>
<input matInput />
</mat-form-field>
<mat-form-field>
<span matPrefix>+123 </span>
<mat-label>Phone Number</mat-label>
<input matInput />
</mat-form-field>
<mat-form-field appearance="outline">
<span matPrefix>+123 </span>
<mat-label>Phone Number</mat-label>
<input matInput />
</mat-form-field>
<mat-form-field appearance="outline">
<mat-icon matPrefix>calendar_today</mat-icon>
<mat-label>Name</mat-label>
<input matInput />
</mat-form-field>
<mat-form-field>
<mat-icon matPrefix>calendar_today</mat-icon>
<mat-label>Name</mat-label>
<input matInput />
</mat-form-field>
<h2>List</h2>
<mat-list>
<mat-list-item>Robot</mat-list-item>
<mat-list-item>Android</mat-list-item>
<mat-list-item>Cyborg</mat-list-item>
</mat-list>
<mat-nav-list>
<a mat-list-item href="https://google.com">Search</a>
<a mat-list-item href="https://google.com">Find</a>
<a mat-list-item href="https://google.com">Seek</a>
</mat-nav-list>
<mat-action-list>
<button mat-list-item>First action</button>
<button mat-list-item>Second action</button>
<button mat-list-item>Third action</button>
</mat-action-list>
<mat-selection-list>
<h3 mat-subheader>Groceries</h3>
<mat-list-option value="apples">Apples</mat-list-option>
<mat-list-option value="bananas">Bananas</mat-list-option>
<mat-list-option value="oranges">Oranges</mat-list-option>
</mat-selection-list>
<h2>Menu</h2>
<button mat-button [matMenuTriggerFor]="menu">Open</button>
<mat-menu #menu="matMenu">
<button mat-menu-item>Mercy</button>
<button mat-menu-item>Lucio</button>
<button mat-menu-item disabled>Sombra</button>
</mat-menu>
<h2>Progress bar</h2>
<mat-progress-bar [value]="25"></mat-progress-bar>
<mat-progress-bar mode="buffer" [value]="25" [bufferValue]="60"></mat-progress-bar>
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
<mat-progress-bar mode="query"></mat-progress-bar>
<h2>Progress spinner</h2>
<mat-progress-spinner [value]="25"></mat-progress-spinner>
<mat-spinner></mat-spinner>
<mat-progress-spinner mode="indeterminate" [diameter]="37"></mat-progress-spinner>
<mat-spinner [strokeWidth]="4"></mat-spinner>
<h2>Radio buttons</h2>
<h3>Radio group</h3> | {
"end_byte": 6801,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/universal-app/kitchen-sink/kitchen-sink.html"
} |
components/src/universal-app/kitchen-sink/kitchen-sink.html_6802_12746 | <mat-radio-group>
<mat-radio-button>Charmander</mat-radio-button>
<mat-radio-button>Squirtle</mat-radio-button>
<mat-radio-button>Bulbasaur</mat-radio-button>
</mat-radio-group>
<h3>Standalone radios</h3>
<mat-radio-button name="onions">White</mat-radio-button>
<mat-radio-button name="onions">Yellow</mat-radio-button>
<mat-radio-button name="onions">Green</mat-radio-button>
<mat-radio-button name="onions" disabled>Red</mat-radio-button>
<h2>Select</h2>
<mat-form-field>
<mat-select value="ceramic">
<mat-option value="glass">Glass</mat-option>
<mat-option value="ceramic">Ceramic</mat-option>
<mat-option value="steel">Steel</mat-option>
</mat-select>
</mat-form-field>
<h2>Sidenav</h2>
<mat-sidenav-container>
<!--
Place the end sidenav first to test the behavior where we manually change the DOM order.
-->
<mat-sidenav #endSidenav position="end" mode="push">
End sidenav
<button (click)="endSidenav.toggle()">Close</button>
</mat-sidenav>
<!--
Only attempt to capture focus when automated, otherwise it makes the page jump around.
-->
<mat-sidenav #startSidenav opened [autoFocus]="isAutomated ? 'first-tabbable' : false">
Start sidenav
<button (click)="startSidenav.toggle()">Button for testing focus trapping</button>
</mat-sidenav>
Main content
<button (click)="startSidenav.toggle()">Toggle start</button>
<button (click)="endSidenav.toggle()">Toggle end</button>
</mat-sidenav-container>
<h2>Slide-toggle</h2>
<mat-slide-toggle></mat-slide-toggle>
<mat-slide-toggle checked></mat-slide-toggle>
<mat-slide-toggle checked disabled></mat-slide-toggle>
<mat-slide-toggle>with a label</mat-slide-toggle>
<h2>Slider</h2>
<mat-slider>
<input matSliderThumb value="60" />
</mat-slider>
<mat-slider>
<input matSliderThumb value="50" disabled />
</mat-slider>
<mat-slider min="200" max="500" step="100" discrete showTickMarks>
<input value="300" matSliderStartThumb />
<input value="400" matSliderEndThumb />
</mat-slider>
<h2>Snack bar</h2>
<button mat-raised-button (click)="openSnackbar()">Open snackbar</button>
<h2>Tabs</h2>
<!--
Note that we set the `selectedIndex` here to hit the code path
where we might need to do some measurements.
-->
<mat-tab-group [selectedIndex]="1">
<mat-tab label="Overview">
<h3>The overview</h3>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Doloremque assumenda doloribus, rerum
temporibus fugit aliquid adipisci aliquam eaque sint voluptas dolore cumque voluptatibus quam
quod. Quasi adipisci officia similique in?
</p>
<p>
Deleniti neque placeat magnam, voluptatibus eligendi illo consectetur dolore minima dolorem
nemo suscipit dolorum accusantium? Numquam officia culpa itaque qui repudiandae nulla,
laboriosam nihil molestiae ad aut perferendis alias amet.
</p>
<p>
Officia esse temporibus consequatur ipsa! Veritatis alias facere amet reiciendis sint impedit
atque iste doloremque dolor? Ullam, aspernatur? Alias, fuga! At dolorum odio molestiae
laudantium nihil alias inventore veritatis voluptatum.
</p>
<button mat-raised-button color="primary">See the overview</button>
</mat-tab>
<mat-tab>
<ng-template mat-tab-label>API docs</ng-template>
<h3>The API docs</h3>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorum facere quasi natus rerum
quae, nisi, quis, voluptate assumenda necessitatibus labore illo. Illum ipsum consequatur,
excepturi aspernatur odio veritatis sint perferendis!
</p>
<p>
Dicta ex laborum repudiandae nesciunt. Ea asperiores quo totam velit! Aliquid cum laudantium
officiis molestias, excepturi odio, autem magni dignissimos perspiciatis, amet qui! Dolorem
molestiae similique necessitatibus cupiditate ipsa aspernatur?
</p>
<button mat-raised-button color="accent">See the API docs</button>
</mat-tab>
<mat-tab>
<ng-template mat-tab-label>Examples</ng-template>
<h3>The examples</h3>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Modi animi saepe, optio sequi
accusantium, eos perspiciatis reprehenderit, nobis exercitationem sunt ducimus molestiae
laborum inventore itaque incidunt. Neque dolorum adipisci quidem.
</p>
<button mat-raised-button color="warn">See the examples</button>
</mat-tab>
</mat-tab-group>
<nav mat-tab-nav-bar [tabPanel]="tabPanel">
<a mat-tab-link href="https://google.com">Google</a>
<a mat-tab-link href="https://google.com" [active]="true">Also Google</a>
</nav>
<mat-tab-nav-panel #tabPanel></mat-tab-nav-panel>
<h2>Paginator</h2>
<mat-paginator [length]="100" [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page">
</mat-paginator>
<h2>Toolbar</h2>
<mat-toolbar>Basic toolbar</mat-toolbar>
<mat-toolbar>
<mat-toolbar-row>Multi row</mat-toolbar-row>
<mat-toolbar-row>Toolbar</mat-toolbar-row>
</mat-toolbar>
<h2>Sort</h2>
<table matSort>
<thead>
<tr>
<th mat-sort-header="name">Name</th>
<th mat-sort-header="calories">Calories</th>
<th mat-sort-header="fat">Fat</th>
<th mat-sort-header="carbs">Carbs</th>
<th mat-sort-header="protein">Protein</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cupcake</td>
<td>305</td>
<td>4</td>
<td>67</td>
<td>4</td>
</tr>
</tbody>
</table>
<h2>Tooltip</h2>
<button matTooltip="Action!">Go</button>
<h2>Autosize textarea</h2>
<textarea cdkTextareaAutosize cdkAutosizeMaxRows="10"></textarea>
<h2>Expansion Panel</h2>
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-panel-description>This is a panel description.</mat-panel-description>
<mat-panel-title>Panel Title</mat-panel-title>
</mat-expansion-panel-header>
This is the content text that makes sense here.
<mat-action-row>Action</mat-action-row>
</mat-expansion-panel>
<h2>CDK Table</h2> | {
"end_byte": 12746,
"start_byte": 6802,
"url": "https://github.com/angular/components/blob/main/src/universal-app/kitchen-sink/kitchen-sink.html"
} |
components/src/universal-app/kitchen-sink/kitchen-sink.html_12748_18082 | <cdk-table class="test-cdk-table" [dataSource]="tableDataSource">
<ng-container cdkColumnDef="position">
<cdk-header-cell *cdkHeaderCellDef>No.</cdk-header-cell>
<cdk-cell *cdkCellDef="let element">{{element.position}}</cdk-cell>
</ng-container>
<ng-container cdkColumnDef="name">
<cdk-header-cell *cdkHeaderCellDef>Name</cdk-header-cell>
<cdk-cell *cdkCellDef="let element">{{element.name}}</cdk-cell>
</ng-container>
<ng-container cdkColumnDef="weight">
<cdk-header-cell *cdkHeaderCellDef>Weight</cdk-header-cell>
<cdk-cell *cdkCellDef="let element">{{element.weight}}</cdk-cell>
</ng-container>
<ng-container cdkColumnDef="symbol">
<cdk-header-cell *cdkHeaderCellDef>Symbol</cdk-header-cell>
<cdk-cell *cdkCellDef="let element">{{element.symbol}}</cdk-cell>
</ng-container>
<cdk-header-row *cdkHeaderRowDef="tableColumns" />
<cdk-row *cdkRowDef="let row; columns: tableColumns;" />
</cdk-table>
<h2>Material Table</h2>
<mat-table [dataSource]="tableDataSource">
<ng-container matColumnDef="position">
<mat-header-cell *matHeaderCellDef>No.</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.position}}</mat-cell>
</ng-container>
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.name}}</mat-cell>
</ng-container>
<ng-container matColumnDef="weight">
<mat-header-cell *matHeaderCellDef>Weight</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.weight}}</mat-cell>
</ng-container>
<ng-container matColumnDef="symbol">
<mat-header-cell *matHeaderCellDef>Symbol</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.symbol}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="tableColumns" />
<mat-row *matRowDef="let row; columns: tableColumns;" />
</mat-table>
<h2>Native table with sticky header and footer</h2>
<table mat-table [dataSource]="tableDataSource">
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef>No.</th>
<td mat-cell *matCellDef="let element">{{element.position}}</td>
<th mat-footer-cell *matFooterCellDef>No.</th>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef>Name</th>
<td mat-cell *matCellDef="let element">{{element.name}}</td>
<th mat-footer-cell *matFooterCellDef>Name</th>
</ng-container>
<ng-container matColumnDef="weight">
<th mat-header-cell *matHeaderCellDef>Weight</th>
<td mat-cell *matCellDef="let element">{{element.weight}}</td>
<th mat-footer-cell *matFooterCellDef>Weight</th>
</ng-container>
<ng-container matColumnDef="symbol">
<th mat-header-cell *matHeaderCellDef>Symbol</th>
<td mat-cell *matCellDef="let element">{{element.symbol}}</td>
<th mat-footer-cell *matFooterCellDef>Symbol</th>
</ng-container>
<tr mat-header-row *matHeaderRowDef="tableColumns; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: tableColumns;"></tr>
<tr mat-footer-row *matFooterRowDef="tableColumns; sticky: true"></tr>
</table>
<h2>CDK Listbox</h2>
<div class="test-cdk-listbox">
<label>Favorite color</label>
<ul cdkListbox>
<li cdkOption="red">Red</li>
<li cdkOption="green">Green</li>
<li cdkOption="blue">Blue</li>
</ul>
</div>
<h2>Selection list</h2>
<mat-selection-list>
<h3 mat-subheader>Groceries</h3>
<mat-list-option value="apples">Apples</mat-list-option>
<mat-list-option value="bananas">Bananas</mat-list-option>
<mat-list-option value="oranges">Oranges</mat-list-option>
</mat-selection-list>
<h2>Vertical Stepper</h2>
<mat-stepper orientation="vertical">
<mat-step label="Step 1">Content 1</mat-step>
<mat-step label="Step 1">Content 2</mat-step>
</mat-stepper>
<h2>Vertical Stepper (with label template)</h2>
<mat-stepper orientation="vertical">
<mat-step>
<ng-template matStepLabel>NgTemplate Label #1</ng-template>
Content 1
</mat-step>
<mat-step>
<ng-template matStepLabel>NgTemplate Label #2</ng-template>
Content 2
</mat-step>
</mat-stepper>
<h2>Horizontal Stepper</h2>
<mat-stepper>
<mat-step label="Step 1">Content 1</mat-step>
<mat-step label="Step 2">Content 2</mat-step>
</mat-stepper>
<h2>Focus trap</h2>
<div cdkTrapFocus [cdkTrapFocusAutoCapture]="isAutomated">
<button>Oh no, I'm trapped!</button>
</div>
<h2>Badge</h2>
<button mat-raised-button matBadge="99">Clicky thing</button>
<h2>Drag and Drop</h2>
<button cdkDrag>Drag me around</button>
<ul cdkDropList>
<li cdkDrag>One</li>
<li cdkDrag>Two</li>
</ul>
<h2>Virtual scroll</h2>
<cdk-virtual-scroll-viewport itemSize="50" class="universal-viewport">
<div *cdkVirtualFor="let size of virtualScrollData; let i = index" style="height: 50px;">
Item #{{i}}
</div>
</cdk-virtual-scroll-viewport>
<cdk-virtual-scroll-viewport autosize class="universal-viewport">
<div
*cdkVirtualFor="let size of virtualScrollData; let i = index"
[style.height.px]="i % 2 == 0 ? 50 : 25"
>
Item #{{i}}
</div>
</cdk-virtual-scroll-viewport>
<h2>YouTube player</h2>
<youtube-player videoId="dQw4w9WgXcQ"></youtube-player>
<h2>Google Map</h2>
<!-- position: relative prevents the "Map failed to load" element from leaving the container --> | {
"end_byte": 18082,
"start_byte": 12748,
"url": "https://github.com/angular/components/blob/main/src/universal-app/kitchen-sink/kitchen-sink.html"
} |
components/src/universal-app/kitchen-sink/kitchen-sink.html_18083_20226 | <google-map height="400px" width="750px" mapId="123" style="position: relative">
<map-marker [position]="{lat: 24, lng: 12}"></map-marker>
<map-advanced-marker [position]="{lat: 12, lng: 12}"></map-advanced-marker>
<map-info-window>Hello</map-info-window>
<map-polyline
[options]="{
path: [{lat: 25, lng: 26}, {lat: 26, lng: 27}, {lat: 30, lng: 34}],
strokeColor: 'grey',
strokeOpacity: 0.8
}"
></map-polyline>
<map-polygon
[options]="{
paths: [{lat: 20, lng: 21}, {lat: 22, lng: 23}, {lat: 24, lng: 25}],
strokeColor: 'grey',
strokeOpacity: 0.8
}"
></map-polygon>
<map-rectangle
[options]="{
bounds: {east: 30, north: 15, west: 10, south: -5},
strokeColor: 'grey',
strokeOpacity: 0.8
}"
></map-rectangle>
<map-circle
[options]="{
center: {lat: 19, lng: 20},
radius: 500000,
strokeColor: 'grey',
strokeOpacity: 0.8
}"
></map-circle>
<map-ground-overlay
url="https://angular.io/assets/images/logos/angular/angular.svg"
[bounds]="{
east: 30,
north: 15,
west: 10,
south: -5
}"
></map-ground-overlay>
<map-kml-layer
url="https://developers.google.com/maps/documentation/javascript/examples/kml/westcampus.kml"
></map-kml-layer>
<map-traffic-layer></map-traffic-layer>
<map-transit-layer></map-transit-layer>
<map-bicycling-layer></map-bicycling-layer>
<map-heatmap-layer
[data]="[
{lat: 37.782, lng: -122.447},
{lat: 37.782, lng: -122.445},
{lat: 37.782, lng: -122.443}
]"
></map-heatmap-layer>
<deprecated-map-marker-clusterer
imagePath="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m"
>
<map-marker [position]="{lat: 24, lng: 12}"></map-marker>
<map-marker [position]="{lat: 12, lng: 24}"></map-marker>
<map-marker [position]="{lat: 12, lng: 12}"></map-marker>
</deprecated-map-marker-clusterer>
</google-map>
<h2>Popover edit</h2>
<cdk-popover-edit-cdk-table-example></cdk-popover-edit-cdk-table-example>
<!-- Element used to determine when rendering is done. -->
<div class="render-marker"></div> | {
"end_byte": 20226,
"start_byte": 18083,
"url": "https://github.com/angular/components/blob/main/src/universal-app/kitchen-sink/kitchen-sink.html"
} |
components/src/material/_index.scss_0_8315 | // Expose the M2 APIs under an `m2-` prefix in order to distinguish them from the M3 APIs.
@forward './core/m2' as m2-*;
// New theming APIs
@forward './core/theming/inspection' show get-theme-version, get-theme-type, get-theme-color,
get-theme-typography, get-theme-density, theme-has, theme-remove;
@forward './core/theming/definition' show define-theme, define-colors, define-typography,
define-density;
@forward './core/theming/palettes' show $red-palette, $green-palette, $blue-palette,
$yellow-palette, $cyan-palette, $magenta-palette, $orange-palette,
$chartreuse-palette, $spring-green-palette, $azure-palette, $violet-palette, $rose-palette;
@forward './core/theming/color-api-backwards-compatibility' show
color-variants-backwards-compatibility;
@forward './core/theming/theming' show $theme-ignore-duplication-warnings,
$theme-legacy-inspection-api-compatibility;
@forward './core/theming/theming' as private-* show private-clamp-density;
@forward './core/typography/typography' show typography-hierarchy;
@forward './core/typography/typography-utils' show font-shorthand;
@forward './core/tokens/m2' show m2-tokens-from-theme;
@forward './core/tokens/m3-system' show system-level-colors,
system-level-typography, system-level-elevation, system-level-shape,
system-level-motion, system-level-state, theme, theme-overrides;
// Private/Internal
@forward './core/density/private/all-density' show all-component-densities;
@forward './core/theming/theming' show private-check-duplicate-theme-styles,
private-legacy-get-theme, private-is-theme-object;
@forward './core/style/private' show private-theme-elevation;
@forward './core/style/vendor-prefixes' as private-* show private-user-select;
@forward './core/style/variables' as private-* show $private-swift-ease-in-duration,
$private-swift-ease-in-timing-function, $private-swift-ease-out-timing-function,
$private-ease-in-out-curve-function, $private-swift-ease-out-duration, $private-xsmall;
@forward './core/style/sass-utils' as private-*;
@forward './core/style/validation' as private-*;
// Structural
@forward './core/core' show core, app-background, elevation-classes;
@forward './core/ripple/ripple' show ripple;
@forward './core/focus-indicators/private' show strong-focus-indicators,
strong-focus-indicators-color, strong-focus-indicators-theme;
@forward './core/style/elevation' show elevation, overridable-elevation, elevation-transition;
// Theme bundles
@forward './core/theming/all-theme' show all-component-themes, all-component-bases;
@forward './core/color/all-color' show all-component-colors;
@forward './core/typography/all-typography' show all-component-typographies;
// Component themes
@forward './core/core-theme' as core-* show core-color, core-theme, core-typography, core-density,
core-base, core-overrides;
@forward './core/ripple/ripple-theme' as ripple-* show ripple-color, ripple-theme, ripple-base,
ripple-overrides;
@forward './core/option/option-theme' as option-* show option-color, option-typography,
option-theme, option-density, option-base, option-overrides;
@forward './core/option/optgroup-theme' as optgroup-* show optgroup-color, optgroup-typography,
optgroup-theme, optgroup-density, optgroup-base, optgroup-overrides;
@forward './core/selection/pseudo-checkbox/pseudo-checkbox-theme' as pseudo-checkbox-* show
pseudo-checkbox-color, pseudo-checkbox-typography, pseudo-checkbox-theme, pseudo-checkbox-density,
pseudo-checkbox-base, pseudo-checkbox-overrides;
@forward './core/selection/pseudo-checkbox/pseudo-checkbox-common' as pseudo-checkbox-* show
pseudo-checkbox-legacy-size;
@forward './autocomplete/autocomplete-theme' as autocomplete-* show autocomplete-theme,
autocomplete-color, autocomplete-typography, autocomplete-density, autocomplete-base,
autocomplete-overrides;
@forward './badge/badge-theme' as badge-* show badge-theme, badge-color, badge-typography,
badge-density, badge-base, badge-overrides;
@forward './bottom-sheet/bottom-sheet-theme' as bottom-sheet-* show bottom-sheet-theme,
bottom-sheet-color, bottom-sheet-typography, bottom-sheet-density, bottom-sheet-base,
bottom-sheet-overrides;
@forward './button/button-theme' as button-* show button-theme, button-color, button-typography,
button-density, button-base, button-overrides;
@forward './button/fab-theme' as fab-* show fab-color, fab-typography,
fab-density, fab-theme, fab-base, fab-overrides;
@forward './button/icon-button-theme' as icon-button-* show icon-button-color,
icon-button-typography, icon-button-density, icon-button-theme, icon-button-base,
icon-button-overrides;
@forward './button-toggle/button-toggle-theme' as button-toggle-* show button-toggle-theme,
button-toggle-color, button-toggle-typography, button-toggle-density, button-toggle-base,
button-toggle-overrides;
@forward './card/card-theme' as card-* show card-theme, card-color, card-typography, card-density,
card-base, card-overrides;
@forward './checkbox/checkbox-theme' as checkbox-* show checkbox-theme, checkbox-color,
checkbox-typography, checkbox-density, checkbox-base, checkbox-overrides;
@forward './chips/chips-theme' as chips-* show chips-theme, chips-color, chips-typography,
chips-density, chips-base, chips-overrides;
@forward './datepicker/datepicker-theme' as datepicker-* show datepicker-theme, datepicker-color,
datepicker-typography, datepicker-date-range-colors, datepicker-density, datepicker-base,
datepicker-overrides;
@forward './dialog/dialog-theme' as dialog-* show dialog-theme, dialog-color, dialog-typography,
dialog-density, dialog-base, dialog-overrides;
@forward './dialog/dialog-legacy-padding' as dialog-* show dialog-legacy-padding;
@forward './divider/divider-theme' as divider-* show divider-theme, divider-color,
divider-typography, divider-density, divider-base, divider-overrides;
@forward './expansion/expansion-theme' as expansion-* show expansion-theme, expansion-color,
expansion-typography, expansion-density, expansion-base, expansion-overrides;
@forward './form-field/form-field-theme' as form-field-* show form-field-theme,
form-field-color, form-field-typography, form-field-density, form-field-base,
form-field-overrides;
@forward './grid-list/grid-list-theme' as grid-list-* show grid-list-theme, grid-list-color,
grid-list-typography, grid-list-density, grid-list-base, grid-list-overrides;
@forward './icon/icon-theme' as icon-* show icon-theme, icon-color, icon-typography, icon-density,
icon-base, icon-overrides;
@forward './input/input-theme' as input-* show input-theme, input-color, input-typography,
input-density, input-base, input-overrides;
@forward './list/list-theme' as list-* show list-theme, list-color, list-typography,
list-density, list-base, list-overrides;
@forward './menu/menu-theme' as menu-* show menu-theme, menu-color, menu-typography, menu-density,
menu-base, menu-overrides;
@forward './paginator/paginator-theme' as paginator-* show paginator-theme, paginator-color,
paginator-typography, paginator-density, paginator-base, paginator-overrides;
@forward './progress-bar/progress-bar-theme' as progress-bar-* show
progress-bar-theme, progress-bar-color, progress-bar-typography,
progress-bar-density, progress-bar-base, progress-bar-overrides;
@forward './progress-spinner/progress-spinner-theme' as progress-spinner-* show
progress-spinner-theme, progress-spinner-color, progress-spinner-typography,
progress-spinner-density, progress-spinner-base, progress-spinner-overrides;
@forward './radio/radio-theme' as radio-* show radio-theme, radio-color, radio-typography,
radio-density, radio-base, radio-overrides;
@forward './select/select-theme' as select-* show select-theme, select-color, select-typography,
select-density, select-base, select-overrides;
@forward './sidenav/sidenav-theme' as sidenav-* show sidenav-theme, sidenav-color,
sidenav-typography, sidenav-density, sidenav-base, sidenav-overrides;
@forward './slide-toggle/slide-toggle-theme' as slide-toggle-* show
slide-toggle-theme, slide-toggle-color, slide-toggle-typography, slide-toggle-density,
slide-toggle-base, slide-toggle-overrides;
@forward './slider/slider-theme' as slider-* show slider-theme, slider-color, slider-typography,
slider-density, slider-base, slider-overrides; | {
"end_byte": 8315,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/_index.scss"
} |
components/src/material/_index.scss_8316_9656 | @forward './snack-bar/snack-bar-theme' as snack-bar-* show snack-bar-theme, snack-bar-color,
snack-bar-typography, snack-bar-density, snack-bar-base, snack-bar-overrides;
@forward './sort/sort-theme' as sort-* show sort-theme, sort-color, sort-typography, sort-density,
sort-base, sort-overrides;
@forward './stepper/stepper-theme' as stepper-* show stepper-theme, stepper-color,
stepper-typography, stepper-density, stepper-base, stepper-overrides;
@forward './table/table-theme' as table-* show table-theme, table-color, table-typography,
table-density, table-base, table-overrides;
@forward './tabs/tabs-theme' as tabs-* show tabs-theme, tabs-color, tabs-typography, tabs-density,
tabs-base, tabs-overrides;
@forward './toolbar/toolbar-theme' as toolbar-* show toolbar-theme, toolbar-color,
toolbar-typography, toolbar-density, toolbar-base, toolbar-overrides;
@forward './tooltip/tooltip-theme' as tooltip-* show tooltip-theme, tooltip-color,
tooltip-typography, tooltip-density, tooltip-base, tooltip-overrides;
@forward './tree/tree-theme' as tree-* show tree-theme, tree-color, tree-typography, tree-density,
tree-base, tree-overrides;
@forward './timepicker/timepicker-theme' as timepicker-* show timepicker-theme, timepicker-color,
timepicker-typography, timepicker-density, timepicker-base, timepicker-overrides; | {
"end_byte": 9656,
"start_byte": 8316,
"url": "https://github.com/angular/components/blob/main/src/material/_index.scss"
} |
components/src/material/config.bzl_0_2447 | entryPoints = [
"autocomplete",
"autocomplete/testing",
"badge",
"badge/testing",
"bottom-sheet",
"bottom-sheet/testing",
"button",
"button/testing",
"button-toggle",
"button-toggle/testing",
"card",
"card/testing",
"checkbox",
"checkbox/testing",
"chips",
"chips/testing",
"core",
"core/testing",
"datepicker",
"datepicker/testing",
"dialog",
"dialog/testing",
"divider",
"divider/testing",
"expansion",
"expansion/testing",
"form-field",
"form-field/testing",
"form-field/testing/control",
"grid-list",
"grid-list/testing",
"icon",
"icon/testing",
"input",
"input/testing",
"list",
"list/testing",
"menu",
"menu/testing",
"paginator",
"paginator/testing",
"progress-bar",
"progress-bar/testing",
"progress-spinner",
"progress-spinner/testing",
"radio",
"radio/testing",
"select",
"select/testing",
"sidenav",
"sidenav/testing",
"slide-toggle",
"slide-toggle/testing",
"slider",
"slider/testing",
"snack-bar",
"snack-bar/testing",
"sort",
"sort/testing",
"stepper",
"stepper/testing",
"table",
"table/testing",
"tabs",
"tabs/testing",
"timepicker",
"timepicker/testing",
"toolbar",
"toolbar/testing",
"tooltip",
"tooltip/testing",
"tree",
"tree/testing",
]
# List of all non-testing entry-points of the Angular Material package.
MATERIAL_ENTRYPOINTS = [
ep
for ep in entryPoints
if not "/testing" in ep
]
# List of all testing entry-points of the Angular Material package.
MATERIAL_TESTING_ENTRYPOINTS = [
ep
for ep in entryPoints
if not ep in MATERIAL_ENTRYPOINTS
]
# List of all non-testing entry-point targets of the Angular Material package.
MATERIAL_TARGETS = ["//src/material"] + \
["//src/material/%s" % ep for ep in MATERIAL_ENTRYPOINTS]
# List of all testing entry-point targets of the Angular Material package.
MATERIAL_TESTING_TARGETS = ["//src/material/%s" % ep for ep in MATERIAL_TESTING_ENTRYPOINTS]
# List that references the sass libraries for each Material non-testing entry-point. This
# can be used to specify dependencies for the "all-theme.scss" file in core.
MATERIAL_SCSS_LIBS = [
"//src/material/%s:%s_scss_lib" % (ep, ep.replace("-", "_"))
for ep in MATERIAL_ENTRYPOINTS
]
| {
"end_byte": 2447,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/config.bzl"
} |
components/src/material/BUILD.bazel_0_1600 | load(
"//src/material:config.bzl",
"MATERIAL_ENTRYPOINTS",
"MATERIAL_SCSS_LIBS",
"MATERIAL_TARGETS",
"MATERIAL_TESTING_TARGETS",
)
load("//tools:defaults.bzl", "ng_package", "sass_library", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "material",
srcs = ["index.ts"],
)
filegroup(
name = "overviews",
srcs = ["//src/material/%s:overview" % name for name in MATERIAL_ENTRYPOINTS],
)
filegroup(
name = "tokens",
srcs = ["//src/material/%s:tokens" % name for name in MATERIAL_ENTRYPOINTS],
)
sass_library(
name = "sass_lib",
srcs = [
"_index.scss",
],
deps = [
"//src/material/core:core_scss_lib",
"//src/material/core:theming_scss_lib",
],
)
# Creates the @angular/material package published to npm.
ng_package(
name = "npm_package",
srcs = [
"package.json",
":sass_lib",
"//src/material/core:theming_scss_lib",
"//src/material/prebuilt-themes:azure-blue",
"//src/material/prebuilt-themes:cyan-orange",
"//src/material/prebuilt-themes:deeppurple-amber",
"//src/material/prebuilt-themes:indigo-pink",
"//src/material/prebuilt-themes:magenta-violet",
"//src/material/prebuilt-themes:pink-bluegrey",
"//src/material/prebuilt-themes:purple-green",
"//src/material/prebuilt-themes:rose-red",
] + MATERIAL_SCSS_LIBS,
nested_packages = ["//src/material/schematics:npm_package"],
tags = ["release-package"],
deps = MATERIAL_TARGETS + MATERIAL_TESTING_TARGETS,
)
| {
"end_byte": 1600,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/BUILD.bazel"
} |
components/src/material/index.ts_0_638 | /**
* @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
*/
// primary entry-point which is empty as of version 9. All components should
// be imported through their individual entry-points. This file is needed to
// satisfy the "ng_package" bazel rule which also requires a primary entry-point.
// Workaround for: https://github.com/microsoft/rushstack/issues/2806.
// This is a private export that can be removed at any time.
export const ɵɵtsModuleIndicatorApiExtractorWorkaround = true;
| {
"end_byte": 638,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/index.ts"
} |
components/src/material/tabs/tab-group.spec.ts_0_1337 | import {LEFT_ARROW, RIGHT_ARROW} from '@angular/cdk/keycodes';
import {dispatchFakeEvent, dispatchKeyboardEvent} from '@angular/cdk/testing/private';
import {AsyncPipe} from '@angular/common';
import {Component, DebugElement, OnInit, QueryList, ViewChild, ViewChildren} from '@angular/core';
import {
ComponentFixture,
TestBed,
fakeAsync,
flush,
tick,
waitForAsync,
} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {BrowserAnimationsModule, NoopAnimationsModule} from '@angular/platform-browser/animations';
import {Observable} from 'rxjs';
import {
MAT_TABS_CONFIG,
MatTab,
MatTabGroup,
MatTabHeader,
MatTabHeaderPosition,
MatTabsModule,
} from './index';
describe('MatTabGroup', () => {
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [
MatTabsModule,
NoopAnimationsModule,
SimpleTabsTestApp,
SimpleDynamicTabsTestApp,
BindedTabsTestApp,
AsyncTabsTestApp,
DisabledTabsTestApp,
TabGroupWithSimpleApi,
TemplateTabs,
TabGroupWithAriaInputs,
TabGroupWithIsActiveBinding,
NestedTabs,
TabGroupWithIndirectDescendantTabs,
TabGroupWithSpaceAbove,
NestedTabGroupWithLabel,
TabsWithClassesTestApp,
],
});
})); | {
"end_byte": 1337,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-group.spec.ts"
} |
components/src/material/tabs/tab-group.spec.ts_1341_10723 | describe('basic behavior', () => {
let fixture: ComponentFixture<SimpleTabsTestApp>;
let element: HTMLElement;
beforeEach(() => {
fixture = TestBed.createComponent(SimpleTabsTestApp);
element = fixture.nativeElement;
});
it('should default to the first tab', () => {
checkSelectedIndex(1, fixture);
});
it('will properly load content on first change detection pass', () => {
fixture.detectChanges();
const tabBodies = element.querySelectorAll('.mat-mdc-tab-body');
expect(tabBodies[1].querySelectorAll('span').length).toBe(3);
});
it('should change selected index on click', () => {
let component = fixture.debugElement.componentInstance;
component.selectedIndex = 0;
checkSelectedIndex(0, fixture);
// select the second tab
let tabLabel = fixture.debugElement.queryAll(By.css('.mat-mdc-tab'))[1];
tabLabel.nativeElement.click();
checkSelectedIndex(1, fixture);
// select the third tab
tabLabel = fixture.debugElement.queryAll(By.css('.mat-mdc-tab'))[2];
tabLabel.nativeElement.click();
checkSelectedIndex(2, fixture);
});
it('should support two-way binding for selectedIndex', fakeAsync(() => {
let component = fixture.componentInstance;
component.selectedIndex = 0;
fixture.detectChanges();
let tabLabel = fixture.debugElement.queryAll(By.css('.mat-mdc-tab'))[1];
tabLabel.nativeElement.click();
fixture.detectChanges();
tick();
expect(component.selectedIndex).toBe(1);
}));
// Note: needs to be `async` in order to fail when we expect it to.
it('should set to correct tab on fast change', waitForAsync(() => {
let component = fixture.componentInstance;
component.selectedIndex = 0;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
setTimeout(() => {
component.selectedIndex = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
setTimeout(() => {
component.selectedIndex = 0;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(component.selectedIndex).toBe(0);
});
}, 1);
}, 1);
}));
it('should change tabs based on selectedIndex', fakeAsync(() => {
let component = fixture.componentInstance;
let tabComponent = fixture.debugElement.query(By.css('mat-tab-group')).componentInstance;
spyOn(component, 'handleSelection').and.callThrough();
checkSelectedIndex(1, fixture);
tabComponent.selectedIndex = 2;
fixture.changeDetectorRef.markForCheck();
checkSelectedIndex(2, fixture);
tick();
expect(component.handleSelection).toHaveBeenCalledTimes(1);
expect(component.selectEvent.index).toBe(2);
}));
it('should update tab positions when selected index is changed', () => {
fixture.detectChanges();
const component: MatTabGroup = fixture.debugElement.query(
By.css('mat-tab-group'),
).componentInstance;
const tabs: MatTab[] = component._tabs.toArray();
expect(tabs[0].position).toBeLessThan(0);
expect(tabs[1].position).toBe(0);
expect(tabs[2].position).toBeGreaterThan(0);
// Move to third tab
component.selectedIndex = 2;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tabs[0].position).toBeLessThan(0);
expect(tabs[1].position).toBeLessThan(0);
expect(tabs[2].position).toBe(0);
// Move to the first tab
component.selectedIndex = 0;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tabs[0].position).toBe(0);
expect(tabs[1].position).toBeGreaterThan(0);
expect(tabs[2].position).toBeGreaterThan(0);
});
it('should clamp the selected index to the size of the number of tabs', () => {
fixture.detectChanges();
const component: MatTabGroup = fixture.debugElement.query(
By.css('mat-tab-group'),
).componentInstance;
// Set the index to be negative, expect first tab selected
fixture.componentInstance.selectedIndex = -1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(component.selectedIndex).toBe(0);
// Set the index beyond the size of the tabs, expect last tab selected
fixture.componentInstance.selectedIndex = 3;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(component.selectedIndex).toBe(2);
});
it('should not crash when setting the selected index to NaN', () => {
let component = fixture.debugElement.componentInstance;
expect(() => {
component.selectedIndex = NaN;
fixture.detectChanges();
}).not.toThrow();
});
it('should show ripples for tab-group labels', () => {
fixture.detectChanges();
const testElement = fixture.nativeElement;
const tabLabel = fixture.debugElement.queryAll(By.css('.mat-mdc-tab'))[1];
expect(testElement.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected no ripples to show up initially.')
.toBe(0);
dispatchFakeEvent(tabLabel.nativeElement, 'mousedown');
expect(testElement.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected one ripple to show up on label mousedown.')
.toBe(1);
});
it('should allow disabling ripples for tab-group labels', () => {
fixture.componentInstance.disableRipple = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const testElement = fixture.nativeElement;
const tabLabel = fixture.debugElement.queryAll(By.css('.mat-mdc-tab'))[1];
expect(testElement.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected no ripples to show up initially.')
.toBe(0);
dispatchFakeEvent(tabLabel.nativeElement, 'mousedown');
dispatchFakeEvent(tabLabel.nativeElement, 'mouseup');
expect(testElement.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected no ripple to show up on label mousedown.')
.toBe(0);
});
it('should set the isActive flag on each of the tabs', fakeAsync(() => {
fixture.detectChanges();
tick();
const tabs = fixture.componentInstance.tabs.toArray();
expect(tabs[0].isActive).toBe(false);
expect(tabs[1].isActive).toBe(true);
expect(tabs[2].isActive).toBe(false);
fixture.componentInstance.selectedIndex = 2;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(tabs[0].isActive).toBe(false);
expect(tabs[1].isActive).toBe(false);
expect(tabs[2].isActive).toBe(true);
}));
it('should fire animation done event', fakeAsync(() => {
fixture.detectChanges();
spyOn(fixture.componentInstance, 'animationDone');
let tabLabel = fixture.debugElement.queryAll(By.css('.mat-mdc-tab'))[1];
tabLabel.nativeElement.click();
fixture.detectChanges();
tick();
expect(fixture.componentInstance.animationDone).toHaveBeenCalledTimes(1);
}));
it('should add the proper `aria-setsize` and `aria-posinset`', () => {
fixture.detectChanges();
const labels = Array.from(element.querySelectorAll('.mat-mdc-tab'));
expect(labels.map(label => label.getAttribute('aria-posinset'))).toEqual(['1', '2', '3']);
expect(labels.every(label => label.getAttribute('aria-setsize') === '3')).toBe(true);
});
it('should emit focusChange event on click', () => {
spyOn(fixture.componentInstance, 'handleFocus');
fixture.detectChanges();
const tabLabels = fixture.debugElement.queryAll(By.css('.mat-mdc-tab'));
expect(fixture.componentInstance.handleFocus).toHaveBeenCalledTimes(0);
tabLabels[2].nativeElement.click();
fixture.detectChanges();
expect(fixture.componentInstance.handleFocus).toHaveBeenCalledTimes(1);
expect(fixture.componentInstance.handleFocus).toHaveBeenCalledWith(
jasmine.objectContaining({index: 2}),
);
});
it('should emit focusChange on arrow key navigation', () => {
spyOn(fixture.componentInstance, 'handleFocus');
fixture.detectChanges();
const tabLabels = fixture.debugElement.queryAll(By.css('.mat-mdc-tab'));
const tabLabelContainer = fixture.debugElement.query(By.css('.mat-mdc-tab-label-container'))
.nativeElement as HTMLElement;
expect(fixture.componentInstance.handleFocus).toHaveBeenCalledTimes(0);
// In order to verify that the `focusChange` event also fires with the correct
// index, we focus the third tab before testing the keyboard navigation.
tabLabels[2].nativeElement.click();
fixture.detectChanges();
expect(fixture.componentInstance.handleFocus).toHaveBeenCalledTimes(1);
dispatchKeyboardEvent(tabLabelContainer, 'keydown', LEFT_ARROW);
expect(fixture.componentInstance.handleFocus).toHaveBeenCalledTimes(2);
expect(fixture.componentInstance.handleFocus).toHaveBeenCalledWith(
jasmine.objectContaining({index: 1}),
);
}); | {
"end_byte": 10723,
"start_byte": 1341,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-group.spec.ts"
} |
components/src/material/tabs/tab-group.spec.ts_10729_19277 | it('should clean up the tabs QueryList on destroy', () => {
const component: MatTabGroup = fixture.debugElement.query(
By.css('mat-tab-group'),
)!.componentInstance;
const spy = jasmine.createSpy('complete spy');
const subscription = component._tabs.changes.subscribe({complete: spy});
fixture.destroy();
expect(spy).toHaveBeenCalled();
subscription.unsubscribe();
});
it('should have a focus indicator', () => {
const tabLabelNativeElements = [
...fixture.debugElement.nativeElement.querySelectorAll('.mat-mdc-tab'),
];
expect(tabLabelNativeElements.every(el => el.classList.contains('mat-focus-indicator'))).toBe(
true,
);
});
it('should emit focusChange when a tab receives focus', fakeAsync(() => {
spyOn(fixture.componentInstance, 'handleFocus');
fixture.detectChanges();
const tabLabels = fixture.debugElement.queryAll(By.css('.mat-mdc-tab'));
expect(fixture.componentInstance.handleFocus).toHaveBeenCalledTimes(0);
// In order to verify that the `focusChange` event also fires with the correct
// index, we focus the second tab before testing the keyboard navigation.
dispatchFakeEvent(tabLabels[2].nativeElement, 'focus');
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(fixture.componentInstance.handleFocus).toHaveBeenCalledTimes(1);
expect(fixture.componentInstance.handleFocus).toHaveBeenCalledWith(
jasmine.objectContaining({index: 2}),
);
}));
it('should be able to programmatically focus a particular tab', () => {
fixture.detectChanges();
const tabGroup: MatTabGroup = fixture.debugElement.query(
By.css('mat-tab-group'),
).componentInstance;
const tabHeader: MatTabHeader = fixture.debugElement.query(
By.css('mat-tab-header'),
).componentInstance;
expect(tabHeader.focusIndex).not.toBe(3);
tabGroup.focusTab(3);
fixture.detectChanges();
expect(tabHeader.focusIndex).not.toBe(3);
});
it('should be able to set a tabindex on the inner content element', () => {
fixture.componentInstance.contentTabIndex = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const contentElements = Array.from<HTMLElement>(
fixture.nativeElement.querySelectorAll('mat-tab-body'),
);
expect(contentElements.map(e => e.getAttribute('tabindex'))).toEqual([null, '1', null]);
fixture.componentInstance.selectedIndex = 0;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(contentElements.map(e => e.getAttribute('tabindex'))).toEqual(['1', null, null]);
});
it('should update the tabindex of the labels when navigating via keyboard', () => {
fixture.detectChanges();
const tabLabels = fixture.debugElement
.queryAll(By.css('.mat-mdc-tab'))
.map(label => label.nativeElement);
const tabLabelContainer = fixture.debugElement.query(By.css('.mat-mdc-tab-label-container'))
.nativeElement as HTMLElement;
expect(tabLabels.map(label => label.getAttribute('tabindex'))).toEqual(['-1', '0', '-1']);
dispatchKeyboardEvent(tabLabelContainer, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(tabLabels.map(label => label.getAttribute('tabindex'))).toEqual(['-1', '-1', '0']);
});
it('should be able to set the aria-label of the tablist', fakeAsync(() => {
fixture.detectChanges();
tick();
const tabList = fixture.nativeElement.querySelector('.mat-mdc-tab-list') as HTMLElement;
expect(tabList.hasAttribute('aria-label')).toBe(false);
fixture.componentInstance.ariaLabel = 'hello';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tabList.getAttribute('aria-label')).toBe('hello');
fixture.componentInstance.ariaLabel = '';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tabList.hasAttribute('aria-label')).toBe(false);
}));
it('should be able to set the aria-labelledby of the tablist', fakeAsync(() => {
fixture.detectChanges();
tick();
const tabList = fixture.nativeElement.querySelector('.mat-mdc-tab-list') as HTMLElement;
expect(tabList.hasAttribute('aria-labelledby')).toBe(false);
fixture.componentInstance.ariaLabelledby = 'some-label';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tabList.getAttribute('aria-labelledby')).toBe('some-label');
fixture.componentInstance.ariaLabelledby = '';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tabList.hasAttribute('aria-labelledby')).toBe(false);
}));
});
describe('aria labelling', () => {
let fixture: ComponentFixture<TabGroupWithAriaInputs>;
let tab: HTMLElement;
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(TabGroupWithAriaInputs);
fixture.detectChanges();
tick();
tab = fixture.nativeElement.querySelector('.mat-mdc-tab');
}));
it('should not set aria-label or aria-labelledby attributes if they are not passed in', () => {
expect(tab.hasAttribute('aria-label')).toBe(false);
expect(tab.hasAttribute('aria-labelledby')).toBe(false);
});
it('should set the aria-label attribute', () => {
fixture.componentInstance.ariaLabel = 'Fruit';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tab.getAttribute('aria-label')).toBe('Fruit');
});
it('should set the aria-labelledby attribute', () => {
fixture.componentInstance.ariaLabelledby = 'fruit-label';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tab.getAttribute('aria-labelledby')).toBe('fruit-label');
});
it('should not be able to set both an aria-label and aria-labelledby', () => {
fixture.componentInstance.ariaLabel = 'Fruit';
fixture.componentInstance.ariaLabelledby = 'fruit-label';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tab.getAttribute('aria-label')).toBe('Fruit');
expect(tab.hasAttribute('aria-labelledby')).toBe(false);
fixture.componentInstance.ariaLabel = 'Veggie';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tab.getAttribute('aria-label')).toBe('Veggie');
});
});
describe('aria labelling of tab panels', () => {
let fixture: ComponentFixture<BindedTabsTestApp>;
let tabPanels: HTMLElement[];
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(BindedTabsTestApp);
fixture.detectChanges();
tick();
tabPanels = Array.from(fixture.nativeElement.querySelectorAll('.mat-mdc-tab-body'));
}));
it('should set `aria-hidden="true"` on inactive tab panels', () => {
fixture.detectChanges();
expect(tabPanels[0].getAttribute('aria-hidden')).not.toBe('true');
expect(tabPanels[1].getAttribute('aria-hidden')).toBe('true');
});
});
describe('disable tabs', () => {
let fixture: ComponentFixture<DisabledTabsTestApp>;
beforeEach(() => {
fixture = TestBed.createComponent(DisabledTabsTestApp);
});
it('should have one disabled tab', () => {
fixture.detectChanges();
const labels = fixture.debugElement.queryAll(By.css('.mat-mdc-tab-disabled'));
expect(labels.length).toBe(1);
expect(labels[0].nativeElement.getAttribute('aria-disabled')).toBe('true');
});
it('should set the disabled flag on tab', () => {
fixture.detectChanges();
const tabs = fixture.componentInstance.tabs.toArray();
let labels = fixture.debugElement.queryAll(By.css('.mat-mdc-tab-disabled'));
expect(tabs[2].disabled).toBe(false);
expect(labels.length).toBe(1);
expect(labels[0].nativeElement.getAttribute('aria-disabled')).toBe('true');
fixture.componentInstance.isDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tabs[2].disabled).toBe(true);
labels = fixture.debugElement.queryAll(By.css('.mat-mdc-tab-disabled'));
expect(labels.length).toBe(2);
expect(
labels.every(label => label.nativeElement.getAttribute('aria-disabled') === 'true'),
).toBe(true);
});
}); | {
"end_byte": 19277,
"start_byte": 10729,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-group.spec.ts"
} |
components/src/material/tabs/tab-group.spec.ts_19281_26281 | describe('dynamic binding tabs', () => {
let fixture: ComponentFixture<SimpleDynamicTabsTestApp>;
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(SimpleDynamicTabsTestApp);
fixture.detectChanges();
tick();
fixture.detectChanges();
}));
it('should be able to add a new tab, select it, and have correct origin position', fakeAsync(() => {
const component: MatTabGroup = fixture.debugElement.query(
By.css('mat-tab-group'),
).componentInstance;
let tabs: MatTab[] = component._tabs.toArray();
expect(tabs[0].origin).toBe(null);
expect(tabs[1].origin).toBe(0);
expect(tabs[2].origin).toBe(null);
// Add a new tab on the right and select it, expect an origin >= than 0 (animate right)
fixture.componentInstance.tabs.push({label: 'New tab', content: 'to right of index'});
fixture.componentInstance.selectedIndex = 4;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
tabs = component._tabs.toArray();
expect(tabs[3].origin).toBeGreaterThanOrEqual(0);
// Add a new tab in the beginning and select it, expect an origin < than 0 (animate left)
fixture.componentInstance.selectedIndex = 0;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
fixture.componentInstance.tabs.push({label: 'New tab', content: 'to left of index'});
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
tabs = component._tabs.toArray();
expect(tabs[0].origin).toBeLessThan(0);
}));
it('should update selected index if the last tab removed while selected', fakeAsync(() => {
const component: MatTabGroup = fixture.debugElement.query(
By.css('mat-tab-group'),
).componentInstance;
const numberOfTabs = component._tabs.length;
fixture.componentInstance.selectedIndex = numberOfTabs - 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
// Remove last tab while last tab is selected, expect next tab over to be selected
fixture.componentInstance.tabs.pop();
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(component.selectedIndex).toBe(numberOfTabs - 2);
}));
it('should maintain the selected tab if a new tab is added', () => {
fixture.detectChanges();
const component: MatTabGroup = fixture.debugElement.query(
By.css('mat-tab-group'),
).componentInstance;
fixture.componentInstance.selectedIndex = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Add a new tab at the beginning.
fixture.componentInstance.tabs.unshift({label: 'New tab', content: 'at the start'});
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(component.selectedIndex).toBe(2);
expect(component._tabs.toArray()[2].isActive).toBe(true);
});
it('should maintain the selected tab if a tab is removed', () => {
// Select the second tab.
fixture.componentInstance.selectedIndex = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const component: MatTabGroup = fixture.debugElement.query(
By.css('mat-tab-group'),
).componentInstance;
// Remove the first tab that is right before the selected one.
fixture.componentInstance.tabs.splice(0, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Since the first tab has been removed and the second one was selected before, the selected
// tab moved one position to the right. Meaning that the tab is now the first tab.
expect(component.selectedIndex).toBe(0);
expect(component._tabs.toArray()[0].isActive).toBe(true);
});
it('should be able to select a new tab after creation', fakeAsync(() => {
fixture.detectChanges();
const component: MatTabGroup = fixture.debugElement.query(
By.css('mat-tab-group'),
).componentInstance;
fixture.componentInstance.tabs.push({label: 'Last tab', content: 'at the end'});
fixture.componentInstance.selectedIndex = 3;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(component.selectedIndex).toBe(3);
expect(component._tabs.toArray()[3].isActive).toBe(true);
}));
it('should not fire `selectedTabChange` when the amount of tabs changes', fakeAsync(() => {
fixture.detectChanges();
fixture.componentInstance.selectedIndex = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Add a new tab at the beginning.
spyOn(fixture.componentInstance, 'handleSelection');
fixture.componentInstance.tabs.unshift({label: 'New tab', content: 'at the start'});
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(fixture.componentInstance.handleSelection).not.toHaveBeenCalled();
}));
it('should update the newly-selected tab if the previously-selected tab is replaced', fakeAsync(() => {
const component: MatTabGroup = fixture.debugElement.query(
By.css('mat-tab-group'),
)!.componentInstance;
spyOn(fixture.componentInstance, 'handleSelection');
fixture.componentInstance.tabs[fixture.componentInstance.selectedIndex] = {
label: 'New',
content: 'New',
};
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(component._tabs.get(1)?.isActive).toBe(true);
expect(fixture.componentInstance.handleSelection).toHaveBeenCalledWith(
jasmine.objectContaining({index: 1}),
);
}));
it('should be able to disable the pagination', fakeAsync(() => {
fixture.componentInstance.disablePagination = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
for (let i = 0; i < 50; i++) {
fixture.componentInstance.tabs.push({label: `Extra ${i}`, content: ''});
}
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(
fixture.nativeElement.querySelector('.mat-mdc-tab-header-pagination-controls-enabled'),
).toBeFalsy();
}));
});
describe('async tabs', () => {
let fixture: ComponentFixture<AsyncTabsTestApp>;
it('should show tabs when they are available', fakeAsync(() => {
fixture = TestBed.createComponent(AsyncTabsTestApp);
expect(fixture.debugElement.queryAll(By.css('.mat-mdc-tab')).length).toBe(0);
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
expect(fixture.debugElement.queryAll(By.css('.mat-mdc-tab')).length).toBe(2);
}));
}); | {
"end_byte": 26281,
"start_byte": 19281,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-group.spec.ts"
} |
components/src/material/tabs/tab-group.spec.ts_26285_33974 | describe('with simple api', () => {
let fixture: ComponentFixture<TabGroupWithSimpleApi>;
let tabGroup: MatTabGroup;
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(TabGroupWithSimpleApi);
fixture.detectChanges();
tick();
tabGroup = fixture.debugElement.query(By.directive(MatTabGroup))
.componentInstance as MatTabGroup;
}));
it('should support a tab-group with the simple api', fakeAsync(() => {
expect(getSelectedLabel(fixture).textContent).toMatch('Junk food');
expect(getSelectedContent(fixture).textContent).toMatch('Pizza, fries');
tabGroup.selectedIndex = 2;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(getSelectedLabel(fixture).textContent).toMatch('Fruit');
expect(getSelectedContent(fixture).textContent).toMatch('Apples, grapes');
fixture.componentInstance.otherLabel = 'Chips';
fixture.componentInstance.otherContent = 'Salt, vinegar';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(getSelectedLabel(fixture).textContent).toMatch('Chips');
expect(getSelectedContent(fixture).textContent).toMatch('Salt, vinegar');
}));
it('should support @ViewChild in the tab content', () => {
expect(fixture.componentInstance.legumes).toBeTruthy();
});
it('should only have the active tab in the DOM', fakeAsync(() => {
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
expect(fixture.nativeElement.textContent).not.toContain('Peanuts');
tabGroup.selectedIndex = 3;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(fixture.nativeElement.textContent).not.toContain('Pizza, fries');
expect(fixture.nativeElement.textContent).toContain('Peanuts');
}));
it('should support setting the header position', () => {
let tabGroupNode = fixture.debugElement.query(By.css('mat-tab-group')).nativeElement;
expect(tabGroupNode.classList).not.toContain('mat-mdc-tab-group-inverted-header');
tabGroup.headerPosition = 'below';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tabGroupNode.classList).toContain('mat-mdc-tab-group-inverted-header');
});
it('should be able to opt into keeping the inactive tab content in the DOM', fakeAsync(() => {
fixture.componentInstance.preserveContent = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
expect(fixture.nativeElement.textContent).not.toContain('Peanuts');
tabGroup.selectedIndex = 3;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
expect(fixture.nativeElement.textContent).toContain('Peanuts');
}));
it('should visibly hide the content of inactive tabs', fakeAsync(() => {
const contentElements: HTMLElement[] = Array.from(
fixture.nativeElement.querySelectorAll('.mat-mdc-tab-body-content'),
);
expect(contentElements.map(element => element.style.visibility)).toEqual([
'visible',
'hidden',
'hidden',
'hidden',
]);
tabGroup.selectedIndex = 2;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(contentElements.map(element => element.style.visibility)).toEqual([
'hidden',
'hidden',
'visible',
'hidden',
]);
tabGroup.selectedIndex = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(contentElements.map(element => element.style.visibility)).toEqual([
'hidden',
'visible',
'hidden',
'hidden',
]);
}));
});
describe('lazy loaded tabs', () => {
it('should lazy load the second tab', fakeAsync(() => {
const fixture = TestBed.createComponent(TemplateTabs);
fixture.detectChanges();
tick();
const secondLabel = fixture.debugElement.queryAll(By.css('.mat-mdc-tab'))[1];
secondLabel.nativeElement.click();
fixture.detectChanges();
tick();
fixture.detectChanges();
const child = fixture.debugElement.query(By.css('.child'));
expect(child.nativeElement).toBeDefined();
}));
});
describe('special cases', () => {
it('should not throw an error when binding isActive to the view', fakeAsync(() => {
const fixture = TestBed.createComponent(TabGroupWithIsActiveBinding);
expect(() => {
fixture.detectChanges();
tick();
fixture.detectChanges();
}).not.toThrow();
expect(fixture.nativeElement.textContent).toContain('pizza is active');
}));
it('should not pick up mat-tab-label from a child tab', fakeAsync(() => {
const fixture = TestBed.createComponent(NestedTabGroupWithLabel);
fixture.detectChanges();
tick();
fixture.detectChanges();
const labels = fixture.nativeElement.querySelectorAll('.mdc-tab__text-label');
const contents = Array.from<HTMLElement>(labels).map(label => label.textContent?.trim());
expect(contents).toEqual([
'Parent 1',
'Parent 2',
'Parent 3',
'Child 1',
'Child 2',
'Child 3',
]);
}));
});
describe('nested tabs', () => {
it('should not pick up the tabs from descendant tab groups', fakeAsync(() => {
const fixture = TestBed.createComponent(NestedTabs);
fixture.detectChanges();
tick();
fixture.detectChanges();
const groups = fixture.componentInstance.groups.toArray();
expect(groups.length).toBe(2);
expect(groups[0]._tabs.map((tab: MatTab) => tab.textLabel)).toEqual(['One', 'Two']);
expect(groups[1]._tabs.map((tab: MatTab) => tab.textLabel)).toEqual([
'Inner tab one',
'Inner tab two',
]);
}));
it('should pick up indirect descendant tabs', fakeAsync(() => {
const fixture = TestBed.createComponent(TabGroupWithIndirectDescendantTabs);
fixture.detectChanges();
tick();
fixture.detectChanges();
const tabs = fixture.componentInstance.tabGroup._tabs;
expect(tabs.map((tab: MatTab) => tab.textLabel)).toEqual(['One', 'Two']);
}));
});
describe('tall tabs', () => {
beforeEach(() => {
window.scrollTo({top: 0});
});
it('should not scroll when changing tabs by clicking', fakeAsync(() => {
const fixture = TestBed.createComponent(TabGroupWithSpaceAbove);
fixture.detectChanges();
tick();
fixture.detectChanges();
window.scrollBy(0, 250);
expect(window.scrollY).toBe(250);
// select the second tab
let tabLabel = fixture.debugElement.queryAll(By.css('.mat-mdc-tab'))[1];
tabLabel.nativeElement.click();
checkSelectedIndex(1, fixture);
expect(window.scrollY).toBe(250);
tick();
}));
it('should not scroll when changing tabs programatically', fakeAsync(() => {
const fixture = TestBed.createComponent(TabGroupWithSpaceAbove);
fixture.detectChanges();
tick();
fixture.detectChanges();
window.scrollBy(0, 250);
expect(window.scrollY).toBe(250);
fixture.componentInstance.tabGroup.selectedIndex = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(window.scrollY).toBe(250);
tick();
}));
}); | {
"end_byte": 33974,
"start_byte": 26285,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-group.spec.ts"
} |
components/src/material/tabs/tab-group.spec.ts_33978_41902 | describe('tabs with custom css classes', () => {
let fixture: ComponentFixture<TabsWithClassesTestApp>;
let labelElements: DebugElement[];
let bodyElements: DebugElement[];
beforeEach(() => {
fixture = TestBed.createComponent(TabsWithClassesTestApp);
fixture.detectChanges();
labelElements = fixture.debugElement.queryAll(By.css('.mdc-tab'));
bodyElements = fixture.debugElement.queryAll(By.css('mat-tab-body'));
});
it('should apply label/body classes', () => {
expect(labelElements[1].nativeElement.classList).toContain('hardcoded-label-class');
expect(bodyElements[1].nativeElement.classList).toContain('hardcoded-body-class');
});
it('should set classes as strings dynamically', () => {
expect(labelElements[0].nativeElement.classList).not.toContain('custom-label-class');
expect(bodyElements[0].nativeElement.classList).not.toContain('custom-body-class');
fixture.componentInstance.labelClassList = 'custom-label-class';
fixture.componentInstance.bodyClassList = 'custom-body-class';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(labelElements[0].nativeElement.classList).toContain('custom-label-class');
expect(bodyElements[0].nativeElement.classList).toContain('custom-body-class');
delete fixture.componentInstance.labelClassList;
delete fixture.componentInstance.bodyClassList;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(labelElements[0].nativeElement.classList).not.toContain('custom-label-class');
expect(bodyElements[0].nativeElement.classList).not.toContain('custom-body-class');
});
it('should set classes as strings array dynamically', () => {
expect(labelElements[0].nativeElement.classList).not.toContain('custom-label-class');
expect(bodyElements[0].nativeElement.classList).not.toContain('custom-body-class');
fixture.componentInstance.labelClassList = ['custom-label-class'];
fixture.componentInstance.bodyClassList = ['custom-body-class'];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(labelElements[0].nativeElement.classList).toContain('custom-label-class');
expect(bodyElements[0].nativeElement.classList).toContain('custom-body-class');
delete fixture.componentInstance.labelClassList;
delete fixture.componentInstance.bodyClassList;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(labelElements[0].nativeElement.classList).not.toContain('custom-label-class');
expect(bodyElements[0].nativeElement.classList).not.toContain('custom-body-class');
});
});
/**
* Checks that the `selectedIndex` has been updated; checks that the label and body have their
* respective `active` classes
*/
function checkSelectedIndex(expectedIndex: number, fixture: ComponentFixture<any>) {
fixture.detectChanges();
let tabComponent: MatTabGroup = fixture.debugElement.query(
By.css('mat-tab-group'),
).componentInstance;
expect(tabComponent.selectedIndex).toBe(expectedIndex);
let tabLabelElement = fixture.debugElement.query(
By.css(`.mat-mdc-tab:nth-of-type(${expectedIndex + 1})`),
).nativeElement;
expect(tabLabelElement.classList.contains('mdc-tab--active')).toBe(true);
let tabContentElement = fixture.debugElement.query(
By.css(`mat-tab-body:nth-of-type(${expectedIndex + 1})`),
).nativeElement;
expect(tabContentElement.classList.contains('mat-mdc-tab-body-active')).toBe(true);
}
function getSelectedLabel(fixture: ComponentFixture<any>): HTMLElement {
return fixture.nativeElement.querySelector('.mdc-tab--active');
}
function getSelectedContent(fixture: ComponentFixture<any>): HTMLElement {
return fixture.nativeElement.querySelector('.mat-mdc-tab-body-active');
}
});
describe('nested MatTabGroup with enabled animations', () => {
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [
MatTabsModule,
BrowserAnimationsModule,
NestedTabs,
TabsWithCustomAnimationDuration,
],
});
}));
it('should not throw when creating a component with nested tab groups', fakeAsync(() => {
expect(() => {
let fixture = TestBed.createComponent(NestedTabs);
fixture.detectChanges();
tick();
}).not.toThrow();
}));
it('should not throw when setting an animationDuration without units', fakeAsync(() => {
expect(() => {
let fixture = TestBed.createComponent(TabsWithCustomAnimationDuration);
fixture.detectChanges();
tick();
}).not.toThrow();
}));
it('should set appropiate css variable given a specified animationDuration', fakeAsync(() => {
let fixture = TestBed.createComponent(TabsWithCustomAnimationDuration);
fixture.detectChanges();
tick();
const tabGroup = fixture.nativeElement.querySelector('.mat-mdc-tab-group');
expect(tabGroup.style.getPropertyValue('--mat-tab-animation-duration')).toBe('500ms');
}));
});
describe('MatTabGroup with ink bar fit to content', () => {
let fixture: ComponentFixture<TabGroupWithInkBarFitToContent>;
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [MatTabsModule, BrowserAnimationsModule, TabGroupWithInkBarFitToContent],
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(TabGroupWithInkBarFitToContent);
fixture.detectChanges();
});
it('should properly nest the ink bar when fit to content', () => {
const tabElement = fixture.nativeElement.querySelector('.mdc-tab');
const contentElement = tabElement.querySelector('.mdc-tab__content');
const indicatorElement = tabElement.querySelector('.mdc-tab-indicator');
expect(indicatorElement.parentElement).toBeTruthy();
expect(indicatorElement.parentElement).toBe(contentElement);
});
it('should be able to move the ink bar between content and full', () => {
fixture.componentInstance.fitInkBarToContent = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const tabElement = fixture.nativeElement.querySelector('.mdc-tab');
const indicatorElement = tabElement.querySelector('.mdc-tab-indicator');
expect(indicatorElement.parentElement).toBeTruthy();
expect(indicatorElement.parentElement).toBe(tabElement);
fixture.componentInstance.fitInkBarToContent = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const contentElement = tabElement.querySelector('.mdc-tab__content');
expect(indicatorElement.parentElement).toBeTruthy();
expect(indicatorElement.parentElement).toBe(contentElement);
});
});
describe('MatTabNavBar with a default config', () => {
let fixture: ComponentFixture<SimpleTabsTestApp>;
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [MatTabsModule, BrowserAnimationsModule, SimpleTabsTestApp],
providers: [
{
provide: MAT_TABS_CONFIG,
useValue: {fitInkBarToContent: true, dynamicHeight: true},
},
],
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(SimpleTabsTestApp);
fixture.detectChanges();
});
it('should set whether the ink bar fits to content', () => {
const tabElement = fixture.nativeElement.querySelector('.mdc-tab');
const contentElement = tabElement.querySelector('.mdc-tab__content');
const indicatorElement = tabElement.querySelector('.mdc-tab-indicator');
expect(indicatorElement.parentElement).toBeTruthy();
expect(indicatorElement.parentElement).toBe(contentElement);
});
it('should set whether the height of the tab group is dynamic', () => {
expect(fixture.componentInstance.tabGroup.dynamicHeight).toBe(true);
});
}); | {
"end_byte": 41902,
"start_byte": 33978,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-group.spec.ts"
} |
components/src/material/tabs/tab-group.spec.ts_41904_49944 | describe('MatTabGroup labels aligned with a config', () => {
it('should work with start align', () => {
const fixture = TestBed.configureTestingModule({
imports: [MatTabsModule, BrowserAnimationsModule, TabsWithAlignConfig],
providers: [
{
provide: MAT_TABS_CONFIG,
useValue: {alignTabs: 'start'},
},
],
}).createComponent(TabsWithAlignConfig);
fixture.detectChanges();
const tabElement = fixture.nativeElement.querySelector('[mat-align-tabs="start"]');
expect(tabElement).toBeTruthy();
});
it('should work with center align', () => {
const fixture = TestBed.configureTestingModule({
imports: [MatTabsModule, BrowserAnimationsModule, TabsWithAlignConfig],
providers: [
{
provide: MAT_TABS_CONFIG,
useValue: {alignTabs: 'center'},
},
],
}).createComponent(TabsWithAlignConfig);
fixture.detectChanges();
const tabElement = fixture.nativeElement.querySelector('[mat-align-tabs="center"]');
expect(tabElement).toBeTruthy();
});
it('should work with end align', () => {
const fixture = TestBed.configureTestingModule({
imports: [MatTabsModule, BrowserAnimationsModule, TabsWithAlignConfig],
providers: [
{
provide: MAT_TABS_CONFIG,
useValue: {alignTabs: 'end'},
},
],
}).createComponent(TabsWithAlignConfig);
fixture.detectChanges();
const tabElement = fixture.nativeElement.querySelector('[mat-align-tabs="end"]');
expect(tabElement).toBeTruthy();
});
it('should not add align if default config doesnt set align', () => {
const fixture = TestBed.configureTestingModule({
imports: [MatTabsModule, BrowserAnimationsModule, TabsWithAlignConfig],
}).createComponent(TabsWithAlignConfig);
fixture.detectChanges();
let tabElement = fixture.nativeElement.querySelector('[mat-align-tabs="start"]');
expect(tabElement).toBeFalsy();
tabElement = fixture.nativeElement.querySelector('[mat-align-tabs="center"]');
expect(tabElement).toBeFalsy();
tabElement = fixture.nativeElement.querySelector('[mat-align-tabs="end"]');
expect(tabElement).toBeFalsy();
tabElement = fixture.nativeElement.querySelector('.mat-mdc-tab-group');
expect(tabElement).toBeTruthy();
});
it('should not break if config sets align on already aligned tabs', () => {
const fixture = TestBed.configureTestingModule({
imports: [MatTabsModule, BrowserAnimationsModule, TabsWithAlignCenter],
providers: [{provide: MAT_TABS_CONFIG, useValue: {alignTabs: 'end'}}],
}).createComponent(TabsWithAlignCenter);
fixture.detectChanges();
let tabElement = fixture.nativeElement.querySelector('[mat-align-tabs="start"]');
expect(tabElement).toBeFalsy();
tabElement = fixture.nativeElement.querySelector('[mat-align-tabs="center"]');
expect(tabElement).toBeTruthy();
tabElement = fixture.nativeElement.querySelector('[mat-align-tabs="end"]');
expect(tabElement).toBeFalsy();
tabElement = fixture.nativeElement.querySelector('.mat-mdc-tab-group');
expect(tabElement).toBeTruthy();
});
});
@Component({
template: `
<mat-tab-group class="tab-group"
[(selectedIndex)]="selectedIndex"
[headerPosition]="headerPosition"
[disableRipple]="disableRipple"
[contentTabIndex]="contentTabIndex"
[aria-label]="ariaLabel"
[aria-labelledby]="ariaLabelledby"
(animationDone)="animationDone()"
(focusChange)="handleFocus($event)"
(selectedTabChange)="handleSelection($event)">
<mat-tab>
<ng-template mat-tab-label>Tab One</ng-template>
Tab one content
</mat-tab>
<mat-tab>
<ng-template mat-tab-label>Tab Two</ng-template>
<span>Tab </span><span>two</span><span>content</span>
</mat-tab>
<mat-tab>
<ng-template mat-tab-label>Tab Three</ng-template>
Tab three content
</mat-tab>
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class SimpleTabsTestApp {
@ViewChild(MatTabGroup) tabGroup: MatTabGroup;
@ViewChildren(MatTab) tabs: QueryList<MatTab>;
selectedIndex: number = 1;
focusEvent: any;
selectEvent: any;
disableRipple: boolean = false;
contentTabIndex: number | null = null;
headerPosition: MatTabHeaderPosition = 'above';
ariaLabel: string;
ariaLabelledby: string;
handleFocus(event: any) {
this.focusEvent = event;
}
handleSelection(event: any) {
this.selectEvent = event;
}
animationDone() {}
}
@Component({
template: `
<mat-tab-group class="tab-group"
[(selectedIndex)]="selectedIndex"
(focusChange)="handleFocus($event)"
(selectedTabChange)="handleSelection($event)"
[disablePagination]="disablePagination">
@for (tab of tabs; track tab) {
<mat-tab>
<ng-template mat-tab-label>{{tab.label}}</ng-template>
{{tab.content}}
</mat-tab>
}
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class SimpleDynamicTabsTestApp {
tabs = [
{label: 'Label 1', content: 'Content 1'},
{label: 'Label 2', content: 'Content 2'},
{label: 'Label 3', content: 'Content 3'},
];
selectedIndex: number = 1;
focusEvent: any;
selectEvent: any;
disablePagination = false;
handleFocus(event: any) {
this.focusEvent = event;
}
handleSelection(event: any) {
this.selectEvent = event;
}
}
@Component({
template: `
<mat-tab-group class="tab-group" [(selectedIndex)]="selectedIndex">
@for (tab of tabs; track tab) {
<mat-tab label="{{tab.label}}">{{tab.content}}</mat-tab>
}
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class BindedTabsTestApp {
tabs = [
{label: 'one', content: 'one'},
{label: 'two', content: 'two'},
];
selectedIndex = 0;
addNewActiveTab(): void {
this.tabs.push({
label: 'new tab',
content: 'new content',
});
this.selectedIndex = this.tabs.length - 1;
}
}
@Component({
template: `
<mat-tab-group class="tab-group">
<mat-tab>
<ng-template mat-tab-label>Tab One</ng-template>
Tab one content
</mat-tab>
<mat-tab disabled>
<ng-template mat-tab-label>Tab Two</ng-template>
Tab two content
</mat-tab>
<mat-tab [disabled]="isDisabled">
<ng-template mat-tab-label>Tab Three</ng-template>
Tab three content
</mat-tab>
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class DisabledTabsTestApp {
@ViewChildren(MatTab) tabs: QueryList<MatTab>;
isDisabled = false;
}
@Component({
template: `
<mat-tab-group class="tab-group">
@for (tab of tabs | async; track tab) {
<mat-tab>
<ng-template mat-tab-label>{{ tab.label }}</ng-template>
{{ tab.content }}
</mat-tab>
}
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule, AsyncPipe],
})
class AsyncTabsTestApp implements OnInit {
private _tabs = [
{label: 'one', content: 'one'},
{label: 'two', content: 'two'},
];
tabs: Observable<any>;
ngOnInit() {
// Use ngOnInit because there is some issue with scheduling the async task in the constructor.
this.tabs = new Observable((observer: any) => {
setTimeout(() => observer.next(this._tabs));
});
}
}
@Component({
template: `
<mat-tab-group [preserveContent]="preserveContent">
<mat-tab label="Junk food"> Pizza, fries </mat-tab>
<mat-tab label="Vegetables"> Broccoli, spinach </mat-tab>
<mat-tab [label]="otherLabel"> {{otherContent}} </mat-tab>
<mat-tab label="Legumes"> <p #legumes>Peanuts</p> </mat-tab>
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class TabGroupWithSimpleApi {
preserveContent = false;
otherLabel = 'Fruit';
otherContent = 'Apples, grapes';
@ViewChild('legumes') legumes: any;
} | {
"end_byte": 49944,
"start_byte": 41904,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-group.spec.ts"
} |
components/src/material/tabs/tab-group.spec.ts_49946_54697 | @Component({
template: `
<mat-tab-group>
<mat-tab label="One">Tab one content</mat-tab>
<mat-tab label="Two">
Tab two content
<mat-tab-group [dynamicHeight]="true">
<mat-tab label="Inner tab one">Inner content one</mat-tab>
<mat-tab label="Inner tab two">Inner content two</mat-tab>
</mat-tab-group>
</mat-tab>
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class NestedTabs {
@ViewChildren(MatTabGroup) groups: QueryList<MatTabGroup>;
}
@Component({
template: `
<mat-tab-group>
<mat-tab label="One">
Eager
</mat-tab>
<mat-tab label="Two">
<ng-template matTabContent>
<div class="child">Hi</div>
</ng-template>
</mat-tab>
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class TemplateTabs {}
@Component({
template: `
<mat-tab-group>
<mat-tab [aria-label]="ariaLabel" [aria-labelledby]="ariaLabelledby"></mat-tab>
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class TabGroupWithAriaInputs {
ariaLabel: string;
ariaLabelledby: string;
}
@Component({
template: `
<mat-tab-group>
<mat-tab label="Junk food" #pizza> Pizza, fries </mat-tab>
<mat-tab label="Vegetables"> Broccoli, spinach </mat-tab>
</mat-tab-group>
@if (pizza.isActive) {
<div>pizza is active</div>
}
`,
standalone: true,
imports: [MatTabsModule],
})
class TabGroupWithIsActiveBinding {}
@Component({
template: `
<mat-tab-group animationDuration="500">
<mat-tab label="One">Tab one content</mat-tab>
<mat-tab label="Two">Tab two content</mat-tab>
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class TabsWithCustomAnimationDuration {}
@Component({
template: `
<mat-tab-group>
@if (true) {
<mat-tab label="One">Tab one content</mat-tab>
<mat-tab label="Two">Tab two content</mat-tab>
}
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class TabGroupWithIndirectDescendantTabs {
@ViewChild(MatTabGroup) tabGroup: MatTabGroup;
}
@Component({
template: `
<mat-tab-group [fitInkBarToContent]="fitInkBarToContent">
<mat-tab label="One">Tab one content</mat-tab>
<mat-tab label="Two">Tab two content</mat-tab>
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class TabGroupWithInkBarFitToContent {
fitInkBarToContent = true;
}
@Component({
template: `
<div style="height: 300px; background-color: aqua">
Top Content here
</div>
<mat-tab-group>
<ng-container>
<mat-tab label="One">
<div style="height: 3000px; background-color: red"></div>
</mat-tab>
<mat-tab label="Two">
<div style="height: 3000px; background-color: green"></div>
</mat-tab>
</ng-container>
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class TabGroupWithSpaceAbove {
@ViewChild(MatTabGroup) tabGroup: MatTabGroup;
}
@Component({
template: `
<mat-tab-group>
<mat-tab label="Parent 1">
<mat-tab-group>
<mat-tab label="Child 1">Content 1</mat-tab>
<mat-tab>
<ng-template mat-tab-label>Child 2</ng-template>
Content 2
</mat-tab>
<mat-tab label="Child 3">Child 3</mat-tab>
</mat-tab-group>
</mat-tab>
<mat-tab label="Parent 2">Parent 2</mat-tab>
<mat-tab label="Parent 3">Parent 3</mat-tab>
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class NestedTabGroupWithLabel {}
@Component({
template: `
<mat-tab-group class="tab-group">
<mat-tab label="Tab One" [labelClass]="labelClassList" [bodyClass]="bodyClassList">
Tab one content
</mat-tab>
<mat-tab label="Tab Two" labelClass="hardcoded-label-class"
bodyClass="hardcoded-body-class">
Tab two content
</mat-tab>
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class TabsWithClassesTestApp {
labelClassList?: string | string[];
bodyClassList?: string | string[];
}
@Component({
template: `
<mat-tab-group>
<mat-tab>
First
</mat-tab>
<mat-tab>
Second
</mat-tab>
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class TabsWithAlignConfig {}
@Component({
template: `
<mat-tab-group mat-align-tabs="center">
<mat-tab>
First
</mat-tab>
<mat-tab>
Second
</mat-tab>
</mat-tab-group>
`,
standalone: true,
imports: [MatTabsModule],
})
class TabsWithAlignCenter {} | {
"end_byte": 54697,
"start_byte": 49946,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-group.spec.ts"
} |
components/src/material/tabs/tab-header.spec.ts_0_9379 | import {Dir, Direction} from '@angular/cdk/bidi';
import {END, ENTER, HOME, LEFT_ARROW, RIGHT_ARROW, SPACE} from '@angular/cdk/keycodes';
import {MutationObserverFactory, ObserversModule} from '@angular/cdk/observers';
import {SharedResizeObserver} from '@angular/cdk/observers/private';
import {PortalModule} from '@angular/cdk/portal';
import {ScrollingModule, ViewportRuler} from '@angular/cdk/scrolling';
import {
createKeyboardEvent,
createMouseEvent,
dispatchEvent,
dispatchFakeEvent,
dispatchKeyboardEvent,
} from '@angular/cdk/testing/private';
import {ChangeDetectorRef, Component, ViewChild, inject} from '@angular/core';
import {
ComponentFixture,
TestBed,
discardPeriodicTasks,
fakeAsync,
flush,
flushMicrotasks,
tick,
waitForAsync,
} from '@angular/core/testing';
import {MatRippleModule} from '@angular/material/core';
import {By} from '@angular/platform-browser';
import {Subject} from 'rxjs';
import {MatTabHeader} from './tab-header';
import {MatTabLabelWrapper} from './tab-label-wrapper';
describe('MatTabHeader', () => {
let fixture: ComponentFixture<SimpleTabHeaderApp>;
let appComponent: SimpleTabHeaderApp;
let resizeEvents: Subject<ResizeObserverEntry[]>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
PortalModule,
MatRippleModule,
ScrollingModule,
ObserversModule,
MatTabHeader,
MatTabLabelWrapper,
SimpleTabHeaderApp,
],
providers: [ViewportRuler],
});
resizeEvents = new Subject();
spyOn(TestBed.inject(SharedResizeObserver), 'observe').and.returnValue(resizeEvents);
}));
describe('focusing', () => {
let tabListContainer: HTMLElement;
beforeEach(() => {
fixture = TestBed.createComponent(SimpleTabHeaderApp);
fixture.detectChanges();
appComponent = fixture.componentInstance;
tabListContainer = appComponent.tabHeader._tabListContainer.nativeElement;
});
it('should initialize to the selected index', () => {
// Recreate the fixture so we can test that it works with a non-default selected index
fixture.destroy();
fixture = TestBed.createComponent(SimpleTabHeaderApp);
fixture.componentInstance.selectedIndex = 1;
fixture.detectChanges();
appComponent = fixture.componentInstance;
tabListContainer = appComponent.tabHeader._tabListContainer.nativeElement;
expect(appComponent.tabHeader.focusIndex).toBe(1);
});
it('should send focus change event', () => {
appComponent.tabHeader.focusIndex = 2;
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(2);
});
it('should be able to focus a disabled tab', () => {
appComponent.tabHeader.focusIndex = 0;
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(0);
appComponent.tabHeader.focusIndex = appComponent.disabledTabIndex;
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(appComponent.disabledTabIndex);
});
it('should move focus right including over disabled tabs', () => {
appComponent.tabHeader.focusIndex = 0;
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(0);
expect(appComponent.disabledTabIndex).toBe(1);
dispatchKeyboardEvent(tabListContainer, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(1);
dispatchKeyboardEvent(tabListContainer, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(2);
});
it('should move focus left including over disabled tabs', () => {
appComponent.tabHeader.focusIndex = 3;
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(3);
// Move focus left to index 3
dispatchKeyboardEvent(tabListContainer, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(2);
expect(appComponent.disabledTabIndex).toBe(1);
dispatchKeyboardEvent(tabListContainer, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(1);
});
it('should support key down events to move and select focus', () => {
appComponent.tabHeader.focusIndex = 0;
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(0);
// Move focus right to 1
dispatchKeyboardEvent(tabListContainer, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(1);
// Try to select 1. Should not work since it's disabled.
expect(appComponent.selectedIndex).toBe(0);
const firstEnterEvent = dispatchKeyboardEvent(tabListContainer, 'keydown', ENTER);
fixture.detectChanges();
expect(appComponent.selectedIndex).toBe(0);
expect(firstEnterEvent.defaultPrevented).toBe(false);
// Move focus right to 2
dispatchKeyboardEvent(tabListContainer, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(2);
// Select 2 which is enabled.
expect(appComponent.selectedIndex).toBe(0);
const secondEnterEvent = dispatchKeyboardEvent(tabListContainer, 'keydown', ENTER);
fixture.detectChanges();
expect(appComponent.selectedIndex).toBe(2);
expect(secondEnterEvent.defaultPrevented).toBe(true);
// Move focus left to 1
dispatchKeyboardEvent(tabListContainer, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(1);
// Move again to 0
dispatchKeyboardEvent(tabListContainer, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(0);
// Select the focused 0 using space.
expect(appComponent.selectedIndex).toBe(2);
const spaceEvent = dispatchKeyboardEvent(tabListContainer, 'keydown', SPACE);
fixture.detectChanges();
expect(appComponent.selectedIndex).toBe(0);
expect(spaceEvent.defaultPrevented).toBe(true);
});
it('should not prevent the default space/enter action if the current is selected', () => {
appComponent.tabHeader.focusIndex = appComponent.tabHeader.selectedIndex = 0;
fixture.detectChanges();
const spaceEvent = dispatchKeyboardEvent(tabListContainer, 'keydown', SPACE);
fixture.detectChanges();
expect(spaceEvent.defaultPrevented).toBe(false);
const enterEvent = dispatchKeyboardEvent(tabListContainer, 'keydown', ENTER);
fixture.detectChanges();
expect(enterEvent.defaultPrevented).toBe(false);
});
it('should move focus to the first tab when pressing HOME', () => {
appComponent.tabHeader.focusIndex = 3;
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(3);
const event = dispatchKeyboardEvent(tabListContainer, 'keydown', HOME);
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(0);
expect(event.defaultPrevented).toBe(true);
});
it('should focus disabled items when moving focus using HOME', () => {
appComponent.tabHeader.focusIndex = 3;
appComponent.tabs[0].disabled = true;
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(3);
dispatchKeyboardEvent(tabListContainer, 'keydown', HOME);
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(0);
});
it('should move focus to the last tab when pressing END', () => {
appComponent.tabHeader.focusIndex = 0;
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(0);
const event = dispatchKeyboardEvent(tabListContainer, 'keydown', END);
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(3);
expect(event.defaultPrevented).toBe(true);
});
it('should focus disabled items when moving focus using END', () => {
appComponent.tabHeader.focusIndex = 0;
appComponent.tabs[3].disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(0);
dispatchKeyboardEvent(tabListContainer, 'keydown', END);
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(3);
});
it('should not do anything if a modifier key is pressed', () => {
const rightArrowEvent = createKeyboardEvent('keydown', RIGHT_ARROW, undefined, {shift: true});
const enterEvent = createKeyboardEvent('keydown', ENTER, undefined, {shift: true});
appComponent.tabHeader.focusIndex = 0;
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(0);
dispatchEvent(tabListContainer, rightArrowEvent);
fixture.detectChanges();
expect(appComponent.tabHeader.focusIndex).toBe(0);
expect(rightArrowEvent.defaultPrevented).toBe(false);
expect(appComponent.selectedIndex).toBe(0);
dispatchEvent(tabListContainer, enterEvent);
fixture.detectChanges();
expect(appComponent.selectedIndex).toBe(0);
expect(enterEvent.defaultPrevented).toBe(false);
});
}); | {
"end_byte": 9379,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-header.spec.ts"
} |
components/src/material/tabs/tab-header.spec.ts_9383_14989 | describe('pagination', () => {
describe('ltr', () => {
beforeEach(() => {
fixture = TestBed.createComponent(SimpleTabHeaderApp);
appComponent = fixture.componentInstance;
appComponent.dir = 'ltr';
fixture.detectChanges();
});
it('should show width when tab list width exceeds container', () => {
fixture.detectChanges();
expect(appComponent.tabHeader._showPaginationControls).toBe(false);
// Add enough tabs that it will obviously exceed the width
appComponent.addTabsForScrolling();
fixture.detectChanges();
expect(appComponent.tabHeader._showPaginationControls).toBe(true);
});
it('should scroll to show the focused tab label', () => {
appComponent.addTabsForScrolling();
fixture.detectChanges();
expect(appComponent.tabHeader.scrollDistance).toBe(0);
// Focus on the last tab, expect this to be the maximum scroll distance.
appComponent.tabHeader.focusIndex = appComponent.tabs.length - 1;
fixture.detectChanges();
const {offsetLeft, offsetWidth} = appComponent.getSelectedLabel(
appComponent.tabHeader.focusIndex,
);
const viewLength = appComponent.getViewLength();
expect(appComponent.tabHeader.scrollDistance).toBe(offsetLeft + offsetWidth - viewLength);
// Focus on the first tab, expect this to be the maximum scroll distance.
appComponent.tabHeader.focusIndex = 0;
fixture.detectChanges();
expect(appComponent.tabHeader.scrollDistance).toBe(0);
});
it('should show ripples for pagination buttons', () => {
appComponent.addTabsForScrolling();
fixture.detectChanges();
expect(appComponent.tabHeader._showPaginationControls).toBe(true);
const buttonAfter = fixture.debugElement.query(
By.css('.mat-mdc-tab-header-pagination-after'),
);
expect(fixture.nativeElement.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected no ripple to show up initially.')
.toBe(0);
dispatchFakeEvent(buttonAfter.nativeElement, 'mousedown');
dispatchFakeEvent(buttonAfter.nativeElement, 'mouseup');
expect(fixture.nativeElement.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected one ripple to show up after mousedown')
.toBe(1);
});
it('should allow disabling ripples for pagination buttons', () => {
appComponent.addTabsForScrolling();
appComponent.disableRipple = true;
fixture.detectChanges();
expect(appComponent.tabHeader._showPaginationControls).toBe(true);
const buttonAfter = fixture.debugElement.query(
By.css('.mat-mdc-tab-header-pagination-after'),
);
expect(fixture.nativeElement.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected no ripple to show up initially.')
.toBe(0);
dispatchFakeEvent(buttonAfter.nativeElement, 'mousedown');
dispatchFakeEvent(buttonAfter.nativeElement, 'mouseup');
expect(fixture.nativeElement.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected no ripple to show up after mousedown')
.toBe(0);
});
it('should update the scroll distance if a tab is removed and no tabs are selected', fakeAsync(() => {
appComponent.selectedIndex = 0;
fixture.changeDetectorRef.markForCheck();
appComponent.addTabsForScrolling();
fixture.detectChanges();
// Focus the last tab so the header scrolls to the end.
appComponent.tabHeader.focusIndex = appComponent.tabs.length - 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const {offsetLeft, offsetWidth} = appComponent.getSelectedLabel(
appComponent.tabHeader.focusIndex,
);
const viewLength = appComponent.getViewLength();
expect(appComponent.tabHeader.scrollDistance).toBe(offsetLeft + offsetWidth - viewLength);
// Remove the first two tabs which includes the selected tab.
appComponent.tabs = appComponent.tabs.slice(2);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(appComponent.tabHeader.scrollDistance).toBe(
appComponent.tabHeader._getMaxScrollDistance(),
);
}));
});
describe('rtl', () => {
beforeEach(() => {
fixture = TestBed.createComponent(SimpleTabHeaderApp);
appComponent = fixture.componentInstance;
appComponent.dir = 'rtl';
fixture.detectChanges();
});
it('should scroll to show the focused tab label', () => {
appComponent.addTabsForScrolling();
fixture.detectChanges();
expect(appComponent.tabHeader.scrollDistance).toBe(0);
// Focus on the last tab, expect this to be the maximum scroll distance.
appComponent.tabHeader.focusIndex = appComponent.tabs.length - 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const {offsetLeft} = appComponent.getSelectedLabel(appComponent.tabHeader.focusIndex);
expect(offsetLeft).toBe(0);
// Focus on the first tab, expect this to be the maximum scroll distance.
appComponent.tabHeader.focusIndex = 0;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(appComponent.tabHeader.scrollDistance).toBe(0);
});
}); | {
"end_byte": 14989,
"start_byte": 9383,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-header.spec.ts"
} |
components/src/material/tabs/tab-header.spec.ts_14995_24961 | describe('scrolling when holding paginator', () => {
let nextButton: HTMLElement;
let prevButton: HTMLElement;
let header: MatTabHeader;
let headerElement: HTMLElement;
beforeEach(() => {
fixture = TestBed.createComponent(SimpleTabHeaderApp);
fixture.componentInstance.disableRipple = true;
fixture.detectChanges();
fixture.componentInstance.addTabsForScrolling(50);
fixture.detectChanges();
nextButton = fixture.nativeElement.querySelector('.mat-mdc-tab-header-pagination-after');
prevButton = fixture.nativeElement.querySelector('.mat-mdc-tab-header-pagination-before');
header = fixture.componentInstance.tabHeader;
headerElement = fixture.nativeElement.querySelector('.mat-mdc-tab-header');
});
it('should scroll towards the end while holding down the next button using a mouse', fakeAsync(() => {
assertNextButtonScrolling('mousedown', 'click');
}));
it('should scroll towards the start while holding down the prev button using a mouse', fakeAsync(() => {
assertPrevButtonScrolling('mousedown', 'click');
}));
it('should scroll towards the end while holding down the next button using touch', fakeAsync(() => {
assertNextButtonScrolling('touchstart', 'touchend');
}));
it('should scroll towards the start while holding down the prev button using touch', fakeAsync(() => {
assertPrevButtonScrolling('touchstart', 'touchend');
}));
it('should not scroll if the sequence is interrupted quickly', fakeAsync(() => {
expect(header.scrollDistance).withContext('Expected to start off not scrolled.').toBe(0);
dispatchFakeEvent(nextButton, 'mousedown');
fixture.detectChanges();
tick(100);
dispatchFakeEvent(headerElement, 'mouseleave');
fixture.detectChanges();
tick(3000);
expect(header.scrollDistance)
.withContext('Expected not to have scrolled after a while.')
.toBe(0);
}));
it('should clear the timeouts on destroy', fakeAsync(() => {
dispatchFakeEvent(nextButton, 'mousedown');
fixture.detectChanges();
fixture.destroy();
// No need to assert. If fakeAsync doesn't throw, it means that the timers were cleared.
}));
it('should clear the timeouts on click', fakeAsync(() => {
dispatchFakeEvent(nextButton, 'mousedown');
fixture.detectChanges();
dispatchFakeEvent(nextButton, 'click');
fixture.detectChanges();
// No need to assert. If fakeAsync doesn't throw, it means that the timers were cleared.
}));
it('should clear the timeouts on touchend', fakeAsync(() => {
dispatchFakeEvent(nextButton, 'touchstart');
fixture.detectChanges();
dispatchFakeEvent(nextButton, 'touchend');
fixture.detectChanges();
// No need to assert. If fakeAsync doesn't throw, it means that the timers were cleared.
}));
it('should clear the timeouts when reaching the end', fakeAsync(() => {
dispatchFakeEvent(nextButton, 'mousedown');
fixture.detectChanges();
// Simulate a very long timeout.
tick(60000);
// No need to assert. If fakeAsync doesn't throw, it means that the timers were cleared.
}));
it('should clear the timeouts when reaching the start', fakeAsync(() => {
header.scrollDistance = Infinity;
fixture.detectChanges();
dispatchFakeEvent(prevButton, 'mousedown');
fixture.detectChanges();
// Simulate a very long timeout.
tick(60000);
// No need to assert. If fakeAsync doesn't throw, it means that the timers were cleared.
}));
it('should stop scrolling if the pointer leaves the header', fakeAsync(() => {
expect(header.scrollDistance).withContext('Expected to start off not scrolled.').toBe(0);
dispatchFakeEvent(nextButton, 'mousedown');
fixture.detectChanges();
tick(300);
expect(header.scrollDistance)
.withContext('Expected not to scroll after short amount of time.')
.toBe(0);
tick(1000);
expect(header.scrollDistance)
.withContext('Expected to scroll after some time.')
.toBeGreaterThan(0);
let previousDistance = header.scrollDistance;
dispatchFakeEvent(headerElement, 'mouseleave');
fixture.detectChanges();
tick(100);
expect(header.scrollDistance).toBe(previousDistance);
}));
it('should not scroll when pressing the right mouse button', fakeAsync(() => {
expect(header.scrollDistance).withContext('Expected to start off not scrolled.').toBe(0);
dispatchEvent(
nextButton,
createMouseEvent('mousedown', undefined, undefined, undefined, undefined, 2),
);
fixture.detectChanges();
tick(3000);
expect(header.scrollDistance)
.withContext('Expected not to have scrolled after a while.')
.toBe(0);
}));
/**
* Asserts that auto scrolling using the next button works.
* @param startEventName Name of the event that is supposed to start the scrolling.
* @param endEventName Name of the event that is supposed to end the scrolling.
*/
function assertNextButtonScrolling(startEventName: string, endEventName: string) {
expect(header.scrollDistance).withContext('Expected to start off not scrolled.').toBe(0);
dispatchFakeEvent(nextButton, startEventName);
fixture.detectChanges();
tick(300);
expect(header.scrollDistance)
.withContext('Expected not to scroll after short amount of time.')
.toBe(0);
tick(1000);
expect(header.scrollDistance)
.withContext('Expected to scroll after some time.')
.toBeGreaterThan(0);
let previousDistance = header.scrollDistance;
tick(100);
expect(header.scrollDistance)
.withContext('Expected to scroll again after some more time.')
.toBeGreaterThan(previousDistance);
dispatchFakeEvent(nextButton, endEventName);
flush();
}
/**
* Asserts that auto scrolling using the previous button works.
* @param startEventName Name of the event that is supposed to start the scrolling.
* @param endEventName Name of the event that is supposed to end the scrolling.
*/
function assertPrevButtonScrolling(startEventName: string, endEventName: string) {
header.scrollDistance = Infinity;
fixture.detectChanges();
let currentScroll = header.scrollDistance;
expect(currentScroll).withContext('Expected to start off scrolled.').toBeGreaterThan(0);
dispatchFakeEvent(prevButton, startEventName);
fixture.detectChanges();
tick(300);
expect(header.scrollDistance)
.withContext('Expected not to scroll after short amount of time.')
.toBe(currentScroll);
tick(1000);
expect(header.scrollDistance)
.withContext('Expected to scroll after some time.')
.toBeLessThan(currentScroll);
currentScroll = header.scrollDistance;
tick(100);
expect(header.scrollDistance)
.withContext('Expected to scroll again after some more time.')
.toBeLessThan(currentScroll);
dispatchFakeEvent(nextButton, endEventName);
flush();
}
});
describe('disabling pagination', () => {
it('should not show the pagination controls if pagination is disabled', () => {
fixture = TestBed.createComponent(SimpleTabHeaderApp);
appComponent = fixture.componentInstance;
appComponent.disablePagination = true;
fixture.detectChanges();
expect(appComponent.tabHeader._showPaginationControls).toBe(false);
// Add enough tabs that it will obviously exceed the width
appComponent.addTabsForScrolling();
fixture.detectChanges();
expect(appComponent.tabHeader._showPaginationControls).toBe(false);
});
it('should not change the scroll position if pagination is disabled', () => {
fixture = TestBed.createComponent(SimpleTabHeaderApp);
appComponent = fixture.componentInstance;
appComponent.disablePagination = true;
fixture.detectChanges();
appComponent.addTabsForScrolling();
fixture.detectChanges();
expect(appComponent.tabHeader.scrollDistance).toBe(0);
appComponent.tabHeader.focusIndex = appComponent.tabs.length - 1;
fixture.detectChanges();
expect(appComponent.tabHeader.scrollDistance).toBe(0);
appComponent.tabHeader.focusIndex = 0;
fixture.detectChanges();
expect(appComponent.tabHeader.scrollDistance).toBe(0);
});
});
it('should re-align the ink bar when the direction changes', fakeAsync(() => {
fixture = TestBed.createComponent(SimpleTabHeaderApp);
fixture.detectChanges();
const inkBar = fixture.componentInstance.tabHeader._inkBar;
spyOn(inkBar, 'alignToElement');
fixture.detectChanges();
fixture.componentInstance.dir = 'rtl';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(inkBar.alignToElement).toHaveBeenCalled();
}));
it('should re-align the ink bar when the header is resized', fakeAsync(() => {
fixture = TestBed.createComponent(SimpleTabHeaderApp);
fixture.detectChanges();
const inkBar = fixture.componentInstance.tabHeader._inkBar;
spyOn(inkBar, 'alignToElement');
resizeEvents.next([]);
fixture.detectChanges();
tick(32);
expect(inkBar.alignToElement).toHaveBeenCalled();
discardPeriodicTasks();
})); | {
"end_byte": 24961,
"start_byte": 14995,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-header.spec.ts"
} |
components/src/material/tabs/tab-header.spec.ts_24967_28303 | it('should update arrows when the header is resized', fakeAsync(() => {
fixture = TestBed.createComponent(SimpleTabHeaderApp);
const header = fixture.componentInstance.tabHeader;
spyOn(header, '_checkPaginationEnabled');
resizeEvents.next([]);
fixture.detectChanges();
flushMicrotasks();
expect(header._checkPaginationEnabled).toHaveBeenCalled();
discardPeriodicTasks();
}));
it('should update the pagination state if the content of the labels changes', () => {
const mutationCallbacks: Function[] = [];
spyOn(TestBed.inject(MutationObserverFactory), 'create').and.callFake(
(callback: Function) => {
mutationCallbacks.push(callback);
return {observe: () => {}, disconnect: () => {}} as any;
},
);
fixture = TestBed.createComponent(SimpleTabHeaderApp);
fixture.detectChanges();
const tabHeaderElement: HTMLElement =
fixture.nativeElement.querySelector('.mat-mdc-tab-header');
const labels = Array.from<HTMLElement>(
fixture.nativeElement.querySelectorAll('.label-content'),
);
const extraText = new Array(100).fill('w').join();
const enabledClass = 'mat-mdc-tab-header-pagination-controls-enabled';
expect(tabHeaderElement.classList).not.toContain(enabledClass);
labels.forEach(label => {
label.style.width = '';
label.textContent += extraText;
});
mutationCallbacks.forEach(callback => callback([{type: 'fake'}]));
fixture.detectChanges();
expect(tabHeaderElement.classList).toContain(enabledClass);
});
});
});
interface Tab {
label: string;
disabled?: boolean;
}
@Component({
template: `
<div [dir]="dir">
<mat-tab-header [selectedIndex]="selectedIndex" [disableRipple]="disableRipple"
(indexFocused)="focusedIndex = $event"
(selectFocusedIndex)="selectedIndex = $event"
[disablePagination]="disablePagination">
@for (tab of tabs; track tab; let i = $index) {
<div matTabLabelWrapper class="label-content" style="min-width: 30px; width: 30px"
[disabled]="!!tab.disabled"
(click)="selectedIndex = i">{{tab.label}}</div>
}
</mat-tab-header>
</div>
`,
styles: `
:host {
width: 130px;
}
`,
standalone: true,
imports: [Dir, MatTabHeader, MatTabLabelWrapper],
})
class SimpleTabHeaderApp {
disableRipple: boolean = false;
selectedIndex: number = 0;
focusedIndex: number;
disabledTabIndex = 1;
tabs: Tab[] = [{label: 'tab one'}, {label: 'tab one'}, {label: 'tab one'}, {label: 'tab one'}];
dir: Direction = 'ltr';
disablePagination: boolean;
@ViewChild(MatTabHeader, {static: true}) tabHeader: MatTabHeader;
private readonly _changeDetectorRef = inject(ChangeDetectorRef);
constructor() {
this.tabs[this.disabledTabIndex].disabled = true;
}
addTabsForScrolling(amount = 4) {
for (let i = 0; i < amount; i++) {
this.tabs.push({label: 'new'});
}
this._changeDetectorRef.markForCheck();
}
getViewLength() {
return this.tabHeader._tabListContainer.nativeElement.offsetWidth;
}
getSelectedLabel(index: number) {
return this.tabHeader._items.toArray()[this.tabHeader.focusIndex].elementRef.nativeElement;
}
} | {
"end_byte": 28303,
"start_byte": 24967,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-header.spec.ts"
} |
components/src/material/tabs/tab-body.spec.ts_0_7684 | import {Direction, Directionality} from '@angular/cdk/bidi';
import {PortalModule, TemplatePortal} from '@angular/cdk/portal';
import {CdkScrollable, ScrollingModule} from '@angular/cdk/scrolling';
import {
AfterViewInit,
Component,
TemplateRef,
ViewChild,
ViewContainerRef,
inject,
signal,
} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {MatRippleModule} from '@angular/material/core';
import {By} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {Subject} from 'rxjs';
import {MatTabBody, MatTabBodyPortal} from './tab-body';
describe('MatTabBody', () => {
let dir: Direction = 'ltr';
let dirChange: Subject<Direction> = new Subject<Direction>();
beforeEach(waitForAsync(() => {
dir = 'ltr';
TestBed.configureTestingModule({
imports: [
PortalModule,
MatRippleModule,
NoopAnimationsModule,
MatTabBody,
MatTabBodyPortal,
SimpleTabBodyApp,
],
providers: [{provide: Directionality, useFactory: () => ({value: dir, change: dirChange})}],
});
}));
describe('when initialized as center', () => {
let fixture: ComponentFixture<SimpleTabBodyApp>;
it('should be center position if origin is unchanged', () => {
fixture = TestBed.createComponent(SimpleTabBodyApp);
fixture.componentInstance.position = 0;
fixture.detectChanges();
expect(fixture.componentInstance.tabBody._position).toBe('center');
});
it('should be center position if origin is explicitly set to null', () => {
fixture = TestBed.createComponent(SimpleTabBodyApp);
fixture.componentInstance.position = 0;
// It can happen that the `origin` is explicitly set to null through the Angular input
// binding. This test should ensure that the body does properly such origin value.
// The `MatTab` class sets the origin by default to null. See related issue: #12455
fixture.componentInstance.origin = null;
fixture.detectChanges();
expect(fixture.componentInstance.tabBody._position).toBe('center');
});
describe('in LTR direction', () => {
beforeEach(() => {
dir = 'ltr';
fixture = TestBed.createComponent(SimpleTabBodyApp);
});
it('should be left-origin-center position with negative or zero origin', () => {
fixture.componentInstance.position = 0;
fixture.componentInstance.origin = 0;
fixture.detectChanges();
expect(fixture.componentInstance.tabBody._position).toBe('left-origin-center');
});
it('should be right-origin-center position with positive nonzero origin', () => {
fixture.componentInstance.position = 0;
fixture.componentInstance.origin = 1;
fixture.detectChanges();
expect(fixture.componentInstance.tabBody._position).toBe('right-origin-center');
});
});
describe('in RTL direction', () => {
beforeEach(() => {
dir = 'rtl';
fixture = TestBed.createComponent(SimpleTabBodyApp);
});
it('should be right-origin-center position with negative or zero origin', () => {
fixture.componentInstance.position = 0;
fixture.componentInstance.origin = 0;
fixture.detectChanges();
expect(fixture.componentInstance.tabBody._position).toBe('right-origin-center');
});
it('should be left-origin-center position with positive nonzero origin', () => {
fixture.componentInstance.position = 0;
fixture.componentInstance.origin = 1;
fixture.detectChanges();
expect(fixture.componentInstance.tabBody._position).toBe('left-origin-center');
});
});
});
describe('should properly set the position in LTR', () => {
let fixture: ComponentFixture<SimpleTabBodyApp>;
beforeEach(() => {
dir = 'ltr';
fixture = TestBed.createComponent(SimpleTabBodyApp);
fixture.detectChanges();
});
it('to be left position with negative position', () => {
fixture.componentInstance.position = -1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.tabBody._position).toBe('left');
});
it('to be center position with zero position', () => {
fixture.componentInstance.position = 0;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.tabBody._position).toBe('center');
});
it('to be left position with positive position', () => {
fixture.componentInstance.position = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.tabBody._position).toBe('right');
});
});
describe('should properly set the position in RTL', () => {
let fixture: ComponentFixture<SimpleTabBodyApp>;
beforeEach(() => {
dir = 'rtl';
fixture = TestBed.createComponent(SimpleTabBodyApp);
fixture.detectChanges();
});
it('to be right position with negative position', () => {
fixture.componentInstance.position = -1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.tabBody._position).toBe('right');
});
it('to be center position with zero position', () => {
fixture.componentInstance.position = 0;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.tabBody._position).toBe('center');
});
it('to be left position with positive position', () => {
fixture.componentInstance.position = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.tabBody._position).toBe('left');
});
});
it('should update position if direction changed at runtime', () => {
const fixture = TestBed.createComponent(SimpleTabBodyApp);
fixture.componentInstance.position = 1;
fixture.detectChanges();
expect(fixture.componentInstance.tabBody._position).toBe('right');
dirChange.next('rtl');
dir = 'rtl';
fixture.detectChanges();
expect(fixture.componentInstance.tabBody._position).toBe('left');
});
it('should mark the tab body content as a scrollable container', () => {
TestBed.resetTestingModule().configureTestingModule({
imports: [
PortalModule,
MatRippleModule,
NoopAnimationsModule,
ScrollingModule,
SimpleTabBodyApp,
],
});
const fixture = TestBed.createComponent(SimpleTabBodyApp);
const tabBodyContent = fixture.nativeElement.querySelector('.mat-mdc-tab-body-content');
const scrollable = fixture.debugElement.query(By.directive(CdkScrollable));
expect(scrollable).toBeTruthy();
expect(scrollable.nativeElement).toBe(tabBodyContent);
});
});
@Component({
template: `
<ng-template>Tab Body Content</ng-template>
<mat-tab-body [content]="content()" [position]="position" [origin]="origin"></mat-tab-body>
`,
standalone: true,
imports: [PortalModule, MatRippleModule, MatTabBody],
})
class SimpleTabBodyApp implements AfterViewInit {
content = signal<TemplatePortal | undefined>(undefined);
position: number;
origin: number | null;
@ViewChild(MatTabBody) tabBody: MatTabBody;
@ViewChild(TemplateRef) template: TemplateRef<any>;
private readonly _viewContainerRef = inject(ViewContainerRef);
ngAfterViewInit() {
this.content.set(new TemplatePortal(this.template, this._viewContainerRef));
}
}
| {
"end_byte": 7684,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-body.spec.ts"
} |
components/src/material/tabs/_tabs-theme.scss_0_7588 | @use '../core/style/sass-utils';
@use '../core/tokens/m2/mdc/secondary-navigation-tab' as tokens-mdc-secondary-navigation-tab;
@use '../core/tokens/m2/mdc/tab-indicator' as tokens-mdc-tab-indicator;
@use '../core/tokens/m2/mat/tab-header' as tokens-mat-tab-header;
@use '../core/tokens/m2/mat/tab-header-with-background' as tokens-mat-tab-header-with-background;
@use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/typography/typography';
@use '../core/tokens/token-utils';
/// Outputs base theme styles (styles not dependent on the color, typography, or density settings)
/// for the mat-tab.
/// @param {Map} $theme The theme to generate base styles for.
@mixin base($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, base));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mdc-secondary-navigation-tab.$prefix,
tokens-mdc-secondary-navigation-tab.get-unthemable-tokens()
);
@include token-utils.create-token-values(
tokens-mdc-tab-indicator.$prefix,
tokens-mdc-tab-indicator.get-unthemable-tokens()
);
@include token-utils.create-token-values(
tokens-mat-tab-header.$prefix,
tokens-mat-tab-header.get-unthemable-tokens()
);
@include token-utils.create-token-values(
tokens-mat-tab-header-with-background.$prefix,
tokens-mat-tab-header-with-background.get-unthemable-tokens()
);
}
}
}
/// Outputs color theme styles for the mat-tab.
/// @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 tab indicator: 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 {
.mat-mdc-tab-group,
.mat-mdc-tab-nav-bar {
@include _palette-styles($theme, primary);
&.mat-accent {
@include _palette-styles($theme, accent);
}
&.mat-warn {
@include _palette-styles($theme, warn);
}
&.mat-background-primary {
@include _background-styles($theme, primary);
}
&.mat-background-accent {
@include _background-styles($theme, accent);
}
&.mat-background-warn {
@include _background-styles($theme, warn);
}
}
}
}
@mixin _background-styles($theme, $palette-name) {
@include token-utils.create-token-values(
tokens-mat-tab-header-with-background.$prefix,
tokens-mat-tab-header-with-background.get-color-tokens($theme, $palette-name)
);
}
@mixin _palette-styles($theme, $palette-name) {
@include token-utils.create-token-values(
tokens-mdc-secondary-navigation-tab.$prefix,
tokens-mdc-secondary-navigation-tab.get-color-tokens($theme, $palette-name)
);
@include token-utils.create-token-values(
tokens-mdc-tab-indicator.$prefix,
tokens-mdc-tab-indicator.get-color-tokens($theme, $palette-name)
);
@include token-utils.create-token-values(
tokens-mat-tab-header.$prefix,
tokens-mat-tab-header.get-color-tokens($theme, $palette-name)
);
}
/// Outputs typography theme styles for the mat-tab.
/// @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 {
.mat-mdc-tab-header {
@include token-utils.create-token-values(
tokens-mdc-secondary-navigation-tab.$prefix,
tokens-mdc-secondary-navigation-tab.get-typography-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mdc-tab-indicator.$prefix,
tokens-mdc-tab-indicator.get-typography-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-tab-header.$prefix,
tokens-mat-tab-header.get-typography-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-tab-header-with-background.$prefix,
tokens-mat-tab-header-with-background.get-typography-tokens($theme)
);
}
}
}
/// Outputs density theme styles for the mat-tab.
/// @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 {
.mat-mdc-tab-header {
@include token-utils.create-token-values(
tokens-mdc-secondary-navigation-tab.$prefix,
tokens-mdc-secondary-navigation-tab.get-density-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mdc-tab-indicator.$prefix,
tokens-mdc-tab-indicator.get-density-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-tab-header.$prefix,
tokens-mat-tab-header.get-density-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-tab-header-with-background.$prefix,
tokens-mat-tab-header-with-background.get-density-tokens($theme)
);
}
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
$tab-tokens: tokens-mdc-secondary-navigation-tab.get-token-slots();
$tab-indicator-tokens: tokens-mdc-tab-indicator.get-token-slots();
$tab-header-tokens: tokens-mat-tab-header.get-token-slots();
$tab-header-with-background-tokens: tokens-mat-tab-header-with-background.get-token-slots();
@return (
(
namespace: tokens-mdc-secondary-navigation-tab.$prefix,
tokens: $tab-tokens,
),
(
namespace: tokens-mdc-tab-indicator.$prefix,
tokens: $tab-indicator-tokens,
),
(
namespace: tokens-mat-tab-header.$prefix,
tokens: $tab-header-tokens,
),
(
namespace: tokens-mat-tab-header-with-background.$prefix,
tokens: $tab-header-with-background-tokens,
),
);
}
/// 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-tab.
/// @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 tab indicator: primary, secondary,
/// tertiary, or error (If not specified, default primary color will be used).
@mixin theme($theme, $options...) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-tabs') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme), $options...);
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
} | {
"end_byte": 7588,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/_tabs-theme.scss"
} |
components/src/material/tabs/_tabs-theme.scss_7591_8660 | }
}
@mixin _theme-from-tokens($tokens, $options...) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
$mdc-tab-indicator-tokens: token-utils.get-tokens-for(
$tokens,
tokens-mdc-tab-indicator.$prefix,
$options...
);
$mat-tab-header-tokens: token-utils.get-tokens-for(
$tokens,
tokens-mat-tab-header.$prefix,
$options...
);
// Don't pass $options here, because the mdc-tab doesn't have color variants,
// only the mdc-tab-indicator and mat-tab-header do.
$mdc-secondary-navigation-tab-tokens: token-utils.get-tokens-for(
$tokens,
tokens-mdc-secondary-navigation-tab.$prefix
);
@include token-utils.create-token-values(
tokens-mdc-secondary-navigation-tab.$prefix,
$mdc-secondary-navigation-tab-tokens
);
@include token-utils.create-token-values(
tokens-mdc-tab-indicator.$prefix,
$mdc-tab-indicator-tokens
);
@include token-utils.create-token-values(tokens-mat-tab-header.$prefix, $mat-tab-header-tokens);
} | {
"end_byte": 8660,
"start_byte": 7591,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/_tabs-theme.scss"
} |
components/src/material/tabs/tab-content.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 {Directive, InjectionToken, TemplateRef, inject} from '@angular/core';
/**
* Injection token that can be used to reference instances of `MatTabContent`. It serves as
* alternative token to the actual `MatTabContent` class which could cause unnecessary
* retention of the class and its directive metadata.
*/
export const MAT_TAB_CONTENT = new InjectionToken<MatTabContent>('MatTabContent');
/** Decorates the `ng-template` tags and reads out the template from it. */
@Directive({
selector: '[matTabContent]',
providers: [{provide: MAT_TAB_CONTENT, useExisting: MatTabContent}],
})
export class MatTabContent {
template = inject<TemplateRef<any>>(TemplateRef);
constructor(...args: unknown[]);
constructor() {}
}
| {
"end_byte": 940,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-content.ts"
} |
components/src/material/tabs/tabs-animations.ts_0_2246 | /**
* @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 {
AnimationTriggerMetadata,
animate,
state,
style,
transition,
trigger,
} from '@angular/animations';
/**
* Animations used by the Material tabs.
* @docs-private
*/
export const matTabsAnimations: {
readonly translateTab: AnimationTriggerMetadata;
} = {
/** Animation translates a tab along the X axis. */
translateTab: trigger('translateTab', [
// Transitions to `none` instead of 0, because some browsers might blur the content.
state(
'center, void, left-origin-center, right-origin-center',
style({transform: 'none', visibility: 'visible'}),
),
// If the tab is either on the left or right, we additionally add a `min-height` of 1px
// in order to ensure that the element has a height before its state changes. This is
// necessary because Chrome does seem to skip the transition in RTL mode if the element does
// not have a static height and is not rendered. See related issue: #9465
state(
'left',
style({
transform: 'translate3d(-100%, 0, 0)',
minHeight: '1px',
// Normally this is redundant since we detach the content from the DOM, but if the user
// opted into keeping the content in the DOM, we have to hide it so it isn't focusable.
visibility: 'hidden',
}),
),
state(
'right',
style({
transform: 'translate3d(100%, 0, 0)',
minHeight: '1px',
visibility: 'hidden',
}),
),
transition(
'* => left, * => right, left => center, right => center',
animate('{{animationDuration}} cubic-bezier(0.35, 0, 0.25, 1)'),
),
transition('void => left-origin-center', [
style({transform: 'translate3d(-100%, 0, 0)', visibility: 'hidden'}),
animate('{{animationDuration}} cubic-bezier(0.35, 0, 0.25, 1)'),
]),
transition('void => right-origin-center', [
style({transform: 'translate3d(100%, 0, 0)', visibility: 'hidden'}),
animate('{{animationDuration}} cubic-bezier(0.35, 0, 0.25, 1)'),
]),
]),
};
| {
"end_byte": 2246,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tabs-animations.ts"
} |
components/src/material/tabs/tab.ts_0_5518 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ChangeDetectionStrategy,
Component,
ContentChild,
InjectionToken,
Input,
OnChanges,
OnDestroy,
OnInit,
SimpleChanges,
TemplateRef,
ViewChild,
ViewContainerRef,
ViewEncapsulation,
booleanAttribute,
inject,
} from '@angular/core';
import {MatTabContent} from './tab-content';
import {MAT_TAB, MatTabLabel} from './tab-label';
import {TemplatePortal} from '@angular/cdk/portal';
import {Subject} from 'rxjs';
import {_CdkPrivateStyleLoader} from '@angular/cdk/private';
import {_StructuralStylesLoader} from '@angular/material/core';
/**
* Used to provide a tab group to a tab without causing a circular dependency.
* @docs-private
*/
export const MAT_TAB_GROUP = new InjectionToken<any>('MAT_TAB_GROUP');
@Component({
selector: 'mat-tab',
// Note that usually we'd go through a bit more trouble and set up another class so that
// the inlined template of `MatTab` isn't duplicated, however the template is small enough
// that creating the extra class will generate more code than just duplicating the template.
templateUrl: 'tab.html',
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.None,
exportAs: 'matTab',
providers: [{provide: MAT_TAB, useExisting: MatTab}],
host: {
// This element will be rendered on the server in order to support hydration.
// Hide it so it doesn't cause a layout shift when it's removed on the client.
'hidden': '',
},
})
export class MatTab implements OnInit, OnChanges, OnDestroy {
private _viewContainerRef = inject(ViewContainerRef);
_closestTabGroup = inject(MAT_TAB_GROUP, {optional: true});
/** whether the tab is disabled. */
@Input({transform: booleanAttribute})
disabled: boolean = false;
/** Content for the tab label given by `<ng-template mat-tab-label>`. */
@ContentChild(MatTabLabel)
get templateLabel(): MatTabLabel {
return this._templateLabel;
}
set templateLabel(value: MatTabLabel) {
this._setTemplateLabelInput(value);
}
private _templateLabel: MatTabLabel;
/**
* Template provided in the tab content that will be used if present, used to enable lazy-loading
*/
@ContentChild(MatTabContent, {read: TemplateRef, static: true})
// We need an initializer here to avoid a TS error. The value will be set in `ngAfterViewInit`.
private _explicitContent: TemplateRef<any> = undefined!;
/** Template inside the MatTab view that contains an `<ng-content>`. */
@ViewChild(TemplateRef, {static: true}) _implicitContent: TemplateRef<any>;
/** Plain text label for the tab, used when there is no template label. */
@Input('label') textLabel: string = '';
/** Aria label for the tab. */
@Input('aria-label') ariaLabel: string;
/**
* Reference to the element that the tab is labelled by.
* Will be cleared if `aria-label` is set at the same time.
*/
@Input('aria-labelledby') ariaLabelledby: string;
/** Classes to be passed to the tab label inside the mat-tab-header container. */
@Input() labelClass: string | string[];
/** Classes to be passed to the tab mat-tab-body container. */
@Input() bodyClass: string | string[];
/** Portal that will be the hosted content of the tab */
private _contentPortal: TemplatePortal | null = null;
/** @docs-private */
get content(): TemplatePortal | null {
return this._contentPortal;
}
/** Emits whenever the internal state of the tab changes. */
readonly _stateChanges = new Subject<void>();
/**
* The relatively indexed position where 0 represents the center, negative is left, and positive
* represents the right.
*/
position: number | null = null;
/**
* The initial relatively index origin of the tab if it was created and selected after there
* was already a selected tab. Provides context of what position the tab should originate from.
*/
origin: number | null = null;
/**
* Whether the tab is currently active.
*/
isActive = false;
constructor(...args: unknown[]);
constructor() {
inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader);
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.hasOwnProperty('textLabel') || changes.hasOwnProperty('disabled')) {
this._stateChanges.next();
}
}
ngOnDestroy(): void {
this._stateChanges.complete();
}
ngOnInit(): void {
this._contentPortal = new TemplatePortal(
this._explicitContent || this._implicitContent,
this._viewContainerRef,
);
}
/**
* This has been extracted to a util because of TS 4 and VE.
* View Engine doesn't support property rename inheritance.
* TS 4.0 doesn't allow properties to override accessors or vice-versa.
* @docs-private
*/
private _setTemplateLabelInput(value: MatTabLabel | undefined) {
// Only update the label if the query managed to find one. This works around an issue where a
// user may have manually set `templateLabel` during creation mode, which would then get
// clobbered by `undefined` when the query resolves. Also note that we check that the closest
// tab matches the current one so that we don't pick up labels from nested tabs.
if (value && value._closestTab === this) {
this._templateLabel = value;
}
}
}
| {
"end_byte": 5518,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab.ts"
} |
components/src/material/tabs/module.ts_0_894 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {MatCommonModule} from '@angular/material/core';
import {MatTabContent} from './tab-content';
import {MatTabLabel} from './tab-label';
import {MatTab} from './tab';
import {MatTabGroup} from './tab-group';
import {MatTabNav, MatTabNavPanel, MatTabLink} from './tab-nav-bar/tab-nav-bar';
@NgModule({
imports: [
MatCommonModule,
MatTabContent,
MatTabLabel,
MatTab,
MatTabGroup,
MatTabNav,
MatTabNavPanel,
MatTabLink,
],
exports: [
MatCommonModule,
MatTabContent,
MatTabLabel,
MatTab,
MatTabGroup,
MatTabNav,
MatTabNavPanel,
MatTabLink,
],
})
export class MatTabsModule {}
| {
"end_byte": 894,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/module.ts"
} |
components/src/material/tabs/tab-group.scss_0_1046 | @use '../core/style/private';
@use '../core/style/variables';
@use './tabs-common';
@include tabs-common.structural-styles;
.mat-mdc-tab {
@include tabs-common.tab;
// Note that we only want to target direct descendant tabs.
.mat-mdc-tab-group.mat-mdc-tab-group-stretch-tabs > .mat-mdc-tab-header & {
flex-grow: 1;
}
}
.mat-mdc-tab-group {
display: flex;
flex-direction: column;
// Fixes pagination issues inside flex containers (see #23157).
max-width: 100%;
@include tabs-common.paginated-tab-header-with-background('.mat-mdc-tab-header', '.mat-mdc-tab');
&.mat-mdc-tab-group-inverted-header {
flex-direction: column-reverse;
.mdc-tab-indicator__content--underline {
align-self: flex-start;
}
}
}
// The bottom section of the view; contains the tab bodies
.mat-mdc-tab-body-wrapper {
position: relative;
overflow: hidden;
display: flex;
transition: height tabs-common.$mat-tab-animation-duration variables.$ease-in-out-curve-function;
@include private.private-animation-noop();
}
| {
"end_byte": 1046,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-group.scss"
} |
components/src/material/tabs/paginated-tab-header.ts_0_2161 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {FocusKeyManager, FocusableOption} from '@angular/cdk/a11y';
import {Direction, Directionality} from '@angular/cdk/bidi';
import {ENTER, SPACE, hasModifierKey} from '@angular/cdk/keycodes';
import {SharedResizeObserver} from '@angular/cdk/observers/private';
import {Platform, normalizePassiveListenerOptions} from '@angular/cdk/platform';
import {ViewportRuler} from '@angular/cdk/scrolling';
import {
ANIMATION_MODULE_TYPE,
AfterContentChecked,
AfterContentInit,
AfterViewInit,
ChangeDetectorRef,
Directive,
ElementRef,
EventEmitter,
Injector,
Input,
NgZone,
OnDestroy,
Output,
QueryList,
afterNextRender,
booleanAttribute,
inject,
numberAttribute,
} from '@angular/core';
import {
EMPTY,
Observable,
Observer,
Subject,
fromEvent,
merge,
of as observableOf,
timer,
} from 'rxjs';
import {debounceTime, filter, skip, startWith, switchMap, takeUntil} from 'rxjs/operators';
/** Config used to bind passive event listeners */
const passiveEventListenerOptions = normalizePassiveListenerOptions({
passive: true,
}) as EventListenerOptions;
/**
* The directions that scrolling can go in when the header's tabs exceed the header width. 'After'
* will scroll the header towards the end of the tabs list and 'before' will scroll towards the
* beginning of the list.
*/
export type ScrollDirection = 'after' | 'before';
/**
* Amount of milliseconds to wait before starting to scroll the header automatically.
* Set a little conservatively in order to handle fake events dispatched on touch devices.
*/
const HEADER_SCROLL_DELAY = 650;
/**
* Interval in milliseconds at which to scroll the header
* while the user is holding their pointer.
*/
const HEADER_SCROLL_INTERVAL = 100;
/** Item inside a paginated tab header. */
export type MatPaginatedTabHeaderItem = FocusableOption & {elementRef: ElementRef};
/**
* Base class for a tab header that supported pagination.
* @docs-private
*/ | {
"end_byte": 2161,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/paginated-tab-header.ts"
} |
components/src/material/tabs/paginated-tab-header.ts_2162_10974 | @Directive()
export abstract class MatPaginatedTabHeader
implements AfterContentChecked, AfterContentInit, AfterViewInit, OnDestroy
{
protected _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
protected _changeDetectorRef = inject(ChangeDetectorRef);
private _viewportRuler = inject(ViewportRuler);
private _dir = inject(Directionality, {optional: true});
private _ngZone = inject(NgZone);
private _platform = inject(Platform);
_animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true});
abstract _items: QueryList<MatPaginatedTabHeaderItem>;
abstract _inkBar: {hide: () => void; alignToElement: (element: HTMLElement) => void};
abstract _tabListContainer: ElementRef<HTMLElement>;
abstract _tabList: ElementRef<HTMLElement>;
abstract _tabListInner: ElementRef<HTMLElement>;
abstract _nextPaginator: ElementRef<HTMLElement>;
abstract _previousPaginator: ElementRef<HTMLElement>;
/** The distance in pixels that the tab labels should be translated to the left. */
private _scrollDistance = 0;
/** Whether the header should scroll to the selected index after the view has been checked. */
private _selectedIndexChanged = false;
/** Emits when the component is destroyed. */
protected readonly _destroyed = new Subject<void>();
/** Whether the controls for pagination should be displayed */
_showPaginationControls = false;
/** Whether the tab list can be scrolled more towards the end of the tab label list. */
_disableScrollAfter = true;
/** Whether the tab list can be scrolled more towards the beginning of the tab label list. */
_disableScrollBefore = true;
/**
* The number of tab labels that are displayed on the header. When this changes, the header
* should re-evaluate the scroll position.
*/
private _tabLabelCount: number;
/** Whether the scroll distance has changed and should be applied after the view is checked. */
private _scrollDistanceChanged: boolean;
/** Used to manage focus between the tabs. */
private _keyManager: FocusKeyManager<MatPaginatedTabHeaderItem>;
/** Cached text content of the header. */
private _currentTextContent: string;
/** Stream that will stop the automated scrolling. */
private _stopScrolling = new Subject<void>();
/**
* Whether pagination should be disabled. This can be used to avoid unnecessary
* layout recalculations if it's known that pagination won't be required.
*/
@Input({transform: booleanAttribute})
disablePagination: boolean = false;
/** The index of the active tab. */
@Input({transform: numberAttribute})
get selectedIndex(): number {
return this._selectedIndex;
}
set selectedIndex(v: number) {
const value = isNaN(v) ? 0 : v;
if (this._selectedIndex != value) {
this._selectedIndexChanged = true;
this._selectedIndex = value;
if (this._keyManager) {
this._keyManager.updateActiveItem(value);
}
}
}
private _selectedIndex: number = 0;
/** Event emitted when the option is selected. */
@Output() readonly selectFocusedIndex: EventEmitter<number> = new EventEmitter<number>();
/** Event emitted when a label is focused. */
@Output() readonly indexFocused: EventEmitter<number> = new EventEmitter<number>();
private _sharedResizeObserver = inject(SharedResizeObserver);
private _injector = inject(Injector);
constructor(...args: unknown[]);
constructor() {
// Bind the `mouseleave` event on the outside since it doesn't change anything in the view.
this._ngZone.runOutsideAngular(() => {
fromEvent(this._elementRef.nativeElement, 'mouseleave')
.pipe(takeUntil(this._destroyed))
.subscribe(() => this._stopInterval());
});
}
/** Called when the user has selected an item via the keyboard. */
protected abstract _itemSelected(event: KeyboardEvent): void;
ngAfterViewInit() {
// We need to handle these events manually, because we want to bind passive event listeners.
fromEvent(this._previousPaginator.nativeElement, 'touchstart', passiveEventListenerOptions)
.pipe(takeUntil(this._destroyed))
.subscribe(() => {
this._handlePaginatorPress('before');
});
fromEvent(this._nextPaginator.nativeElement, 'touchstart', passiveEventListenerOptions)
.pipe(takeUntil(this._destroyed))
.subscribe(() => {
this._handlePaginatorPress('after');
});
}
ngAfterContentInit() {
const dirChange = this._dir ? this._dir.change : observableOf('ltr');
// We need to debounce resize events because the alignment logic is expensive.
// If someone animates the width of tabs, we don't want to realign on every animation frame.
// Once we haven't seen any more resize events in the last 32ms (~2 animaion frames) we can
// re-align.
const resize = this._sharedResizeObserver
.observe(this._elementRef.nativeElement)
.pipe(debounceTime(32), takeUntil(this._destroyed));
// Note: We do not actually need to watch these events for proper functioning of the tabs,
// the resize events above should capture any viewport resize that we care about. However,
// removing this is fairly breaking for screenshot tests, so we're leaving it here for now.
const viewportResize = this._viewportRuler.change(150).pipe(takeUntil(this._destroyed));
const realign = () => {
this.updatePagination();
this._alignInkBarToSelectedTab();
};
this._keyManager = new FocusKeyManager<MatPaginatedTabHeaderItem>(this._items)
.withHorizontalOrientation(this._getLayoutDirection())
.withHomeAndEnd()
.withWrap()
// Allow focus to land on disabled tabs, as per https://w3c.github.io/aria-practices/#kbd_disabled_controls
.skipPredicate(() => false);
this._keyManager.updateActiveItem(this._selectedIndex);
// Note: We do not need to realign after the first render for proper functioning of the tabs
// the resize events above should fire when we first start observing the element. However,
// removing this is fairly breaking for screenshot tests, so we're leaving it here for now.
afterNextRender(realign, {injector: this._injector});
// On dir change or resize, realign the ink bar and update the orientation of
// the key manager if the direction has changed.
merge(dirChange, viewportResize, resize, this._items.changes, this._itemsResized())
.pipe(takeUntil(this._destroyed))
.subscribe(() => {
// We need to defer this to give the browser some time to recalculate
// the element dimensions. The call has to be wrapped in `NgZone.run`,
// because the viewport change handler runs outside of Angular.
this._ngZone.run(() => {
Promise.resolve().then(() => {
// Clamp the scroll distance, because it can change with the number of tabs.
this._scrollDistance = Math.max(
0,
Math.min(this._getMaxScrollDistance(), this._scrollDistance),
);
realign();
});
});
this._keyManager.withHorizontalOrientation(this._getLayoutDirection());
});
// If there is a change in the focus key manager we need to emit the `indexFocused`
// event in order to provide a public event that notifies about focus changes. Also we realign
// the tabs container by scrolling the new focused tab into the visible section.
this._keyManager.change.subscribe(newFocusIndex => {
this.indexFocused.emit(newFocusIndex);
this._setTabFocus(newFocusIndex);
});
}
/** Sends any changes that could affect the layout of the items. */
private _itemsResized(): Observable<ResizeObserverEntry[]> {
if (typeof ResizeObserver !== 'function') {
return EMPTY;
}
return this._items.changes.pipe(
startWith(this._items),
switchMap(
(tabItems: QueryList<MatPaginatedTabHeaderItem>) =>
new Observable((observer: Observer<ResizeObserverEntry[]>) =>
this._ngZone.runOutsideAngular(() => {
const resizeObserver = new ResizeObserver(entries => observer.next(entries));
tabItems.forEach(item => resizeObserver.observe(item.elementRef.nativeElement));
return () => {
resizeObserver.disconnect();
};
}),
),
),
// Skip the first emit since the resize observer emits when an item
// is observed for new items when the tab is already inserted
skip(1),
// Skip emissions where all the elements are invisible since we don't want
// the header to try and re-render with invalid measurements. See #25574.
filter(entries => entries.some(e => e.contentRect.width > 0 && e.contentRect.height > 0)),
);
} | {
"end_byte": 10974,
"start_byte": 2162,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/paginated-tab-header.ts"
} |
components/src/material/tabs/paginated-tab-header.ts_10978_18582 | ngAfterContentChecked(): void {
// If the number of tab labels have changed, check if scrolling should be enabled
if (this._tabLabelCount != this._items.length) {
this.updatePagination();
this._tabLabelCount = this._items.length;
this._changeDetectorRef.markForCheck();
}
// If the selected index has changed, scroll to the label and check if the scrolling controls
// should be disabled.
if (this._selectedIndexChanged) {
this._scrollToLabel(this._selectedIndex);
this._checkScrollingControls();
this._alignInkBarToSelectedTab();
this._selectedIndexChanged = false;
this._changeDetectorRef.markForCheck();
}
// If the scroll distance has been changed (tab selected, focused, scroll controls activated),
// then translate the header to reflect this.
if (this._scrollDistanceChanged) {
this._updateTabScrollPosition();
this._scrollDistanceChanged = false;
this._changeDetectorRef.markForCheck();
}
}
ngOnDestroy() {
this._keyManager?.destroy();
this._destroyed.next();
this._destroyed.complete();
this._stopScrolling.complete();
}
/** Handles keyboard events on the header. */
_handleKeydown(event: KeyboardEvent) {
// We don't handle any key bindings with a modifier key.
if (hasModifierKey(event)) {
return;
}
switch (event.keyCode) {
case ENTER:
case SPACE:
if (this.focusIndex !== this.selectedIndex) {
const item = this._items.get(this.focusIndex);
if (item && !item.disabled) {
this.selectFocusedIndex.emit(this.focusIndex);
this._itemSelected(event);
}
}
break;
default:
this._keyManager.onKeydown(event);
}
}
/**
* Callback for when the MutationObserver detects that the content has changed.
*/
_onContentChanges() {
const textContent = this._elementRef.nativeElement.textContent;
// We need to diff the text content of the header, because the MutationObserver callback
// will fire even if the text content didn't change which is inefficient and is prone
// to infinite loops if a poorly constructed expression is passed in (see #14249).
if (textContent !== this._currentTextContent) {
this._currentTextContent = textContent || '';
// The content observer runs outside the `NgZone` by default, which
// means that we need to bring the callback back in ourselves.
this._ngZone.run(() => {
this.updatePagination();
this._alignInkBarToSelectedTab();
this._changeDetectorRef.markForCheck();
});
}
}
/**
* Updates the view whether pagination should be enabled or not.
*
* WARNING: Calling this method can be very costly in terms of performance. It should be called
* as infrequently as possible from outside of the Tabs component as it causes a reflow of the
* page.
*/
updatePagination() {
this._checkPaginationEnabled();
this._checkScrollingControls();
this._updateTabScrollPosition();
}
/** Tracks which element has focus; used for keyboard navigation */
get focusIndex(): number {
return this._keyManager ? this._keyManager.activeItemIndex! : 0;
}
/** When the focus index is set, we must manually send focus to the correct label */
set focusIndex(value: number) {
if (!this._isValidIndex(value) || this.focusIndex === value || !this._keyManager) {
return;
}
this._keyManager.setActiveItem(value);
}
/**
* Determines if an index is valid. If the tabs are not ready yet, we assume that the user is
* providing a valid index and return true.
*/
_isValidIndex(index: number): boolean {
return this._items ? !!this._items.toArray()[index] : true;
}
/**
* Sets focus on the HTML element for the label wrapper and scrolls it into the view if
* scrolling is enabled.
*/
_setTabFocus(tabIndex: number) {
if (this._showPaginationControls) {
this._scrollToLabel(tabIndex);
}
if (this._items && this._items.length) {
this._items.toArray()[tabIndex].focus();
// Do not let the browser manage scrolling to focus the element, this will be handled
// by using translation. In LTR, the scroll left should be 0. In RTL, the scroll width
// should be the full width minus the offset width.
const containerEl = this._tabListContainer.nativeElement;
const dir = this._getLayoutDirection();
if (dir == 'ltr') {
containerEl.scrollLeft = 0;
} else {
containerEl.scrollLeft = containerEl.scrollWidth - containerEl.offsetWidth;
}
}
}
/** The layout direction of the containing app. */
_getLayoutDirection(): Direction {
return this._dir && this._dir.value === 'rtl' ? 'rtl' : 'ltr';
}
/** Performs the CSS transformation on the tab list that will cause the list to scroll. */
_updateTabScrollPosition() {
if (this.disablePagination) {
return;
}
const scrollDistance = this.scrollDistance;
const translateX = this._getLayoutDirection() === 'ltr' ? -scrollDistance : scrollDistance;
// Don't use `translate3d` here because we don't want to create a new layer. A new layer
// seems to cause flickering and overflow in Internet Explorer. For example, the ink bar
// and ripples will exceed the boundaries of the visible tab bar.
// See: https://github.com/angular/components/issues/10276
// We round the `transform` here, because transforms with sub-pixel precision cause some
// browsers to blur the content of the element.
this._tabList.nativeElement.style.transform = `translateX(${Math.round(translateX)}px)`;
// Setting the `transform` on IE will change the scroll offset of the parent, causing the
// position to be thrown off in some cases. We have to reset it ourselves to ensure that
// it doesn't get thrown off. Note that we scope it only to IE and Edge, because messing
// with the scroll position throws off Chrome 71+ in RTL mode (see #14689).
if (this._platform.TRIDENT || this._platform.EDGE) {
this._tabListContainer.nativeElement.scrollLeft = 0;
}
}
/** Sets the distance in pixels that the tab header should be transformed in the X-axis. */
get scrollDistance(): number {
return this._scrollDistance;
}
set scrollDistance(value: number) {
this._scrollTo(value);
}
/**
* Moves the tab list in the 'before' or 'after' direction (towards the beginning of the list or
* the end of the list, respectively). The distance to scroll is computed to be a third of the
* length of the tab list view window.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_scrollHeader(direction: ScrollDirection) {
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
// Move the scroll distance one-third the length of the tab list's viewport.
const scrollAmount = ((direction == 'before' ? -1 : 1) * viewLength) / 3;
return this._scrollTo(this._scrollDistance + scrollAmount);
}
/** Handles click events on the pagination arrows. */
_handlePaginatorClick(direction: ScrollDirection) {
this._stopInterval();
this._scrollHeader(direction);
}
/**
* Moves the tab list such that the desired tab label (marked by index) is moved into view.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/ | {
"end_byte": 18582,
"start_byte": 10978,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/paginated-tab-header.ts"
} |
components/src/material/tabs/paginated-tab-header.ts_18585_25553 | _scrollToLabel(labelIndex: number) {
if (this.disablePagination) {
return;
}
const selectedLabel = this._items ? this._items.toArray()[labelIndex] : null;
if (!selectedLabel) {
return;
}
// The view length is the visible width of the tab labels.
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
const {offsetLeft, offsetWidth} = selectedLabel.elementRef.nativeElement;
let labelBeforePos: number, labelAfterPos: number;
if (this._getLayoutDirection() == 'ltr') {
labelBeforePos = offsetLeft;
labelAfterPos = labelBeforePos + offsetWidth;
} else {
labelAfterPos = this._tabListInner.nativeElement.offsetWidth - offsetLeft;
labelBeforePos = labelAfterPos - offsetWidth;
}
const beforeVisiblePos = this.scrollDistance;
const afterVisiblePos = this.scrollDistance + viewLength;
if (labelBeforePos < beforeVisiblePos) {
// Scroll header to move label to the before direction
this.scrollDistance -= beforeVisiblePos - labelBeforePos;
} else if (labelAfterPos > afterVisiblePos) {
// Scroll header to move label to the after direction
this.scrollDistance += Math.min(
labelAfterPos - afterVisiblePos,
labelBeforePos - beforeVisiblePos,
);
}
}
/**
* Evaluate whether the pagination controls should be displayed. If the scroll width of the
* tab list is wider than the size of the header container, then the pagination controls should
* be shown.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_checkPaginationEnabled() {
if (this.disablePagination) {
this._showPaginationControls = false;
} else {
const scrollWidth = this._tabListInner.nativeElement.scrollWidth;
const containerWidth = this._elementRef.nativeElement.offsetWidth;
// Usually checking that the scroll width is greater than the container width should be
// enough, but on Safari at specific widths the browser ends up rounding up when there's
// no pagination and rounding down once the pagination is added. This can throw the component
// into an infinite loop where the pagination shows up and disappears constantly. We work
// around it by adding a threshold to the calculation. From manual testing the threshold
// can be lowered to 2px and still resolve the issue, but we set a higher one to be safe.
// This shouldn't cause any content to be clipped, because tabs have a 24px horizontal
// padding. See b/316395154 for more information.
const isEnabled = scrollWidth - containerWidth >= 5;
if (!isEnabled) {
this.scrollDistance = 0;
}
if (isEnabled !== this._showPaginationControls) {
this._showPaginationControls = isEnabled;
this._changeDetectorRef.markForCheck();
}
}
}
/**
* Evaluate whether the before and after controls should be enabled or disabled.
* If the header is at the beginning of the list (scroll distance is equal to 0) then disable the
* before button. If the header is at the end of the list (scroll distance is equal to the
* maximum distance we can scroll), then disable the after button.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_checkScrollingControls() {
if (this.disablePagination) {
this._disableScrollAfter = this._disableScrollBefore = true;
} else {
// Check if the pagination arrows should be activated.
this._disableScrollBefore = this.scrollDistance == 0;
this._disableScrollAfter = this.scrollDistance == this._getMaxScrollDistance();
this._changeDetectorRef.markForCheck();
}
}
/**
* Determines what is the maximum length in pixels that can be set for the scroll distance. This
* is equal to the difference in width between the tab list container and tab header container.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
*/
_getMaxScrollDistance(): number {
const lengthOfTabList = this._tabListInner.nativeElement.scrollWidth;
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
return lengthOfTabList - viewLength || 0;
}
/** Tells the ink-bar to align itself to the current label wrapper */
_alignInkBarToSelectedTab(): void {
const selectedItem =
this._items && this._items.length ? this._items.toArray()[this.selectedIndex] : null;
const selectedLabelWrapper = selectedItem ? selectedItem.elementRef.nativeElement : null;
if (selectedLabelWrapper) {
this._inkBar.alignToElement(selectedLabelWrapper);
} else {
this._inkBar.hide();
}
}
/** Stops the currently-running paginator interval. */
_stopInterval() {
this._stopScrolling.next();
}
/**
* Handles the user pressing down on one of the paginators.
* Starts scrolling the header after a certain amount of time.
* @param direction In which direction the paginator should be scrolled.
*/
_handlePaginatorPress(direction: ScrollDirection, mouseEvent?: MouseEvent) {
// Don't start auto scrolling for right mouse button clicks. Note that we shouldn't have to
// null check the `button`, but we do it so we don't break tests that use fake events.
if (mouseEvent && mouseEvent.button != null && mouseEvent.button !== 0) {
return;
}
// Avoid overlapping timers.
this._stopInterval();
// Start a timer after the delay and keep firing based on the interval.
timer(HEADER_SCROLL_DELAY, HEADER_SCROLL_INTERVAL)
// Keep the timer going until something tells it to stop or the component is destroyed.
.pipe(takeUntil(merge(this._stopScrolling, this._destroyed)))
.subscribe(() => {
const {maxScrollDistance, distance} = this._scrollHeader(direction);
// Stop the timer if we've reached the start or the end.
if (distance === 0 || distance >= maxScrollDistance) {
this._stopInterval();
}
});
}
/**
* Scrolls the header to a given position.
* @param position Position to which to scroll.
* @returns Information on the current scroll distance and the maximum.
*/
private _scrollTo(position: number) {
if (this.disablePagination) {
return {maxScrollDistance: 0, distance: 0};
}
const maxScrollDistance = this._getMaxScrollDistance();
this._scrollDistance = Math.max(0, Math.min(maxScrollDistance, position));
// Mark that the scroll distance has changed so that after the view is checked, the CSS
// transformation can move the header.
this._scrollDistanceChanged = true;
this._checkScrollingControls();
return {maxScrollDistance, distance: this._scrollDistance};
}
} | {
"end_byte": 25553,
"start_byte": 18585,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/paginated-tab-header.ts"
} |
components/src/material/tabs/public-api.ts_0_1135 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './module';
export {ScrollDirection, MatPaginatedTabHeader} from './paginated-tab-header';
export {
MatTabBodyPortal,
MatTabBody,
MatTabBodyPositionState,
MatTabBodyOriginState,
} from './tab-body';
export {MatTabsConfig, MAT_TABS_CONFIG} from './tab-config';
export {MatTabContent, MAT_TAB_CONTENT} from './tab-content';
export {MatTabLabel, MAT_TAB, MAT_TAB_LABEL} from './tab-label';
export {MatTab, MAT_TAB_GROUP} from './tab';
export {
MatInkBar,
_MatInkBarPositioner,
_MAT_INK_BAR_POSITIONER_FACTORY,
_MAT_INK_BAR_POSITIONER,
} from './ink-bar';
export {MatTabHeader} from './tab-header';
export {
MatTabGroup,
MatTabChangeEvent,
MatTabGroupBaseHeader,
MatTabHeaderPosition,
} from './tab-group';
export {MatTabNav, MatTabNavPanel, MatTabLink} from './tab-nav-bar/tab-nav-bar';
export {matTabsAnimations} from './tabs-animations';
export {MatTabLabelWrapper} from './tab-label-wrapper';
| {
"end_byte": 1135,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/public-api.ts"
} |
components/src/material/tabs/tab-header.ts_0_2712 | /**
* @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 {
AfterContentChecked,
AfterContentInit,
AfterViewInit,
ChangeDetectionStrategy,
Component,
ContentChildren,
ElementRef,
Input,
OnDestroy,
QueryList,
ViewChild,
ViewEncapsulation,
booleanAttribute,
} from '@angular/core';
import {MatTabLabelWrapper} from './tab-label-wrapper';
import {MatInkBar} from './ink-bar';
import {MatPaginatedTabHeader} from './paginated-tab-header';
import {CdkObserveContent} from '@angular/cdk/observers';
import {MatRipple} from '@angular/material/core';
/**
* The header of the tab group which displays a list of all the tabs in the tab group. Includes
* an ink bar that follows the currently selected tab. When the tabs list's width exceeds the
* width of the header container, then arrows will be displayed to allow the user to scroll
* left and right across the header.
* @docs-private
*/
@Component({
selector: 'mat-tab-header',
templateUrl: 'tab-header.html',
styleUrl: 'tab-header.css',
encapsulation: ViewEncapsulation.None,
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
host: {
'class': 'mat-mdc-tab-header',
'[class.mat-mdc-tab-header-pagination-controls-enabled]': '_showPaginationControls',
'[class.mat-mdc-tab-header-rtl]': "_getLayoutDirection() == 'rtl'",
},
imports: [MatRipple, CdkObserveContent],
})
export class MatTabHeader
extends MatPaginatedTabHeader
implements AfterContentChecked, AfterContentInit, AfterViewInit, OnDestroy
{
@ContentChildren(MatTabLabelWrapper, {descendants: false}) _items: QueryList<MatTabLabelWrapper>;
@ViewChild('tabListContainer', {static: true}) _tabListContainer: ElementRef;
@ViewChild('tabList', {static: true}) _tabList: ElementRef;
@ViewChild('tabListInner', {static: true}) _tabListInner: ElementRef;
@ViewChild('nextPaginator') _nextPaginator: ElementRef<HTMLElement>;
@ViewChild('previousPaginator') _previousPaginator: ElementRef<HTMLElement>;
_inkBar: MatInkBar;
/** Aria label of the header. */
@Input('aria-label') ariaLabel: string;
/** Sets the `aria-labelledby` of the header. */
@Input('aria-labelledby') ariaLabelledby: string;
/** Whether the ripple effect is disabled or not. */
@Input({transform: booleanAttribute})
disableRipple: boolean = false;
override ngAfterContentInit() {
this._inkBar = new MatInkBar(this._items);
super.ngAfterContentInit();
}
protected _itemSelected(event: KeyboardEvent) {
event.preventDefault();
}
}
| {
"end_byte": 2712,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-header.ts"
} |
components/src/material/tabs/tab-config.ts_0_1695 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {InjectionToken} from '@angular/core';
/** Object that can be used to configure the default options for the tabs module. */
export interface MatTabsConfig {
/** Duration for the tab animation. Must be a valid CSS value (e.g. 600ms). */
animationDuration?: string;
/**
* Whether pagination should be disabled. This can be used to avoid unnecessary
* layout recalculations if it's known that pagination won't be required.
*/
disablePagination?: boolean;
/**
* Whether the ink bar should fit its width to the size of the tab label content.
* This only applies to the MDC-based tabs.
*/
fitInkBarToContent?: boolean;
/** Whether the tab group should grow to the size of the active tab. */
dynamicHeight?: boolean;
/** `tabindex` to be set on the inner element that wraps the tab content. */
contentTabIndex?: number;
/**
* By default tabs remove their content from the DOM while it's off-screen.
* Setting this to `true` will keep it in the DOM which will prevent elements
* like iframes and videos from reloading next time it comes back into the view.
*/
preserveContent?: boolean;
/** Whether tabs should be stretched to fill the header. */
stretchTabs?: boolean;
/** Alignment for the tabs label. */
alignTabs?: 'start' | 'center' | 'end';
}
/** Injection token that can be used to provide the default options the tabs module. */
export const MAT_TABS_CONFIG = new InjectionToken<MatTabsConfig>('MAT_TABS_CONFIG');
| {
"end_byte": 1695,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-config.ts"
} |
components/src/material/tabs/tab-group.html_0_3526 | <mat-tab-header #tabHeader
[selectedIndex]="selectedIndex || 0"
[disableRipple]="disableRipple"
[disablePagination]="disablePagination"
[aria-label]="ariaLabel"
[aria-labelledby]="ariaLabelledby"
(indexFocused)="_focusChanged($event)"
(selectFocusedIndex)="selectedIndex = $event">
@for (tab of _tabs; track tab; let i = $index) {
<div class="mdc-tab mat-mdc-tab mat-focus-indicator"
#tabNode
role="tab"
matTabLabelWrapper
cdkMonitorElementFocus
[id]="_getTabLabelId(i)"
[attr.tabIndex]="_getTabIndex(i)"
[attr.aria-posinset]="i + 1"
[attr.aria-setsize]="_tabs.length"
[attr.aria-controls]="_getTabContentId(i)"
[attr.aria-selected]="selectedIndex === i"
[attr.aria-label]="tab.ariaLabel || null"
[attr.aria-labelledby]="(!tab.ariaLabel && tab.ariaLabelledby) ? tab.ariaLabelledby : null"
[class.mdc-tab--active]="selectedIndex === i"
[class]="tab.labelClass"
[disabled]="tab.disabled"
[fitInkBarToContent]="fitInkBarToContent"
(click)="_handleClick(tab, tabHeader, i)"
(cdkFocusChange)="_tabFocusChanged($event, i)">
<span class="mdc-tab__ripple"></span>
<!-- Needs to be a separate element, because we can't put
`overflow: hidden` on tab due to the ink bar. -->
<div
class="mat-mdc-tab-ripple"
mat-ripple
[matRippleTrigger]="tabNode"
[matRippleDisabled]="tab.disabled || disableRipple"></div>
<span class="mdc-tab__content">
<span class="mdc-tab__text-label">
<!--
If there is a label template, use it, otherwise fall back to the text label.
Note that we don't have indentation around the text label, because it adds
whitespace around the text which breaks some internal tests.
-->
@if (tab.templateLabel) {
<ng-template [cdkPortalOutlet]="tab.templateLabel"></ng-template>
} @else {{{tab.textLabel}}}
</span>
</span>
</div>
}
</mat-tab-header>
<!--
We need to project the content somewhere to avoid hydration errors. Some observations:
1. This is only necessary on the server.
2. We get a hydration error if there aren't any nodes after the `ng-content`.
3. We get a hydration error if `ng-content` is wrapped in another element.
-->
@if (_isServer) {
<ng-content/>
}
<div
class="mat-mdc-tab-body-wrapper"
[class._mat-animation-noopable]="_animationMode === 'NoopAnimations'"
#tabBodyWrapper>
@for (tab of _tabs; track tab; let i = $index) {
<mat-tab-body role="tabpanel"
[id]="_getTabContentId(i)"
[attr.tabindex]="(contentTabIndex != null && selectedIndex === i) ? contentTabIndex : null"
[attr.aria-labelledby]="_getTabLabelId(i)"
[attr.aria-hidden]="selectedIndex !== i"
[class.mat-mdc-tab-body-active]="selectedIndex === i"
[class]="tab.bodyClass"
[content]="tab.content!"
[position]="tab.position!"
[origin]="tab.origin"
[animationDuration]="animationDuration"
[preserveContent]="preserveContent"
(_onCentered)="_removeTabBodyWrapperHeight()"
(_onCentering)="_setTabBodyWrapperHeight($event)">
</mat-tab-body>
}
</div>
| {
"end_byte": 3526,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-group.html"
} |
components/src/material/tabs/README.md_0_95 | Please see the official documentation at https://material.angular.io/components/component/tabs
| {
"end_byte": 95,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/README.md"
} |
components/src/material/tabs/tab-header.html_0_1618 | <!--
Note that this intentionally uses a `div` instead of a `button`, because it's not part of
the regular tabs flow and is only here to support mouse users. It should also not be focusable.
-->
<div class="mat-mdc-tab-header-pagination mat-mdc-tab-header-pagination-before"
#previousPaginator
mat-ripple
[matRippleDisabled]="_disableScrollBefore || disableRipple"
[class.mat-mdc-tab-header-pagination-disabled]="_disableScrollBefore"
(click)="_handlePaginatorClick('before')"
(mousedown)="_handlePaginatorPress('before', $event)"
(touchend)="_stopInterval()">
<div class="mat-mdc-tab-header-pagination-chevron"></div>
</div>
<div
class="mat-mdc-tab-label-container"
#tabListContainer
(keydown)="_handleKeydown($event)"
[class._mat-animation-noopable]="_animationMode === 'NoopAnimations'">
<div
#tabList
class="mat-mdc-tab-list"
role="tablist"
[attr.aria-label]="ariaLabel || null"
[attr.aria-labelledby]="ariaLabelledby || null"
(cdkObserveContent)="_onContentChanges()">
<div class="mat-mdc-tab-labels" #tabListInner>
<ng-content></ng-content>
</div>
</div>
</div>
<div class="mat-mdc-tab-header-pagination mat-mdc-tab-header-pagination-after"
#nextPaginator
mat-ripple
[matRippleDisabled]="_disableScrollAfter || disableRipple"
[class.mat-mdc-tab-header-pagination-disabled]="_disableScrollAfter"
(mousedown)="_handlePaginatorPress('after', $event)"
(click)="_handlePaginatorClick('after')"
(touchend)="_stopInterval()">
<div class="mat-mdc-tab-header-pagination-chevron"></div>
</div>
| {
"end_byte": 1618,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-header.html"
} |
components/src/material/tabs/tabs.md_0_5541 | Angular Material tabs organize content into separate views where only one view can be
visible at a time. Each tab's label is shown in the tab header and the active
tab's label is designated with the animated ink bar. When the list of tab labels exceeds the width
of the header, pagination controls appear to let the user scroll left and right across the labels.
The active tab may be set using the `selectedIndex` input or when the user selects one of the
tab labels in the header.
<!-- example(tab-group-basic) -->
### Events
The `selectedTabChange` output event is emitted when the active tab changes.
The `focusChange` output event is emitted when the user puts focus on any of the tab labels in
the header, usually through keyboard navigation.
### Labels
If a tab's label is only text then the simple tab-group API can be used.
<!-- example({"example": "tab-group-basic",
"file": "tab-group-basic-example.html"}) -->
For more complex labels, add a template with the `mat-tab-label` directive inside the `mat-tab`.
<!-- example({"example": "tab-group-custom-label",
"file": "tab-group-custom-label-example.html",
"region": "label-directive"}) -->
### Dynamic Height
By default, the tab group will not change its height to the height of the currently active tab. To
change this, set the `dynamicHeight` input to true. The tab body will animate its height according
to the height of the active tab.
<!-- example({"example": "tab-group-dynamic-height",
"file": "tab-group-dynamic-height-example.html",
"region": "dynamic-height"}) -->
### Tabs and navigation
While `<mat-tab-group>` is used to switch between views within a single route, `<nav mat-tab-nav-bar>`
provides a tab-like UI for navigating between routes.
<!-- example({"example": "tab-nav-bar-basic",
"file": "tab-nav-bar-basic-example.html",
"region": "mat-tab-nav"}) -->
The `mat-tab-nav-bar` is not tied to any particular router; it works with normal `<a>` elements and
uses the `active` property to determine which tab is currently active. The corresponding
`<router-outlet>` must be wrapped in an `<mat-tab-nav-panel>` component and should typically be
placed relatively close to the `mat-tab-nav-bar` (see [Accessibility](#accessibility)).
### Lazy Loading
By default, the tab contents are eagerly loaded. Eagerly loaded tabs
will initialize the child components but not inject them into the DOM
until the tab is activated.
If the tab contains several complex child components or the tab's contents
rely on DOM calculations during initialization, it is advised
to lazy load the tab's content.
Tab contents can be lazy loaded by declaring the body in a `ng-template`
with the `matTabContent` attribute.
<!-- example({"example": "tab-group-lazy-loaded",
"file": "tab-group-lazy-loaded-example.html",
"region": "mat-tab-content"}) -->
### Label alignment
If you want to align the tab labels in the center or towards the end of the container, you can
do so using the `[mat-align-tabs]` attribute.
<!-- example({"example": "tab-group-align",
"file": "tab-group-align-example.html",
"region": "align-start"}) -->
### Controlling the tab animation
You can control the duration of the tabs' animation using the `animationDuration` input. If you
want to disable the animation completely, you can do so by setting the properties to `0ms`. The
duration can be configured globally using the `MAT_TABS_CONFIG` injection token.
<!-- example({"example": "tab-group-animations",
"file": "tab-group-animations-example.html",
"region": "slow-animation-duration"}) -->
### Keeping the tab content inside the DOM while it's off-screen
By default the `<mat-tab-group>` will remove the content of off-screen tabs from the DOM until they
come into the view. This is optimal for most cases since it keeps the DOM size smaller, but it
isn't great for others like when a tab has an `<audio>` or `<video>` element, because the content
will be re-initialized whenever the user navigates to the tab. If you want to keep the content of
off-screen tabs in the DOM, you can set the `preserveContent` input to `true`.
<!-- example(tab-group-preserve-content) -->
### Accessibility
`MatTabGroup` and `MatTabNavBar` both implement the
[ARIA Tabs design pattern](https://www.w3.org/TR/wai-aria-practices-1.1/#tabpanel). Both components
compose `tablist`, `tab`, and `tabpanel` elements with handling for keyboard inputs and focus
management.
When using `MatTabNavBar`, you should place the `<mat-tab-nav-panel>` component relatively close to
if not immediately adjacent to the `<nav mat-tab-nav-bar>` component so that it's easy for screen
reader users to identify the association.
#### Labels
Always provide an accessible label via `aria-label` or `aria-describedby` for tabs without
descriptive text content.
When using `MatTabNavGroup`, always specify a label for the `<nav>` element.
#### Keyboard interaction
`MatTabGroup` and `MatTabNavBar` both implement the following keyboard interactions:
| Shortcut | Action |
|----------------------|----------------------------|
| `LEFT_ARROW` | Move focus to previous tab |
| `RIGHT_ARROW` | Move focus to next tab |
| `HOME` | Move focus to first tab |
| `END` | Move focus to last tab |
| `SPACE` or `ENTER` | Switch to focused tab |
| {
"end_byte": 5541,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tabs.md"
} |
components/src/material/tabs/tab-body.ts_0_8490 | /**
* @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 {AnimationEvent} from '@angular/animations';
import {Direction, Directionality} from '@angular/cdk/bidi';
import {CdkPortalOutlet, TemplatePortal} from '@angular/cdk/portal';
import {CdkScrollable} from '@angular/cdk/scrolling';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
Directive,
ElementRef,
EventEmitter,
Input,
OnDestroy,
OnInit,
Output,
ViewChild,
ViewEncapsulation,
inject,
} from '@angular/core';
import {Subject, Subscription} from 'rxjs';
import {startWith} from 'rxjs/operators';
import {matTabsAnimations} from './tabs-animations';
/**
* The portal host directive for the contents of the tab.
* @docs-private
*/
@Directive({
selector: '[matTabBodyHost]',
})
export class MatTabBodyPortal extends CdkPortalOutlet implements OnInit, OnDestroy {
private _host = inject(MatTabBody);
/** Subscription to events for when the tab body begins centering. */
private _centeringSub = Subscription.EMPTY;
/** Subscription to events for when the tab body finishes leaving from center position. */
private _leavingSub = Subscription.EMPTY;
constructor(...args: unknown[]);
constructor() {
super();
}
/** Set initial visibility or set up subscription for changing visibility. */
override ngOnInit(): void {
super.ngOnInit();
this._centeringSub = this._host._beforeCentering
.pipe(startWith(this._host._isCenterPosition(this._host._position)))
.subscribe((isCentering: boolean) => {
if (this._host._content && isCentering && !this.hasAttached()) {
this.attach(this._host._content);
}
});
this._leavingSub = this._host._afterLeavingCenter.subscribe(() => {
if (!this._host.preserveContent) {
this.detach();
}
});
}
/** Clean up centering subscription. */
override ngOnDestroy(): void {
super.ngOnDestroy();
this._centeringSub.unsubscribe();
this._leavingSub.unsubscribe();
}
}
/**
* These position states are used internally as animation states for the tab body. Setting the
* position state to left, right, or center will transition the tab body from its current
* position to its respective state. If there is not current position (void, in the case of a new
* tab body), then there will be no transition animation to its state.
*
* In the case of a new tab body that should immediately be centered with an animating transition,
* then left-origin-center or right-origin-center can be used, which will use left or right as its
* pseudo-prior state.
*/
export type MatTabBodyPositionState =
| 'left'
| 'center'
| 'right'
| 'left-origin-center'
| 'right-origin-center';
/**
* Wrapper for the contents of a tab.
* @docs-private
*/
@Component({
selector: 'mat-tab-body',
templateUrl: 'tab-body.html',
styleUrl: 'tab-body.css',
encapsulation: ViewEncapsulation.None,
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
animations: [matTabsAnimations.translateTab],
host: {
'class': 'mat-mdc-tab-body',
},
imports: [MatTabBodyPortal, CdkScrollable],
})
export class MatTabBody implements OnInit, OnDestroy {
private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private _dir = inject(Directionality, {optional: true});
/** Current position of the tab-body in the tab-group. Zero means that the tab is visible. */
private _positionIndex: number;
/** Subscription to the directionality change observable. */
private _dirChangeSubscription = Subscription.EMPTY;
/** Tab body position state. Used by the animation trigger for the current state. */
_position: MatTabBodyPositionState;
/** Emits when an animation on the tab is complete. */
readonly _translateTabComplete = new Subject<AnimationEvent>();
/** Event emitted when the tab begins to animate towards the center as the active tab. */
@Output() readonly _onCentering: EventEmitter<number> = new EventEmitter<number>();
/** Event emitted before the centering of the tab begins. */
@Output() readonly _beforeCentering: EventEmitter<boolean> = new EventEmitter<boolean>();
/** Event emitted before the centering of the tab begins. */
@Output() readonly _afterLeavingCenter: EventEmitter<void> = new EventEmitter<void>();
/** Event emitted when the tab completes its animation towards the center. */
@Output() readonly _onCentered: EventEmitter<void> = new EventEmitter<void>(true);
/** The portal host inside of this container into which the tab body content will be loaded. */
@ViewChild(CdkPortalOutlet) _portalHost: CdkPortalOutlet;
/** The tab body content to display. */
@Input('content') _content: TemplatePortal;
/** Position that will be used when the tab is immediately becoming visible after creation. */
@Input() origin: number | null;
// Note that the default value will always be overwritten by `MatTabBody`, but we need one
// anyway to prevent the animations module from throwing an error if the body is used on its own.
/** Duration for the tab's animation. */
@Input() animationDuration: string = '500ms';
/** Whether the tab's content should be kept in the DOM while it's off-screen. */
@Input() preserveContent: boolean = false;
/** The shifted index position of the tab body, where zero represents the active center tab. */
@Input()
set position(position: number) {
this._positionIndex = position;
this._computePositionAnimationState();
}
constructor(...args: unknown[]);
constructor() {
if (this._dir) {
const changeDetectorRef = inject(ChangeDetectorRef);
this._dirChangeSubscription = this._dir.change.subscribe((dir: Direction) => {
this._computePositionAnimationState(dir);
changeDetectorRef.markForCheck();
});
}
this._translateTabComplete.subscribe(event => {
// If the transition to the center is complete, emit an event.
if (this._isCenterPosition(event.toState) && this._isCenterPosition(this._position)) {
this._onCentered.emit();
}
if (this._isCenterPosition(event.fromState) && !this._isCenterPosition(this._position)) {
this._afterLeavingCenter.emit();
}
});
}
/**
* After initialized, check if the content is centered and has an origin. If so, set the
* special position states that transition the tab from the left or right before centering.
*/
ngOnInit() {
if (this._position == 'center' && this.origin != null) {
this._position = this._computePositionFromOrigin(this.origin);
}
}
ngOnDestroy() {
this._dirChangeSubscription.unsubscribe();
this._translateTabComplete.complete();
}
_onTranslateTabStarted(event: AnimationEvent): void {
const isCentering = this._isCenterPosition(event.toState);
this._beforeCentering.emit(isCentering);
if (isCentering) {
this._onCentering.emit(this._elementRef.nativeElement.clientHeight);
}
}
/** The text direction of the containing app. */
_getLayoutDirection(): Direction {
return this._dir && this._dir.value === 'rtl' ? 'rtl' : 'ltr';
}
/** Whether the provided position state is considered center, regardless of origin. */
_isCenterPosition(position: MatTabBodyPositionState | string): boolean {
return (
position == 'center' || position == 'left-origin-center' || position == 'right-origin-center'
);
}
/** Computes the position state that will be used for the tab-body animation trigger. */
private _computePositionAnimationState(dir: Direction = this._getLayoutDirection()) {
if (this._positionIndex < 0) {
this._position = dir == 'ltr' ? 'left' : 'right';
} else if (this._positionIndex > 0) {
this._position = dir == 'ltr' ? 'right' : 'left';
} else {
this._position = 'center';
}
}
/**
* Computes the position state based on the specified origin position. This is used if the
* tab is becoming visible immediately after creation.
*/
private _computePositionFromOrigin(origin: number): MatTabBodyPositionState {
const dir = this._getLayoutDirection();
if ((dir == 'ltr' && origin <= 0) || (dir == 'rtl' && origin > 0)) {
return 'left-origin-center';
}
return 'right-origin-center';
}
} | {
"end_byte": 8490,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-body.ts"
} |
components/src/material/tabs/tab-body.ts_8492_8921 | /**
* The origin state is an internally used state that is set on a new tab body indicating if it
* began to the left or right of the prior selected index. For example, if the selected index was
* set to 1, and a new tab is created and selected at index 2, then the tab body would have an
* origin of right because its index was greater than the prior selected index.
*/
export type MatTabBodyOriginState = 'left' | 'right'; | {
"end_byte": 8921,
"start_byte": 8492,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-body.ts"
} |
components/src/material/tabs/tab-label-wrapper.ts_0_1051 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Directive, ElementRef, Input, booleanAttribute, inject} from '@angular/core';
import {InkBarItem} from './ink-bar';
/**
* Used in the `mat-tab-group` view to display tab labels.
* @docs-private
*/
@Directive({
selector: '[matTabLabelWrapper]',
host: {
'[class.mat-mdc-tab-disabled]': 'disabled',
'[attr.aria-disabled]': '!!disabled',
},
})
export class MatTabLabelWrapper extends InkBarItem {
elementRef = inject(ElementRef);
/** Whether the tab is disabled. */
@Input({transform: booleanAttribute})
disabled: boolean = false;
/** Sets focus on the wrapper element */
focus(): void {
this.elementRef.nativeElement.focus();
}
getOffsetLeft(): number {
return this.elementRef.nativeElement.offsetLeft;
}
getOffsetWidth(): number {
return this.elementRef.nativeElement.offsetWidth;
}
}
| {
"end_byte": 1051,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-label-wrapper.ts"
} |
components/src/material/tabs/_tabs-common.scss_0_4367 | @use '../core/style/vendor-prefixes';
@use '../core/tokens/m2/mdc/tab-indicator' as tokens-mdc-tab-indicator;
@use '../core/tokens/m2/mdc/secondary-navigation-tab' as tokens-mdc-secondary-navigation-tab;
@use '../core/tokens/m2/mat/tab-header' as tokens-mat-tab-header;
@use '../core/tokens/m2/mat/tab-header-with-background' as tokens-mat-tab-header-with-background;
@use '../core/tokens/token-utils';
$mat-tab-animation-duration: 500ms !default;
// Combines the various structural styles we need for the tab group and tab nav bar.
@mixin structural-styles {
.mdc-tab {
min-width: 90px;
padding: 0 24px;
display: flex;
flex: 1 0 auto;
justify-content: center;
box-sizing: border-box;
border: none;
outline: none;
text-align: center;
white-space: nowrap;
cursor: pointer;
z-index: 1;
}
.mdc-tab__content {
display: flex;
align-items: center;
justify-content: center;
height: inherit;
pointer-events: none;
}
.mdc-tab__text-label {
transition: 150ms color linear;
display: inline-block;
line-height: 1;
z-index: 2;
}
.mdc-tab--active .mdc-tab__text-label {
transition-delay: 100ms;
}
._mat-animation-noopable .mdc-tab__text-label {
transition: none;
}
.mdc-tab-indicator {
display: flex;
position: absolute;
top: 0;
left: 0;
justify-content: center;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 1;
}
.mdc-tab-indicator__content {
transition: var(--mat-tab-animation-duration, 250ms) transform cubic-bezier(0.4, 0, 0.2, 1);
transform-origin: left;
opacity: 0;
}
.mdc-tab-indicator__content--underline {
align-self: flex-end;
box-sizing: border-box;
width: 100%;
border-top-style: solid;
}
.mdc-tab-indicator--active .mdc-tab-indicator__content {
opacity: 1;
}
._mat-animation-noopable, .mdc-tab-indicator--no-transition {
.mdc-tab-indicator__content {
transition: none;
}
}
.mat-mdc-tab-ripple.mat-mdc-tab-ripple {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
pointer-events: none;
}
}
@mixin tab {
-webkit-tap-highlight-color: transparent;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-decoration: none;
// Tabs might be `button` elements so we have to reset the user agent styling.
background: none;
@include token-utils.use-tokens(
tokens-mdc-secondary-navigation-tab.$prefix,
tokens-mdc-secondary-navigation-tab.get-token-slots()
) {
@include token-utils.create-token-slot(height, container-height);
}
@include token-utils.use-tokens(
tokens-mat-tab-header.$prefix,
tokens-mat-tab-header.get-token-slots()
) {
@include token-utils.create-token-slot(font-family, label-text-font);
@include token-utils.create-token-slot(font-size, label-text-size);
@include token-utils.create-token-slot(letter-spacing, label-text-tracking);
@include token-utils.create-token-slot(line-height, label-text-line-height);
@include token-utils.create-token-slot(font-weight, label-text-weight);
}
&.mdc-tab {
// MDC's tabs stretch to fit the header by default, whereas stretching on our current ones
// is an opt-in behavior. Also technically we don't need to combine the two classes, but
// we need the extra specificity to avoid issues with CSS insertion order.
flex-grow: 0;
}
.mdc-tab-indicator__content--underline {
@include token-utils.use-tokens(
tokens-mdc-tab-indicator.$prefix,
tokens-mdc-tab-indicator.get-token-slots()
) {
@include token-utils.create-token-slot(border-color, active-indicator-color);
@include token-utils.create-token-slot(border-top-width, active-indicator-height);
@include token-utils.create-token-slot(border-radius, active-indicator-shape);
}
}
@include token-utils.use-tokens(
tokens-mat-tab-header.$prefix,
tokens-mat-tab-header.get-token-slots()
) {
&:hover .mdc-tab__text-label {
@include token-utils.create-token-slot(color, inactive-hover-label-text-color);
}
&:focus .mdc-tab__text-label {
@include token-utils.create-token-slot(color, inactive-focus-label-text-color);
}
&.mdc-tab--active {
.mdc-tab__text-label {
@include token-utils | {
"end_byte": 4367,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/_tabs-common.scss"
} |
components/src/material/tabs/_tabs-common.scss_4367_12265 | .create-token-slot(color, active-label-text-color);
}
.mdc-tab__ripple::before,
.mat-ripple-element {
@include token-utils.create-token-slot(background-color, active-ripple-color);
}
&:hover {
.mdc-tab__text-label {
@include token-utils.create-token-slot(color, active-hover-label-text-color);
}
.mdc-tab-indicator__content--underline {
@include token-utils.create-token-slot(border-color, active-hover-indicator-color);
}
}
&:focus {
.mdc-tab__text-label {
@include token-utils.create-token-slot(color, active-focus-label-text-color);
}
.mdc-tab-indicator__content--underline {
@include token-utils.create-token-slot(border-color, active-focus-indicator-color);
}
}
}
}
&.mat-mdc-tab-disabled {
// MDC doesn't support disabled tabs so we need to improvise.
opacity: 0.4;
// We use `pointer-events` to make the element unclickable when it's disabled, rather than
// preventing the default action through JS, because we can't prevent the action reliably
// due to other directives potentially registering their events earlier. This shouldn't cause
// the user to click through, because we always have a header behind the tab. Furthermore, this
// saves us some CSS, because we don't have to add `:not(.mat-mdc-tab-disabled)` to all the
// hover and focus selectors.
pointer-events: none;
// We also need to prevent content from being clickable.
.mdc-tab__content {
pointer-events: none;
}
@include token-utils.use-tokens(
tokens-mat-tab-header.$prefix,
tokens-mat-tab-header.get-token-slots()
) {
.mdc-tab__ripple::before,
.mat-ripple-element {
@include token-utils.create-token-slot(background-color, disabled-ripple-color);
}
}
}
// Used to render out the background tint when hovered/focused. Usually this is done by
// MDC's ripple styles, however we're using our own ripples due to size concerns.
.mdc-tab__ripple::before {
content: '';
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
opacity: 0;
pointer-events: none;
@include token-utils.use-tokens(
tokens-mat-tab-header.$prefix,
tokens-mat-tab-header.get-token-slots()
) {
@include token-utils.create-token-slot(background-color, inactive-ripple-color);
}
}
.mdc-tab__text-label {
@include token-utils.use-tokens(
tokens-mat-tab-header.$prefix,
tokens-mat-tab-header.get-token-slots()
) {
@include token-utils.create-token-slot(color, inactive-label-text-color);
}
// We support projecting icons into the tab. These styles ensure that they're centered.
display: inline-flex;
align-items: center;
}
.mdc-tab__content {
// Required for `fitInkBarToContent` to work. This used to be included with MDC's
// `without-ripple` mixin, but that no longer appears to be the case with `static-styles`.
// Since the latter is ~10kb smaller, we include this one extra style ourselves.
position: relative;
// MDC sets `pointer-events: none` on the content which prevents interactions with the
// nested content. Re-enable it since we allow nesting any content in the tab (see #26195).
pointer-events: auto;
}
// We need to handle the hover and focus indication ourselves, because we don't use MDC's ripple.
&:hover .mdc-tab__ripple::before {
opacity: 0.04;
}
&.cdk-program-focused,
&.cdk-keyboard-focused {
.mdc-tab__ripple::before {
opacity: 0.12;
}
}
.mat-ripple-element {
opacity: 0.12;
@include token-utils.use-tokens(
tokens-mat-tab-header.$prefix,
tokens-mat-tab-header.get-token-slots()
) {
@include token-utils.create-token-slot(background-color, inactive-ripple-color);
}
}
}
// Structural styles for a tab header. Used by both `mat-tab-header` and `mat-tab-nav-bar`.
// We need this styles on top of MDC's, because MDC doesn't support pagination like ours.
@mixin paginated-tab-header {
.mat-mdc-tab-header {
display: flex;
overflow: hidden;
position: relative;
flex-shrink: 0;
}
.mdc-tab-indicator .mdc-tab-indicator__content {
transition-duration: var(--mat-tab-animation-duration, 250ms);
}
.mat-mdc-tab-header-pagination {
@include vendor-prefixes.user-select(none);
position: relative;
display: none;
justify-content: center;
align-items: center;
min-width: 32px;
cursor: pointer;
z-index: 2;
-webkit-tap-highlight-color: transparent;
touch-action: none;
box-sizing: content-box;
outline: 0;
&::-moz-focus-inner {
border: 0;
}
.mat-ripple-element {
opacity: 0.12;
@include token-utils.use-tokens(
tokens-mat-tab-header.$prefix,
tokens-mat-tab-header.get-token-slots()
) {
@include token-utils.create-token-slot(background-color, inactive-ripple-color);
}
}
.mat-mdc-tab-header-pagination-controls-enabled & {
display: flex;
}
}
// The pagination control that is displayed on the left side of the tab header.
.mat-mdc-tab-header-pagination-before,
.mat-mdc-tab-header-rtl .mat-mdc-tab-header-pagination-after {
padding-left: 4px;
.mat-mdc-tab-header-pagination-chevron {
transform: rotate(-135deg);
}
}
// The pagination control that is displayed on the right side of the tab header.
.mat-mdc-tab-header-rtl .mat-mdc-tab-header-pagination-before,
.mat-mdc-tab-header-pagination-after {
padding-right: 4px;
.mat-mdc-tab-header-pagination-chevron {
transform: rotate(45deg);
}
}
.mat-mdc-tab-header-pagination-chevron {
border-style: solid;
border-width: 2px 2px 0 0;
height: 8px;
width: 8px;
@include token-utils.use-tokens(
tokens-mat-tab-header.$prefix,
tokens-mat-tab-header.get-token-slots()
) {
@include token-utils.create-token-slot(border-color, pagination-icon-color);
}
}
.mat-mdc-tab-header-pagination-disabled {
box-shadow: none;
cursor: default;
pointer-events: none;
.mat-mdc-tab-header-pagination-chevron {
opacity: 0.4;
}
}
.mat-mdc-tab-list {
flex-grow: 1;
position: relative;
transition: transform 500ms cubic-bezier(0.35, 0, 0.25, 1);
._mat-animation-noopable & {
transition: none;
}
}
}
// Structural styles for the element that wraps the paginated header items.
@mixin paginated-tab-header-item-wrapper($parent) {
display: flex;
flex: 1 0 auto;
// We need to set the parent here explicitly, in order to prevent the alignment
// from any parent tab groups from propagating down to the children when nesting.
// Note that these are used as inputs so they shouldn't be changed to `mat-mdc-`.
[mat-align-tabs='center'] > #{$parent} & {
justify-content: center;
}
[mat-align-tabs='end'] > #{$parent} & {
justify-content: flex-end;
}
// Prevent the header from collapsing when it is a drop list. This is useful,
// because its height may become zero once all the tabs are dragged out.
// Note that ideally we would do this by default, rather than only in a drop
// list, but it ended up being hugely breaking internally.
.cdk-drop-list &,
&.cdk-drop-list {
@include token-utils.use-tokens(
tokens-mdc-secondary-navigation-tab.$prefix,
tokens-mdc-secondary-navigation-tab.get-token-slots()
) {
@include token-utils.create-token-slot(min-height, container-height);
}
}
}
// Structural styles for the element that wraps the paginated container's content.
// Include a selector for an inverted header if the header may be optionally positioned on the
// bottom of the content. | {
"end_byte": 12265,
"start_byte": 4367,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/_tabs-common.scss"
} |
components/src/material/tabs/_tabs-common.scss_12266_15298 | @mixin paginated-tab-header-container($inverted-header-selector: null) {
display: flex;
flex-grow: 1;
overflow: hidden;
z-index: 1;
@include token-utils.use-tokens(
tokens-mat-tab-header.$prefix,
tokens-mat-tab-header.get-token-slots()
) {
border-bottom-style: solid;
@include token-utils.create-token-slot(border-bottom-width, divider-height);
@include token-utils.create-token-slot(border-bottom-color, divider-color);
@if ($inverted-header-selector) {
#{$inverted-header-selector} & {
border-bottom: none;
border-top-style: solid;
@include token-utils.create-token-slot(border-top-width, divider-height);
@include token-utils.create-token-slot(border-top-color, divider-color);
}
}
}
}
@mixin paginated-tab-header-with-background($header-selector, $tab-selector) {
&.mat-tabs-with-background {
@include token-utils.use-tokens(
tokens-mat-tab-header-with-background.$prefix,
tokens-mat-tab-header-with-background.get-token-slots()
) {
// Note that these selectors target direct descendants so
// that the styles don't apply to any nested tab groups.
> #{$header-selector}, > .mat-mdc-tab-header-pagination {
// Set background color for the tab group
@include token-utils.create-token-slot(background-color, background-color);
}
// Note: this is only scoped to primary, because the legacy tabs had the incorrect behavior
// where setting both a background and `mat-accent` would add the background, but keep
// accent on the selected tab. There are some internal apps whose design depends on this now
// so we have to replicate it here.
&.mat-primary > #{$header-selector} {
// Set labels to contrast against background
#{$tab-selector} .mdc-tab__text-label {
@include token-utils.create-token-slot(color, foreground-color);
}
.mdc-tab-indicator__content--underline {
@include token-utils.create-token-slot(border-color, foreground-color);
}
}
&:not(.mat-primary) > #{$header-selector} {
#{$tab-selector}:not(.mdc-tab--active) {
.mdc-tab__text-label {
@include token-utils.create-token-slot(color, foreground-color);
}
.mdc-tab-indicator__content--underline {
@include token-utils.create-token-slot(border-color, foreground-color);
}
}
}
> #{$header-selector}, > .mat-mdc-tab-header-pagination {
.mat-mdc-tab-header-pagination-chevron,
.mat-focus-indicator::before {
@include token-utils.create-token-slot(border-color, foreground-color);
}
.mat-ripple-element, .mdc-tab__ripple::before {
@include token-utils.create-token-slot(background-color, foreground-color);
}
.mat-mdc-tab-header-pagination-chevron {
@include token-utils.create-token-slot(color, foreground-color);
}
}
}
}
} | {
"end_byte": 15298,
"start_byte": 12266,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/_tabs-common.scss"
} |
components/src/material/tabs/tab-header.scss_0_776 | @use '@angular/cdk';
@use './tabs-common';
@include tabs-common.paginated-tab-header;
.mat-mdc-tab-label-container {
@include tabs-common.paginated-tab-header-container('.mat-mdc-tab-group-inverted-header');
}
.mat-mdc-tab-labels {
@include tabs-common.paginated-tab-header-item-wrapper('.mat-mdc-tab-header');
}
.mat-mdc-tab {
// For the tab element, default inset/offset values are necessary to ensure that
// the focus indicator is sufficiently contrastive and renders appropriately.
&::before {
margin: 5px;
}
@include cdk.high-contrast {
// When a tab is disabled in high contrast mode, set the text color to the disabled
// color, which is (unintuitively) named "GrayText".
&[aria-disabled='true'] {
color: GrayText;
}
}
}
| {
"end_byte": 776,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-header.scss"
} |
components/src/material/tabs/BUILD.bazel_0_2591 | 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 = "tabs",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = [
":tab-body.css",
":tab-header.css",
":tab-group.css",
":tab-nav-bar/tab-nav-bar.css",
":tab-nav-bar/tab-link.css",
] + glob(["**/*.html"]),
deps = [
"//src:dev_mode_types",
"//src/cdk/a11y",
"//src/cdk/bidi",
"//src/cdk/coercion",
"//src/cdk/keycodes",
"//src/cdk/observers",
"//src/cdk/observers/private",
"//src/cdk/platform",
"//src/cdk/portal",
"//src/cdk/scrolling",
"//src/material/core",
"@npm//@angular/animations",
"@npm//@angular/common",
"@npm//@angular/core",
],
)
sass_library(
name = "tabs_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = [
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "tab_body_scss",
src = "tab-body.scss",
deps = [
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "tab_header_scss",
src = "tab-header.scss",
deps = [":tabs_scss_lib"],
)
sass_binary(
name = "tab_group_scss",
src = "tab-group.scss",
deps = [
":tabs_scss_lib",
],
)
sass_binary(
name = "tab_nav_bar_scss",
src = "tab-nav-bar/tab-nav-bar.scss",
deps = [":tabs_scss_lib"],
)
sass_binary(
name = "tab_link_scss",
src = "tab-nav-bar/tab-link.scss",
deps = [
":tabs_scss_lib",
],
)
ng_test_library(
name = "tabs_tests_lib",
srcs = glob(
["**/*.spec.ts"],
),
deps = [
":tabs",
"//src/cdk/bidi",
"//src/cdk/keycodes",
"//src/cdk/observers",
"//src/cdk/observers/private",
"//src/cdk/portal",
"//src/cdk/scrolling",
"//src/cdk/testing/private",
"//src/cdk/testing/testbed",
"//src/material/core",
"@npm//@angular/common",
"@npm//@angular/platform-browser",
"@npm//rxjs",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":tabs_tests_lib",
],
)
markdown_to_html(
name = "overview",
srcs = [":tabs.md"],
)
extract_tokens(
name = "tokens",
srcs = [":tabs_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 2591,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/BUILD.bazel"
} |
components/src/material/tabs/tab-label.ts_0_1088 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Directive, InjectionToken, inject} from '@angular/core';
import {CdkPortal} from '@angular/cdk/portal';
/**
* Injection token that can be used to reference instances of `MatTabLabel`. It serves as
* alternative token to the actual `MatTabLabel` class which could cause unnecessary
* retention of the class and its directive metadata.
*/
export const MAT_TAB_LABEL = new InjectionToken<MatTabLabel>('MatTabLabel');
/**
* Used to provide a tab label to a tab without causing a circular dependency.
* @docs-private
*/
export const MAT_TAB = new InjectionToken<any>('MAT_TAB');
/** Used to flag tab labels for use with the portal directive */
@Directive({
selector: '[mat-tab-label], [matTabLabel]',
providers: [{provide: MAT_TAB_LABEL, useExisting: MatTabLabel}],
})
export class MatTabLabel extends CdkPortal {
_closestTab = inject(MAT_TAB, {optional: true});
}
| {
"end_byte": 1088,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-label.ts"
} |
components/src/material/tabs/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/index.ts"
} |
components/src/material/tabs/tab-body.scss_0_1375 | @use '../core/style/layout-common';
// Wraps each tab body. We need to add these styles ourselves,
// because MDC only provides styling for the tab header.
.mat-mdc-tab-body {
@include layout-common.fill();
display: block;
overflow: hidden;
outline: 0;
// Fix for auto content wrapping in IE11
flex-basis: 100%;
&.mat-mdc-tab-body-active {
position: relative;
overflow-x: hidden;
overflow-y: auto;
z-index: 1;
flex-grow: 1;
}
.mat-mdc-tab-group.mat-mdc-tab-group-dynamic-height &.mat-mdc-tab-body-active {
overflow-y: hidden;
}
}
.mat-mdc-tab-body-content {
height: 100%;
overflow: auto;
.mat-mdc-tab-group-dynamic-height & {
overflow: hidden;
}
// Usually the `visibility: hidden` added by the animation is enough to prevent focus from
// entering the collapsed content, but children with their own `visibility` can override it.
// This is a fallback that completely hides the content when the element becomes hidden.
// Note that we can't do this in the animation definition, because the style gets recomputed too
// late, breaking the animation because Angular didn't have time to figure out the target height.
// This can also be achieved with JS, but it has issues when starting an animation before
// the previous one has finished.
&[style*='visibility: hidden'] {
display: none;
}
}
| {
"end_byte": 1375,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-body.scss"
} |
components/src/material/tabs/ink-bar.ts_0_6633 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Directive,
ElementRef,
InjectionToken,
Input,
OnDestroy,
OnInit,
QueryList,
booleanAttribute,
inject,
} from '@angular/core';
/**
* Item inside a tab header relative to which the ink bar can be aligned.
* @docs-private
*/
export interface MatInkBarItem extends OnInit, OnDestroy {
elementRef: ElementRef<HTMLElement>;
activateInkBar(previousIndicatorClientRect?: DOMRect): void;
deactivateInkBar(): void;
fitInkBarToContent: boolean;
}
/** Class that is applied when a tab indicator is active. */
const ACTIVE_CLASS = 'mdc-tab-indicator--active';
/** Class that is applied when the tab indicator should not transition. */
const NO_TRANSITION_CLASS = 'mdc-tab-indicator--no-transition';
/**
* Abstraction around the MDC tab indicator that acts as the tab header's ink bar.
* @docs-private
*/
export class MatInkBar {
/** Item to which the ink bar is aligned currently. */
private _currentItem: MatInkBarItem | undefined;
constructor(private _items: QueryList<MatInkBarItem>) {}
/** Hides the ink bar. */
hide() {
this._items.forEach(item => item.deactivateInkBar());
}
/** Aligns the ink bar to a DOM node. */
alignToElement(element: HTMLElement) {
const correspondingItem = this._items.find(item => item.elementRef.nativeElement === element);
const currentItem = this._currentItem;
if (correspondingItem === currentItem) {
return;
}
currentItem?.deactivateInkBar();
if (correspondingItem) {
const domRect = currentItem?.elementRef.nativeElement.getBoundingClientRect?.();
// The ink bar won't animate unless we give it the `DOMRect` of the previous item.
correspondingItem.activateInkBar(domRect);
this._currentItem = correspondingItem;
}
}
}
@Directive()
export abstract class InkBarItem implements OnInit, OnDestroy {
private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private _inkBarElement: HTMLElement | null;
private _inkBarContentElement: HTMLElement | null;
private _fitToContent = false;
/** Whether the ink bar should fit to the entire tab or just its content. */
@Input({transform: booleanAttribute})
get fitInkBarToContent(): boolean {
return this._fitToContent;
}
set fitInkBarToContent(newValue: boolean) {
if (this._fitToContent !== newValue) {
this._fitToContent = newValue;
if (this._inkBarElement) {
this._appendInkBarElement();
}
}
}
/** Aligns the ink bar to the current item. */
activateInkBar(previousIndicatorClientRect?: DOMRect) {
const element = this._elementRef.nativeElement;
// Early exit if no indicator is present to handle cases where an indicator
// may be activated without a prior indicator state
if (
!previousIndicatorClientRect ||
!element.getBoundingClientRect ||
!this._inkBarContentElement
) {
element.classList.add(ACTIVE_CLASS);
return;
}
// This animation uses the FLIP approach. You can read more about it at the link below:
// https://aerotwist.com/blog/flip-your-animations/
// Calculate the dimensions based on the dimensions of the previous indicator
const currentClientRect = element.getBoundingClientRect();
const widthDelta = previousIndicatorClientRect.width / currentClientRect.width;
const xPosition = previousIndicatorClientRect.left - currentClientRect.left;
element.classList.add(NO_TRANSITION_CLASS);
this._inkBarContentElement.style.setProperty(
'transform',
`translateX(${xPosition}px) scaleX(${widthDelta})`,
);
// Force repaint before updating classes and transform to ensure the transform properly takes effect
element.getBoundingClientRect();
element.classList.remove(NO_TRANSITION_CLASS);
element.classList.add(ACTIVE_CLASS);
this._inkBarContentElement.style.setProperty('transform', '');
}
/** Removes the ink bar from the current item. */
deactivateInkBar() {
this._elementRef.nativeElement.classList.remove(ACTIVE_CLASS);
}
/** Initializes the foundation. */
ngOnInit() {
this._createInkBarElement();
}
/** Destroys the foundation. */
ngOnDestroy() {
this._inkBarElement?.remove();
this._inkBarElement = this._inkBarContentElement = null!;
}
/** Creates and appends the ink bar element. */
private _createInkBarElement() {
const documentNode = this._elementRef.nativeElement.ownerDocument || document;
const inkBarElement = (this._inkBarElement = documentNode.createElement('span'));
const inkBarContentElement = (this._inkBarContentElement = documentNode.createElement('span'));
inkBarElement.className = 'mdc-tab-indicator';
inkBarContentElement.className =
'mdc-tab-indicator__content mdc-tab-indicator__content--underline';
inkBarElement.appendChild(this._inkBarContentElement);
this._appendInkBarElement();
}
/**
* Appends the ink bar to the tab host element or content, depending on whether
* the ink bar should fit to content.
*/
private _appendInkBarElement() {
if (!this._inkBarElement && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('Ink bar element has not been created and cannot be appended');
}
const parentElement = this._fitToContent
? this._elementRef.nativeElement.querySelector('.mdc-tab__content')
: this._elementRef.nativeElement;
if (!parentElement && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('Missing element to host the ink bar');
}
parentElement!.appendChild(this._inkBarElement!);
}
}
/**
* Interface for a MatInkBar positioner method, defining the positioning and width of the ink
* bar in a set of tabs.
*/
export interface _MatInkBarPositioner {
(element: HTMLElement): {left: string; width: string};
}
/**
* The default positioner function for the MatInkBar.
* @docs-private
*/
export function _MAT_INK_BAR_POSITIONER_FACTORY(): _MatInkBarPositioner {
const method = (element: HTMLElement) => ({
left: element ? (element.offsetLeft || 0) + 'px' : '0',
width: element ? (element.offsetWidth || 0) + 'px' : '0',
});
return method;
}
/** Injection token for the MatInkBar's Positioner. */
export const _MAT_INK_BAR_POSITIONER = new InjectionToken<_MatInkBarPositioner>(
'MatInkBarPositioner',
{
providedIn: 'root',
factory: _MAT_INK_BAR_POSITIONER_FACTORY,
},
);
| {
"end_byte": 6633,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/ink-bar.ts"
} |
components/src/material/tabs/tab-group.ts_0_2709 | /**
* @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 {
AfterContentChecked,
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
EventEmitter,
Input,
OnDestroy,
Output,
QueryList,
ViewChild,
ViewEncapsulation,
booleanAttribute,
inject,
numberAttribute,
ANIMATION_MODULE_TYPE,
} from '@angular/core';
import {MAT_TAB_GROUP, MatTab} from './tab';
import {MatTabHeader} from './tab-header';
import {ThemePalette, MatRipple} from '@angular/material/core';
import {merge, Subscription} from 'rxjs';
import {MAT_TABS_CONFIG, MatTabsConfig} from './tab-config';
import {startWith} from 'rxjs/operators';
import {CdkMonitorFocus, FocusOrigin} from '@angular/cdk/a11y';
import {MatTabBody} from './tab-body';
import {CdkPortalOutlet} from '@angular/cdk/portal';
import {MatTabLabelWrapper} from './tab-label-wrapper';
import {Platform} from '@angular/cdk/platform';
/** Used to generate unique ID's for each tab component */
let nextId = 0;
/** @docs-private */
export interface MatTabGroupBaseHeader {
_alignInkBarToSelectedTab(): void;
updatePagination(): void;
focusIndex: number;
}
/** Possible positions for the tab header. */
export type MatTabHeaderPosition = 'above' | 'below';
/** Boolean constant that determines whether the tab group supports the `backgroundColor` input */
const ENABLE_BACKGROUND_INPUT = true;
/**
* Material design tab-group component. Supports basic tab pairs (label + content) and includes
* animated ink-bar, keyboard navigation, and screen reader.
* See: https://material.io/design/components/tabs.html
*/
@Component({
selector: 'mat-tab-group',
exportAs: 'matTabGroup',
templateUrl: 'tab-group.html',
styleUrl: 'tab-group.css',
encapsulation: ViewEncapsulation.None,
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
providers: [
{
provide: MAT_TAB_GROUP,
useExisting: MatTabGroup,
},
],
host: {
'class': 'mat-mdc-tab-group',
'[class]': '"mat-" + (color || "primary")',
'[class.mat-mdc-tab-group-dynamic-height]': 'dynamicHeight',
'[class.mat-mdc-tab-group-inverted-header]': 'headerPosition === "below"',
'[class.mat-mdc-tab-group-stretch-tabs]': 'stretchTabs',
'[attr.mat-align-tabs]': 'alignTabs',
'[style.--mat-tab-animation-duration]': 'animationDuration',
},
imports: [
MatTabHeader,
MatTabLabelWrapper,
CdkMonitorFocus,
MatRipple,
CdkPortalOutlet,
MatTabBody,
],
})
export | {
"end_byte": 2709,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-group.ts"
} |
components/src/material/tabs/tab-group.ts_2710_10856 | class MatTabGroup implements AfterContentInit, AfterContentChecked, OnDestroy {
readonly _elementRef = inject(ElementRef);
private _changeDetectorRef = inject(ChangeDetectorRef);
_animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true});
/**
* All tabs inside the tab group. This includes tabs that belong to groups that are nested
* inside the current one. We filter out only the tabs that belong to this group in `_tabs`.
*/
@ContentChildren(MatTab, {descendants: true}) _allTabs: QueryList<MatTab>;
@ViewChild('tabBodyWrapper') _tabBodyWrapper: ElementRef;
@ViewChild('tabHeader') _tabHeader: MatTabHeader;
/** All of the tabs that belong to the group. */
_tabs: QueryList<MatTab> = new QueryList<MatTab>();
/** The tab index that should be selected after the content has been checked. */
private _indexToSelect: number | null = 0;
/** Index of the tab that was focused last. */
private _lastFocusedTabIndex: number | null = null;
/** Snapshot of the height of the tab body wrapper before another tab is activated. */
private _tabBodyWrapperHeight: number = 0;
/** Subscription to tabs being added/removed. */
private _tabsSubscription = Subscription.EMPTY;
/** Subscription to changes in the tab labels. */
private _tabLabelSubscription = Subscription.EMPTY;
/**
* Theme color of the tab group. This API is supported in M2 themes only, it
* has no effect in M3 themes.
*
* For information on applying color variants in M3, see
* https://material.angular.io/guide/theming#using-component-color-variants.
*/
@Input()
color: ThemePalette;
/** Whether the ink bar should fit its width to the size of the tab label content. */
@Input({transform: booleanAttribute})
get fitInkBarToContent(): boolean {
return this._fitInkBarToContent;
}
set fitInkBarToContent(value: boolean) {
this._fitInkBarToContent = value;
this._changeDetectorRef.markForCheck();
}
private _fitInkBarToContent = false;
/** Whether tabs should be stretched to fill the header. */
@Input({alias: 'mat-stretch-tabs', transform: booleanAttribute})
stretchTabs: boolean = true;
/** Alignment for tabs label. */
@Input({alias: 'mat-align-tabs'})
alignTabs: string | null = null;
/** Whether the tab group should grow to the size of the active tab. */
@Input({transform: booleanAttribute})
dynamicHeight: boolean = false;
/** The index of the active tab. */
@Input({transform: numberAttribute})
get selectedIndex(): number | null {
return this._selectedIndex;
}
set selectedIndex(value: number) {
this._indexToSelect = isNaN(value) ? null : value;
}
private _selectedIndex: number | null = null;
/** Position of the tab header. */
@Input() headerPosition: MatTabHeaderPosition = 'above';
/** Duration for the tab animation. Will be normalized to milliseconds if no units are set. */
@Input()
get animationDuration(): string {
return this._animationDuration;
}
set animationDuration(value: string | number) {
const stringValue = value + '';
this._animationDuration = /^\d+$/.test(stringValue) ? value + 'ms' : stringValue;
}
private _animationDuration: string;
/**
* `tabindex` to be set on the inner element that wraps the tab content. Can be used for improved
* accessibility when the tab does not have focusable elements or if it has scrollable content.
* The `tabindex` will be removed automatically for inactive tabs.
* Read more at https://www.w3.org/TR/wai-aria-practices/examples/tabs/tabs-2/tabs.html
*/
@Input({transform: numberAttribute})
get contentTabIndex(): number | null {
return this._contentTabIndex;
}
set contentTabIndex(value: number) {
this._contentTabIndex = isNaN(value) ? null : value;
}
private _contentTabIndex: number | null;
/**
* Whether pagination should be disabled. This can be used to avoid unnecessary
* layout recalculations if it's known that pagination won't be required.
*/
@Input({transform: booleanAttribute})
disablePagination: boolean = false;
/** Whether ripples in the tab group are disabled. */
@Input({transform: booleanAttribute})
disableRipple: boolean = false;
/**
* By default tabs remove their content from the DOM while it's off-screen.
* Setting this to `true` will keep it in the DOM which will prevent elements
* like iframes and videos from reloading next time it comes back into the view.
*/
@Input({transform: booleanAttribute})
preserveContent: boolean = false;
/**
* Theme color of the background of the tab group. This API is supported in M2 themes only, it
* has no effect in M3 themes.
*
* For information on applying color variants in M3, see
* https://material.angular.io/guide/theming#using-component-color-variants.
*
* @deprecated The background color should be customized through Sass theming APIs.
* @breaking-change 20.0.0 Remove this input
*/
@Input()
get backgroundColor(): ThemePalette {
return this._backgroundColor;
}
set backgroundColor(value: ThemePalette) {
if (!ENABLE_BACKGROUND_INPUT) {
throw new Error(`mat-tab-group background color must be set through the Sass theming API`);
}
const classList: DOMTokenList = this._elementRef.nativeElement.classList;
classList.remove('mat-tabs-with-background', `mat-background-${this.backgroundColor}`);
if (value) {
classList.add('mat-tabs-with-background', `mat-background-${value}`);
}
this._backgroundColor = value;
}
private _backgroundColor: ThemePalette;
/** Aria label of the inner `tablist` of the group. */
@Input('aria-label') ariaLabel: string;
/** Sets the `aria-labelledby` of the inner `tablist` of the group. */
@Input('aria-labelledby') ariaLabelledby: string;
/** Output to enable support for two-way binding on `[(selectedIndex)]` */
@Output() readonly selectedIndexChange: EventEmitter<number> = new EventEmitter<number>();
/** Event emitted when focus has changed within a tab group. */
@Output() readonly focusChange: EventEmitter<MatTabChangeEvent> =
new EventEmitter<MatTabChangeEvent>();
/** Event emitted when the body animation has completed */
@Output() readonly animationDone: EventEmitter<void> = new EventEmitter<void>();
/** Event emitted when the tab selection has changed. */
@Output() readonly selectedTabChange: EventEmitter<MatTabChangeEvent> =
new EventEmitter<MatTabChangeEvent>(true);
private _groupId: number;
/** Whether the tab group is rendered on the server. */
protected _isServer: boolean = !inject(Platform).isBrowser;
constructor(...args: unknown[]);
constructor() {
const defaultConfig = inject<MatTabsConfig>(MAT_TABS_CONFIG, {optional: true});
this._groupId = nextId++;
this.animationDuration =
defaultConfig && defaultConfig.animationDuration ? defaultConfig.animationDuration : '500ms';
this.disablePagination =
defaultConfig && defaultConfig.disablePagination != null
? defaultConfig.disablePagination
: false;
this.dynamicHeight =
defaultConfig && defaultConfig.dynamicHeight != null ? defaultConfig.dynamicHeight : false;
if (defaultConfig?.contentTabIndex != null) {
this.contentTabIndex = defaultConfig.contentTabIndex;
}
this.preserveContent = !!defaultConfig?.preserveContent;
this.fitInkBarToContent =
defaultConfig && defaultConfig.fitInkBarToContent != null
? defaultConfig.fitInkBarToContent
: false;
this.stretchTabs =
defaultConfig && defaultConfig.stretchTabs != null ? defaultConfig.stretchTabs : true;
this.alignTabs =
defaultConfig && defaultConfig.alignTabs != null ? defaultConfig.alignTabs : null;
}
/**
* After the content is checked, this component knows what tabs have been defined
* and what the selected index should be. This is where we can know exactly what position
* each tab should be in according to the new selected index, and additionally we know how
* a new selected tab should transition in (from the left or right).
*/ | {
"end_byte": 10856,
"start_byte": 2710,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-group.ts"
} |
components/src/material/tabs/tab-group.ts_10859_19395 | ngAfterContentChecked() {
// Don't clamp the `indexToSelect` immediately in the setter because it can happen that
// the amount of tabs changes before the actual change detection runs.
const indexToSelect = (this._indexToSelect = this._clampTabIndex(this._indexToSelect));
// If there is a change in selected index, emit a change event. Should not trigger if
// the selected index has not yet been initialized.
if (this._selectedIndex != indexToSelect) {
const isFirstRun = this._selectedIndex == null;
if (!isFirstRun) {
this.selectedTabChange.emit(this._createChangeEvent(indexToSelect));
// Preserve the height so page doesn't scroll up during tab change.
// Fixes https://stackblitz.com/edit/mat-tabs-scroll-page-top-on-tab-change
const wrapper = this._tabBodyWrapper.nativeElement;
wrapper.style.minHeight = wrapper.clientHeight + 'px';
}
// Changing these values after change detection has run
// since the checked content may contain references to them.
Promise.resolve().then(() => {
this._tabs.forEach((tab, index) => (tab.isActive = index === indexToSelect));
if (!isFirstRun) {
this.selectedIndexChange.emit(indexToSelect);
// Clear the min-height, this was needed during tab change to avoid
// unnecessary scrolling.
this._tabBodyWrapper.nativeElement.style.minHeight = '';
}
});
}
// Setup the position for each tab and optionally setup an origin on the next selected tab.
this._tabs.forEach((tab: MatTab, index: number) => {
tab.position = index - indexToSelect;
// If there is already a selected tab, then set up an origin for the next selected tab
// if it doesn't have one already.
if (this._selectedIndex != null && tab.position == 0 && !tab.origin) {
tab.origin = indexToSelect - this._selectedIndex;
}
});
if (this._selectedIndex !== indexToSelect) {
this._selectedIndex = indexToSelect;
this._lastFocusedTabIndex = null;
this._changeDetectorRef.markForCheck();
}
}
ngAfterContentInit() {
this._subscribeToAllTabChanges();
this._subscribeToTabLabels();
// Subscribe to changes in the amount of tabs, in order to be
// able to re-render the content as new tabs are added or removed.
this._tabsSubscription = this._tabs.changes.subscribe(() => {
const indexToSelect = this._clampTabIndex(this._indexToSelect);
// Maintain the previously-selected tab if a new tab is added or removed and there is no
// explicit change that selects a different tab.
if (indexToSelect === this._selectedIndex) {
const tabs = this._tabs.toArray();
let selectedTab: MatTab | undefined;
for (let i = 0; i < tabs.length; i++) {
if (tabs[i].isActive) {
// Assign both to the `_indexToSelect` and `_selectedIndex` so we don't fire a changed
// event, otherwise the consumer may end up in an infinite loop in some edge cases like
// adding a tab within the `selectedIndexChange` event.
this._indexToSelect = this._selectedIndex = i;
this._lastFocusedTabIndex = null;
selectedTab = tabs[i];
break;
}
}
// If we haven't found an active tab and a tab exists at the selected index, it means
// that the active tab was swapped out. Since this won't be picked up by the rendering
// loop in `ngAfterContentChecked`, we need to sync it up manually.
if (!selectedTab && tabs[indexToSelect]) {
Promise.resolve().then(() => {
tabs[indexToSelect].isActive = true;
this.selectedTabChange.emit(this._createChangeEvent(indexToSelect));
});
}
}
this._changeDetectorRef.markForCheck();
});
}
/** Listens to changes in all of the tabs. */
private _subscribeToAllTabChanges() {
// Since we use a query with `descendants: true` to pick up the tabs, we may end up catching
// some that are inside of nested tab groups. We filter them out manually by checking that
// the closest group to the tab is the current one.
this._allTabs.changes.pipe(startWith(this._allTabs)).subscribe((tabs: QueryList<MatTab>) => {
this._tabs.reset(
tabs.filter(tab => {
return tab._closestTabGroup === this || !tab._closestTabGroup;
}),
);
this._tabs.notifyOnChanges();
});
}
ngOnDestroy() {
this._tabs.destroy();
this._tabsSubscription.unsubscribe();
this._tabLabelSubscription.unsubscribe();
}
/** Re-aligns the ink bar to the selected tab element. */
realignInkBar() {
if (this._tabHeader) {
this._tabHeader._alignInkBarToSelectedTab();
}
}
/**
* Recalculates the tab group's pagination dimensions.
*
* WARNING: Calling this method can be very costly in terms of performance. It should be called
* as infrequently as possible from outside of the Tabs component as it causes a reflow of the
* page.
*/
updatePagination() {
if (this._tabHeader) {
this._tabHeader.updatePagination();
}
}
/**
* Sets focus to a particular tab.
* @param index Index of the tab to be focused.
*/
focusTab(index: number) {
const header = this._tabHeader;
if (header) {
header.focusIndex = index;
}
}
_focusChanged(index: number) {
this._lastFocusedTabIndex = index;
this.focusChange.emit(this._createChangeEvent(index));
}
private _createChangeEvent(index: number): MatTabChangeEvent {
const event = new MatTabChangeEvent();
event.index = index;
if (this._tabs && this._tabs.length) {
event.tab = this._tabs.toArray()[index];
}
return event;
}
/**
* Subscribes to changes in the tab labels. This is needed, because the @Input for the label is
* on the MatTab component, whereas the data binding is inside the MatTabGroup. In order for the
* binding to be updated, we need to subscribe to changes in it and trigger change detection
* manually.
*/
private _subscribeToTabLabels() {
if (this._tabLabelSubscription) {
this._tabLabelSubscription.unsubscribe();
}
this._tabLabelSubscription = merge(...this._tabs.map(tab => tab._stateChanges)).subscribe(() =>
this._changeDetectorRef.markForCheck(),
);
}
/** Clamps the given index to the bounds of 0 and the tabs length. */
private _clampTabIndex(index: number | null): number {
// Note the `|| 0`, which ensures that values like NaN can't get through
// and which would otherwise throw the component into an infinite loop
// (since Math.max(NaN, 0) === NaN).
return Math.min(this._tabs.length - 1, Math.max(index || 0, 0));
}
/** Returns a unique id for each tab label element */
_getTabLabelId(i: number): string {
return `mat-tab-label-${this._groupId}-${i}`;
}
/** Returns a unique id for each tab content element */
_getTabContentId(i: number): string {
return `mat-tab-content-${this._groupId}-${i}`;
}
/**
* Sets the height of the body wrapper to the height of the activating tab if dynamic
* height property is true.
*/
_setTabBodyWrapperHeight(tabHeight: number): void {
if (!this.dynamicHeight || !this._tabBodyWrapperHeight) {
return;
}
const wrapper: HTMLElement = this._tabBodyWrapper.nativeElement;
wrapper.style.height = this._tabBodyWrapperHeight + 'px';
// This conditional forces the browser to paint the height so that
// the animation to the new height can have an origin.
if (this._tabBodyWrapper.nativeElement.offsetHeight) {
wrapper.style.height = tabHeight + 'px';
}
}
/** Removes the height of the tab body wrapper. */
_removeTabBodyWrapperHeight(): void {
const wrapper = this._tabBodyWrapper.nativeElement;
this._tabBodyWrapperHeight = wrapper.clientHeight;
wrapper.style.height = '';
this.animationDone.emit();
}
/** Handle click events, setting new selected index if appropriate. */
_handleClick(tab: MatTab, tabHeader: MatTabGroupBaseHeader, index: number) {
tabHeader.focusIndex = index;
if (!tab.disabled) {
this.selectedIndex = index;
}
}
/** Retrieves the tabindex for the tab. */
_getTabIndex(index: number): number {
const targetIndex = this._lastFocusedTabIndex ?? this.selectedIndex;
return index === targetIndex ? 0 : -1;
} | {
"end_byte": 19395,
"start_byte": 10859,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-group.ts"
} |
components/src/material/tabs/tab-group.ts_19399_20214 | /** Callback for when the focused state of a tab has changed. */
_tabFocusChanged(focusOrigin: FocusOrigin, index: number) {
// Mouse/touch focus happens during the `mousedown`/`touchstart` phase which
// can cause the tab to be moved out from under the pointer, interrupting the
// click sequence (see #21898). We don't need to scroll the tab into view for
// such cases anyway, because it will be done when the tab becomes selected.
if (focusOrigin && focusOrigin !== 'mouse' && focusOrigin !== 'touch') {
this._tabHeader.focusIndex = index;
}
}
}
/** A simple change event emitted on focus or selection changes. */
export class MatTabChangeEvent {
/** Index of the currently-selected tab. */
index: number;
/** Reference to the currently-selected tab. */
tab: MatTab;
} | {
"end_byte": 20214,
"start_byte": 19399,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-group.ts"
} |
components/src/material/tabs/tab.html_0_265 | <!-- Create a template for the content of the <mat-tab> so that we can grab a reference to this
TemplateRef and use it in a Portal to render the tab content in the appropriate place in the
tab-group. -->
<ng-template><ng-content></ng-content></ng-template>
| {
"end_byte": 265,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab.html"
} |
components/src/material/tabs/tab-body.html_0_355 | <div class="mat-mdc-tab-body-content" #content
[@translateTab]="{
value: _position,
params: {animationDuration: animationDuration}
}"
(@translateTab.start)="_onTranslateTabStarted($event)"
(@translateTab.done)="_translateTabComplete.next($event)"
cdkScrollable>
<ng-template matTabBodyHost></ng-template>
</div>
| {
"end_byte": 355,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-body.html"
} |
components/src/material/tabs/tab-nav-bar/tab-nav-bar.scss_0_451 | @use '../tabs-common';
@include tabs-common.structural-styles;
@include tabs-common.paginated-tab-header;
.mat-mdc-tab-links {
@include tabs-common.paginated-tab-header-item-wrapper('.mat-mdc-tab-link-container');
}
.mat-mdc-tab-link-container {
@include tabs-common.paginated-tab-header-container;
}
.mat-mdc-tab-nav-bar {
@include tabs-common.paginated-tab-header-with-background('.mat-mdc-tab-link-container',
'.mat-mdc-tab-link');
}
| {
"end_byte": 451,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-nav-bar/tab-nav-bar.scss"
} |
components/src/material/tabs/tab-nav-bar/tab-nav-bar.spec.ts_0_847 | import {Direction, Directionality} from '@angular/cdk/bidi';
import {ENTER, SPACE} from '@angular/cdk/keycodes';
import {SharedResizeObserver} from '@angular/cdk/observers/private';
import {
dispatchFakeEvent,
dispatchKeyboardEvent,
dispatchMouseEvent,
} from '@angular/cdk/testing/private';
import {Component, QueryList, ViewChild, ViewChildren} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, tick, waitForAsync} from '@angular/core/testing';
import {MAT_RIPPLE_GLOBAL_OPTIONS, RippleGlobalOptions} from '@angular/material/core';
import {By} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {Subject} from 'rxjs';
import {MAT_TABS_CONFIG} from '../index';
import {MatTabsModule} from '../module';
import {MatTabLink, MatTabNav} from './tab-nav-bar'; | {
"end_byte": 847,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-nav-bar/tab-nav-bar.spec.ts"
} |
components/src/material/tabs/tab-nav-bar/tab-nav-bar.spec.ts_849_10127 | describe('MatTabNavBar', () => {
let dir: Direction = 'ltr';
let dirChange = new Subject();
let globalRippleOptions: RippleGlobalOptions;
let resizeEvents: Subject<ResizeObserverEntry[]>;
beforeEach(waitForAsync(() => {
globalRippleOptions = {};
TestBed.configureTestingModule({
imports: [
MatTabsModule,
SimpleTabNavBarTestApp,
TabLinkWithNgIf,
TabBarWithInactiveTabsOnInit,
],
providers: [
{provide: MAT_RIPPLE_GLOBAL_OPTIONS, useFactory: () => globalRippleOptions},
{provide: Directionality, useFactory: () => ({value: dir, change: dirChange})},
],
});
resizeEvents = new Subject();
spyOn(TestBed.inject(SharedResizeObserver), 'observe').and.returnValue(resizeEvents);
}));
describe('basic behavior', () => {
let fixture: ComponentFixture<SimpleTabNavBarTestApp>;
beforeEach(() => {
fixture = TestBed.createComponent(SimpleTabNavBarTestApp);
fixture.detectChanges();
});
it('should change active index on click', () => {
// select the second link
let tabLink = fixture.debugElement.queryAll(By.css('a'))[1];
tabLink.nativeElement.click();
expect(fixture.componentInstance.activeIndex).toBe(1);
// select the third link
tabLink = fixture.debugElement.queryAll(By.css('a'))[2];
tabLink.nativeElement.click();
expect(fixture.componentInstance.activeIndex).toBe(2);
});
it('should add the active class if active', () => {
let tabLink1 = fixture.debugElement.queryAll(By.css('a'))[0];
let tabLink2 = fixture.debugElement.queryAll(By.css('a'))[1];
const tabLinkElements = fixture.debugElement
.queryAll(By.css('a'))
.map(tabLinkDebugEl => tabLinkDebugEl.nativeElement);
tabLink1.nativeElement.click();
fixture.detectChanges();
expect(tabLinkElements[0].classList.contains('mdc-tab--active')).toBeTruthy();
expect(tabLinkElements[1].classList.contains('mdc-tab--active')).toBeFalsy();
tabLink2.nativeElement.click();
fixture.detectChanges();
expect(tabLinkElements[0].classList.contains('mdc-tab--active')).toBeFalsy();
expect(tabLinkElements[1].classList.contains('mdc-tab--active')).toBeTruthy();
});
it('should update aria-disabled if disabled', () => {
const tabLinkElements = fixture.debugElement
.queryAll(By.css('a'))
.map(tabLinkDebugEl => tabLinkDebugEl.nativeElement);
expect(tabLinkElements.every(tabLink => tabLink.getAttribute('aria-disabled') === 'false'))
.withContext('Expected aria-disabled to be set to "false" by default.')
.toBe(true);
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tabLinkElements.every(tabLink => tabLink.getAttribute('aria-disabled') === 'true'))
.withContext('Expected aria-disabled to be set to "true" if link is disabled.')
.toBe(true);
});
it('should update the tabindex if links are disabled', () => {
const tabLinkElements = fixture.debugElement
.queryAll(By.css('a'))
.map(tabLinkDebugEl => tabLinkDebugEl.nativeElement);
expect(tabLinkElements.map(tabLink => tabLink.tabIndex))
.withContext('Expected first element to be keyboard focusable by default')
.toEqual([0, -1, -1]);
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tabLinkElements.every(tabLink => tabLink.tabIndex === -1))
.withContext('Expected element to no longer be keyboard focusable if disabled.')
.toBe(true);
});
it('should mark disabled links', () => {
const tabLinkElement = fixture.debugElement.query(By.css('a')).nativeElement;
expect(tabLinkElement.classList).not.toContain('mat-mdc-tab-disabled');
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tabLinkElement.classList).toContain('mat-mdc-tab-disabled');
});
it('should prevent default keyboard actions on disabled links', () => {
const link = fixture.debugElement.query(By.css('a')).nativeElement;
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const spaceEvent = dispatchKeyboardEvent(link, 'keydown', SPACE);
fixture.detectChanges();
expect(spaceEvent.defaultPrevented).toBe(true);
const enterEvent = dispatchKeyboardEvent(link, 'keydown', ENTER);
fixture.detectChanges();
expect(enterEvent.defaultPrevented).toBe(true);
});
it('should re-align the ink bar when the direction changes', fakeAsync(() => {
const inkBar = fixture.componentInstance.tabNavBar._inkBar;
spyOn(inkBar, 'alignToElement');
dirChange.next();
tick();
fixture.detectChanges();
expect(inkBar.alignToElement).toHaveBeenCalled();
}));
it('should re-align the ink bar when the tabs list change', fakeAsync(() => {
const inkBar = fixture.componentInstance.tabNavBar._inkBar;
spyOn(inkBar, 'alignToElement');
fixture.componentInstance.tabs = [1, 2, 3, 4];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(inkBar.alignToElement).toHaveBeenCalled();
}));
it('should re-align the ink bar when the tab labels change the width', done => {
const inkBar = fixture.componentInstance.tabNavBar._inkBar;
const spy = spyOn(inkBar, 'alignToElement').and.callFake(() => {
expect(spy.calls.any()).toBe(true);
done();
});
fixture.componentInstance.label = 'label change';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy.calls.any()).toBe(false);
});
it('should re-align the ink bar when the nav bar is resized', fakeAsync(() => {
const inkBar = fixture.componentInstance.tabNavBar._inkBar;
spyOn(inkBar, 'alignToElement');
resizeEvents.next([]);
fixture.detectChanges();
tick(32);
expect(inkBar.alignToElement).toHaveBeenCalled();
}));
it('should hide the ink bar when all the links are inactive', () => {
const inkBar = fixture.componentInstance.tabNavBar._inkBar;
spyOn(inkBar, 'hide');
fixture.componentInstance.tabLinks.forEach(link => (link.active = false));
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(inkBar.hide).toHaveBeenCalled();
});
it('should update the focusIndex when a tab receives focus directly', () => {
const thirdLink = fixture.debugElement.queryAll(By.css('a'))[2];
dispatchFakeEvent(thirdLink.nativeElement, 'focus');
fixture.detectChanges();
expect(fixture.componentInstance.tabNavBar.focusIndex).toBe(2);
});
});
it('should hide the ink bar if no tabs are active on init', fakeAsync(() => {
const fixture = TestBed.createComponent(TabBarWithInactiveTabsOnInit);
fixture.detectChanges();
tick(20); // Angular turns rAF calls into 16.6ms timeouts in tests.
fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('.mdc-tab-indicator--active').length).toBe(0);
}));
it('should clean up the ripple event handlers on destroy', () => {
let fixture: ComponentFixture<TabLinkWithNgIf> = TestBed.createComponent(TabLinkWithNgIf);
fixture.detectChanges();
let link = fixture.debugElement.nativeElement.querySelector('.mat-mdc-tab-link');
fixture.componentInstance.isDestroyed = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(link, 'mousedown');
expect(link.querySelector('.mat-ripple-element'))
.withContext('Expected no ripple to be created when ripple target is destroyed.')
.toBeFalsy();
});
it('should select the proper tab, if the tabs come in after init', () => {
const fixture = TestBed.createComponent(SimpleTabNavBarTestApp);
const instance = fixture.componentInstance;
instance.tabs = [];
instance.activeIndex = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(instance.tabNavBar.selectedIndex).toBe(-1);
instance.tabs = [0, 1, 2];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(instance.tabNavBar.selectedIndex).toBe(1);
});
it('should have the proper roles', () => {
const fixture = TestBed.createComponent(SimpleTabNavBarTestApp);
fixture.detectChanges();
const tabBar = fixture.nativeElement.querySelector('.mat-mdc-tab-nav-bar')!;
expect(tabBar.getAttribute('role')).toBe('tablist');
const tabLinks = fixture.nativeElement.querySelectorAll('.mat-mdc-tab-link');
expect(tabLinks[0].getAttribute('role')).toBe('tab');
expect(tabLinks[1].getAttribute('role')).toBe('tab');
expect(tabLinks[2].getAttribute('role')).toBe('tab');
const tabPanel = fixture.nativeElement.querySelector('.mat-mdc-tab-nav-panel')!;
expect(tabPanel.getAttribute('role')).toBe('tabpanel');
}); | {
"end_byte": 10127,
"start_byte": 849,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-nav-bar/tab-nav-bar.spec.ts"
} |
components/src/material/tabs/tab-nav-bar/tab-nav-bar.spec.ts_10131_19146 | it('should manage tabindex properly', () => {
const fixture = TestBed.createComponent(SimpleTabNavBarTestApp);
fixture.detectChanges();
const tabLinks = fixture.nativeElement.querySelectorAll('.mat-mdc-tab-link');
expect(tabLinks[0].tabIndex).toBe(0);
expect(tabLinks[1].tabIndex).toBe(-1);
expect(tabLinks[2].tabIndex).toBe(-1);
tabLinks[1].click();
fixture.detectChanges();
expect(tabLinks[0].tabIndex).toBe(-1);
expect(tabLinks[1].tabIndex).toBe(0);
expect(tabLinks[2].tabIndex).toBe(-1);
});
it('should setup aria-controls properly', () => {
const fixture = TestBed.createComponent(SimpleTabNavBarTestApp);
fixture.detectChanges();
const tabLinks = fixture.nativeElement.querySelectorAll('.mat-mdc-tab-link');
expect(tabLinks[0].getAttribute('aria-controls')).toBe('tab-panel');
expect(tabLinks[1].getAttribute('aria-controls')).toBe('tab-panel');
expect(tabLinks[2].getAttribute('aria-controls')).toBe('tab-panel');
});
it('should not manage aria-current', () => {
const fixture = TestBed.createComponent(SimpleTabNavBarTestApp);
fixture.detectChanges();
const tabLinks = fixture.nativeElement.querySelectorAll('.mat-mdc-tab-link');
expect(tabLinks[0].getAttribute('aria-current')).toBe(null);
expect(tabLinks[1].getAttribute('aria-current')).toBe(null);
expect(tabLinks[2].getAttribute('aria-current')).toBe(null);
});
it('should manage aria-selected properly', () => {
const fixture = TestBed.createComponent(SimpleTabNavBarTestApp);
fixture.detectChanges();
const tabLinks = fixture.nativeElement.querySelectorAll('.mat-mdc-tab-link');
expect(tabLinks[0].getAttribute('aria-selected')).toBe('true');
expect(tabLinks[1].getAttribute('aria-selected')).toBe('false');
expect(tabLinks[2].getAttribute('aria-selected')).toBe('false');
tabLinks[1].click();
fixture.detectChanges();
expect(tabLinks[0].getAttribute('aria-selected')).toBe('false');
expect(tabLinks[1].getAttribute('aria-selected')).toBe('true');
expect(tabLinks[2].getAttribute('aria-selected')).toBe('false');
});
it('should activate a link when space is pressed', () => {
const fixture = TestBed.createComponent(SimpleTabNavBarTestApp);
fixture.detectChanges();
const tabLinks = fixture.nativeElement.querySelectorAll('.mat-mdc-tab-link');
expect(tabLinks[1].classList.contains('mdc-tab--active')).toBe(false);
dispatchKeyboardEvent(tabLinks[1], 'keydown', SPACE);
fixture.detectChanges();
expect(tabLinks[1].classList.contains('mdc-tab--active')).toBe(true);
});
it('should activate a link when enter is pressed', () => {
const fixture = TestBed.createComponent(SimpleTabNavBarTestApp);
fixture.detectChanges();
const tabLinks = fixture.nativeElement.querySelectorAll('.mat-mdc-tab-link');
expect(tabLinks[1].classList.contains('mdc-tab--active')).toBe(false);
dispatchKeyboardEvent(tabLinks[1], 'keydown', ENTER);
fixture.detectChanges();
expect(tabLinks[1].classList.contains('mdc-tab--active')).toBe(true);
});
describe('ripples', () => {
let fixture: ComponentFixture<SimpleTabNavBarTestApp>;
beforeEach(() => {
fixture = TestBed.createComponent(SimpleTabNavBarTestApp);
fixture.detectChanges();
});
it('should be disabled on all tab links when they are disabled on the nav bar', () => {
expect(fixture.componentInstance.tabLinks.toArray().every(tabLink => !tabLink.rippleDisabled))
.withContext('Expected every tab link to have ripples enabled')
.toBe(true);
fixture.componentInstance.disableRippleOnBar = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.tabLinks.toArray().every(tabLink => tabLink.rippleDisabled))
.withContext('Expected every tab link to have ripples disabled')
.toBe(true);
});
it('should have the `disableRipple` from the tab take precedence over the nav bar', () => {
const firstTab = fixture.componentInstance.tabLinks.first;
expect(firstTab.rippleDisabled)
.withContext('Expected ripples to be enabled on first tab')
.toBe(false);
firstTab.disableRipple = true;
fixture.componentInstance.disableRippleOnBar = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(firstTab.rippleDisabled)
.withContext('Expected ripples to be disabled on first tab')
.toBe(true);
});
it('should show up for tab link elements on mousedown', () => {
const tabLink = fixture.debugElement.nativeElement.querySelector('.mat-mdc-tab-link');
dispatchMouseEvent(tabLink, 'mousedown');
dispatchMouseEvent(tabLink, 'mouseup');
expect(tabLink.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected one ripple to show up if user clicks on tab link.')
.toBe(1);
});
it('should be able to disable ripples on an individual tab link', () => {
const tabLinkDebug = fixture.debugElement.query(By.css('a'));
const tabLinkElement = tabLinkDebug.nativeElement;
fixture.componentInstance.disableRippleOnLink = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(tabLinkElement, 'mousedown');
dispatchMouseEvent(tabLinkElement, 'mouseup');
expect(tabLinkElement.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected no ripple to show up if ripples are disabled.')
.toBe(0);
});
it('should be able to disable ripples through global options at runtime', () => {
expect(fixture.componentInstance.tabLinks.toArray().every(tabLink => !tabLink.rippleDisabled))
.withContext('Expected every tab link to have ripples enabled')
.toBe(true);
globalRippleOptions.disabled = true;
expect(fixture.componentInstance.tabLinks.toArray().every(tabLink => tabLink.rippleDisabled))
.withContext('Expected every tab link to have ripples disabled')
.toBe(true);
});
it('should have a focus indicator', () => {
const tabLinkNativeElements = [
...fixture.debugElement.nativeElement.querySelectorAll('.mat-mdc-tab-link'),
];
expect(
tabLinkNativeElements.every(element => element.classList.contains('mat-focus-indicator')),
).toBe(true);
});
});
describe('with the ink bar fit to content', () => {
let fixture: ComponentFixture<SimpleTabNavBarTestApp>;
beforeEach(() => {
fixture = TestBed.createComponent(SimpleTabNavBarTestApp);
fixture.componentInstance.fitInkBarToContent = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
});
it('should properly nest the ink bar when fit to content', () => {
const tabElement = fixture.nativeElement.querySelector('.mdc-tab');
const contentElement = tabElement.querySelector('.mdc-tab__content');
const indicatorElement = tabElement.querySelector('.mdc-tab-indicator');
expect(indicatorElement.parentElement).toBeTruthy();
expect(indicatorElement.parentElement).toBe(contentElement);
});
it('should be able to move the ink bar between content and full', () => {
fixture.componentInstance.fitInkBarToContent = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const tabElement = fixture.nativeElement.querySelector('.mdc-tab');
const indicatorElement = tabElement.querySelector('.mdc-tab-indicator');
expect(indicatorElement.parentElement).toBeTruthy();
expect(indicatorElement.parentElement).toBe(tabElement);
fixture.componentInstance.fitInkBarToContent = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const contentElement = tabElement.querySelector('.mdc-tab__content');
expect(indicatorElement.parentElement).toBeTruthy();
expect(indicatorElement.parentElement).toBe(contentElement);
});
});
});
describe('MatTabNavBar with a default config', () => {
let fixture: ComponentFixture<TabLinkWithNgIf>;
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [MatTabsModule, BrowserAnimationsModule, TabLinkWithNgIf],
providers: [{provide: MAT_TABS_CONFIG, useValue: {fitInkBarToContent: true}}],
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(TabLinkWithNgIf);
fixture.detectChanges();
});
it('should set whether the ink bar fits to content', () => {
const tabElement = fixture.nativeElement.querySelector('.mdc-tab');
const contentElement = tabElement.querySelector('.mdc-tab__content');
const indicatorElement = tabElement.querySelector('.mdc-tab-indicator');
expect(indicatorElement.parentElement).toBeTruthy();
expect(indicatorElement.parentElement).toBe(contentElement);
});
}); | {
"end_byte": 19146,
"start_byte": 10131,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-nav-bar/tab-nav-bar.spec.ts"
} |
components/src/material/tabs/tab-nav-bar/tab-nav-bar.spec.ts_19148_22055 | describe('MatTabNavBar with enabled animations', () => {
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [MatTabsModule, BrowserAnimationsModule, TabsWithCustomAnimationDuration],
});
}));
it('should not throw when setting an animationDuration without units', fakeAsync(() => {
expect(() => {
let fixture = TestBed.createComponent(TabsWithCustomAnimationDuration);
fixture.detectChanges();
tick();
}).not.toThrow();
}));
it('should set appropiate css variable given a specified animationDuration', fakeAsync(() => {
let fixture = TestBed.createComponent(TabsWithCustomAnimationDuration);
fixture.detectChanges();
tick();
const tabNavBar = fixture.nativeElement.querySelector('.mat-mdc-tab-nav-bar');
expect(tabNavBar.style.getPropertyValue('--mat-tab-animation-duration')).toBe('500ms');
}));
});
@Component({
selector: 'test-app',
template: `
<nav mat-tab-nav-bar
[disableRipple]="disableRippleOnBar"
[fitInkBarToContent]="fitInkBarToContent"
[tabPanel]="tabPanel">
@for (tab of tabs; track tab; let index = $index) {
<a mat-tab-link
[active]="activeIndex === index"
[disabled]="disabled"
(click)="activeIndex = index"
[disableRipple]="disableRippleOnLink">Tab link {{label}}</a>
}
</nav>
<mat-tab-nav-panel #tabPanel id="tab-panel">Tab panel</mat-tab-nav-panel>
`,
standalone: true,
imports: [MatTabsModule],
})
class SimpleTabNavBarTestApp {
@ViewChild(MatTabNav) tabNavBar: MatTabNav;
@ViewChildren(MatTabLink) tabLinks: QueryList<MatTabLink>;
label = '';
disabled = false;
disableRippleOnBar = false;
disableRippleOnLink = false;
tabs = [0, 1, 2];
fitInkBarToContent = false;
activeIndex = 0;
}
@Component({
template: `
<nav mat-tab-nav-bar [tabPanel]="tabPanel">
@if (!isDestroyed) {
<a mat-tab-link>Link</a>
}
</nav>
<mat-tab-nav-panel #tabPanel>Tab panel</mat-tab-nav-panel>
`,
standalone: true,
imports: [MatTabsModule],
})
class TabLinkWithNgIf {
isDestroyed = false;
}
@Component({
template: `
<nav mat-tab-nav-bar [tabPanel]="tabPanel">
@for (tab of tabs; track tab) {
<a mat-tab-link [active]="false">Tab link {{label}}</a>
}
</nav>
<mat-tab-nav-panel #tabPanel>Tab panel</mat-tab-nav-panel>
`,
standalone: true,
imports: [MatTabsModule],
})
class TabBarWithInactiveTabsOnInit {
tabs = [0, 1, 2];
}
@Component({
template: `
<nav [animationDuration]="500" mat-tab-nav-bar [tabPanel]="tabPanel">
@for (link of links; track link) {
<a mat-tab-link>{{link}}</a>
}
</nav>
<mat-tab-nav-panel #tabPanel></mat-tab-nav-panel>,
`,
standalone: true,
imports: [MatTabsModule],
})
class TabsWithCustomAnimationDuration {
links = ['First', 'Second', 'Third'];
} | {
"end_byte": 22055,
"start_byte": 19148,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-nav-bar/tab-nav-bar.spec.ts"
} |
components/src/material/tabs/tab-nav-bar/tab-nav-bar.html_0_1413 | <!--
Note that this intentionally uses a `div` instead of a `button`, because it's not part of
the regular tabs flow and is only here to support mouse users. It should also not be focusable.
-->
<div class="mat-mdc-tab-header-pagination mat-mdc-tab-header-pagination-before"
#previousPaginator
mat-ripple
[matRippleDisabled]="_disableScrollBefore || disableRipple"
[class.mat-mdc-tab-header-pagination-disabled]="_disableScrollBefore"
(click)="_handlePaginatorClick('before')"
(mousedown)="_handlePaginatorPress('before', $event)"
(touchend)="_stopInterval()">
<div class="mat-mdc-tab-header-pagination-chevron"></div>
</div>
<div class="mat-mdc-tab-link-container" #tabListContainer (keydown)="_handleKeydown($event)">
<div class="mat-mdc-tab-list" #tabList (cdkObserveContent)="_onContentChanges()">
<div class="mat-mdc-tab-links" #tabListInner>
<ng-content></ng-content>
</div>
</div>
</div>
<div class="mat-mdc-tab-header-pagination mat-mdc-tab-header-pagination-after"
#nextPaginator
mat-ripple
[matRippleDisabled]="_disableScrollAfter || disableRipple"
[class.mat-mdc-tab-header-pagination-disabled]="_disableScrollAfter"
(mousedown)="_handlePaginatorPress('after', $event)"
(click)="_handlePaginatorClick('after')"
(touchend)="_stopInterval()">
<div class="mat-mdc-tab-header-pagination-chevron"></div>
</div>
| {
"end_byte": 1413,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-nav-bar/tab-nav-bar.html"
} |
components/src/material/tabs/tab-nav-bar/tab-link.html_0_299 | <span class="mdc-tab__ripple"></span>
<div
class="mat-mdc-tab-ripple"
mat-ripple
[matRippleTrigger]="elementRef.nativeElement"
[matRippleDisabled]="rippleDisabled"></div>
<span class="mdc-tab__content">
<span class="mdc-tab__text-label">
<ng-content></ng-content>
</span>
</span>
| {
"end_byte": 299,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-nav-bar/tab-link.html"
} |
components/src/material/tabs/tab-nav-bar/tab-nav-bar.ts_0_8047 | /**
* @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 {
AfterContentChecked,
AfterContentInit,
AfterViewInit,
booleanAttribute,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
forwardRef,
Input,
NgZone,
numberAttribute,
OnDestroy,
QueryList,
ViewChild,
ViewEncapsulation,
ANIMATION_MODULE_TYPE,
inject,
HostAttributeToken,
} from '@angular/core';
import {
MAT_RIPPLE_GLOBAL_OPTIONS,
MatRipple,
RippleConfig,
RippleGlobalOptions,
RippleTarget,
ThemePalette,
_StructuralStylesLoader,
} from '@angular/material/core';
import {FocusableOption, FocusMonitor} from '@angular/cdk/a11y';
import {Directionality} from '@angular/cdk/bidi';
import {ViewportRuler} from '@angular/cdk/scrolling';
import {Platform} from '@angular/cdk/platform';
import {MatInkBar, InkBarItem} from '../ink-bar';
import {BehaviorSubject, Subject} from 'rxjs';
import {startWith, takeUntil} from 'rxjs/operators';
import {ENTER, SPACE} from '@angular/cdk/keycodes';
import {MAT_TABS_CONFIG, MatTabsConfig} from '../tab-config';
import {MatPaginatedTabHeader} from '../paginated-tab-header';
import {CdkObserveContent} from '@angular/cdk/observers';
import {_CdkPrivateStyleLoader} from '@angular/cdk/private';
// Increasing integer for generating unique ids for tab nav components.
let nextUniqueId = 0;
/**
* Navigation component matching the styles of the tab group header.
* Provides anchored navigation with animated ink bar.
*/
@Component({
selector: '[mat-tab-nav-bar]',
exportAs: 'matTabNavBar, matTabNav',
templateUrl: 'tab-nav-bar.html',
styleUrl: 'tab-nav-bar.css',
host: {
'[attr.role]': '_getRole()',
'class': 'mat-mdc-tab-nav-bar mat-mdc-tab-header',
'[class.mat-mdc-tab-header-pagination-controls-enabled]': '_showPaginationControls',
'[class.mat-mdc-tab-header-rtl]': "_getLayoutDirection() == 'rtl'",
'[class.mat-mdc-tab-nav-bar-stretch-tabs]': 'stretchTabs',
'[class.mat-primary]': 'color !== "warn" && color !== "accent"',
'[class.mat-accent]': 'color === "accent"',
'[class.mat-warn]': 'color === "warn"',
'[class._mat-animation-noopable]': '_animationMode === "NoopAnimations"',
'[style.--mat-tab-animation-duration]': 'animationDuration',
},
encapsulation: ViewEncapsulation.None,
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
imports: [MatRipple, CdkObserveContent],
})
export class MatTabNav
extends MatPaginatedTabHeader
implements AfterContentChecked, AfterContentInit, OnDestroy, AfterViewInit
{
/** Whether the ink bar should fit its width to the size of the tab label content. */
@Input({transform: booleanAttribute})
get fitInkBarToContent(): boolean {
return this._fitInkBarToContent.value;
}
set fitInkBarToContent(value: boolean) {
this._fitInkBarToContent.next(value);
this._changeDetectorRef.markForCheck();
}
_fitInkBarToContent = new BehaviorSubject(false);
/** Whether tabs should be stretched to fill the header. */
@Input({alias: 'mat-stretch-tabs', transform: booleanAttribute})
stretchTabs: boolean = true;
@Input()
get animationDuration(): string {
return this._animationDuration;
}
set animationDuration(value: string | number) {
const stringValue = value + '';
this._animationDuration = /^\d+$/.test(stringValue) ? value + 'ms' : stringValue;
}
private _animationDuration: string;
/** Query list of all tab links of the tab navigation. */
@ContentChildren(forwardRef(() => MatTabLink), {descendants: true}) _items: QueryList<MatTabLink>;
/**
* Theme color of the background of the tab nav. This API is supported in M2 themes only, it
* has no effect in M3 themes.
*
* For information on applying color variants in M3, see
* https://material.angular.io/guide/theming#using-component-color-variants.
*/
@Input()
get backgroundColor(): ThemePalette {
return this._backgroundColor;
}
set backgroundColor(value: ThemePalette) {
const classList = this._elementRef.nativeElement.classList;
classList.remove('mat-tabs-with-background', `mat-background-${this.backgroundColor}`);
if (value) {
classList.add('mat-tabs-with-background', `mat-background-${value}`);
}
this._backgroundColor = value;
}
private _backgroundColor: ThemePalette;
/** Whether the ripple effect is disabled or not. */
@Input({transform: booleanAttribute})
disableRipple: boolean = false;
/**
* Theme color of the nav bar. This API is supported in M2 themes only, it has
* no effect in M3 themes.
*
* For information on applying color variants in M3, see
* https://material.angular.io/guide/theming#using-component-color-variants.
*/
@Input() color: ThemePalette = 'primary';
/**
* Associated tab panel controlled by the nav bar. If not provided, then the nav bar
* follows the ARIA link / navigation landmark pattern. If provided, it follows the
* ARIA tabs design pattern.
*/
@Input() tabPanel?: MatTabNavPanel;
@ViewChild('tabListContainer', {static: true}) _tabListContainer: ElementRef;
@ViewChild('tabList', {static: true}) _tabList: ElementRef;
@ViewChild('tabListInner', {static: true}) _tabListInner: ElementRef;
@ViewChild('nextPaginator') _nextPaginator: ElementRef<HTMLElement>;
@ViewChild('previousPaginator') _previousPaginator: ElementRef<HTMLElement>;
_inkBar: MatInkBar;
constructor(...args: unknown[]);
constructor() {
const elementRef = inject(ElementRef);
const dir = inject(Directionality, {optional: true});
const ngZone = inject(NgZone);
const changeDetectorRef = inject(ChangeDetectorRef);
const viewportRuler = inject(ViewportRuler);
const platform = inject(Platform);
const animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true});
const defaultConfig = inject<MatTabsConfig>(MAT_TABS_CONFIG, {optional: true});
super(elementRef, changeDetectorRef, viewportRuler, dir, ngZone, platform, animationMode);
this.disablePagination =
defaultConfig && defaultConfig.disablePagination != null
? defaultConfig.disablePagination
: false;
this.fitInkBarToContent =
defaultConfig && defaultConfig.fitInkBarToContent != null
? defaultConfig.fitInkBarToContent
: false;
this.stretchTabs =
defaultConfig && defaultConfig.stretchTabs != null ? defaultConfig.stretchTabs : true;
}
protected _itemSelected() {
// noop
}
override ngAfterContentInit() {
this._inkBar = new MatInkBar(this._items);
// We need this to run before the `changes` subscription in parent to ensure that the
// selectedIndex is up-to-date by the time the super class starts looking for it.
this._items.changes.pipe(startWith(null), takeUntil(this._destroyed)).subscribe(() => {
this.updateActiveLink();
});
super.ngAfterContentInit();
}
override ngAfterViewInit() {
if (!this.tabPanel && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw new Error('A mat-tab-nav-panel must be specified via [tabPanel].');
}
super.ngAfterViewInit();
}
/** Notifies the component that the active link has been changed. */
updateActiveLink() {
if (!this._items) {
return;
}
const items = this._items.toArray();
for (let i = 0; i < items.length; i++) {
if (items[i].active) {
this.selectedIndex = i;
this._changeDetectorRef.markForCheck();
if (this.tabPanel) {
this.tabPanel._activeTabId = items[i].id;
}
return;
}
}
// The ink bar should hide itself if no items are active.
this.selectedIndex = -1;
this._inkBar.hide();
}
_getRole(): string | null {
return this.tabPanel ? 'tablist' : this._elementRef.nativeElement.getAttribute('role');
}
} | {
"end_byte": 8047,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-nav-bar/tab-nav-bar.ts"
} |
components/src/material/tabs/tab-nav-bar/tab-nav-bar.ts_8049_13956 | /**
* Link inside a `mat-tab-nav-bar`.
*/
@Component({
selector: '[mat-tab-link], [matTabLink]',
exportAs: 'matTabLink',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
templateUrl: 'tab-link.html',
styleUrl: 'tab-link.css',
host: {
'class': 'mdc-tab mat-mdc-tab-link mat-focus-indicator',
'[attr.aria-controls]': '_getAriaControls()',
'[attr.aria-current]': '_getAriaCurrent()',
'[attr.aria-disabled]': 'disabled',
'[attr.aria-selected]': '_getAriaSelected()',
'[attr.id]': 'id',
'[attr.tabIndex]': '_getTabIndex()',
'[attr.role]': '_getRole()',
'[class.mat-mdc-tab-disabled]': 'disabled',
'[class.mdc-tab--active]': 'active',
'(focus)': '_handleFocus()',
'(keydown)': '_handleKeydown($event)',
},
imports: [MatRipple],
})
export class MatTabLink
extends InkBarItem
implements AfterViewInit, OnDestroy, RippleTarget, FocusableOption
{
private _tabNavBar = inject(MatTabNav);
elementRef = inject(ElementRef);
private _focusMonitor = inject(FocusMonitor);
private readonly _destroyed = new Subject<void>();
/** Whether the tab link is active or not. */
protected _isActive: boolean = false;
/** Whether the link is active. */
@Input({transform: booleanAttribute})
get active(): boolean {
return this._isActive;
}
set active(value: boolean) {
if (value !== this._isActive) {
this._isActive = value;
this._tabNavBar.updateActiveLink();
}
}
/** Whether the tab link is disabled. */
@Input({transform: booleanAttribute})
disabled: boolean = false;
/** Whether ripples are disabled on the tab link. */
@Input({transform: booleanAttribute})
disableRipple: boolean = false;
@Input({
transform: (value: unknown) => (value == null ? 0 : numberAttribute(value)),
})
tabIndex: number = 0;
/**
* Ripple configuration for ripples that are launched on pointer down. The ripple config
* is set to the global ripple options since we don't have any configurable options for
* the tab link ripples.
* @docs-private
*/
rippleConfig: RippleConfig & RippleGlobalOptions;
/**
* Whether ripples are disabled on interaction.
* @docs-private
*/
get rippleDisabled(): boolean {
return (
this.disabled ||
this.disableRipple ||
this._tabNavBar.disableRipple ||
!!this.rippleConfig.disabled
);
}
/** Unique id for the tab. */
@Input() id = `mat-tab-link-${nextUniqueId++}`;
constructor(...args: unknown[]);
constructor() {
super();
inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader);
const globalRippleOptions = inject<RippleGlobalOptions | null>(MAT_RIPPLE_GLOBAL_OPTIONS, {
optional: true,
});
const tabIndex = inject(new HostAttributeToken('tabindex'), {optional: true});
const animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true});
this.rippleConfig = globalRippleOptions || {};
this.tabIndex = tabIndex == null ? 0 : parseInt(tabIndex) || 0;
if (animationMode === 'NoopAnimations') {
this.rippleConfig.animation = {enterDuration: 0, exitDuration: 0};
}
this._tabNavBar._fitInkBarToContent
.pipe(takeUntil(this._destroyed))
.subscribe(fitInkBarToContent => {
this.fitInkBarToContent = fitInkBarToContent;
});
}
/** Focuses the tab link. */
focus() {
this.elementRef.nativeElement.focus();
}
ngAfterViewInit() {
this._focusMonitor.monitor(this.elementRef);
}
override ngOnDestroy() {
this._destroyed.next();
this._destroyed.complete();
super.ngOnDestroy();
this._focusMonitor.stopMonitoring(this.elementRef);
}
_handleFocus() {
// Since we allow navigation through tabbing in the nav bar, we
// have to update the focused index whenever the link receives focus.
this._tabNavBar.focusIndex = this._tabNavBar._items.toArray().indexOf(this);
}
_handleKeydown(event: KeyboardEvent) {
if (event.keyCode === SPACE || event.keyCode === ENTER) {
if (this.disabled) {
event.preventDefault();
} else if (this._tabNavBar.tabPanel) {
// Only prevent the default action on space since it can scroll the page.
// Don't prevent enter since it can break link navigation.
if (event.keyCode === SPACE) {
event.preventDefault();
}
this.elementRef.nativeElement.click();
}
}
}
_getAriaControls(): string | null {
return this._tabNavBar.tabPanel
? this._tabNavBar.tabPanel?.id
: this.elementRef.nativeElement.getAttribute('aria-controls');
}
_getAriaSelected(): string | null {
if (this._tabNavBar.tabPanel) {
return this.active ? 'true' : 'false';
} else {
return this.elementRef.nativeElement.getAttribute('aria-selected');
}
}
_getAriaCurrent(): string | null {
return this.active && !this._tabNavBar.tabPanel ? 'page' : null;
}
_getRole(): string | null {
return this._tabNavBar.tabPanel ? 'tab' : this.elementRef.nativeElement.getAttribute('role');
}
_getTabIndex(): number {
if (this._tabNavBar.tabPanel) {
return this._isActive && !this.disabled ? 0 : -1;
} else {
return this.disabled ? -1 : this.tabIndex;
}
}
}
/**
* Tab panel component associated with MatTabNav.
*/
@Component({
selector: 'mat-tab-nav-panel',
exportAs: 'matTabNavPanel',
template: '<ng-content></ng-content>',
host: {
'[attr.aria-labelledby]': '_activeTabId',
'[attr.id]': 'id',
'class': 'mat-mdc-tab-nav-panel',
'role': 'tabpanel',
},
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatTabNavPanel {
/** Unique id for the tab panel. */
@Input() id = `mat-tab-nav-panel-${nextUniqueId++}`;
/** Id of the active tab in the nav bar. */
_activeTabId?: string;
} | {
"end_byte": 13956,
"start_byte": 8049,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-nav-bar/tab-nav-bar.ts"
} |
components/src/material/tabs/tab-nav-bar/tab-link.scss_0_569 | @use '../../core/style/variables';
@use '../tabs-common';
// Wraps each link in the header
.mat-mdc-tab-link {
@include tabs-common.tab;
// Note that we only want to target direct descendant tabs.
.mat-mdc-tab-header.mat-mdc-tab-nav-bar-stretch-tabs & {
flex-grow: 1;
}
// For the tab-link element, default inset/offset values are necessary to ensure that
// the focus indicator is sufficiently contrastive and renders appropriately.
&::before {
margin: 5px;
}
}
@media (variables.$xsmall) {
.mat-mdc-tab-link {
min-width: 72px;
}
}
| {
"end_byte": 569,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/tab-nav-bar/tab-link.scss"
} |
components/src/material/tabs/testing/tab-group-harness.ts_0_2522 | /**
* @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 {TabGroupHarnessFilters, TabHarnessFilters} from './tab-harness-filters';
import {MatTabHarness} from './tab-harness';
/** Harness for interacting with a mat-tab-group in tests. */
export class MatTabGroupHarness extends ComponentHarness {
/** The selector for the host element of a `MatTabGroup` instance. */
static hostSelector = '.mat-mdc-tab-group';
/**
* Gets a `HarnessPredicate` that can be used to search for a tab group with specific attributes.
* @param options Options for filtering which tab group instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatTabGroupHarness>(
this: ComponentHarnessConstructor<T>,
options: TabGroupHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options).addOption(
'selectedTabLabel',
options.selectedTabLabel,
async (harness, label) => {
const selectedTab = await harness.getSelectedTab();
return HarnessPredicate.stringMatches(await selectedTab.getLabel(), label);
},
);
}
/**
* Gets the list of tabs in the tab group.
* @param filter Optionally filters which tabs are included.
*/
async getTabs(filter: TabHarnessFilters = {}): Promise<MatTabHarness[]> {
return this.locatorForAll(MatTabHarness.with(filter))();
}
/** Gets the selected tab of the tab group. */
async getSelectedTab(): Promise<MatTabHarness> {
const tabs = await this.getTabs();
const isSelected = await parallel(() => tabs.map(t => t.isSelected()));
for (let i = 0; i < tabs.length; i++) {
if (isSelected[i]) {
return tabs[i];
}
}
throw new Error('No selected tab could be found.');
}
/**
* Selects a tab in this tab group.
* @param filter An optional filter to apply to the child tabs. The first tab matching the filter
* will be selected.
*/
async selectTab(filter: TabHarnessFilters = {}): Promise<void> {
const tabs = await this.getTabs(filter);
if (!tabs.length) {
throw Error(`Cannot find mat-tab matching filter ${JSON.stringify(filter)}`);
}
await tabs[0].select();
}
}
| {
"end_byte": 2522,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/testing/tab-group-harness.ts"
} |
components/src/material/tabs/testing/public-api.ts_0_386 | /**
* @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 './tab-group-harness';
export * from './tab-harness';
export * from './tab-harness-filters';
export * from './tab-nav-bar-harness';
export * from './tab-link-harness';
| {
"end_byte": 386,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/testing/public-api.ts"
} |
components/src/material/tabs/testing/tab-nav-panel-harness.ts_0_1308 | /**
* @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 {TabNavPanelHarnessFilters} from './tab-harness-filters';
/** Harness for interacting with a standard mat-tab-nav-panel in tests. */
export class MatTabNavPanelHarness extends ContentContainerComponentHarness {
/** The selector for the host element of a `MatTabNavPanel` instance. */
static hostSelector = '.mat-mdc-tab-nav-panel';
/**
* Gets a `HarnessPredicate` that can be used to search for a tab nav panel with specific
* attributes.
* @param options Options for filtering which tab nav panel instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatTabNavPanelHarness>(
this: ComponentHarnessConstructor<T>,
options: TabNavPanelHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options);
}
/** Gets the tab panel text content. */
async getTextContent(): Promise<string> {
return (await this.host()).text();
}
}
| {
"end_byte": 1308,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/testing/tab-nav-panel-harness.ts"
} |
components/src/material/tabs/testing/tab-harness.ts_0_3175 | /**
* @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,
HarnessLoader,
HarnessPredicate,
} from '@angular/cdk/testing';
import {TabHarnessFilters} from './tab-harness-filters';
/** Harness for interacting with an Angular Material tab in tests. */
export class MatTabHarness extends ContentContainerComponentHarness<string> {
/** The selector for the host element of a `MatTab` instance. */
static hostSelector = '.mat-mdc-tab';
/**
* Gets a `HarnessPredicate` that can be used to search for a tab with specific attributes.
* @param options Options for filtering which tab instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatTabHarness>(
this: ComponentHarnessConstructor<T>,
options: TabHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options)
.addOption('label', options.label, (harness, label) =>
HarnessPredicate.stringMatches(harness.getLabel(), label),
)
.addOption(
'selected',
options.selected,
async (harness, selected) => (await harness.isSelected()) == selected,
);
}
/** Gets the label of the tab. */
async getLabel(): Promise<string> {
return (await this.host()).text();
}
/** Gets the aria-label of the tab. */
async getAriaLabel(): Promise<string | null> {
return (await this.host()).getAttribute('aria-label');
}
/** Gets the value of the "aria-labelledby" attribute. */
async getAriaLabelledby(): Promise<string | null> {
return (await this.host()).getAttribute('aria-labelledby');
}
/** Whether the tab is selected. */
async isSelected(): Promise<boolean> {
const hostEl = await this.host();
return (await hostEl.getAttribute('aria-selected')) === 'true';
}
/** Whether the tab is disabled. */
async isDisabled(): Promise<boolean> {
const hostEl = await this.host();
return (await hostEl.getAttribute('aria-disabled')) === 'true';
}
/** Selects the given tab by clicking on the label. Tab cannot be selected if disabled. */
async select(): Promise<void> {
await (await this.host()).click('center');
}
/** Gets the text content of the tab. */
async getTextContent(): Promise<string> {
const contentId = await this._getContentId();
const contentEl = await this.documentRootLocatorFactory().locatorFor(`#${contentId}`)();
return contentEl.text();
}
protected override async getRootHarnessLoader(): Promise<HarnessLoader> {
const contentId = await this._getContentId();
return this.documentRootLocatorFactory().harnessLoaderFor(`#${contentId}`);
}
/** Gets the element id for the content of the current tab. */
private async _getContentId(): Promise<string> {
const hostEl = await this.host();
// Tabs never have an empty "aria-controls" attribute.
return (await hostEl.getAttribute('aria-controls'))!;
}
}
| {
"end_byte": 3175,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/tabs/testing/tab-harness.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.