_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
components/src/material-experimental/public-api.ts_0_231
|
/**
* @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 './version';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 231,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/public-api.ts"
}
|
components/src/material-experimental/config.bzl_0_1308
|
entryPoints = [
"column-resize",
"menubar",
"popover-edit",
"selection",
]
# List of all non-testing entry-points of the Angular material-experimental package.
MATERIAL_EXPERIMENTAL_ENTRYPOINTS = [
ep
for ep in entryPoints
if not "/testing" in ep
]
# List of all testing entry-points of the Angular material-experimental package.
MATERIAL_EXPERIMENTAL_TESTING_ENTRYPOINTS = [
ep
for ep in entryPoints
if not ep in MATERIAL_EXPERIMENTAL_ENTRYPOINTS
]
# List of all non-testing entry-point targets of the Angular material-experimental package.
MATERIAL_EXPERIMENTAL_TARGETS = ["//src/material-experimental"] + \
["//src/material-experimental/%s" % ep for ep in MATERIAL_EXPERIMENTAL_ENTRYPOINTS]
# List of all testing entry-point targets of the Angular material-experimental package.
MATERIAL_EXPERIMENTAL_TESTING_TARGETS = ["//src/material-experimental/%s" % ep for ep in MATERIAL_EXPERIMENTAL_TESTING_ENTRYPOINTS]
MATERIAL_EXPERIMENTAL_SCSS_LIBS = [
"//src/material-experimental/%s:%s_scss_lib" % (ep, ep.replace("-", "_"))
# Only secondary entry-points declare theme files currently. Entry-points
# which contain a slash are not in the top-level.
for ep in MATERIAL_EXPERIMENTAL_ENTRYPOINTS
if not "/" in ep
]
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1308,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/config.bzl"
}
|
components/src/material-experimental/README.md_0_2488
|
# Angular Material Experimental
This package contains prototypes and experiments in development for Angular Material. Nothing in
this package is considered stable or production ready. While the package releases with Angular
Material, breaking changes may occur with any release.
## Using the experimental components based on MDC Web
Assuming your application is already up and running using Angular Material, you can add this
component by following these steps:
1. Install Angular Material Experimental:
```bash
npm i @angular/material-experimental
```
2. In your `angular.json`, make sure `node_modules/` is listed as a Sass include path. This is
needed for the Sass compiler to be able to find the MDC Web Sass files.
```json
...
"styles": [
"src/styles.scss"
],
"stylePreprocessorOptions": {
"includePaths": [
"node_modules/"
]
},
...
```
3. Import the `NgModule` for the component you want to use. For example, the checkbox:
```ts
import {MatCheckboxModule} from '@angular/material/checkbox';
@NgModule({
declarations: [MyComponent],
imports: [MatCheckboxModule],
})
export class MyModule {}
```
4. Use the components just as you would the normal Angular Material components. For example,
the checkbox:
```html
<mat-checkbox [checked]="isChecked">Check me</mat-checkbox>
```
5. Add the theme and typography mixins to your Sass. These align with the normal Angular Material
mixins except that they are suffixed with `-mdc`. Some experimental components may not yet
be included in the pre-built CSS mixin and will need to be explicitly included.
```scss
@use '@angular/material' as mat;
@use '@angular/material-experimental' as mat-experimental;
$my-primary: mat.define-palette(mat.$indigo-palette);
$my-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);
$my-theme: mat.define-light-theme((
color: (
primary: $my-primary,
accent: $my-accent
),
// Using `define-mdc-typography-config` rather than `define-typography-config` generates a
// typography config directly from the official Material Design styles. This includes using
// `rem`-based measurements rather than `px`-based ones as the spec recommends.
typography: mat-experimental.define-mdc-typography-config(),
// The density level to use in this theme, defaults to 0 if not specified.
density: 0
));
@include mat-experimental.all-mdc-component-themes($my-theme);
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2488,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/README.md"
}
|
components/src/material-experimental/BUILD.bazel_0_897
|
load(
"//src/material-experimental:config.bzl",
"MATERIAL_EXPERIMENTAL_SCSS_LIBS",
"MATERIAL_EXPERIMENTAL_TARGETS",
"MATERIAL_EXPERIMENTAL_TESTING_TARGETS",
)
load("//tools:defaults.bzl", "ng_package", "sass_library", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "material-experimental",
srcs = glob(
["*.ts"],
exclude = ["**/*.spec.ts"],
),
deps = ["@npm//@angular/core"],
)
sass_library(
name = "theming_scss_lib",
srcs = MATERIAL_EXPERIMENTAL_SCSS_LIBS,
)
sass_library(
name = "sass_lib",
srcs = ["_index.scss"],
deps = [
":theming_scss_lib",
],
)
ng_package(
name = "npm_package",
srcs = [
"package.json",
":sass_lib",
],
tags = ["release-package"],
deps = MATERIAL_EXPERIMENTAL_TARGETS + MATERIAL_EXPERIMENTAL_TESTING_TARGETS,
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 897,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/BUILD.bazel"
}
|
components/src/material-experimental/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';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/index.ts"
}
|
components/src/material-experimental/version.ts_0_362
|
/**
* @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 {Version} from '@angular/core';
/** Current version of the Material experimental package. */
export const VERSION = new Version('0.0.0-PLACEHOLDER');
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 362,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/version.ts"
}
|
components/src/material-experimental/menubar/public-api.ts_0_297
|
/**
* @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 './menubar';
export * from './menubar-item';
export * from './menubar-module';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 297,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/menubar/public-api.ts"
}
|
components/src/material-experimental/menubar/menubar-item.html_0_26
|
<ng-content></ng-content>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 26,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/menubar/menubar-item.html"
}
|
components/src/material-experimental/menubar/menubar.html_0_26
|
<ng-content></ng-content>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 26,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/menubar/menubar.html"
}
|
components/src/material-experimental/menubar/menubar-item.spec.ts_0_2229
|
import {Component, ElementRef, ViewChild} from '@angular/core';
import {ComponentFixture, waitForAsync, TestBed} from '@angular/core/testing';
import {CdkMenuItem, CdkMenuModule, CdkMenu} from '@angular/cdk/menu';
import {MatMenuBarItem} from './menubar-item';
import {MatMenuBarModule} from './menubar-module';
describe('MatMenuBarItem', () => {
let fixture: ComponentFixture<SimpleMenuBarItem>;
let nativeMenubarItem: HTMLElement;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatMenuBarModule, CdkMenuModule, SimpleMenuBarItem],
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(SimpleMenuBarItem);
fixture.detectChanges();
nativeMenubarItem = fixture.componentInstance.nativeMenubarItem.nativeElement;
});
it('should have the menuitem role', () => {
expect(nativeMenubarItem.getAttribute('role')).toBe('menuitem');
});
it('should be a button type', () => {
expect(nativeMenubarItem.getAttribute('type')).toBe('button');
});
it('should not set the aria-disabled attribute when false', () => {
expect(nativeMenubarItem.hasAttribute('aria.disabled')).toBeFalse();
});
it('should have cdk and material classes set', () => {
expect(nativeMenubarItem.classList.contains('cdk-menu-item')).toBeTrue();
expect(nativeMenubarItem.classList.contains('mat-menubar-item')).toBeTrue();
});
it('should open the attached menu on click', () => {
nativeMenubarItem.click();
fixture.detectChanges();
expect(fixture.componentInstance.menu).toBeDefined();
});
it('should have initial tab index set to -1', () => {
expect(nativeMenubarItem.tabIndex).toBe(-1);
});
});
@Component({
template: `
<mat-menubar>
<mat-menubar-item [cdkMenuTriggerFor]="sub">File</mat-menubar-item>
</mat-menubar>
<ng-template #sub>
<div #menu cdkMenu>
<button cdkMenuItem></button>
</div>
</ng-template>
`,
standalone: true,
imports: [MatMenuBarModule, CdkMenuModule],
})
class SimpleMenuBarItem {
@ViewChild(CdkMenuItem) menubarItem: MatMenuBarItem;
@ViewChild(CdkMenuItem, {read: ElementRef}) nativeMenubarItem: ElementRef;
@ViewChild('menu') menu: CdkMenu;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2229,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/menubar/menubar-item.spec.ts"
}
|
components/src/material-experimental/menubar/menubar-item.ts_0_1555
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, ViewEncapsulation, ChangeDetectionStrategy} from '@angular/core';
import {CdkMenuItem} from '@angular/cdk/menu';
/** Removes all icons from within the given element. */
function removeIcons(element: Element) {
for (const icon of Array.from(element.querySelectorAll('mat-icon, .material-icons'))) {
icon.remove();
}
}
/**
* A material design MenubarItem adhering to the functionality of CdkMenuItem and
* CdkMenuItemTrigger. Its main purpose is to trigger menus and it lives inside of
* MatMenubar.
*/
@Component({
selector: 'mat-menubar-item',
exportAs: 'matMenubarItem',
templateUrl: 'menubar-item.html',
styleUrl: 'menubar-item.css',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'[tabindex]': '_tabindex',
'type': 'button',
'role': 'menuitem',
'class': 'cdk-menu-item mat-menubar-item',
'[attr.aria-disabled]': 'disabled || null',
},
providers: [{provide: CdkMenuItem, useExisting: MatMenuBarItem}],
})
export class MatMenuBarItem extends CdkMenuItem {
override getLabel(): string {
if (this.typeaheadLabel !== undefined) {
return this.typeaheadLabel || '';
}
const clone = this._elementRef.nativeElement.cloneNode(true) as Element;
removeIcons(clone);
return clone.textContent?.trim() || '';
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1555,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/menubar/menubar-item.ts"
}
|
components/src/material-experimental/menubar/menubar.spec.ts_0_2007
|
import {Component, ViewChild, ElementRef} from '@angular/core';
import {RIGHT_ARROW} from '@angular/cdk/keycodes';
import {CdkMenuBar} from '@angular/cdk/menu';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {dispatchKeyboardEvent} from '../../cdk/testing/private';
import {MatMenuBarModule} from './menubar-module';
import {MatMenuBar} from './menubar';
describe('MatMenuBar', () => {
let fixture: ComponentFixture<SimpleMatMenuBar>;
let nativeMatMenubar: HTMLElement;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatMenuBarModule, SimpleMatMenuBar],
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(SimpleMatMenuBar);
fixture.detectChanges();
nativeMatMenubar = fixture.componentInstance.nativeMatMenubar.nativeElement;
});
it('should have the menubar role', () => {
expect(nativeMatMenubar.getAttribute('role')).toBe('menubar');
});
it('should have the cdk and material classes set', () => {
expect(nativeMatMenubar.classList.contains('cdk-menu-bar')).toBeTrue();
expect(nativeMatMenubar.classList.contains('mat-menubar')).toBeTrue();
});
it('should have tabindex set to 0', () => {
expect(nativeMatMenubar.getAttribute('tabindex')).toBe('0');
});
it('should toggle focused items on left/right click', () => {
nativeMatMenubar.focus();
expect(document.activeElement!.id).toBe('first');
dispatchKeyboardEvent(nativeMatMenubar, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(document.activeElement!.id).toBe('second');
});
});
@Component({
template: `
<mat-menubar>
<mat-menubar-item id="first"></mat-menubar-item>
<mat-menubar-item id="second"></mat-menubar-item>
</mat-menubar>
`,
standalone: true,
imports: [MatMenuBarModule],
})
class SimpleMatMenuBar {
@ViewChild(CdkMenuBar) matMenubar: MatMenuBar;
@ViewChild(CdkMenuBar, {read: ElementRef}) nativeMatMenubar: ElementRef;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2007,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/menubar/menubar.spec.ts"
}
|
components/src/material-experimental/menubar/menubar-module.ts_0_524
|
/**
* @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 {CdkMenuModule} from '@angular/cdk/menu';
import {MatMenuBar} from './menubar';
import {MatMenuBarItem} from './menubar-item';
@NgModule({
imports: [CdkMenuModule, MatMenuBar, MatMenuBarItem],
exports: [MatMenuBar, MatMenuBarItem],
})
export class MatMenuBarModule {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 524,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/menubar/menubar-module.ts"
}
|
components/src/material-experimental/menubar/BUILD.bazel_0_1186
|
load(
"//tools:defaults.bzl",
"ng_module",
"ng_test_library",
"ng_web_test_suite",
"sass_binary",
"sass_library",
)
package(default_visibility = ["//visibility:public"])
ng_module(
name = "menubar",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = [
":menubar.css",
":menubar-item.css",
] + glob(["**/*.html"]),
deps = [
"//src/cdk/menu",
"@npm//@angular/core",
],
)
sass_library(
name = "menubar_scss_lib",
srcs = glob(["**/_*.scss"]),
)
sass_binary(
name = "menubar_scss",
src = "menubar.scss",
)
sass_binary(
name = "menubar_item_scss",
src = "menubar-item.scss",
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":menubar",
"//src/cdk/keycodes",
"//src/cdk/menu",
"//src/cdk/testing/private",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1186,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/menubar/BUILD.bazel"
}
|
components/src/material-experimental/menubar/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';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/menubar/index.ts"
}
|
components/src/material-experimental/menubar/menubar.ts_0_1084
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ChangeDetectionStrategy, Component, ViewEncapsulation} from '@angular/core';
import {CDK_MENU, CdkMenuBar, CdkMenuGroup, MENU_STACK, MenuStack} from '@angular/cdk/menu';
/**
* A material design Menubar adhering to the functionality of CdkMenuBar. MatMenubar
* should contain MatMenubarItems which trigger their own sub-menus.
*/
@Component({
selector: 'mat-menubar',
exportAs: 'matMenubar',
templateUrl: 'menubar.html',
styleUrl: 'menubar.css',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'[class.mat-menubar]': 'true',
},
providers: [
{provide: CdkMenuGroup, useExisting: MatMenuBar},
{provide: CdkMenuBar, useExisting: MatMenuBar},
{provide: CDK_MENU, useExisting: MatMenuBar},
{provide: MENU_STACK, useClass: MenuStack},
],
})
export class MatMenuBar extends CdkMenuBar {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1084,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/menubar/menubar.ts"
}
|
components/src/material-experimental/column-resize/resize-strategy.ts_0_989
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Injectable, Provider} from '@angular/core';
import {_CoalescedStyleScheduler, _COALESCED_STYLE_SCHEDULER} from '@angular/cdk/table';
import {
ResizeStrategy,
CdkFlexTableResizeStrategy,
TABLE_LAYOUT_FIXED_RESIZE_STRATEGY_PROVIDER,
} from '@angular/cdk-experimental/column-resize';
export {TABLE_LAYOUT_FIXED_RESIZE_STRATEGY_PROVIDER};
/**
* Overrides CdkFlexTableResizeStrategy to match mat-column elements.
*/
@Injectable()
export class MatFlexTableResizeStrategy extends CdkFlexTableResizeStrategy {
protected override getColumnCssClass(cssFriendlyColumnName: string): string {
return `mat-column-${cssFriendlyColumnName}`;
}
}
export const FLEX_RESIZE_STRATEGY_PROVIDER: Provider = {
provide: ResizeStrategy,
useClass: MatFlexTableResizeStrategy,
};
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 989,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/resize-strategy.ts"
}
|
components/src/material-experimental/column-resize/column-resize.spec.ts_0_8559
|
import {BidiModule} from '@angular/cdk/bidi';
import {DataSource} from '@angular/cdk/collections';
import {ESCAPE} from '@angular/cdk/keycodes';
import {ChangeDetectionStrategy, Component, Directive, ElementRef, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush} from '@angular/core/testing';
import {MatTableModule} from '@angular/material/table';
import {BehaviorSubject} from 'rxjs';
import {dispatchKeyboardEvent} from '../../cdk/testing/private';
import {ColumnSize} from '@angular/cdk-experimental/column-resize';
import {AbstractMatColumnResize} from './column-resize-directives/common';
import {
MatColumnResize,
MatColumnResizeFlex,
MatColumnResizeModule,
MatDefaultEnabledColumnResize,
MatDefaultEnabledColumnResizeFlex,
MatDefaultEnabledColumnResizeModule,
} from './index';
function getDefaultEnabledDirectiveStrings() {
return {
table: '',
columnEnabled: '',
columnDisabled: 'disableResize',
};
}
function getOptInDirectiveStrings() {
return {
table: 'columnResize',
columnEnabled: 'resizable',
columnDisabled: '',
};
}
function getTableTemplate(defaultEnabled: boolean) {
const directives = defaultEnabled
? getDefaultEnabledDirectiveStrings()
: getOptInDirectiveStrings();
return `
<style>
.mat-mdc-resizable {
box-sizing: border-box;
}
.mat-mdc-header-cell {
border: 1px solid green;
}
table {
width: 800px;
}
</style>
<div #table [dir]="direction">
<table ${directives.table} mat-table [dataSource]="dataSource"
style="table-layout: fixed;">
<!-- Position Column -->
<ng-container matColumnDef="position" sticky>
<th mat-header-cell *matHeaderCellDef
${directives.columnEnabled} [matResizableMaxWidthPx]="100"> No. </th>
<td mat-cell *matCellDef="let element"> {{element.position}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name" sticky>
<th mat-header-cell *matHeaderCellDef
${directives.columnEnabled} [matResizableMinWidthPx]="150"> Name </th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>
<!-- Weight Column (not resizable) -->
<ng-container matColumnDef="weight" sticky>
<th mat-header-cell *matHeaderCellDef ${directives.columnDisabled}>
Weight (Not resizable)
</th>
<td mat-cell *matCellDef="let element"> {{element.weight}} </td>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="symbol">
<th mat-header-cell *matHeaderCellDef ${directives.columnEnabled}> Symbol </th>
<td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
`;
}
function getFlexTemplate(defaultEnabled: boolean) {
const directives = defaultEnabled
? getDefaultEnabledDirectiveStrings()
: getOptInDirectiveStrings();
return `
<style>
.mat-mdc-header-cell,
.mat-mdc-cell,
.mat-mdc-resizable {
box-sizing: border-box;
}
.mat-mdc-header-cell {
border: 1px solid green;
}
mat-table {
width: 800px;
}
</style>
<div #table [dir]="direction">
<mat-table ${directives.table} [dataSource]="dataSource">
<!-- Position Column -->
<ng-container matColumnDef="position" sticky>
<mat-header-cell *matHeaderCellDef
${directives.columnEnabled} [matResizableMaxWidthPx]="100"> No. </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.position}} </mat-cell>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name" sticky>
<mat-header-cell *matHeaderCellDef
${directives.columnEnabled} [matResizableMinWidthPx]="150"> Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
</ng-container>
<!-- Weight Column (not resizable) -->
<ng-container matColumnDef="weight" sticky>
<mat-header-cell *matHeaderCellDef ${directives.columnDisabled}>
Weight (Not resizable)
</mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.weight}} </mat-cell>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="symbol">
<mat-header-cell *matHeaderCellDef ${directives.columnEnabled}>
Symbol
</mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.symbol}} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
</div>
`;
}
const MOUSE_START_OFFSET = 1000;
@Directive()
abstract class BaseTestComponent {
@ViewChild('table') table: ElementRef;
abstract columnResize: AbstractMatColumnResize;
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
dataSource = new ElementDataSource();
direction = 'ltr';
getTableHeight(): number {
return this.table.nativeElement.querySelector('.mat-mdc-table').offsetHeight;
}
getTableWidth(): number {
return this.table.nativeElement.querySelector('.mat-mdc-table').offsetWidth;
}
getHeaderRowHeight(): number {
return this.table.nativeElement.querySelector('.mat-mdc-header-row .mat-mdc-header-cell')
.offsetHeight;
}
getColumnElement(index: number): HTMLElement {
return this.table.nativeElement!.querySelectorAll('.mat-mdc-header-cell')[index] as HTMLElement;
}
getColumnWidth(index: number): number {
return this.getColumnElement(index).offsetWidth;
}
getColumnOriginPosition(index: number): number {
return this.getColumnElement(index).offsetLeft + this.getColumnWidth(index);
}
triggerHoverState(): void {
const headerCell = this.table.nativeElement.querySelector('.mat-mdc-header-cell');
headerCell.dispatchEvent(new Event('mouseover', {bubbles: true}));
}
endHoverState(): void {
const dataRow = this.table.nativeElement.querySelector('.mat-mdc-row');
dataRow.dispatchEvent(new Event('mouseover', {bubbles: true}));
}
getOverlayThumbElement(index: number): HTMLElement {
return document.querySelectorAll('.mat-column-resize-overlay-thumb')[index] as HTMLElement;
}
getOverlayThumbTopElement(index: number): HTMLElement {
return document.querySelectorAll('.mat-column-resize-overlay-thumb-top')[index] as HTMLElement;
}
getOverlayThumbPosition(index: number): number {
const thumbPositionElement = this.getOverlayThumbElement(index)!.parentNode as HTMLElement;
const left = parseInt(thumbPositionElement.style.left!, 10);
const translateX = Number(
/translateX\((-?\d+)px\)/.exec(thumbPositionElement.style.transform)?.[1] ?? 0,
);
return left + translateX;
}
beginColumnResizeWithMouse(index: number, button = 0): void {
const thumbElement = this.getOverlayThumbElement(index);
this.table.nativeElement!.dispatchEvent(
new MouseEvent('mouseleave', {bubbles: true, relatedTarget: thumbElement, button}),
);
thumbElement.dispatchEvent(
new MouseEvent('mousedown', {
bubbles: true,
screenX: MOUSE_START_OFFSET,
button,
} as MouseEventInit),
);
}
updateResizeWithMouseInProgress(totalDelta: number): void {
document.dispatchEvent(
new MouseEvent('mousemove', {
bubbles: true,
screenX: MOUSE_START_OFFSET + totalDelta,
} as MouseEventInit),
);
}
completeResizeWithMouseInProgress(totalDelta: number): void {
document.dispatchEvent(
new MouseEvent('mouseup', {
bubbles: true,
screenX: MOUSE_START_OFFSET + totalDelta,
} as MouseEventInit),
);
}
resizeColumnWithMouse(index: number, resizeDelta: number): void {
this.beginColumnResizeWithMouse(index);
this.updateResizeWithMouseInProgress(resizeDelta);
this.completeResizeWithMouseInProgress(resizeDelta);
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 8559,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/column-resize.spec.ts"
}
|
components/src/material-experimental/column-resize/column-resize.spec.ts_8561_12113
|
@Directive()
abstract class BaseTestComponentRtl extends BaseTestComponent {
override direction = 'rtl';
override getColumnOriginPosition(index: number): number {
return this.getColumnElement(index).offsetLeft;
}
override updateResizeWithMouseInProgress(totalDelta: number): void {
super.updateResizeWithMouseInProgress(-totalDelta);
}
override completeResizeWithMouseInProgress(totalDelta: number): void {
super.completeResizeWithMouseInProgress(-totalDelta);
}
}
@Component({template: getTableTemplate(false), standalone: false})
class MatResizeTest extends BaseTestComponent {
@ViewChild(MatColumnResize) columnResize: AbstractMatColumnResize;
}
@Component({
template: getTableTemplate(false),
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
class MatResizeOnPushTest extends MatResizeTest {}
@Component({template: getTableTemplate(true), standalone: false})
class MatResizeDefaultTest extends BaseTestComponent {
@ViewChild(MatDefaultEnabledColumnResize) columnResize: AbstractMatColumnResize;
}
@Component({template: getTableTemplate(true), standalone: false})
class MatResizeDefaultRtlTest extends BaseTestComponentRtl {
@ViewChild(MatDefaultEnabledColumnResize) columnResize: AbstractMatColumnResize;
}
@Component({template: getFlexTemplate(false), standalone: false})
class MatResizeFlexTest extends BaseTestComponent {
@ViewChild(MatColumnResizeFlex) columnResize: AbstractMatColumnResize;
}
@Component({template: getFlexTemplate(true), standalone: false})
class MatResizeDefaultFlexTest extends BaseTestComponent {
@ViewChild(MatDefaultEnabledColumnResizeFlex)
columnResize: AbstractMatColumnResize;
}
@Component({template: getFlexTemplate(true), standalone: false})
class MatResizeDefaultFlexRtlTest extends BaseTestComponentRtl {
@ViewChild(MatDefaultEnabledColumnResizeFlex)
columnResize: AbstractMatColumnResize;
}
interface PeriodicElement {
name: string;
position: number;
weight: number;
symbol: string;
}
class ElementDataSource extends DataSource<PeriodicElement> {
/** Stream of data that is provided to the table. */
data = new BehaviorSubject(createElementData());
/** Connect function called by the table to retrieve one stream containing the data to render. */
connect() {
return this.data;
}
disconnect() {}
}
// There's 1px of variance between different browsers in terms of positioning.
const approximateMatcher = {
isApproximately: () => ({
compare: (actual: number, expected: number) => {
const result = {
pass: false,
message: `Expected ${actual} to be within 1 of ${expected}`,
};
result.pass = actual === expected || actual === expected + 1 || actual === expected - 1;
return result;
},
}),
};
const testCases = [
[MatColumnResizeModule, MatResizeTest, 'opt-in table-based mat-table'],
[MatColumnResizeModule, MatResizeOnPushTest, 'inside OnPush component'],
[MatColumnResizeModule, MatResizeFlexTest, 'opt-in flex-based mat-table'],
[
MatDefaultEnabledColumnResizeModule,
MatResizeDefaultTest,
'default enabled table-based mat-table',
],
[
MatDefaultEnabledColumnResizeModule,
MatResizeDefaultRtlTest,
'default enabled rtl table-based mat-table',
],
[
MatDefaultEnabledColumnResizeModule,
MatResizeDefaultFlexTest,
'default enabled flex-based mat-table',
],
[
MatDefaultEnabledColumnResizeModule,
MatResizeDefaultFlexRtlTest,
'default enabled rtl flex-based mat-table',
],
] as const;
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 12113,
"start_byte": 8561,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/column-resize.spec.ts"
}
|
components/src/material-experimental/column-resize/column-resize.spec.ts_12115_21374
|
describe('Material Popover Edit', () => {
for (const [resizeModule, componentClass, label] of testCases) {
describe(label, () => {
let component: BaseTestComponent;
let fixture: ComponentFixture<BaseTestComponent>;
beforeEach(fakeAsync(() => {
jasmine.addMatchers(approximateMatcher);
TestBed.configureTestingModule({
imports: [BidiModule, MatTableModule, resizeModule],
declarations: [componentClass],
});
fixture = TestBed.createComponent(componentClass);
component = fixture.componentInstance;
fixture.detectChanges();
flush();
}));
it('shows resize handle overlays on header row hover and while a resize handle is in use', fakeAsync(() => {
expect(component.getOverlayThumbElement(0)).toBeUndefined();
const headerRowHeight = component.getHeaderRowHeight();
const tableHeight = component.getTableHeight();
component.triggerHoverState();
fixture.detectChanges();
expect(
component.getOverlayThumbElement(0).classList.contains('mat-column-resize-overlay-thumb'),
).toBe(true);
expect(
component.getOverlayThumbElement(2).classList.contains('mat-column-resize-overlay-thumb'),
).toBe(true);
(expect(component.getOverlayThumbElement(0).offsetHeight) as any).isApproximately(
headerRowHeight,
);
(expect(component.getOverlayThumbElement(2).offsetHeight) as any).isApproximately(
headerRowHeight,
);
component.beginColumnResizeWithMouse(0);
expect(
component.getOverlayThumbElement(0).classList.contains('mat-column-resize-overlay-thumb'),
).toBe(true);
expect(
component.getOverlayThumbElement(2).classList.contains('mat-column-resize-overlay-thumb'),
).toBe(true);
(expect(component.getOverlayThumbElement(0).offsetHeight) as any).isApproximately(
tableHeight,
);
(expect(component.getOverlayThumbTopElement(0).offsetHeight) as any).isApproximately(
headerRowHeight,
);
(expect(component.getOverlayThumbElement(2).offsetHeight) as any).isApproximately(
headerRowHeight,
);
component.completeResizeWithMouseInProgress(0);
component.endHoverState();
fixture.detectChanges();
flush();
expect(component.getOverlayThumbElement(0)).toBeUndefined();
}));
it('resizes the target column via mouse input', fakeAsync(() => {
const initialTableWidth = component.getTableWidth();
const initialColumnWidth = component.getColumnWidth(1);
const initialColumnPosition = component.getColumnOriginPosition(1);
// const initialNextColumnPosition = component.getColumnOriginPosition(2);
component.triggerHoverState();
fixture.detectChanges();
component.beginColumnResizeWithMouse(1);
const initialThumbPosition = component.getOverlayThumbPosition(1);
component.updateResizeWithMouseInProgress(5);
fixture.detectChanges();
flush();
let thumbPositionDelta = component.getOverlayThumbPosition(1) - initialThumbPosition;
let columnPositionDelta = component.getColumnOriginPosition(1) - initialColumnPosition;
// let nextColumnPositionDelta =
// component.getColumnOriginPosition(2) - initialNextColumnPosition;
(expect(thumbPositionDelta) as any).isApproximately(columnPositionDelta);
// TODO: This was commented out after switching from the legacy table to the current
// MDC-based table. This failed by being inaccurate by several pixels.
// (expect(nextColumnPositionDelta) as any).isApproximately(columnPositionDelta);
// TODO: This was commented out after switching from the legacy table to the current
// MDC-based table. This failed by being inaccurate by several pixels.
// (expect(component.getTableWidth()) as any).isApproximately(initialTableWidth + 5);
(expect(component.getColumnWidth(1)) as any).isApproximately(initialColumnWidth + 5);
component.updateResizeWithMouseInProgress(1);
fixture.detectChanges();
flush();
thumbPositionDelta = component.getOverlayThumbPosition(1) - initialThumbPosition;
columnPositionDelta = component.getColumnOriginPosition(1) - initialColumnPosition;
(expect(thumbPositionDelta) as any).isApproximately(columnPositionDelta);
(expect(component.getTableWidth()) as any).isApproximately(initialTableWidth + 1);
(expect(component.getColumnWidth(1)) as any).isApproximately(initialColumnWidth + 1);
component.completeResizeWithMouseInProgress(1);
flush();
(expect(component.getColumnWidth(1)) as any).isApproximately(initialColumnWidth + 1);
component.endHoverState();
fixture.detectChanges();
}));
it('should not start dragging using the right mouse button', fakeAsync(() => {
const initialColumnWidth = component.getColumnWidth(1);
component.triggerHoverState();
fixture.detectChanges();
component.beginColumnResizeWithMouse(1, 2);
const initialPosition = component.getOverlayThumbPosition(1);
component.updateResizeWithMouseInProgress(5);
expect(component.getOverlayThumbPosition(1)).toBe(initialPosition);
expect(component.getColumnWidth(1)).toBe(initialColumnWidth);
}));
it('cancels an active mouse resize with the escape key', fakeAsync(() => {
const initialTableWidth = component.getTableWidth();
const initialColumnWidth = component.getColumnWidth(1);
const initialColumnPosition = component.getColumnOriginPosition(1);
component.triggerHoverState();
fixture.detectChanges();
component.beginColumnResizeWithMouse(1);
const initialThumbPosition = component.getOverlayThumbPosition(1);
component.updateResizeWithMouseInProgress(5);
fixture.detectChanges();
flush();
let thumbPositionDelta = component.getOverlayThumbPosition(1) - initialThumbPosition;
let columnPositionDelta = component.getColumnOriginPosition(1) - initialColumnPosition;
(expect(thumbPositionDelta) as any).isApproximately(columnPositionDelta);
(expect(component.getColumnWidth(1)) as any).isApproximately(initialColumnWidth + 5);
// TODO: This was commented out after switching from the legacy table to the current
// MDC-based table. This failed by being inaccurate by several pixels.
// (expect(component.getTableWidth()) as any).isApproximately(initialTableWidth + 5);
dispatchKeyboardEvent(document, 'keyup', ESCAPE);
flush();
(expect(component.getColumnWidth(1)) as any).isApproximately(initialColumnWidth);
(expect(component.getTableWidth()) as any).isApproximately(initialTableWidth);
component.endHoverState();
fixture.detectChanges();
}));
it('notifies subscribers of a completed resize via ColumnResizeNotifier', fakeAsync(() => {
const initialColumnWidth = component.getColumnWidth(1);
let resize: ColumnSize | null = null;
component.columnResize.columnResizeNotifier.resizeCompleted.subscribe(size => {
resize = size;
});
component.triggerHoverState();
fixture.detectChanges();
expect(resize).toBe(null);
component.resizeColumnWithMouse(1, 5);
fixture.detectChanges();
flush();
expect(resize).toEqual({columnId: 'name', size: initialColumnWidth + 5} as any);
component.endHoverState();
fixture.detectChanges();
}));
it('does not notify subscribers of a canceled resize', fakeAsync(() => {
let resize: ColumnSize | null = null;
component.columnResize.columnResizeNotifier.resizeCompleted.subscribe(size => {
resize = size;
});
component.triggerHoverState();
fixture.detectChanges();
component.beginColumnResizeWithMouse(0);
component.updateResizeWithMouseInProgress(5);
flush();
dispatchKeyboardEvent(document, 'keyup', ESCAPE);
flush();
component.endHoverState();
fixture.detectChanges();
expect(resize).toBe(null);
}));
it('performs a column resize triggered via ColumnResizeNotifier', fakeAsync(() => {
// Pre-verify that we are not updating the size to the initial size.
(expect(component.getColumnWidth(1)) as any).not.isApproximately(173);
component.columnResize.columnResizeNotifier.resize('name', 173);
flush();
(expect(component.getColumnWidth(1)) as any).isApproximately(173);
}));
});
}
});
function createElementData() {
return [
{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'},
];
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 21374,
"start_byte": 12115,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/column-resize.spec.ts"
}
|
components/src/material-experimental/column-resize/column-resize-module.ts_0_1718
|
/**
* @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 {OverlayModule} from '@angular/cdk/overlay';
import {MatColumnResize} from './column-resize-directives/column-resize';
import {MatColumnResizeFlex} from './column-resize-directives/column-resize-flex';
import {MatDefaultEnabledColumnResize} from './column-resize-directives/default-enabled-column-resize';
import {MatDefaultEnabledColumnResizeFlex} from './column-resize-directives/default-enabled-column-resize-flex';
import {MatDefaultResizable} from './resizable-directives/default-enabled-resizable';
import {MatResizable} from './resizable-directives/resizable';
import {MatColumnResizeOverlayHandle} from './overlay-handle';
const ENTRY_COMMON_COMPONENTS = [MatColumnResizeOverlayHandle];
@NgModule({
imports: [...ENTRY_COMMON_COMPONENTS],
exports: ENTRY_COMMON_COMPONENTS,
})
export class MatColumnResizeCommonModule {}
const IMPORTS = [MatCommonModule, OverlayModule, MatColumnResizeCommonModule];
@NgModule({
imports: [
...IMPORTS,
MatDefaultEnabledColumnResize,
MatDefaultEnabledColumnResizeFlex,
MatDefaultResizable,
],
exports: [MatDefaultEnabledColumnResize, MatDefaultEnabledColumnResizeFlex, MatDefaultResizable],
})
export class MatDefaultEnabledColumnResizeModule {}
@NgModule({
imports: [...IMPORTS, MatColumnResize, MatColumnResizeFlex, MatResizable],
exports: [MatColumnResize, MatColumnResizeFlex, MatResizable],
})
export class MatColumnResizeModule {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1718,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/column-resize-module.ts"
}
|
components/src/material-experimental/column-resize/overlay-handle.ts_0_2409
|
/**
* @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,
ElementRef,
NgZone,
ViewChild,
ViewEncapsulation,
inject,
} from '@angular/core';
import {DOCUMENT} from '@angular/common';
import {
CdkColumnDef,
_CoalescedStyleScheduler,
_COALESCED_STYLE_SCHEDULER,
} from '@angular/cdk/table';
import {Directionality} from '@angular/cdk/bidi';
import {
ColumnResize,
ColumnResizeNotifierSource,
HeaderRowEventDispatcher,
ResizeOverlayHandle,
ResizeRef,
} from '@angular/cdk-experimental/column-resize';
import {AbstractMatColumnResize} from './column-resize-directives/common';
/**
* Component shown over the edge of a resizable column that is responsible
* for handling column resize mouse events and displaying a vertical line along the column edge.
*/
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
host: {'class': 'mat-column-resize-overlay-thumb'},
template: '<div #top class="mat-column-resize-overlay-thumb-top"></div>',
})
export class MatColumnResizeOverlayHandle extends ResizeOverlayHandle {
protected readonly columnDef = inject(CdkColumnDef);
protected readonly columnResize = inject(ColumnResize);
protected readonly directionality = inject(Directionality);
protected readonly elementRef = inject(ElementRef);
protected readonly eventDispatcher = inject(HeaderRowEventDispatcher);
protected readonly ngZone = inject(NgZone);
protected readonly resizeNotifier = inject(ColumnResizeNotifierSource);
protected readonly resizeRef = inject(ResizeRef);
protected readonly styleScheduler = inject<_CoalescedStyleScheduler>(_COALESCED_STYLE_SCHEDULER);
protected readonly document = inject(DOCUMENT);
@ViewChild('top', {static: true}) topElement: ElementRef<HTMLElement>;
protected override updateResizeActive(active: boolean): void {
super.updateResizeActive(active);
const originHeight = this.resizeRef.origin.nativeElement.offsetHeight;
this.topElement.nativeElement.style.height = `${originHeight}px`;
this.resizeRef.overlayRef.updateSize({
height: active
? (this.columnResize as AbstractMatColumnResize).getTableHeight()
: originHeight,
});
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2409,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/overlay-handle.ts"
}
|
components/src/material-experimental/column-resize/public-api.ts_0_703
|
/**
* @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 './column-resize-directives/column-resize';
export * from './column-resize-directives/column-resize-flex';
export * from './column-resize-directives/default-enabled-column-resize';
export * from './column-resize-directives/default-enabled-column-resize-flex';
export * from './column-resize-module';
export * from './resizable-directives/default-enabled-resizable';
export * from './resizable-directives/resizable';
export * from './resize-strategy';
export * from './overlay-handle';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 703,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/public-api.ts"
}
|
components/src/material-experimental/column-resize/_column-resize-theme.scss_0_3942
|
@use '@angular/material' as mat;
@mixin color($theme) {
$non-resizable-hover-divider: mat.get-theme-color($theme, foreground, divider);
$resizable-hover-divider: mat.get-theme-color($theme, primary, 600);
$resizable-active-divider: mat.get-theme-color($theme, primary, 600);
// TODO: these styles don't really belong in the `color` part of the theme.
// We should figure out a better place for them.
// Required for resizing to work properly.
.mat-column-resize-table.cdk-column-resize-with-resized-column {
table-layout: fixed;
}
.mat-column-resize-flex {
.mat-header-cell,
.mat-mdc-header-cell,
.mat-cell,
.mat-mdc-cell {
box-sizing: border-box;
min-width: 32px;
}
}
.mat-header-cell,
.mat-mdc-header-cell {
position: relative;
}
.mat-resizable {
box-sizing: border-box;
}
.mat-header-cell:not(.mat-resizable)::after,
.mat-mdc-header-cell:not(.mat-resizable)::after,
.mat-resizable-handle {
background: transparent;
bottom: 0;
position: absolute;
top: 0;
transition: background mat.$private-swift-ease-in-duration
mat.$private-swift-ease-in-timing-function;
width: 1px;
}
.mat-header-cell:not(.mat-resizable)::after,
.mat-mdc-header-cell:not(.mat-resizable)::after {
content: '';
}
.mat-header-cell:not(.mat-resizable)::after,
.mat-mdc-header-cell:not(.mat-resizable)::after,
.mat-resizable-handle {
right: 0;
}
.mat-header-row.cdk-column-resize-hover-or-active,
.mat-mdc-header-row.cdk-column-resize-hover-or-active {
.mat-header-cell,
.mat-mdc-header-cell {
border-right: none;
}
.mat-header-cell:not(.mat-resizable)::after,
.mat-mdc-header-cell:not(.mat-resizable)::after {
background: $non-resizable-hover-divider;
}
.mat-resizable-handle {
background: $resizable-hover-divider;
}
}
[dir='rtl'] {
.mat-header-cell:not(.mat-resizable)::after,
.mat-mdc-header-cell:not(.mat-resizable)::after,
.mat-resizable-handle {
left: 0;
right: auto;
}
.mat-header-row.cdk-column-resize-hover-or-active,
.mat-mdc-header-row.cdk-column-resize-hover-or-active {
.mat-header-cell,
.mat-mdc-header-cell {
border-left: none;
}
}
}
.mat-resizable.cdk-resizable-overlay-thumb-active > .mat-resizable-handle {
opacity: 0;
transition: none;
}
.mat-resizable-handle:focus,
.mat-header-row.cdk-column-resize-hover-or-active .mat-resizable-handle:focus,
.mat-mdc-header-row.cdk-column-resize-hover-or-active .mat-resizable-handle:focus {
background: $resizable-active-divider;
outline: none;
}
.mat-column-resize-overlay-thumb {
background: transparent;
cursor: col-resize;
height: 100%;
transition: background mat.$private-swift-ease-in-duration
mat.$private-swift-ease-in-timing-function;
@include mat.private-user-select(none);
width: 100%;
&:active {
background: linear-gradient(90deg,
transparent, transparent 7px,
$resizable-active-divider 7px, $resizable-active-divider 9px,
transparent 9px, transparent);
will-change: transform;
.mat-column-resize-overlay-thumb-top {
background: linear-gradient(90deg,
transparent, transparent 4px,
$resizable-active-divider 4px, $resizable-active-divider 12px,
transparent 12px, transparent);
}
}
}
.mat-column-resize-overlay-thumb-top {
width: 100%;
}
}
@mixin typography($theme) {}
@mixin density($theme) {}
@mixin theme($theme) {
@include mat.private-check-duplicate-theme-styles($theme, 'mat-column-resize') {
@if mat.theme-has($theme, color) {
@include color($theme);
}
@if mat.theme-has($theme, density) {
@include density($theme);
}
@if mat.theme-has($theme, typography) {
@include typography($theme);
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 3942,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/_column-resize-theme.scss"
}
|
components/src/material-experimental/column-resize/BUILD.bazel_0_1095
|
load("//tools:defaults.bzl", "ng_module", "ng_test_library", "ng_web_test_suite", "sass_library")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "column-resize",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
deps = [
"//src/cdk-experimental/column-resize",
"//src/cdk/overlay",
"//src/cdk/table",
"//src/material/table",
"@npm//@angular/core",
],
)
sass_library(
name = "column_resize_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = [
"//src/material:sass_lib",
],
)
ng_test_library(
name = "column_resize_test_sources",
srcs = glob(["**/*.spec.ts"]),
deps = [
":column-resize",
"//src/cdk-experimental/column-resize",
"//src/cdk/bidi",
"//src/cdk/collections",
"//src/cdk/keycodes",
"//src/cdk/overlay",
"//src/cdk/testing/private",
"//src/material/table",
"@npm//rxjs",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":column_resize_test_sources"],
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1095,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/BUILD.bazel"
}
|
components/src/material-experimental/column-resize/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';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/index.ts"
}
|
components/src/material-experimental/column-resize/column-resize-directives/column-resize.ts_0_1215
|
/**
* @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, NgZone, inject} from '@angular/core';
import {
ColumnResize,
ColumnResizeNotifier,
ColumnResizeNotifierSource,
HeaderRowEventDispatcher,
} from '@angular/cdk-experimental/column-resize';
import {AbstractMatColumnResize, TABLE_HOST_BINDINGS, TABLE_PROVIDERS} from './common';
/**
* Explicitly enables column resizing for a table-based mat-table.
* Individual columns must be annotated specifically.
*/
@Directive({
selector: 'table[mat-table][columnResize]',
host: TABLE_HOST_BINDINGS,
providers: [...TABLE_PROVIDERS, {provide: ColumnResize, useExisting: MatColumnResize}],
})
export class MatColumnResize extends AbstractMatColumnResize {
readonly columnResizeNotifier = inject(ColumnResizeNotifier);
readonly elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
protected readonly eventDispatcher = inject(HeaderRowEventDispatcher);
protected readonly ngZone = inject(NgZone);
protected readonly notifier = inject(ColumnResizeNotifierSource);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1215,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/column-resize-directives/column-resize.ts"
}
|
components/src/material-experimental/column-resize/column-resize-directives/column-resize-flex.ts_0_1214
|
/**
* @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, NgZone, inject} from '@angular/core';
import {
ColumnResize,
ColumnResizeNotifier,
ColumnResizeNotifierSource,
HeaderRowEventDispatcher,
} from '@angular/cdk-experimental/column-resize';
import {AbstractMatColumnResize, FLEX_HOST_BINDINGS, FLEX_PROVIDERS} from './common';
/**
* Explicitly enables column resizing for a flexbox-based mat-table.
* Individual columns must be annotated specifically.
*/
@Directive({
selector: 'mat-table[columnResize]',
host: FLEX_HOST_BINDINGS,
providers: [...FLEX_PROVIDERS, {provide: ColumnResize, useExisting: MatColumnResizeFlex}],
})
export class MatColumnResizeFlex extends AbstractMatColumnResize {
readonly columnResizeNotifier = inject(ColumnResizeNotifier);
readonly elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
protected readonly eventDispatcher = inject(HeaderRowEventDispatcher);
protected readonly ngZone = inject(NgZone);
protected readonly notifier = inject(ColumnResizeNotifierSource);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1214,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/column-resize-directives/column-resize-flex.ts"
}
|
components/src/material-experimental/column-resize/column-resize-directives/common.ts_0_1147
|
/**
* @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 {Provider} from '@angular/core';
import {
ColumnResize,
ColumnResizeNotifier,
ColumnResizeNotifierSource,
HeaderRowEventDispatcher,
} from '@angular/cdk-experimental/column-resize';
import {
TABLE_LAYOUT_FIXED_RESIZE_STRATEGY_PROVIDER,
FLEX_RESIZE_STRATEGY_PROVIDER,
} from '../resize-strategy';
const PROVIDERS: Provider[] = [
ColumnResizeNotifier,
HeaderRowEventDispatcher,
ColumnResizeNotifierSource,
];
export const TABLE_PROVIDERS: Provider[] = [
...PROVIDERS,
TABLE_LAYOUT_FIXED_RESIZE_STRATEGY_PROVIDER,
];
export const FLEX_PROVIDERS: Provider[] = [...PROVIDERS, FLEX_RESIZE_STRATEGY_PROVIDER];
export const TABLE_HOST_BINDINGS = {
'class': 'mat-column-resize-table',
};
export const FLEX_HOST_BINDINGS = {
'class': 'mat-column-resize-flex',
};
export abstract class AbstractMatColumnResize extends ColumnResize {
getTableHeight() {
return this.elementRef.nativeElement!.offsetHeight;
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1147,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/column-resize-directives/common.ts"
}
|
components/src/material-experimental/column-resize/column-resize-directives/default-enabled-column-resize-flex.ts_0_1245
|
/**
* @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, NgZone, inject} from '@angular/core';
import {
ColumnResize,
ColumnResizeNotifier,
ColumnResizeNotifierSource,
HeaderRowEventDispatcher,
} from '@angular/cdk-experimental/column-resize';
import {AbstractMatColumnResize, FLEX_HOST_BINDINGS, FLEX_PROVIDERS} from './common';
/**
* Implicitly enables column resizing for a flexbox-based mat-table.
* Individual columns will be resizable unless opted out.
*/
@Directive({
selector: 'mat-table',
host: FLEX_HOST_BINDINGS,
providers: [
...FLEX_PROVIDERS,
{provide: ColumnResize, useExisting: MatDefaultEnabledColumnResizeFlex},
],
})
export class MatDefaultEnabledColumnResizeFlex extends AbstractMatColumnResize {
readonly columnResizeNotifier = inject(ColumnResizeNotifier);
readonly elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
protected readonly eventDispatcher = inject(HeaderRowEventDispatcher);
protected readonly ngZone = inject(NgZone);
protected readonly notifier = inject(ColumnResizeNotifierSource);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1245,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/column-resize-directives/default-enabled-column-resize-flex.ts"
}
|
components/src/material-experimental/column-resize/column-resize-directives/default-enabled-column-resize.ts_0_1246
|
/**
* @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, NgZone, inject} from '@angular/core';
import {
ColumnResize,
ColumnResizeNotifier,
ColumnResizeNotifierSource,
HeaderRowEventDispatcher,
} from '@angular/cdk-experimental/column-resize';
import {AbstractMatColumnResize, TABLE_HOST_BINDINGS, TABLE_PROVIDERS} from './common';
/**
* Implicitly enables column resizing for a table-based mat-table.
* Individual columns will be resizable unless opted out.
*/
@Directive({
selector: 'table[mat-table]',
host: TABLE_HOST_BINDINGS,
providers: [
...TABLE_PROVIDERS,
{provide: ColumnResize, useExisting: MatDefaultEnabledColumnResize},
],
})
export class MatDefaultEnabledColumnResize extends AbstractMatColumnResize {
readonly columnResizeNotifier = inject(ColumnResizeNotifier);
readonly elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
protected readonly eventDispatcher = inject(HeaderRowEventDispatcher);
protected readonly ngZone = inject(NgZone);
protected readonly notifier = inject(ColumnResizeNotifierSource);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1246,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/column-resize-directives/default-enabled-column-resize.ts"
}
|
components/src/material-experimental/column-resize/resizable-directives/resizable.ts_0_1975
|
/**
* @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,
Injector,
NgZone,
ViewContainerRef,
ChangeDetectorRef,
inject,
} from '@angular/core';
import {DOCUMENT} from '@angular/common';
import {Directionality} from '@angular/cdk/bidi';
import {Overlay} from '@angular/cdk/overlay';
import {
CdkColumnDef,
_CoalescedStyleScheduler,
_COALESCED_STYLE_SCHEDULER,
} from '@angular/cdk/table';
import {
ColumnResize,
ColumnResizeNotifierSource,
HeaderRowEventDispatcher,
ResizeStrategy,
} from '@angular/cdk-experimental/column-resize';
import {AbstractMatResizable, RESIZABLE_HOST_BINDINGS, RESIZABLE_INPUTS} from './common';
/**
* Explicitly enables column resizing for a mat-header-cell.
*/
@Directive({
selector: 'mat-header-cell[resizable], th[mat-header-cell][resizable]',
host: RESIZABLE_HOST_BINDINGS,
inputs: RESIZABLE_INPUTS,
})
export class MatResizable extends AbstractMatResizable {
protected readonly columnDef = inject(CdkColumnDef);
protected readonly columnResize = inject(ColumnResize);
protected readonly directionality = inject(Directionality);
protected readonly elementRef = inject(ElementRef);
protected readonly eventDispatcher = inject(HeaderRowEventDispatcher);
protected readonly injector = inject(Injector);
protected readonly ngZone = inject(NgZone);
protected readonly overlay = inject(Overlay);
protected readonly resizeNotifier = inject(ColumnResizeNotifierSource);
protected readonly resizeStrategy = inject(ResizeStrategy);
protected readonly styleScheduler = inject<_CoalescedStyleScheduler>(_COALESCED_STYLE_SCHEDULER);
protected readonly viewContainerRef = inject(ViewContainerRef);
protected readonly changeDetectorRef = inject(ChangeDetectorRef);
protected readonly document = inject(DOCUMENT);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1975,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/resizable-directives/resizable.ts"
}
|
components/src/material-experimental/column-resize/resizable-directives/common.ts_0_966
|
/**
* @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 {Type} from '@angular/core';
import {Resizable} from '@angular/cdk-experimental/column-resize';
import {MatColumnResizeOverlayHandle} from '../overlay-handle';
export abstract class AbstractMatResizable extends Resizable<MatColumnResizeOverlayHandle> {
override minWidthPxInternal = 32;
protected override getInlineHandleCssClassName(): string {
return 'mat-resizable-handle';
}
protected override getOverlayHandleComponentType(): Type<MatColumnResizeOverlayHandle> {
return MatColumnResizeOverlayHandle;
}
}
export const RESIZABLE_HOST_BINDINGS = {
'class': 'mat-resizable',
};
export const RESIZABLE_INPUTS = [
{name: 'minWidthPx', alias: 'matResizableMinWidthPx'},
{name: 'maxWidthPx', alias: 'matResizableMaxWidthPx'},
];
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 966,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/resizable-directives/common.ts"
}
|
components/src/material-experimental/column-resize/resizable-directives/default-enabled-resizable.ts_0_2051
|
/**
* @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,
Injector,
NgZone,
ViewContainerRef,
ChangeDetectorRef,
inject,
} from '@angular/core';
import {DOCUMENT} from '@angular/common';
import {Directionality} from '@angular/cdk/bidi';
import {Overlay} from '@angular/cdk/overlay';
import {
CdkColumnDef,
_CoalescedStyleScheduler,
_COALESCED_STYLE_SCHEDULER,
} from '@angular/cdk/table';
import {
ColumnResize,
ColumnResizeNotifierSource,
HeaderRowEventDispatcher,
ResizeStrategy,
} from '@angular/cdk-experimental/column-resize';
import {AbstractMatResizable, RESIZABLE_HOST_BINDINGS, RESIZABLE_INPUTS} from './common';
/**
* Implicitly enables column resizing for a mat-header-cell unless the disableResize attribute
* is present.
*/
@Directive({
selector: 'mat-header-cell:not([disableResize]), th[mat-header-cell]:not([disableResize])',
host: RESIZABLE_HOST_BINDINGS,
inputs: RESIZABLE_INPUTS,
})
export class MatDefaultResizable extends AbstractMatResizable {
protected readonly columnDef = inject(CdkColumnDef);
protected readonly columnResize = inject(ColumnResize);
protected readonly directionality = inject(Directionality);
protected readonly elementRef = inject(ElementRef);
protected readonly eventDispatcher = inject(HeaderRowEventDispatcher);
protected readonly injector = inject(Injector);
protected readonly ngZone = inject(NgZone);
protected readonly overlay = inject(Overlay);
protected readonly resizeNotifier = inject(ColumnResizeNotifierSource);
protected readonly resizeStrategy = inject(ResizeStrategy);
protected readonly styleScheduler = inject<_CoalescedStyleScheduler>(_COALESCED_STYLE_SCHEDULER);
protected readonly viewContainerRef = inject(ViewContainerRef);
protected readonly changeDetectorRef = inject(ChangeDetectorRef);
protected readonly document = inject(DOCUMENT);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2051,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/column-resize/resizable-directives/default-enabled-resizable.ts"
}
|
components/src/material-experimental/popover-edit/table-directives.ts_0_3393
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Directive} from '@angular/core';
import {
_CELL_SELECTOR,
_closest,
CdkPopoverEdit,
CdkPopoverEditTabOut,
CdkRowHoverContent,
CdkEditOpen,
} from '@angular/cdk-experimental/popover-edit';
const POPOVER_EDIT_HOST_BINDINGS = {
'[attr.tabindex]': 'disabled ? null : 0',
'class': 'mat-popover-edit-cell',
'[attr.aria-haspopup]': '!disabled',
};
const POPOVER_EDIT_INPUTS = [
{name: 'template', alias: 'matPopoverEdit'},
{name: 'context', alias: 'matPopoverEditContext'},
{name: 'colspan', alias: 'matPopoverEditColspan'},
{name: 'disabled', alias: 'matPopoverEditDisabled'},
{name: 'ariaLabel', alias: 'matPopoverEditAriaLabel'},
];
const EDIT_PANE_CLASS = 'mat-edit-pane';
const MAT_ROW_HOVER_CLASS = 'mat-row-hover-content';
const MAT_ROW_HOVER_RTL_CLASS = MAT_ROW_HOVER_CLASS + '-rtl';
const MAT_ROW_HOVER_ANIMATE_CLASS = MAT_ROW_HOVER_CLASS + '-visible';
const MAT_ROW_HOVER_CELL_CLASS = MAT_ROW_HOVER_CLASS + '-host-cell';
/**
* Attaches an ng-template to a cell and shows it when instructed to by the
* EditEventDispatcher service.
* Makes the cell focusable.
*/
@Directive({
selector: '[matPopoverEdit]:not([matPopoverEditTabOut])',
host: POPOVER_EDIT_HOST_BINDINGS,
inputs: POPOVER_EDIT_INPUTS,
})
export class MatPopoverEdit<C> extends CdkPopoverEdit<C> {
protected override panelClass(): string {
return EDIT_PANE_CLASS;
}
}
/**
* Attaches an ng-template to a cell and shows it when instructed to by the
* EditEventDispatcher service.
* Makes the cell focusable.
*/
@Directive({
selector: '[matPopoverEdit][matPopoverEditTabOut]',
host: POPOVER_EDIT_HOST_BINDINGS,
inputs: POPOVER_EDIT_INPUTS,
})
export class MatPopoverEditTabOut<C> extends CdkPopoverEditTabOut<C> {
protected override panelClass(): string {
return EDIT_PANE_CLASS;
}
}
/**
* A structural directive that shows its contents when the table row containing
* it is hovered or when an element in the row has focus.
*/
@Directive({
selector: '[matRowHoverContent]',
})
export class MatRowHoverContent extends CdkRowHoverContent {
protected override initElement(element: HTMLElement) {
super.initElement(element);
element.classList.add(MAT_ROW_HOVER_CLASS);
}
protected override makeElementHiddenButFocusable(element: HTMLElement): void {
element.classList.remove(MAT_ROW_HOVER_ANIMATE_CLASS);
}
protected override makeElementVisible(element: HTMLElement): void {
_closest(this.elementRef.nativeElement!, _CELL_SELECTOR)!.classList.add(
MAT_ROW_HOVER_CELL_CLASS,
);
if (this.services.directionality.value === 'rtl') {
element.classList.add(MAT_ROW_HOVER_RTL_CLASS);
} else {
element.classList.remove(MAT_ROW_HOVER_RTL_CLASS);
}
element.classList.remove(MAT_ROW_HOVER_ANIMATE_CLASS);
this.services.ngZone.runOutsideAngular(() => {
setTimeout(() => {
element.classList.add(MAT_ROW_HOVER_ANIMATE_CLASS);
});
});
}
}
/**
* Opens the closest edit popover to this element, whether it's associated with this exact
* element or an ancestor element.
*/
@Directive({
selector: '[matEditOpen]',
})
export class MatEditOpen extends CdkEditOpen {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 3393,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/popover-edit/table-directives.ts"
}
|
components/src/material-experimental/popover-edit/popover-edit-module.ts_0_1018
|
/**
* @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 {CdkEditable, CdkPopoverEditModule} from '@angular/cdk-experimental/popover-edit';
import {
MatPopoverEdit,
MatPopoverEditTabOut,
MatRowHoverContent,
MatEditOpen,
} from './table-directives';
import {MatEditLens, MatEditRevert, MatEditClose} from './lens-directives';
@NgModule({
imports: [
CdkPopoverEditModule,
MatCommonModule,
MatPopoverEdit,
MatPopoverEditTabOut,
MatRowHoverContent,
MatEditLens,
MatEditRevert,
MatEditClose,
MatEditOpen,
],
exports: [
MatPopoverEdit,
MatPopoverEditTabOut,
MatRowHoverContent,
MatEditLens,
MatEditRevert,
MatEditClose,
MatEditOpen,
CdkEditable,
],
})
export class MatPopoverEditModule {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1018,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/popover-edit/popover-edit-module.ts"
}
|
components/src/material-experimental/popover-edit/_popover-edit-theme.scss_0_4192
|
@use '@angular/cdk';
@use '@angular/material' as mat;
@function _hover-content-background($direction, $background-color) {
@return linear-gradient($direction, rgba($background-color, 0), $background-color 8px);
}
@mixin color($theme) {
$background-color: mat.get-theme-color($theme, background, 'card');
// TODO: these structural styles don't belong in the `color` part of a theme.
// We should figure out a better place for them.
.mat-row-hover-content-host-cell {
position: relative;
}
.mat-row-hover-content {
align-items: center;
background: _hover-content-background(90deg, $background-color);
bottom: 0;
display: flex;
opacity: 0;
padding: 0 4px 1px;
position: absolute;
right: 0;
top: 0;
transition: opacity mat.$private-swift-ease-in-duration
mat.$private-swift-ease-in-timing-function;
}
.mat-row-hover-content-rtl {
background: _hover-content-background(270deg, $background-color);
left: 0;
right: auto;
}
.mat-row-hover-content-visible {
opacity: 1;
}
.mat-popover-edit-cell {
position: relative;
&::after {
background-color: mat.get-theme-color($theme, primary);
bottom: 0;
content: '';
height: 2px;
left: 0;
opacity: 0;
position: absolute;
right: 0;
transform-origin: 50%;
transform: scaleX(0.5);
transition: background-color mat.$private-swift-ease-in-duration
mat.$private-swift-ease-in-timing-function;
visibility: hidden;
}
&:focus {
outline: none;
&::after {
opacity: 1;
transform: scaleX(1);
transition: transform 300ms mat.$private-swift-ease-out-timing-function,
opacity 100ms mat.$private-swift-ease-out-timing-function,
background-color 300ms mat.$private-swift-ease-out-timing-function;
visibility: visible;
@include cdk.high-contrast {
border-bottom: 3px dashed black;
}
}
}
}
.mat-edit-pane {
@include mat.private-theme-elevation(2, $theme);
background: $background-color;
color: mat.get-theme-color($theme, foreground, text);
display: block;
padding: 16px 24px;
@include cdk.high-contrast {
// Note that normally we use 1px for high contrast outline, however here we use 3,
// because the popover is rendered on top of a table which already has some borders
// and doesn't have a backdrop. The thicker outline makes it easier to differentiate.
outline: solid 3px;
}
}
.mat-edit-lens {
display: block;
width: 100%;
}
[mat-edit-title] {
display: block;
margin: 0;
}
[mat-edit-content],
[mat-edit-fill] {
display: block;
mat-form-field {
display: block;
// Clear the top padding, because we don't have a label on it and the reserved space
// can throw off the alignment when there isn't a header (see discussion in #17600).
&:not(.mat-form-field-has-label) .mat-form-field-infix {
padding-top: 0;
}
}
// Make mat-selection-lists inside of the look more like mat-select popups.
mat-selection-list {
max-height: 256px; // Same as mat-select.
overflow-y: auto;
}
}
[mat-edit-fill] {
margin: -16px -24px;
mat-selection-list:first-child {
padding-top: 0;
}
}
[mat-edit-actions] {
align-items: center;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
margin: 8px -16px -8px;
}
[mat-edit-fill] + [mat-edit-actions] {
margin-top: 16px;
}
}
@mixin typography($theme) {
[mat-edit-title] {
font: mat.get-theme-typography($theme, headline-6, font);
letter-spacing: mat.get-theme-typography($theme, headline-6, letter-spacing);
}
}
@mixin density($theme) {}
@mixin theme($theme) {
@include mat.private-check-duplicate-theme-styles($theme, 'mat-popover-edit') {
@if mat.theme-has($theme, color) {
@include color($theme);
}
@if mat.theme-has($theme, density) {
@include density($theme);
}
@if mat.theme-has($theme, typography) {
@include typography($theme);
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 4192,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/popover-edit/_popover-edit-theme.scss"
}
|
components/src/material-experimental/popover-edit/public-api.ts_0_314
|
/**
* @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 './lens-directives';
export * from './popover-edit-module';
export * from './table-directives';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 314,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/popover-edit/public-api.ts"
}
|
components/src/material-experimental/popover-edit/lens-directives.ts_0_1529
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Directive} from '@angular/core';
import {
CdkEditControl,
CdkEditRevert,
CdkEditClose,
EditRef,
} from '@angular/cdk-experimental/popover-edit';
/**
* A component that attaches to a form within the edit.
* It coordinates the form state with the table-wide edit system and handles
* closing the edit when the form is submitted or the user clicks
* out.
*/
@Directive({
selector: 'form[matEditLens]',
host: {
'class': 'mat-edit-lens',
},
inputs: [
{name: 'clickOutBehavior', alias: 'matEditLensClickOutBehavior'},
{name: 'preservedFormValue', alias: 'matEditLensPreservedFormValue'},
{name: 'ignoreSubmitUnlessValid', alias: 'matEditLensIgnoreSubmitUnlessValid'},
],
outputs: ['preservedFormValueChange: matEditLensPreservedFormValueChange'],
providers: [EditRef],
})
export class MatEditLens<FormValue> extends CdkEditControl<FormValue> {}
/** Reverts the form to its initial or previously submitted state on click. */
@Directive({
selector: 'button[matEditRevert]',
host: {
'type': 'button', // Prevents accidental form submits.
},
})
export class MatEditRevert<FormValue> extends CdkEditRevert<FormValue> {}
/** Closes the lens on click. */
@Directive({
selector: '[matEditClose]',
})
export class MatEditClose<FormValue> extends CdkEditClose<FormValue> {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1529,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/popover-edit/lens-directives.ts"
}
|
components/src/material-experimental/popover-edit/BUILD.bazel_0_1194
|
load(
"//tools:defaults.bzl",
"ng_module",
"ng_test_library",
"ng_web_test_suite",
"sass_library",
)
package(default_visibility = ["//visibility:public"])
ng_module(
name = "popover-edit",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
deps = [
"//src/cdk-experimental/popover-edit",
"//src/material/core",
"@npm//@angular/core",
"@npm//@angular/forms",
],
)
sass_library(
name = "popover_edit_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = [
"//src/cdk:sass_lib",
"//src/material:sass_lib",
],
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":popover-edit",
"//src/cdk-experimental/popover-edit",
"//src/cdk/collections",
"//src/cdk/keycodes",
"//src/cdk/overlay",
"//src/cdk/testing/private",
"//src/material/table",
"@npm//@angular/common",
"@npm//@angular/forms",
"@npm//rxjs",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1194,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/popover-edit/BUILD.bazel"
}
|
components/src/material-experimental/popover-edit/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';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/popover-edit/index.ts"
}
|
components/src/material-experimental/popover-edit/popover-edit.spec.ts_0_7831
|
import {DataSource} from '@angular/cdk/collections';
import {DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW, TAB, UP_ARROW} from '@angular/cdk/keycodes';
import {Component, Directive, ElementRef, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush, tick} from '@angular/core/testing';
import {FormsModule, NgForm} from '@angular/forms';
import {MatTableModule} from '@angular/material/table';
import {BehaviorSubject} from 'rxjs';
import {dispatchKeyboardEvent} from '../../cdk/testing/private';
import {
CdkPopoverEditColspan,
FormValueContainer,
HoverContentState,
PopoverEditClickOutBehavior,
} from '@angular/cdk-experimental/popover-edit';
import {MatPopoverEditModule} from './index';
const NAME_EDIT_TEMPLATE = `
<div>
<form #f="ngForm"
matEditLens
(ngSubmit)="onSubmit(element, f)"
[(matEditLensPreservedFormValue)]="preservedValues.for(element).value"
[matEditLensIgnoreSubmitUnlessValid]="ignoreSubmitUnlessValid"
[matEditLensClickOutBehavior]="clickOutBehavior">
<input [ngModel]="element.name" name="name" required>
<br>
<button class="submit" type="submit">Confirm</button>
<button class="revert" matEditRevert>Revert</button>
<button class="close" matEditClose>Close</button>
</form>
</div>
`;
const WEIGHT_EDIT_TEMPLATE = `
<div>
<form #f="ngForm" matEditLens>
<input>
</form>
</div>
`;
const CELL_TEMPLATE = `
{{element.name}}
<span *matRowHoverContent>
<button class="open" matEditOpen>Edit</button>
</span>
`;
const POPOVER_EDIT_DIRECTIVE_NAME = `
[matPopoverEdit]="nameEdit"
[matPopoverEditColspan]="colspan"
[matPopoverEditDisabled]="nameEditDisabled"
[matPopoverEditAriaLabel]="nameEditAriaLabel"
`;
const POPOVER_EDIT_DIRECTIVE_WEIGHT = `[matPopoverEdit]="weightEdit" matPopoverEditTabOut`;
interface PeriodicElement {
name: string;
weight: number;
}
@Directive()
abstract class BaseTestComponent {
@ViewChild('table') table: ElementRef;
preservedValues = new FormValueContainer<PeriodicElement, {'name': string}>();
nameEditDisabled = false;
nameEditAriaLabel: string | undefined = undefined;
ignoreSubmitUnlessValid = true;
clickOutBehavior: PopoverEditClickOutBehavior = 'close';
colspan: CdkPopoverEditColspan = {};
onSubmit(element: PeriodicElement, form: NgForm) {
if (!form.valid) {
return;
}
element.name = form.value['name'];
}
triggerHoverState(rowIndex = 0) {
const row = getRows(this.table.nativeElement)[rowIndex];
row.dispatchEvent(new Event('mouseover', {bubbles: true}));
row.dispatchEvent(new Event('mousemove', {bubbles: true}));
// Wait for the mouse hover debounce in edit-event-dispatcher.
tick(41);
}
getRows() {
return getRows(this.table.nativeElement);
}
hoverContentStateForRow(rowIndex = 0) {
const openButton = this.getOpenButton(rowIndex);
if (!openButton) {
return HoverContentState.OFF;
}
return (openButton.parentNode as Element).classList.contains('mat-row-hover-content-visible')
? HoverContentState.ON
: HoverContentState.FOCUSABLE;
}
getEditCell(rowIndex = 0, cellIndex = 1) {
const row = this.getRows()[rowIndex];
return getCells(row)[cellIndex];
}
focusEditCell(rowIndex = 0, cellIndex = 1) {
this.getEditCell(rowIndex, cellIndex).focus();
}
getOpenButton(rowIndex = 0) {
return this.getEditCell(rowIndex).querySelector('.open') as HTMLElement | null;
}
clickOpenButton(rowIndex = 0) {
this.getOpenButton(rowIndex)!.click();
}
openLens(rowIndex = 0, cellIndex = 1) {
this.focusEditCell(rowIndex, cellIndex);
this.getEditCell(rowIndex, cellIndex).dispatchEvent(
new KeyboardEvent('keydown', {bubbles: true, key: 'Enter'}),
);
flush();
}
getEditPane() {
return document.querySelector('.mat-edit-pane');
}
getEditBoundingBox() {
return document.querySelector('.cdk-overlay-connected-position-bounding-box');
}
getInput() {
return document.querySelector('input') as HTMLInputElement | null;
}
lensIsOpen() {
return !!this.getInput();
}
getSubmitButton() {
return document.querySelector('.submit') as HTMLElement | null;
}
clickSubmitButton() {
this.getSubmitButton()!.click();
}
getRevertButton() {
return document.querySelector('.revert') as HTMLElement | null;
}
clickRevertButton() {
this.getRevertButton()!.click();
}
getCloseButton() {
return document.querySelector('.close') as HTMLElement | null;
}
clickCloseButton() {
this.getCloseButton()!.click();
}
}
class ElementDataSource extends DataSource<PeriodicElement> {
/** Stream of data that is provided to the table. */
data = new BehaviorSubject(createElementData());
/** Connect function called by the table to retrieve one stream containing the data to render. */
connect() {
return this.data;
}
disconnect() {}
}
@Component({
template: `
<div #table style="margin: 16px; max-width: 90vw; max-height: 90vh;">
<mat-table editable [dataSource]="dataSource">
<ng-container matColumnDef="before">
<mat-cell *matCellDef="let element">
just a cell
</mat-cell>
</ng-container>
<ng-container matColumnDef="name">
<mat-cell *matCellDef="let element"
${POPOVER_EDIT_DIRECTIVE_NAME}>
${CELL_TEMPLATE}
<ng-template #nameEdit>
${NAME_EDIT_TEMPLATE}
</ng-template>
<span *matIfRowHovered>
<button matEditOpen>Edit</button>
</span>
</mat-cell>
</ng-container>
<ng-container matColumnDef="weight">
<mat-cell *matCellDef="let element"
${POPOVER_EDIT_DIRECTIVE_WEIGHT}>
{{element.weight}}
<ng-template #weightEdit>
${WEIGHT_EDIT_TEMPLATE}
</ng-template>
</mat-cell>
</ng-container>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
</div>
`,
styles: `
mat-table {
margin: 16px;
}
`,
standalone: false,
})
class MatFlexTableInCell extends BaseTestComponent {
displayedColumns = ['before', 'name', 'weight'];
dataSource = new ElementDataSource();
}
@Component({
template: `
<div #table style="margin: 16px">
<table mat-table editable [dataSource]="dataSource">
<ng-container matColumnDef="before">
<td mat-cell *matCellDef="let element">
just a cell
</td>
</ng-container>
<ng-container matColumnDef="name">
<td mat-cell *matCellDef="let element"
${POPOVER_EDIT_DIRECTIVE_NAME}>
${CELL_TEMPLATE}
<ng-template #nameEdit>
${NAME_EDIT_TEMPLATE}
</ng-template>
<span *matIfRowHovered>
<button matEditOpen>Edit</button>
</span>
</td>
</ng-container>
<ng-container matColumnDef="weight">
<td mat-cell *matCellDef="let element"
${POPOVER_EDIT_DIRECTIVE_WEIGHT}>
{{element.weight}}
<ng-template #weightEdit>
${WEIGHT_EDIT_TEMPLATE}
</ng-template>
</td>
</ng-container>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<div>
`,
styles: `
table {
margin: 16px;
}
`,
standalone: false,
})
class MatTableInCell extends BaseTestComponent {
displayedColumns = ['before', 'name', 'weight'];
dataSource = new ElementDataSource();
}
const testCases = [
[MatFlexTableInCell, 'Flex mat-table; edit defined within cell'],
[MatTableInCell, 'Table mat-table; edit defined within cell'],
] as const;
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 7831,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/popover-edit/popover-edit.spec.ts"
}
|
components/src/material-experimental/popover-edit/popover-edit.spec.ts_7833_14398
|
describe('Material Popover Edit', () => {
for (const [componentClass, label] of testCases) {
describe(label, () => {
let component: BaseTestComponent;
let fixture: ComponentFixture<BaseTestComponent>;
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [MatTableModule, MatPopoverEditModule, FormsModule],
declarations: [componentClass],
});
fixture = TestBed.createComponent(componentClass);
component = fixture.componentInstance;
fixture.detectChanges();
tick(10);
fixture.detectChanges();
}));
describe('row hover content', () => {
it('makes the first and last rows focusable but invisible', fakeAsync(() => {
const rows = component.getRows();
expect(component.hoverContentStateForRow(0)).toBe(HoverContentState.FOCUSABLE);
expect(component.hoverContentStateForRow(rows.length - 1)).toBe(
HoverContentState.FOCUSABLE,
);
}));
it('shows and hides on-hover content only after a delay', fakeAsync(() => {
const [row0, row1] = component.getRows();
row0.dispatchEvent(new Event('mouseover', {bubbles: true}));
row0.dispatchEvent(new Event('mousemove', {bubbles: true}));
expect(component.hoverContentStateForRow(0)).toBe(HoverContentState.FOCUSABLE);
tick(20);
row0.dispatchEvent(new Event('mousemove', {bubbles: true}));
tick(20);
expect(component.hoverContentStateForRow(0)).toBe(HoverContentState.FOCUSABLE);
tick(31);
expect(component.hoverContentStateForRow(0)).toBe(HoverContentState.ON);
row1.dispatchEvent(new Event('mouseover', {bubbles: true}));
row1.dispatchEvent(new Event('mousemove', {bubbles: true}));
expect(component.hoverContentStateForRow(0)).toBe(HoverContentState.ON);
expect(component.hoverContentStateForRow(1)).toBe(HoverContentState.OFF);
tick(41);
expect(component.hoverContentStateForRow(0)).toBe(HoverContentState.FOCUSABLE);
expect(component.hoverContentStateForRow(1)).toBe(HoverContentState.ON);
}));
it('shows hover content for the focused row and makes the rows above and below focusable', fakeAsync(() => {
expect(component.hoverContentStateForRow(1)).toBe(HoverContentState.OFF);
expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.OFF);
expect(component.hoverContentStateForRow(3)).toBe(HoverContentState.OFF);
expect(component.hoverContentStateForRow(4)).toBe(HoverContentState.FOCUSABLE);
component.focusEditCell(2);
tick(1);
expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.ON);
expect(component.hoverContentStateForRow(1)).toBe(HoverContentState.FOCUSABLE);
expect(component.hoverContentStateForRow(3)).toBe(HoverContentState.FOCUSABLE);
component.focusEditCell(4);
tick(1);
expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.OFF);
expect(component.hoverContentStateForRow(4)).toBe(HoverContentState.ON);
expect(component.hoverContentStateForRow(3)).toBe(HoverContentState.FOCUSABLE);
component.getEditCell(4).blur();
tick(1);
expect(component.hoverContentStateForRow(1)).toBe(HoverContentState.OFF);
expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.OFF);
expect(component.hoverContentStateForRow(3)).toBe(HoverContentState.OFF);
expect(component.hoverContentStateForRow(4)).toBe(HoverContentState.FOCUSABLE);
}));
it(
'shows hover content for the editing row and makes the rows above and below ' +
'focusable unless focus is in a different table row in which case it takes priority',
fakeAsync(() => {
expect(component.hoverContentStateForRow(1)).toBe(HoverContentState.OFF);
expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.OFF);
expect(component.hoverContentStateForRow(3)).toBe(HoverContentState.OFF);
expect(component.hoverContentStateForRow(4)).toBe(HoverContentState.FOCUSABLE);
component.openLens(2);
tick(1);
expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.ON);
expect(component.hoverContentStateForRow(1)).toBe(HoverContentState.FOCUSABLE);
expect(component.hoverContentStateForRow(3)).toBe(HoverContentState.FOCUSABLE);
component.focusEditCell(4);
tick(1);
expect(component.hoverContentStateForRow(2)).toBe(HoverContentState.OFF);
expect(component.hoverContentStateForRow(4)).toBe(HoverContentState.ON);
expect(component.hoverContentStateForRow(3)).toBe(HoverContentState.FOCUSABLE);
}),
);
});
describe('triggering edit', () => {
it('opens edit from on-hover button', fakeAsync(() => {
component.triggerHoverState();
component.clickOpenButton();
expect(component.lensIsOpen()).toBe(true);
clearLeftoverTimers();
}));
it('opens edit from Enter on focued cell', fakeAsync(() => {
// Uses Enter to open the lens.
component.openLens();
expect(component.lensIsOpen()).toBe(true);
clearLeftoverTimers();
}));
it('does not trigger edit when disabled', fakeAsync(() => {
component.nameEditDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Uses Enter to open the lens.
component.openLens();
expect(component.lensIsOpen()).toBe(false);
clearLeftoverTimers();
}));
it('sets aria label and role dialog on the popup', fakeAsync(() => {
component.nameEditAriaLabel = 'Label of name!!';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Uses Enter to open the lens.
component.openLens();
fixture.detectChanges();
expect(component.lensIsOpen()).toBe(true);
const dialogElem = component.getEditPane()!;
expect(dialogElem.getAttribute('aria-label')).toBe('Label of name!!');
expect(dialogElem.getAttribute('role')).toBe('dialog');
clearLeftoverTimers();
}));
});
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 14398,
"start_byte": 7833,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/popover-edit/popover-edit.spec.ts"
}
|
components/src/material-experimental/popover-edit/popover-edit.spec.ts_14406_19783
|
describe('focus manipulation', () => {
const getRowCells = () => component.getRows().map(getCells);
describe('tabindex', () => {
it('sets tabindex to 0 on editable cells', () => {
expect(component.getEditCell().getAttribute('tabindex')).toBe('0');
});
it('unsets tabindex to 0 on disabled cells', () => {
component.nameEditDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(component.getEditCell().hasAttribute('tabindex')).toBe(false);
});
});
describe('arrow keys', () => {
const dispatchKey = (cell: HTMLElement, keyCode: number) =>
dispatchKeyboardEvent(cell, 'keydown', keyCode);
it('moves focus up/down/left/right and prevents default', () => {
const rowCells = getRowCells();
// Focus the upper-left editable cell.
rowCells[0][1].focus();
const downEvent = dispatchKey(rowCells[0][1], DOWN_ARROW);
expect(document.activeElement).toBe(rowCells[1][1]);
expect(downEvent.defaultPrevented).toBe(true);
const rightEvent = dispatchKey(rowCells[1][1], RIGHT_ARROW);
expect(document.activeElement).toBe(rowCells[1][2]);
expect(rightEvent.defaultPrevented).toBe(true);
const upEvent = dispatchKey(rowCells[1][2], UP_ARROW);
expect(document.activeElement).toBe(rowCells[0][2]);
expect(upEvent.defaultPrevented).toBe(true);
const leftEvent = dispatchKey(rowCells[0][2], LEFT_ARROW);
expect(document.activeElement).toBe(rowCells[0][1]);
expect(leftEvent.defaultPrevented).toBe(true);
});
it('wraps around when reaching start or end of a row, skipping non-editable cells', () => {
const rowCells = getRowCells();
// Focus the upper-right editable cell.
rowCells[0][2].focus();
dispatchKey(rowCells[0][2], RIGHT_ARROW);
expect(document.activeElement).toBe(rowCells[1][1]);
dispatchKey(rowCells[1][1], LEFT_ARROW);
expect(document.activeElement).toBe(rowCells[0][2]);
});
it('does not fall off top or bottom of the table', () => {
const rowCells = getRowCells();
// Focus the upper-left editable cell.
rowCells[0][1].focus();
dispatchKey(rowCells[0][1], UP_ARROW);
expect(document.activeElement).toBe(rowCells[0][1]);
// Focus the bottom-left editable cell.
rowCells[4][1].focus();
dispatchKey(rowCells[4][1], DOWN_ARROW);
expect(document.activeElement).toBe(rowCells[4][1]);
});
it('ignores non arrow key events', () => {
component.focusEditCell();
const cell = component.getEditCell();
expect(dispatchKey(cell, TAB).defaultPrevented).toBe(false);
});
});
describe('lens focus trapping behavior', () => {
const getFocusablePaneElements = () =>
Array.from(
component
.getEditBoundingBox()!
.querySelectorAll('input, button, .cdk-focus-trap-anchor'),
) as HTMLElement[];
it('keeps focus within the lens by default', fakeAsync(() => {
// Open the name lens which has the default behavior.
component.openLens();
const focusableElements = getFocusablePaneElements();
// Focus the last element (end focus trap anchor).
focusableElements[focusableElements.length - 1].focus();
flush();
// Focus should have moved to the top of the lens.
expect(document.activeElement).toBe(focusableElements[1]);
expect(component.lensIsOpen()).toBe(true);
clearLeftoverTimers();
}));
it('moves focus to the next cell when focus leaves end of lens with matPopoverEditTabOut', fakeAsync(() => {
// Open the weight lens which has tab out behavior.
component.openLens(0, 2);
const focusableElements = getFocusablePaneElements();
// Focus the last element (end focus trap anchor).
focusableElements[focusableElements.length - 1].focus();
flush();
// Focus should have moved to the next editable cell.
expect(document.activeElement).toBe(component.getEditCell(1, 1));
expect(component.lensIsOpen()).toBe(false);
clearLeftoverTimers();
}));
it(`moves focus to the previous cell when focus leaves end of lens with
matPopoverEditTabOut`, fakeAsync(() => {
// Open the weight lens which has tab out behavior.
component.openLens(0, 2);
const focusableElements = getFocusablePaneElements();
// Focus the first (start focus trap anchor).
focusableElements[0].focus();
flush();
// Focus should have moved to the next editable cell.
expect(document.activeElement).toBe(component.getEditCell(0, 1));
expect(component.lensIsOpen()).toBe(false);
clearLeftoverTimers();
}));
});
});
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 19783,
"start_byte": 14406,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/popover-edit/popover-edit.spec.ts"
}
|
components/src/material-experimental/popover-edit/popover-edit.spec.ts_19791_29664
|
describe('edit lens', () => {
function expectPixelsToEqual(actual: number, expected: number) {
expect(Math.floor(actual)).toBe(Math.floor(expected));
}
it('shows a lens with the value from the table', fakeAsync(() => {
component.openLens();
expect(component.getInput()!.value).toBe('Hydrogen');
clearLeftoverTimers();
}));
it('positions the lens at the top left corner and spans the full width of the cell', fakeAsync(() => {
component.openLens();
fixture.detectChanges();
const paneRect = component.getEditPane()!.getBoundingClientRect();
const cellRect = component.getEditCell().getBoundingClientRect();
expectPixelsToEqual(paneRect.width, cellRect.width);
expectPixelsToEqual(paneRect.left, cellRect.left);
expectPixelsToEqual(paneRect.top, cellRect.top);
clearLeftoverTimers();
}));
it('adjusts the positioning of the lens based on colspan', fakeAsync(() => {
const cellRects = getCells(getRows(component.table.nativeElement)[0]).map(cell =>
cell.getBoundingClientRect(),
);
component.colspan = {before: 1};
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
component.openLens();
fixture.detectChanges();
let paneRect = component.getEditPane()!.getBoundingClientRect();
expectPixelsToEqual(paneRect.top, cellRects[0].top);
expectPixelsToEqual(paneRect.left, cellRects[0].left);
expectPixelsToEqual(paneRect.right, cellRects[1].right);
component.colspan = {after: 1};
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
paneRect = component.getEditPane()!.getBoundingClientRect();
expectPixelsToEqual(paneRect.top, cellRects[1].top);
// TODO: This was commented out after switching from the legacy table to the current
// MDC-based table. This failed by being inaccurate by several pixels.
// expectPixelsToEqual(paneRect.left, cellRects[1].left);
// expectPixelsToEqual(paneRect.right, cellRects[2].right);
component.colspan = {before: 1, after: 1};
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
paneRect = component.getEditPane()!.getBoundingClientRect();
expectPixelsToEqual(paneRect.top, cellRects[0].top);
expectPixelsToEqual(paneRect.left, cellRects[0].left);
// TODO: This was commented out after switching from the legacy table to the current
// MDC-based table. This failed by being inaccurate by several pixels.
// expectPixelsToEqual(paneRect.right, cellRects[2].right);
clearLeftoverTimers();
}));
it('updates the form and submits, closing the lens', fakeAsync(() => {
component.openLens();
component.getInput()!.value = 'Hydragon';
component.getInput()!.dispatchEvent(new Event('input'));
component.clickSubmitButton();
fixture.detectChanges();
expect(component.getEditCell().firstChild!.textContent!.trim()).toBe('Hydragon');
expect(component.lensIsOpen()).toBe(false);
clearLeftoverTimers();
}));
it('does not close the lens on submit when form is invalid', fakeAsync(() => {
component.openLens();
component.getInput()!.value = '';
component.getInput()!.dispatchEvent(new Event('input'));
component.clickSubmitButton();
expect(component.lensIsOpen()).toBe(true);
clearLeftoverTimers();
}));
it(
'closes lens on submit when form is invalid with ' +
'matEditControlIgnoreSubmitUnlessValid = false',
fakeAsync(() => {
component.ignoreSubmitUnlessValid = false;
component.openLens();
component.getInput()!.value = '';
component.getInput()!.dispatchEvent(new Event('input'));
component.clickSubmitButton();
expect(component.lensIsOpen()).toBe(false);
clearLeftoverTimers();
}),
);
it('closes the lens on close', fakeAsync(() => {
component.openLens();
component.clickCloseButton();
expect(component.lensIsOpen()).toBe(false);
clearLeftoverTimers();
}));
it('closes and reopens a lens with modified value persisted', fakeAsync(() => {
component.openLens();
component.getInput()!.value = 'Hydragon';
component.getInput()!.dispatchEvent(new Event('input'));
component.clickCloseButton();
fixture.detectChanges();
expect(component.getEditCell().firstChild!.textContent!.trim()).toBe('Hydrogen');
expect(component.lensIsOpen()).toBe(false);
component.openLens();
fixture.detectChanges();
expect(component.getInput()!.value).toBe('Hydragon');
clearLeftoverTimers();
}));
it('resets the lens to original value', fakeAsync(() => {
component.openLens();
fixture.detectChanges();
component.getInput()!.value = 'Hydragon';
component.getInput()!.dispatchEvent(new Event('input'));
component.clickRevertButton();
expect(component.getInput()!.value).toBe('Hydrogen');
clearLeftoverTimers();
}));
it('resets the lens to previously submitted value', fakeAsync(() => {
component.openLens();
component.getInput()!.value = 'Hydragon';
component.getInput()!.dispatchEvent(new Event('input'));
component.clickSubmitButton();
fixture.detectChanges();
component.openLens();
fixture.detectChanges();
component.getInput()!.value = 'Hydragon X';
component.getInput()!.dispatchEvent(new Event('input'));
component.clickRevertButton();
expect(component.getInput()!.value).toBe('Hydragon');
clearLeftoverTimers();
}));
it('closes the lens on escape', fakeAsync(() => {
component.openLens();
const event = new KeyboardEvent('keydown', {bubbles: true, key: 'Escape'});
spyOn(event, 'preventDefault').and.callThrough();
component.getInput()!.dispatchEvent(event);
expect(component.lensIsOpen()).toBe(false);
expect(event.preventDefault).toHaveBeenCalled();
clearLeftoverTimers();
}));
it('does not close the lens on escape with a modifier key', fakeAsync(() => {
component.openLens();
const event = new KeyboardEvent('keydown', {bubbles: true, key: 'Escape'});
Object.defineProperty(event, 'altKey', {get: () => true});
spyOn(event, 'preventDefault').and.callThrough();
component.getInput()!.dispatchEvent(event);
expect(component.lensIsOpen()).toBe(true);
expect(event.preventDefault).not.toHaveBeenCalled();
clearLeftoverTimers();
}));
it('does not close the lens on click within lens', fakeAsync(() => {
component.openLens();
component.getInput()!.dispatchEvent(new Event('click', {bubbles: true}));
expect(component.lensIsOpen()).toBe(true);
clearLeftoverTimers();
}));
it('closes the lens on outside click', fakeAsync(() => {
component.openLens();
component.getInput()!.value = 'Hydragon';
component.getInput()!.dispatchEvent(new Event('input'));
document.body.dispatchEvent(new Event('click', {bubbles: true}));
fixture.detectChanges();
expect(component.lensIsOpen()).toBe(false);
expect(component.getEditCell().firstChild!.textContent!.trim()).toBe('Hydrogen');
clearLeftoverTimers();
}));
it(
'submits the lens on outside click with ' + 'matEditControlClickOutBehavior = "submit"',
fakeAsync(() => {
component.clickOutBehavior = 'submit';
component.openLens();
component.getInput()!.value = 'Hydragon';
component.getInput()!.dispatchEvent(new Event('input'));
document.body.dispatchEvent(new Event('click', {bubbles: true}));
fixture.detectChanges();
expect(component.lensIsOpen()).toBe(false);
expect(component.getEditCell().firstChild!.textContent!.trim()).toBe('Hydragon');
clearLeftoverTimers();
}),
);
it(
'does nothing on outside click with ' + 'matEditControlClickOutBehavior = "noop"',
fakeAsync(() => {
component.clickOutBehavior = 'noop';
component.openLens();
component.getInput()!.value = 'Hydragon';
component.getInput()!.dispatchEvent(new Event('input'));
document.body.dispatchEvent(new Event('click', {bubbles: true}));
fixture.detectChanges();
expect(component.lensIsOpen()).toBe(true);
expect(component.getEditCell().firstChild!.textContent!.trim()).toBe('Hydrogen');
clearLeftoverTimers();
}),
);
it('sets focus on the first input in the lens', fakeAsync(() => {
component.openLens();
expect(document.activeElement).toBe(component.getInput());
clearLeftoverTimers();
}));
it('returns focus to the edited cell after closing', fakeAsync(() => {
component.openLens();
component.clickCloseButton();
expect(document.activeElement).toBe(component.getEditCell());
clearLeftoverTimers();
}));
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 29664,
"start_byte": 19791,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/popover-edit/popover-edit.spec.ts"
}
|
components/src/material-experimental/popover-edit/popover-edit.spec.ts_29674_31039
|
it(
'does not focus to the edited cell after closing if another element ' +
'outside the lens is already focused',
fakeAsync(() => {
component.openLens(0);
component.getEditCell(1).focus();
component.getEditCell(1).dispatchEvent(new Event('click', {bubbles: true}));
expect(document.activeElement).toBe(component.getEditCell(1));
clearLeftoverTimers();
}),
);
});
});
}
});
function createElementData() {
return [
{name: 'Hydrogen', weight: 1.007},
{name: 'Helium', weight: 4.0026},
{name: 'Lithium', weight: 6.941},
{name: 'Beryllium', weight: 9.0122},
{name: 'Boron', weight: 10.81},
];
}
function getElements(element: Element, query: string): HTMLElement[] {
return [].slice.call(element.querySelectorAll(query));
}
function getRows(tableElement: Element): HTMLElement[] {
return getElements(tableElement, '.mat-mdc-row, tr');
}
function getCells(row: Element): HTMLElement[] {
if (!row) {
return [];
}
return getElements(row, '.mat-mdc-cell, td');
}
// Common actions like mouse events and focus/blur cause timers to be fired off.
// When not testing this behavior directly, use this function to clear any timers that were
// created in passing.
function clearLeftoverTimers() {
tick(100);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 31039,
"start_byte": 29674,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/popover-edit/popover-edit.spec.ts"
}
|
components/src/material-experimental/selection/selection-column.scss_0_102
|
th.mat-selection-column-header,
td.mat-selection-column-cell {
text-align: center;
width: 48px;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 102,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/selection/selection-column.scss"
}
|
components/src/material-experimental/selection/selection.ts_0_1439
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {CdkSelection, SelectionChange} from '@angular/cdk-experimental/selection';
import {Directive, Input, Output, EventEmitter} from '@angular/core';
/**
* Manages the selection states of the items and provides methods to check and update the selection
* states.
* It must be applied to the parent element if `matSelectionToggle`, `matSelectAll`,
* `matRowSelection` and `matSelectionColumn` are applied.
*/
@Directive({
selector: '[matSelection]',
exportAs: 'matSelection',
providers: [{provide: CdkSelection, useExisting: MatSelection}],
})
// tslint:disable-next-line: coercion-types
export class MatSelection<T> extends CdkSelection<T> {
/** Whether to support multiple selection */
@Input('matSelectionMultiple')
override get multiple(): boolean {
return this._multiple;
}
override set multiple(multiple: boolean) {
this._multiple = coerceBooleanProperty(multiple);
}
/** Emits when selection changes. */
@Output('matSelectionChange') override readonly change = new EventEmitter<SelectionChange<T>>();
}
/**
* Represents the change in the selection set.
*/
export {SelectionChange} from '@angular/cdk-experimental/selection';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1439,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/selection/selection.ts"
}
|
components/src/material-experimental/selection/public-api.ts_0_404
|
/**
* @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 './selection';
export * from './select-all';
export * from './selection-toggle';
export * from './selection-column';
export * from './row-selection';
export * from './selection-module';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 404,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/selection/public-api.ts"
}
|
components/src/material-experimental/selection/selection-toggle.ts_0_1263
|
/**
* @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 {CdkSelectionToggle} from '@angular/cdk-experimental/selection';
import {Directive, Input} from '@angular/core';
/**
* Makes the element a selection toggle.
*
* Must be used within a parent `MatSelection` directive.
* Must be provided with the value. If `trackBy` is used on `MatSelection`, the index of the value
* is required. If the element implements `ControlValueAccessor`, e.g. `MatCheckbox`, the directive
* automatically connects it with the selection state provided by the `MatSelection` directive. If
* not, use `checked$` to get the checked state of the value, and `toggle()` to change the selection
* state.
*/
@Directive({
selector: '[matSelectionToggle]',
exportAs: 'matSelectionToggle',
inputs: [{name: 'index', alias: 'matSelectionToggleIndex'}],
providers: [{provide: CdkSelectionToggle, useExisting: MatSelectionToggle}],
})
export class MatSelectionToggle<T> extends CdkSelectionToggle<T> {
/** The value that is associated with the toggle */
@Input('matSelectionToggleValue') override value: T = undefined!;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1263,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/selection/selection-toggle.ts"
}
|
components/src/material-experimental/selection/row-selection.ts_0_1103
|
/**
* @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 {CdkRowSelection} from '@angular/cdk-experimental/selection';
import {Input, Directive} from '@angular/core';
/**
* Applies `mat-selected` class and `aria-selected` to an element.
*
* Must be used within a parent `MatSelection` directive.
* Must be provided with the value. The index is required if `trackBy` is used on the `CdkSelection`
* directive.
*/
@Directive({
selector: '[matRowSelection]',
host: {
'[class.mat-selected]': '_selection.isSelected(this.value, this.index)',
'[attr.aria-selected]': '_selection.isSelected(this.value, this.index)',
},
providers: [{provide: CdkRowSelection, useExisting: MatRowSelection}],
inputs: [{name: 'index', alias: 'matRowSelectionIndex'}],
})
export class MatRowSelection<T> extends CdkRowSelection<T> {
/** The value that is associated with the row */
@Input('matRowSelectionValue') override value: T = undefined!;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1103,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/selection/row-selection.ts"
}
|
components/src/material-experimental/selection/_selection.scss_0_167
|
@use '@angular/material' as mat;
@mixin theme($theme) {
@include mat.private-check-duplicate-theme-styles($theme, 'mat-selection');
}
@mixin typography($theme) {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 167,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/selection/_selection.scss"
}
|
components/src/material-experimental/selection/selection-column.ts_0_3367
|
/**
* @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 {
MatCell,
MatCellDef,
MatColumnDef,
MatHeaderCell,
MatHeaderCellDef,
MatTable,
} from '@angular/material/table';
import {
Component,
Input,
OnDestroy,
OnInit,
ViewChild,
ChangeDetectionStrategy,
ViewEncapsulation,
inject,
} from '@angular/core';
import {AsyncPipe} from '@angular/common';
import {MatSelection} from './selection';
import {MatCheckbox} from '@angular/material/checkbox';
import {MatSelectionToggle} from './selection-toggle';
import {MatSelectAll} from './select-all';
/**
* Column that adds row selecting checkboxes and a select-all checkbox if `matSelectionMultiple` is
* `true`.
*
* Must be used within a parent `MatSelection` directive.
*/
@Component({
selector: 'mat-selection-column',
template: `
<ng-container matColumnDef>
<th mat-header-cell *matHeaderCellDef class="mat-selection-column-header">
@if (selection && selection.multiple) {
<mat-checkbox
matSelectAll
#allToggler="matSelectAll"
[indeterminate]="allToggler.indeterminate | async"></mat-checkbox>
}
</th>
<td mat-cell *matCellDef="let row; let i = $index" class="mat-selection-column-cell">
<mat-checkbox
matSelectionToggle
[matSelectionToggleValue]="row"
[matSelectionToggleIndex]="i"></mat-checkbox>
</td>
</ng-container>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
styleUrl: 'selection-column.css',
encapsulation: ViewEncapsulation.None,
imports: [
MatColumnDef,
MatHeaderCellDef,
MatHeaderCell,
MatCheckbox,
MatSelectAll,
MatCellDef,
MatCell,
MatSelectionToggle,
AsyncPipe,
],
})
export class MatSelectionColumn<T> implements OnInit, OnDestroy {
private _table = inject<MatTable<T>>(MatTable, {optional: true});
readonly selection = inject<MatSelection<T>>(MatSelection, {optional: true});
/** Column name that should be used to reference this column. */
@Input()
get name(): string {
return this._name;
}
set name(name: string) {
this._name = name;
this._syncColumnDefName();
}
private _name: string;
@ViewChild(MatColumnDef, {static: true}) private readonly _columnDef: MatColumnDef;
@ViewChild(MatCellDef, {static: true}) private readonly _cell: MatCellDef;
@ViewChild(MatHeaderCellDef, {static: true})
private readonly _headerCell: MatHeaderCellDef;
ngOnInit() {
if (!this.selection && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('MatSelectionColumn: missing MatSelection in the parent');
}
this._syncColumnDefName();
if (this._table) {
this._columnDef.cell = this._cell;
this._columnDef.headerCell = this._headerCell;
this._table.addColumnDef(this._columnDef);
} else if (typeof ngDevMode === 'undefined' || ngDevMode) {
throw Error('MatSelectionColumn: missing parent table');
}
}
ngOnDestroy() {
if (this._table) {
this._table.removeColumnDef(this._columnDef);
}
}
private _syncColumnDefName() {
if (this._columnDef) {
this._columnDef.name = this._name;
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 3367,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/selection/selection-column.ts"
}
|
components/src/material-experimental/selection/selection-module.ts_0_1064
|
/**
* @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
*/
// TODO(yifange): Move the table-specific code to a separate module from the other selection
// behaviors once we move it out of experimental.
import {NgModule} from '@angular/core';
import {MatTableModule} from '@angular/material/table';
import {MatCheckboxModule} from '@angular/material/checkbox';
import {MatSelectAll} from './select-all';
import {MatSelection} from './selection';
import {MatSelectionToggle} from './selection-toggle';
import {MatSelectionColumn} from './selection-column';
import {MatRowSelection} from './row-selection';
@NgModule({
imports: [
MatTableModule,
MatCheckboxModule,
MatSelectAll,
MatSelection,
MatSelectionToggle,
MatSelectionColumn,
MatRowSelection,
],
exports: [MatSelectAll, MatSelection, MatSelectionToggle, MatSelectionColumn, MatRowSelection],
})
export class MatSelectionModule {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1064,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/selection/selection-module.ts"
}
|
components/src/material-experimental/selection/select-all.ts_0_1061
|
/**
* @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 {CdkSelectAll} from '@angular/cdk-experimental/selection';
import {Directive} from '@angular/core';
/**
* Makes the element a select-all toggle.
*
* Must be used within a parent `MatSelection` directive. It toggles the selection states
* of all the selection toggles connected with the `MatSelection` directive.
* If the element implements `ControlValueAccessor`, e.g. `MatCheckbox`, the directive
* automatically connects it with the select-all state provided by the `MatSelection` directive. If
* not, use `checked` to get the checked state, `indeterminate` to get the indeterminate state,
* and `toggle()` to change the selection state.
*/
@Directive({
selector: '[matSelectAll]',
exportAs: 'matSelectAll',
providers: [{provide: CdkSelectAll, useExisting: MatSelectAll}],
})
export class MatSelectAll<T> extends CdkSelectAll<T> {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1061,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/selection/select-all.ts"
}
|
components/src/material-experimental/selection/BUILD.bazel_0_660
|
load("//tools:defaults.bzl", "ng_module", "sass_binary", "sass_library")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "selection",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = [":selection_column_scss"],
deps = [
"//src/cdk-experimental/selection",
"//src/material/checkbox",
"//src/material/table",
"@npm//@angular/core",
],
)
sass_library(
name = "selection_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = ["//src/material:sass_lib"],
)
sass_binary(
name = "selection_column_scss",
src = "selection-column.scss",
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 660,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/selection/BUILD.bazel"
}
|
components/src/material-experimental/selection/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';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/selection/index.ts"
}
|
components/src/youtube-player/youtube-player-placeholder.ts_0_2586
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ChangeDetectionStrategy, Component, Input, ViewEncapsulation} from '@angular/core';
/** Quality of the placeholder image. */
export type PlaceholderImageQuality = 'high' | 'standard' | 'low';
@Component({
selector: 'youtube-player-placeholder',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
template: `
<button type="button" class="youtube-player-placeholder-button" [attr.aria-label]="buttonLabel">
<svg
height="100%"
version="1.1"
viewBox="0 0 68 48"
focusable="false"
aria-hidden="true">
<path d="M66.52,7.74c-0.78-2.93-2.49-5.41-5.42-6.19C55.79,.13,34,0,34,0S12.21,.13,6.9,1.55 C3.97,2.33,2.27,4.81,1.48,7.74C0.06,13.05,0,24,0,24s0.06,10.95,1.48,16.26c0.78,2.93,2.49,5.41,5.42,6.19 C12.21,47.87,34,48,34,48s21.79-0.13,27.1-1.55c2.93-0.78,4.64-3.26,5.42-6.19C67.94,34.95,68,24,68,24S67.94,13.05,66.52,7.74z" fill="#f00"></path>
<path d="M 45,24 27,14 27,34" fill="#fff"></path>
</svg>
</button>
`,
styleUrl: 'youtube-player-placeholder.css',
host: {
'class': 'youtube-player-placeholder',
'[class.youtube-player-placeholder-loading]': 'isLoading',
'[style.background-image]': '_getBackgroundImage()',
'[style.width.px]': 'width',
'[style.height.px]': 'height',
},
})
export class YouTubePlayerPlaceholder {
/** ID of the video for which to show the placeholder. */
@Input() videoId: string;
/** Width of the video for which to show the placeholder. */
@Input() width: number;
/** Height of the video for which to show the placeholder. */
@Input() height: number;
/** Whether the video is currently being loaded. */
@Input() isLoading: boolean;
/** Accessible label for the play button. */
@Input() buttonLabel: string;
/** Quality of the placeholder image. */
@Input() quality: PlaceholderImageQuality;
/** Gets the background image showing the placeholder. */
protected _getBackgroundImage(): string | undefined {
let url: string;
if (this.quality === 'low') {
url = `https://i.ytimg.com/vi/${this.videoId}/hqdefault.jpg`;
} else if (this.quality === 'high') {
url = `https://i.ytimg.com/vi/${this.videoId}/maxresdefault.jpg`;
} else {
url = `https://i.ytimg.com/vi_webp/${this.videoId}/sddefault.webp`;
}
return `url(${url})`;
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2586,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/youtube-player-placeholder.ts"
}
|
components/src/youtube-player/youtube-module.ts_0_400
|
/**
* @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 {YouTubePlayer} from './youtube-player';
@NgModule({
imports: [YouTubePlayer],
exports: [YouTubePlayer],
})
export class YouTubePlayerModule {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 400,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/youtube-module.ts"
}
|
components/src/youtube-player/public-api.ts_0_400
|
/**
* @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 './youtube-module';
export {YouTubePlayer, YOUTUBE_PLAYER_CONFIG, YouTubePlayerConfig} from './youtube-player';
export {PlaceholderImageQuality} from './youtube-player-placeholder';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 400,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/public-api.ts"
}
|
components/src/youtube-player/youtube-player.ts_0_3739
|
/**
* @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
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="youtube" preserve="true" />
import {
ChangeDetectionStrategy,
Component,
ElementRef,
Input,
NgZone,
OnDestroy,
Output,
ViewChild,
ViewEncapsulation,
PLATFORM_ID,
OnChanges,
SimpleChanges,
booleanAttribute,
numberAttribute,
InjectionToken,
inject,
CSP_NONCE,
ChangeDetectorRef,
AfterViewInit,
} from '@angular/core';
import {isPlatformBrowser} from '@angular/common';
import {Observable, of as observableOf, Subject, BehaviorSubject, fromEventPattern} from 'rxjs';
import {takeUntil, switchMap} from 'rxjs/operators';
import {PlaceholderImageQuality, YouTubePlayerPlaceholder} from './youtube-player-placeholder';
declare global {
interface Window {
YT: typeof YT | undefined;
onYouTubeIframeAPIReady: (() => void) | undefined;
}
}
/** Injection token used to configure the `YouTubePlayer`. */
export const YOUTUBE_PLAYER_CONFIG = new InjectionToken<YouTubePlayerConfig>(
'YOUTUBE_PLAYER_CONFIG',
);
/** Object that can be used to configure the `YouTubePlayer`. */
export interface YouTubePlayerConfig {
/** Whether to load the YouTube iframe API automatically. Defaults to `true`. */
loadApi?: boolean;
/**
* By default the player shows a placeholder image instead of loading the YouTube API which
* improves the initial page load performance. Use this option to disable the placeholder loading
* behavior globally. Defaults to `false`.
*/
disablePlaceholder?: boolean;
/** Accessible label for the play button inside of the placeholder. */
placeholderButtonLabel?: string;
/**
* Quality of the displayed placeholder image. Defaults to `standard`,
* because not all video have a high-quality placeholder.
*/
placeholderImageQuality?: PlaceholderImageQuality;
}
export const DEFAULT_PLAYER_WIDTH = 640;
export const DEFAULT_PLAYER_HEIGHT = 390;
/**
* Object used to store the state of the player if the
* user tries to interact with the API before it has been loaded.
*/
interface PendingPlayerState {
playbackState?: PlayerState.PLAYING | PlayerState.PAUSED | PlayerState.CUED;
playbackRate?: number;
volume?: number;
muted?: boolean;
seek?: {seconds: number; allowSeekAhead: boolean};
}
/** Coercion function for time values. */
function coerceTime(value: number | undefined): number | undefined {
return value == null ? value : numberAttribute(value, 0);
}
/**
* Equivalent of `YT.PlayerState` which we can't use, because it's meant to
* be read off the `window` which we can't do before the API has been loaded.
*/
enum PlayerState {
UNSTARTED = -1,
ENDED = 0,
PLAYING = 1,
PAUSED = 2,
BUFFERING = 3,
CUED = 5,
}
/**
* Angular component that renders a YouTube player via the YouTube player
* iframe API.
* @see https://developers.google.com/youtube/iframe_api_reference
*/
@Component({
selector: 'youtube-player',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
imports: [YouTubePlayerPlaceholder],
template: `
@if (_shouldShowPlaceholder()) {
<youtube-player-placeholder
[videoId]="videoId!"
[width]="width"
[height]="height"
[isLoading]="_isLoading"
[buttonLabel]="placeholderButtonLabel"
[quality]="placeholderImageQuality"
(click)="_load(true)"/>
}
<div [style.display]="_shouldShowPlaceholder() ? 'none' : ''">
<div #youtubeContainer></div>
</div>
`,
})
export
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 3739,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/youtube-player.ts"
}
|
components/src/youtube-player/youtube-player.ts_3740_12101
|
class YouTubePlayer implements AfterViewInit, OnChanges, OnDestroy {
private _ngZone = inject(NgZone);
private readonly _nonce = inject(CSP_NONCE, {optional: true});
private readonly _changeDetectorRef = inject(ChangeDetectorRef);
private _player: YT.Player | undefined;
private _pendingPlayer: YT.Player | undefined;
private _existingApiReadyCallback: (() => void) | undefined;
private _pendingPlayerState: PendingPlayerState | undefined;
private readonly _destroyed = new Subject<void>();
private readonly _playerChanges = new BehaviorSubject<YT.Player | undefined>(undefined);
protected _isLoading = false;
protected _hasPlaceholder = true;
/** Whether we're currently rendering inside a browser. */
private readonly _isBrowser: boolean;
/** YouTube Video ID to view */
@Input()
videoId: string | undefined;
/** Height of video player */
@Input({transform: numberAttribute})
get height(): number {
return this._height;
}
set height(height: number | undefined) {
this._height = height == null || isNaN(height) ? DEFAULT_PLAYER_HEIGHT : height;
}
private _height = DEFAULT_PLAYER_HEIGHT;
/** Width of video player */
@Input({transform: numberAttribute})
get width(): number {
return this._width;
}
set width(width: number | undefined) {
this._width = width == null || isNaN(width) ? DEFAULT_PLAYER_WIDTH : width;
}
private _width = DEFAULT_PLAYER_WIDTH;
/** The moment when the player is supposed to start playing */
@Input({transform: coerceTime})
startSeconds: number | undefined;
/** The moment when the player is supposed to stop playing */
@Input({transform: coerceTime})
endSeconds: number | undefined;
/** The suggested quality of the player */
@Input()
suggestedQuality: YT.SuggestedVideoQuality | undefined;
/**
* Extra parameters used to configure the player. See:
* https://developers.google.com/youtube/player_parameters.html?playerVersion=HTML5#Parameters
*/
@Input()
playerVars: YT.PlayerVars | undefined;
/** Whether cookies inside the player have been disabled. */
@Input({transform: booleanAttribute})
disableCookies: boolean = false;
/** Whether to automatically load the YouTube iframe API. Defaults to `true`. */
@Input({transform: booleanAttribute})
loadApi: boolean;
/**
* By default the player shows a placeholder image instead of loading the YouTube API which
* improves the initial page load performance. This input allows for the behavior to be disabled.
*/
@Input({transform: booleanAttribute})
disablePlaceholder: boolean = false;
/**
* Whether the iframe will attempt to load regardless of the status of the api on the
* page. Set this to true if you don't want the `onYouTubeIframeAPIReady` field to be
* set on the global window.
*/
@Input({transform: booleanAttribute}) showBeforeIframeApiLoads: boolean = false;
/** Accessible label for the play button inside of the placeholder. */
@Input() placeholderButtonLabel: string;
/**
* Quality of the displayed placeholder image. Defaults to `standard`,
* because not all video have a high-quality placeholder.
*/
@Input() placeholderImageQuality: PlaceholderImageQuality;
/** Outputs are direct proxies from the player itself. */
@Output() readonly ready: Observable<YT.PlayerEvent> =
this._getLazyEmitter<YT.PlayerEvent>('onReady');
@Output() readonly stateChange: Observable<YT.OnStateChangeEvent> =
this._getLazyEmitter<YT.OnStateChangeEvent>('onStateChange');
@Output() readonly error: Observable<YT.OnErrorEvent> =
this._getLazyEmitter<YT.OnErrorEvent>('onError');
@Output() readonly apiChange: Observable<YT.PlayerEvent> =
this._getLazyEmitter<YT.PlayerEvent>('onApiChange');
@Output() readonly playbackQualityChange: Observable<YT.OnPlaybackQualityChangeEvent> =
this._getLazyEmitter<YT.OnPlaybackQualityChangeEvent>('onPlaybackQualityChange');
@Output() readonly playbackRateChange: Observable<YT.OnPlaybackRateChangeEvent> =
this._getLazyEmitter<YT.OnPlaybackRateChangeEvent>('onPlaybackRateChange');
/** The element that will be replaced by the iframe. */
@ViewChild('youtubeContainer', {static: true})
youtubeContainer: ElementRef<HTMLElement>;
constructor(...args: unknown[]);
constructor() {
const platformId = inject<Object>(PLATFORM_ID);
const config = inject(YOUTUBE_PLAYER_CONFIG, {optional: true});
this.loadApi = config?.loadApi ?? true;
this.disablePlaceholder = !!config?.disablePlaceholder;
this.placeholderButtonLabel = config?.placeholderButtonLabel || 'Play video';
this.placeholderImageQuality = config?.placeholderImageQuality || 'standard';
this._isBrowser = isPlatformBrowser(platformId);
}
ngAfterViewInit() {
this._conditionallyLoad();
}
ngOnChanges(changes: SimpleChanges): void {
if (this._shouldRecreatePlayer(changes)) {
this._conditionallyLoad();
} else if (this._player) {
if (changes['width'] || changes['height']) {
this._setSize();
}
if (changes['suggestedQuality']) {
this._setQuality();
}
if (changes['startSeconds'] || changes['endSeconds'] || changes['suggestedQuality']) {
this._cuePlayer();
}
}
}
ngOnDestroy() {
this._pendingPlayer?.destroy();
if (this._player) {
this._player.destroy();
window.onYouTubeIframeAPIReady = this._existingApiReadyCallback;
}
this._playerChanges.complete();
this._destroyed.next();
this._destroyed.complete();
}
/** See https://developers.google.com/youtube/iframe_api_reference#playVideo */
playVideo() {
if (this._player) {
this._player.playVideo();
} else {
this._getPendingState().playbackState = PlayerState.PLAYING;
this._load(true);
}
}
/** See https://developers.google.com/youtube/iframe_api_reference#pauseVideo */
pauseVideo() {
if (this._player) {
this._player.pauseVideo();
} else {
this._getPendingState().playbackState = PlayerState.PAUSED;
}
}
/** See https://developers.google.com/youtube/iframe_api_reference#stopVideo */
stopVideo() {
if (this._player) {
this._player.stopVideo();
} else {
// It seems like YouTube sets the player to CUED when it's stopped.
this._getPendingState().playbackState = PlayerState.CUED;
}
}
/** See https://developers.google.com/youtube/iframe_api_reference#seekTo */
seekTo(seconds: number, allowSeekAhead: boolean) {
if (this._player) {
this._player.seekTo(seconds, allowSeekAhead);
} else {
this._getPendingState().seek = {seconds, allowSeekAhead};
}
}
/** See https://developers.google.com/youtube/iframe_api_reference#mute */
mute() {
if (this._player) {
this._player.mute();
} else {
this._getPendingState().muted = true;
}
}
/** See https://developers.google.com/youtube/iframe_api_reference#unMute */
unMute() {
if (this._player) {
this._player.unMute();
} else {
this._getPendingState().muted = false;
}
}
/** See https://developers.google.com/youtube/iframe_api_reference#isMuted */
isMuted(): boolean {
if (this._player) {
return this._player.isMuted();
}
if (this._pendingPlayerState) {
return !!this._pendingPlayerState.muted;
}
return false;
}
/** See https://developers.google.com/youtube/iframe_api_reference#setVolume */
setVolume(volume: number) {
if (this._player) {
this._player.setVolume(volume);
} else {
this._getPendingState().volume = volume;
}
}
/** See https://developers.google.com/youtube/iframe_api_reference#getVolume */
getVolume(): number {
if (this._player) {
return this._player.getVolume();
}
if (this._pendingPlayerState && this._pendingPlayerState.volume != null) {
return this._pendingPlayerState.volume;
}
return 0;
}
/** See https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate */
setPlaybackRate(playbackRate: number) {
if (this._player) {
return this._player.setPlaybackRate(playbackRate);
} else {
this._getPendingState().playbackRate = playbackRate;
}
}
/** See https://developers.google.com/youtube/iframe_api_reference#getPlaybackRate */
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 12101,
"start_byte": 3740,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/youtube-player.ts"
}
|
components/src/youtube-player/youtube-player.ts_12104_20728
|
getPlaybackRate(): number {
if (this._player) {
return this._player.getPlaybackRate();
}
if (this._pendingPlayerState && this._pendingPlayerState.playbackRate != null) {
return this._pendingPlayerState.playbackRate;
}
return 0;
}
/** See https://developers.google.com/youtube/iframe_api_reference#getAvailablePlaybackRates */
getAvailablePlaybackRates(): number[] {
return this._player ? this._player.getAvailablePlaybackRates() : [];
}
/** See https://developers.google.com/youtube/iframe_api_reference#getVideoLoadedFraction */
getVideoLoadedFraction(): number {
return this._player ? this._player.getVideoLoadedFraction() : 0;
}
/** See https://developers.google.com/youtube/iframe_api_reference#getPlayerState */
getPlayerState(): YT.PlayerState | undefined {
if (!this._isBrowser || !window.YT) {
return undefined;
}
if (this._player) {
return this._player.getPlayerState();
}
if (this._pendingPlayerState && this._pendingPlayerState.playbackState != null) {
return this._pendingPlayerState.playbackState;
}
return PlayerState.UNSTARTED;
}
/** See https://developers.google.com/youtube/iframe_api_reference#getCurrentTime */
getCurrentTime(): number {
if (this._player) {
return this._player.getCurrentTime();
}
if (this._pendingPlayerState && this._pendingPlayerState.seek) {
return this._pendingPlayerState.seek.seconds;
}
return 0;
}
/** See https://developers.google.com/youtube/iframe_api_reference#getPlaybackQuality */
getPlaybackQuality(): YT.SuggestedVideoQuality {
return this._player ? this._player.getPlaybackQuality() : 'default';
}
/** See https://developers.google.com/youtube/iframe_api_reference#getAvailableQualityLevels */
getAvailableQualityLevels(): YT.SuggestedVideoQuality[] {
return this._player ? this._player.getAvailableQualityLevels() : [];
}
/** See https://developers.google.com/youtube/iframe_api_reference#getDuration */
getDuration(): number {
return this._player ? this._player.getDuration() : 0;
}
/** See https://developers.google.com/youtube/iframe_api_reference#getVideoUrl */
getVideoUrl(): string {
return this._player ? this._player.getVideoUrl() : '';
}
/** See https://developers.google.com/youtube/iframe_api_reference#getVideoEmbedCode */
getVideoEmbedCode(): string {
return this._player ? this._player.getVideoEmbedCode() : '';
}
/**
* Loads the YouTube API and sets up the player.
* @param playVideo Whether to automatically play the video once the player is loaded.
*/
protected _load(playVideo: boolean) {
// Don't do anything if we're not in a browser environment.
if (!this._isBrowser) {
return;
}
if (!window.YT || !window.YT.Player) {
if (this.loadApi) {
this._isLoading = true;
loadApi(this._nonce);
} else if (this.showBeforeIframeApiLoads && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw new Error(
'Namespace YT not found, cannot construct embedded youtube player. ' +
'Please install the YouTube Player API Reference for iframe Embeds: ' +
'https://developers.google.com/youtube/iframe_api_reference',
);
}
this._existingApiReadyCallback = window.onYouTubeIframeAPIReady;
window.onYouTubeIframeAPIReady = () => {
this._existingApiReadyCallback?.();
this._ngZone.run(() => this._createPlayer(playVideo));
};
} else {
this._createPlayer(playVideo);
}
}
/** Loads the player depending on the internal state of the component. */
private _conditionallyLoad() {
// If the placeholder isn't shown anymore, we have to trigger a load.
if (!this._shouldShowPlaceholder()) {
this._load(false);
} else if (this.playerVars?.autoplay === 1) {
// If it's an autoplaying video, we have to hide the placeholder and start playing.
this._load(true);
}
}
/** Whether to show the placeholder element. */
protected _shouldShowPlaceholder(): boolean {
if (this.disablePlaceholder) {
return false;
}
// Since we don't load the API on the server, we show the placeholder permanently.
if (!this._isBrowser) {
return true;
}
return this._hasPlaceholder && !!this.videoId && !this._player;
}
/** Gets an object that should be used to store the temporary API state. */
private _getPendingState(): PendingPlayerState {
if (!this._pendingPlayerState) {
this._pendingPlayerState = {};
}
return this._pendingPlayerState;
}
/**
* Determines whether a change in the component state
* requires the YouTube player to be recreated.
*/
private _shouldRecreatePlayer(changes: SimpleChanges): boolean {
const change =
changes['videoId'] ||
changes['playerVars'] ||
changes['disableCookies'] ||
changes['disablePlaceholder'];
return !!change && !change.isFirstChange();
}
/**
* Creates a new YouTube player and destroys the existing one.
* @param playVideo Whether to play the video once it loads.
*/
private _createPlayer(playVideo: boolean) {
this._player?.destroy();
this._pendingPlayer?.destroy();
// A player can't be created if the API isn't loaded,
// or there isn't a video or playlist to be played.
if (typeof YT === 'undefined' || (!this.videoId && !this.playerVars?.list)) {
return;
}
// Important! We need to create the Player object outside of the `NgZone`, because it kicks
// off a 250ms setInterval which will continually trigger change detection if we don't.
const player = this._ngZone.runOutsideAngular(
() =>
new YT.Player(this.youtubeContainer.nativeElement, {
videoId: this.videoId,
host: this.disableCookies ? 'https://www.youtube-nocookie.com' : undefined,
width: this.width,
height: this.height,
// Calling `playVideo` on load doesn't appear to actually play
// the video so we need to trigger it through `playerVars` instead.
playerVars: playVideo ? {...(this.playerVars || {}), autoplay: 1} : this.playerVars,
}),
);
const whenReady = () => {
// Only assign the player once it's ready, otherwise YouTube doesn't expose some APIs.
this._ngZone.run(() => {
this._isLoading = false;
this._hasPlaceholder = false;
this._player = player;
this._pendingPlayer = undefined;
player.removeEventListener('onReady', whenReady);
this._playerChanges.next(player);
this._setSize();
this._setQuality();
if (this._pendingPlayerState) {
this._applyPendingPlayerState(player, this._pendingPlayerState);
this._pendingPlayerState = undefined;
}
// Only cue the player when it either hasn't started yet or it's cued,
// otherwise cuing it can interrupt a player with autoplay enabled.
const state = player.getPlayerState();
if (state === PlayerState.UNSTARTED || state === PlayerState.CUED || state == null) {
this._cuePlayer();
}
this._changeDetectorRef.markForCheck();
});
};
this._pendingPlayer = player;
player.addEventListener('onReady', whenReady);
}
/** Applies any state that changed before the player was initialized. */
private _applyPendingPlayerState(player: YT.Player, pendingState: PendingPlayerState): void {
const {playbackState, playbackRate, volume, muted, seek} = pendingState;
switch (playbackState) {
case PlayerState.PLAYING:
player.playVideo();
break;
case PlayerState.PAUSED:
player.pauseVideo();
break;
case PlayerState.CUED:
player.stopVideo();
break;
}
if (playbackRate != null) {
player.setPlaybackRate(playbackRate);
}
if (volume != null) {
player.setVolume(volume);
}
if (muted != null) {
muted ? player.mute() : player.unMute();
}
if (seek != null) {
player.seekTo(seek.seconds, seek.allowSeekAhead);
}
}
/** Cues the player based on the current component state. */
private _cuePlayer() {
if (this._player && this.videoId) {
this._player.cueVideoById({
videoId: this.videoId,
startSeconds: this.startSeconds,
endSeconds: this.endSeconds,
suggestedQuality: this.suggestedQuality,
});
}
}
/** Sets the player's size based on the current input values. */
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 20728,
"start_byte": 12104,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/youtube-player.ts"
}
|
components/src/youtube-player/youtube-player.ts_20731_23961
|
private _setSize() {
this._player?.setSize(this.width, this.height);
}
/** Sets the player's quality based on the current input values. */
private _setQuality() {
if (this._player && this.suggestedQuality) {
this._player.setPlaybackQuality(this.suggestedQuality);
}
}
/** Gets an observable that adds an event listener to the player when a user subscribes to it. */
private _getLazyEmitter<T extends YT.PlayerEvent>(name: keyof YT.Events): Observable<T> {
// Start with the stream of players. This way the events will be transferred
// over to the new player if it gets swapped out under-the-hood.
return this._playerChanges.pipe(
// Switch to the bound event. `switchMap` ensures that the old event is removed when the
// player is changed. If there's no player, return an observable that never emits.
switchMap(player => {
return player
? fromEventPattern<T>(
(listener: (event: T) => void) => {
player.addEventListener(name, listener);
},
(listener: (event: T) => void) => {
// The API seems to throw when we try to unbind from a destroyed player and it doesn't
// expose whether the player has been destroyed so we have to wrap it in a try/catch to
// prevent the entire stream from erroring out.
try {
player?.removeEventListener?.(name, listener);
} catch {}
},
)
: observableOf<T>();
}),
// By default we run all the API interactions outside the zone
// so we have to bring the events back in manually when they emit.
source =>
new Observable<T>(observer =>
source.subscribe({
next: value => this._ngZone.run(() => observer.next(value)),
error: error => observer.error(error),
complete: () => observer.complete(),
}),
),
// Ensures that everything is cleared out on destroy.
takeUntil(this._destroyed),
);
}
}
let apiLoaded = false;
/** Loads the YouTube API from a specified URL only once. */
function loadApi(nonce: string | null): void {
if (apiLoaded) {
return;
}
// We can use `document` directly here, because this logic doesn't run outside the browser.
const url = 'https://www.youtube.com/iframe_api';
const script = document.createElement('script');
const callback = (event: Event) => {
script.removeEventListener('load', callback);
script.removeEventListener('error', callback);
if (event.type === 'error') {
apiLoaded = false;
if (typeof ngDevMode === 'undefined' || ngDevMode) {
console.error(`Failed to load YouTube API from ${url}`);
}
}
};
script.addEventListener('load', callback);
script.addEventListener('error', callback);
(script as any).src = url;
script.async = true;
if (nonce) {
script.setAttribute('nonce', nonce);
}
// Set this immediately to true so we don't start loading another script
// while this one is pending. If loading fails, we'll flip it back to false.
apiLoaded = true;
document.body.appendChild(script);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 23961,
"start_byte": 20731,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/youtube-player.ts"
}
|
components/src/youtube-player/youtube-player.spec.ts_0_786
|
import {Component, EnvironmentProviders, Provider, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {Subscription} from 'rxjs';
import {createFakeYtNamespace} from './fake-youtube-player';
import {
DEFAULT_PLAYER_HEIGHT,
DEFAULT_PLAYER_WIDTH,
YOUTUBE_PLAYER_CONFIG,
YouTubePlayer,
} from './youtube-player';
import {PlaceholderImageQuality} from './youtube-player-placeholder';
const VIDEO_ID = 'a12345';
const YT_LOADING_STATE_MOCK = {loading: 1, loaded: 0};
const TEST_PROVIDERS: (Provider | EnvironmentProviders)[] = [
{
provide: YOUTUBE_PLAYER_CONFIG,
useValue: {
// Disable API loading in tests since we don't want to pull in any additional scripts.
loadApi: false,
},
},
];
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 786,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/youtube-player.spec.ts"
}
|
components/src/youtube-player/youtube-player.spec.ts_788_10304
|
describe('YoutubePlayer', () => {
let playerCtorSpy: jasmine.Spy;
let playerSpy: jasmine.SpyObj<YT.Player>;
let fixture: ComponentFixture<TestApp>;
let testComponent: TestApp;
let events: Required<YT.Events>;
beforeEach(waitForAsync(() => {
const fake = createFakeYtNamespace();
playerCtorSpy = fake.playerCtorSpy;
playerSpy = fake.playerSpy;
window.YT = fake.namespace;
events = fake.events;
}));
function getVideoHost(componentFixture: ComponentFixture<unknown>): HTMLElement {
// Not the most resilient selector, but we don't want to introduce any
// classes/IDs on the `div` so users don't start depending on it.
return componentFixture.nativeElement.querySelector('div > div');
}
function getPlaceholder(componentFixture: ComponentFixture<unknown>): HTMLElement {
return componentFixture.nativeElement.querySelector('youtube-player-placeholder');
}
describe('API ready', () => {
beforeEach(() => {
TestBed.configureTestingModule({providers: TEST_PROVIDERS});
fixture = TestBed.createComponent(TestApp);
testComponent = fixture.debugElement.componentInstance;
fixture.detectChanges();
});
afterEach(() => {
(window as any).YT = undefined;
window.onYouTubeIframeAPIReady = undefined;
});
it('initializes a youtube player when the placeholder is clicked', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
events.onReady({target: playerSpy});
fixture.detectChanges();
expect(playerCtorSpy).toHaveBeenCalledWith(
getVideoHost(fixture),
jasmine.objectContaining({
videoId: VIDEO_ID,
width: DEFAULT_PLAYER_WIDTH,
height: DEFAULT_PLAYER_HEIGHT,
playerVars: {autoplay: 1},
}),
);
expect(getPlaceholder(fixture)).toBeFalsy();
});
it('destroys the iframe when the component is destroyed', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
events.onReady({target: playerSpy});
testComponent.visible = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerSpy.destroy).toHaveBeenCalled();
});
it('responds to changes in video id', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
const containerElement = getVideoHost(fixture);
testComponent.videoId = 'otherId';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerSpy.cueVideoById).not.toHaveBeenCalled();
events.onReady({target: playerSpy});
expect(playerSpy.cueVideoById).toHaveBeenCalledWith(
jasmine.objectContaining({videoId: 'otherId'}),
);
testComponent.videoId = undefined;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerSpy.destroy).toHaveBeenCalled();
testComponent.videoId = 'otherId2';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerCtorSpy).toHaveBeenCalledWith(
containerElement,
jasmine.objectContaining({videoId: 'otherId2'}),
);
});
it('responds to changes in size', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
testComponent.width = 5;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerSpy.setSize).not.toHaveBeenCalled();
events.onReady({target: playerSpy});
expect(playerSpy.setSize).toHaveBeenCalledWith(5, DEFAULT_PLAYER_HEIGHT);
expect(testComponent.youtubePlayer.width).toBe(5);
expect(testComponent.youtubePlayer.height).toBe(DEFAULT_PLAYER_HEIGHT);
testComponent.height = 6;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerSpy.setSize).toHaveBeenCalledWith(5, 6);
expect(testComponent.youtubePlayer.width).toBe(5);
expect(testComponent.youtubePlayer.height).toBe(6);
testComponent.videoId = undefined;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
testComponent.videoId = VIDEO_ID;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerCtorSpy).toHaveBeenCalledWith(
jasmine.any(Element),
jasmine.objectContaining({width: 5, height: 6}),
);
expect(testComponent.youtubePlayer.width).toBe(5);
expect(testComponent.youtubePlayer.height).toBe(6);
events.onReady({target: playerSpy});
testComponent.width = undefined;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerSpy.setSize).toHaveBeenCalledWith(DEFAULT_PLAYER_WIDTH, 6);
expect(testComponent.youtubePlayer.width).toBe(DEFAULT_PLAYER_WIDTH);
expect(testComponent.youtubePlayer.height).toBe(6);
testComponent.height = undefined;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerSpy.setSize).toHaveBeenCalledWith(DEFAULT_PLAYER_WIDTH, DEFAULT_PLAYER_HEIGHT);
expect(testComponent.youtubePlayer.width).toBe(DEFAULT_PLAYER_WIDTH);
expect(testComponent.youtubePlayer.height).toBe(DEFAULT_PLAYER_HEIGHT);
});
it('passes the configured playerVars to the player', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
events.onReady({target: playerSpy});
const playerVars: YT.PlayerVars = {modestbranding: YT.ModestBranding.Modest};
fixture.componentInstance.playerVars = playerVars;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
events.onReady({target: playerSpy});
const calls = playerCtorSpy.calls.all();
// We expect 2 calls since the first one is run on init and the
// second one happens after the `playerVars` have changed.
expect(calls.length).toBe(2);
expect(calls[0].args[1]).toEqual(jasmine.objectContaining({playerVars: {autoplay: 1}}));
expect(calls[1].args[1]).toEqual(jasmine.objectContaining({playerVars}));
});
it('initializes the player with start and end seconds', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
testComponent.startSeconds = 5;
testComponent.endSeconds = 6;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerSpy.cueVideoById).not.toHaveBeenCalled();
playerSpy.getPlayerState.and.returnValue(window.YT!.PlayerState.CUED);
events.onReady({target: playerSpy});
expect(playerSpy.cueVideoById).toHaveBeenCalledWith(
jasmine.objectContaining({startSeconds: 5, endSeconds: 6}),
);
testComponent.endSeconds = 8;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerSpy.cueVideoById).toHaveBeenCalledWith(
jasmine.objectContaining({startSeconds: 5, endSeconds: 8}),
);
testComponent.startSeconds = 7;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerSpy.cueVideoById).toHaveBeenCalledWith(
jasmine.objectContaining({startSeconds: 7, endSeconds: 8}),
);
testComponent.startSeconds = 10;
testComponent.endSeconds = 11;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerSpy.cueVideoById).toHaveBeenCalledWith(
jasmine.objectContaining({startSeconds: 10, endSeconds: 11}),
);
});
it('sets the suggested quality', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
testComponent.suggestedQuality = 'small';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerSpy.setPlaybackQuality).not.toHaveBeenCalled();
events.onReady({target: playerSpy});
expect(playerSpy.setPlaybackQuality).toHaveBeenCalledWith('small');
testComponent.suggestedQuality = 'large';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerSpy.setPlaybackQuality).toHaveBeenCalledWith('large');
testComponent.videoId = 'other';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerSpy.cueVideoById).toHaveBeenCalledWith(
jasmine.objectContaining({suggestedQuality: 'large'}),
);
});
it('proxies events as output', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
events.onReady({target: playerSpy});
expect(testComponent.onReady).toHaveBeenCalledWith({target: playerSpy});
events.onStateChange({target: playerSpy, data: 5});
expect(testComponent.onStateChange).toHaveBeenCalledWith({target: playerSpy, data: 5});
events.onPlaybackQualityChange({target: playerSpy, data: 'large'});
expect(testComponent.onPlaybackQualityChange).toHaveBeenCalledWith({
target: playerSpy,
data: 'large',
});
events.onPlaybackRateChange({target: playerSpy, data: 2});
expect(testComponent.onPlaybackRateChange).toHaveBeenCalledWith({target: playerSpy, data: 2});
events.onError({target: playerSpy, data: 5});
expect(testComponent.onError).toHaveBeenCalledWith({target: playerSpy, data: 5});
events.onApiChange({target: playerSpy});
expect(testComponent.onApiChange).toHaveBeenCalledWith({target: playerSpy});
});
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 10304,
"start_byte": 788,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/youtube-player.spec.ts"
}
|
components/src/youtube-player/youtube-player.spec.ts_10310_19669
|
it('proxies methods to the player', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
events.onReady({target: playerSpy});
testComponent.youtubePlayer.playVideo();
expect(playerSpy.playVideo).toHaveBeenCalled();
testComponent.youtubePlayer.pauseVideo();
expect(playerSpy.pauseVideo).toHaveBeenCalled();
testComponent.youtubePlayer.stopVideo();
expect(playerSpy.stopVideo).toHaveBeenCalled();
testComponent.youtubePlayer.mute();
expect(playerSpy.mute).toHaveBeenCalled();
testComponent.youtubePlayer.unMute();
expect(playerSpy.unMute).toHaveBeenCalled();
testComponent.youtubePlayer.isMuted();
expect(playerSpy.isMuted).toHaveBeenCalled();
testComponent.youtubePlayer.seekTo(5, true);
expect(playerSpy.seekTo).toHaveBeenCalledWith(5, true);
testComponent.youtubePlayer.isMuted();
expect(playerSpy.isMuted).toHaveBeenCalled();
testComponent.youtubePlayer.setVolume(54);
expect(playerSpy.setVolume).toHaveBeenCalledWith(54);
testComponent.youtubePlayer.getVolume();
expect(playerSpy.getVolume).toHaveBeenCalled();
testComponent.youtubePlayer.setPlaybackRate(1.5);
expect(playerSpy.setPlaybackRate).toHaveBeenCalledWith(1.5);
testComponent.youtubePlayer.getPlaybackRate();
expect(playerSpy.getPlaybackRate).toHaveBeenCalled();
testComponent.youtubePlayer.getAvailablePlaybackRates();
expect(playerSpy.getAvailablePlaybackRates).toHaveBeenCalled();
testComponent.youtubePlayer.getVideoLoadedFraction();
expect(playerSpy.getVideoLoadedFraction).toHaveBeenCalled();
testComponent.youtubePlayer.getPlayerState();
expect(playerSpy.getPlayerState).toHaveBeenCalled();
testComponent.youtubePlayer.getCurrentTime();
expect(playerSpy.getCurrentTime).toHaveBeenCalled();
testComponent.youtubePlayer.getPlaybackQuality();
expect(playerSpy.getPlaybackQuality).toHaveBeenCalled();
testComponent.youtubePlayer.getAvailableQualityLevels();
expect(playerSpy.getAvailableQualityLevels).toHaveBeenCalled();
testComponent.youtubePlayer.getDuration();
expect(playerSpy.getDuration).toHaveBeenCalled();
testComponent.youtubePlayer.getVideoUrl();
expect(playerSpy.getVideoUrl).toHaveBeenCalled();
testComponent.youtubePlayer.getVideoEmbedCode();
expect(playerSpy.getVideoEmbedCode).toHaveBeenCalled();
});
it('should play on init if playVideo was called before the API has loaded', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
testComponent.youtubePlayer.playVideo();
expect(testComponent.youtubePlayer.getPlayerState()).toBe(YT.PlayerState.PLAYING);
events.onReady({target: playerSpy});
expect(playerSpy.playVideo).toHaveBeenCalled();
});
it('should pause on init if pauseVideo was called before the API has loaded', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
testComponent.youtubePlayer.pauseVideo();
expect(testComponent.youtubePlayer.getPlayerState()).toBe(YT.PlayerState.PAUSED);
events.onReady({target: playerSpy});
expect(playerSpy.pauseVideo).toHaveBeenCalled();
});
it('should stop on init if stopVideo was called before the API has loaded', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
testComponent.youtubePlayer.stopVideo();
expect(testComponent.youtubePlayer.getPlayerState()).toBe(YT.PlayerState.CUED);
events.onReady({target: playerSpy});
expect(playerSpy.stopVideo).toHaveBeenCalled();
});
it('should set the playback rate on init if setPlaybackRate was called before the API has loaded', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
testComponent.youtubePlayer.setPlaybackRate(1337);
expect(testComponent.youtubePlayer.getPlaybackRate()).toBe(1337);
events.onReady({target: playerSpy});
expect(playerSpy.setPlaybackRate).toHaveBeenCalledWith(1337);
});
it('should set the volume on init if setVolume was called before the API has loaded', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
testComponent.youtubePlayer.setVolume(37);
expect(testComponent.youtubePlayer.getVolume()).toBe(37);
events.onReady({target: playerSpy});
expect(playerSpy.setVolume).toHaveBeenCalledWith(37);
});
it('should mute on init if mute was called before the API has loaded', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
testComponent.youtubePlayer.mute();
expect(testComponent.youtubePlayer.isMuted()).toBe(true);
events.onReady({target: playerSpy});
expect(playerSpy.mute).toHaveBeenCalled();
});
it('should unmute on init if umMute was called before the API has loaded', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
testComponent.youtubePlayer.unMute();
expect(testComponent.youtubePlayer.isMuted()).toBe(false);
events.onReady({target: playerSpy});
expect(playerSpy.unMute).toHaveBeenCalled();
});
it('should seek on init if seekTo was called before the API has loaded', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
testComponent.youtubePlayer.seekTo(1337, true);
expect(testComponent.youtubePlayer.getCurrentTime()).toBe(1337);
events.onReady({target: playerSpy});
expect(playerSpy.seekTo).toHaveBeenCalledWith(1337, true);
});
it('should be able to disable cookies', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
events.onReady({target: playerSpy});
const containerElement = getVideoHost(fixture);
expect(playerCtorSpy).toHaveBeenCalledWith(
containerElement,
jasmine.objectContaining({
host: undefined,
}),
);
playerCtorSpy.calls.reset();
fixture.componentInstance.disableCookies = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(playerCtorSpy).toHaveBeenCalledWith(
containerElement,
jasmine.objectContaining({
host: 'https://www.youtube-nocookie.com',
}),
);
});
it('should play with a playlist id instead of a video id', () => {
getPlaceholder(fixture).click();
fixture.detectChanges();
playerCtorSpy.calls.reset();
const playerVars: YT.PlayerVars = {
list: 'some-playlist-id',
listType: 'playlist',
};
testComponent.videoId = undefined;
testComponent.playerVars = playerVars;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
let calls = playerCtorSpy.calls.all();
expect(calls.length).toBe(1);
expect(calls[0].args[1]).toEqual(jasmine.objectContaining({playerVars, videoId: undefined}));
playerSpy.destroy.calls.reset();
playerCtorSpy.calls.reset();
// Change the vars so that the list type is undefined
// We only support a "list" if there's an accompanying "listType"
testComponent.playerVars = {
...playerVars,
listType: undefined,
};
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// The previous instance should have been destroyed
expect(playerSpy.destroy).toHaveBeenCalled();
// Don't expect it to have been called
expect(playerCtorSpy.calls.all().length).toHaveSize(0);
});
});
describe('API loaded asynchronously', () => {
let api: typeof YT;
beforeEach(() => {
api = window.YT;
(window as any).YT = undefined;
});
afterEach(() => {
(window as any).YT = undefined;
window.onYouTubeIframeAPIReady = undefined;
});
it('waits until the api is ready before initializing', () => {
(window.YT as any) = YT_LOADING_STATE_MOCK;
TestBed.configureTestingModule({providers: TEST_PROVIDERS});
fixture = TestBed.createComponent(TestApp);
testComponent = fixture.debugElement.componentInstance;
fixture.detectChanges();
getPlaceholder(fixture).click();
fixture.detectChanges();
expect(playerCtorSpy).not.toHaveBeenCalled();
window.YT = api!;
window.onYouTubeIframeAPIReady!();
expect(playerCtorSpy).toHaveBeenCalledWith(
getVideoHost(fixture),
jasmine.objectContaining({
videoId: VIDEO_ID,
width: DEFAULT_PLAYER_WIDTH,
height: DEFAULT_PLAYER_HEIGHT,
}),
);
});
it('should not override any pre-existing API loaded callbacks', () => {
const spy = jasmine.createSpy('other API loaded spy');
window.onYouTubeIframeAPIReady = spy;
TestBed.configureTestingModule({providers: TEST_PROVIDERS});
fixture = TestBed.createComponent(TestApp);
testComponent = fixture.debugElement.componentInstance;
fixture.detectChanges();
getPlaceholder(fixture).click();
fixture.detectChanges();
expect(playerCtorSpy).not.toHaveBeenCalled();
window.YT = api!;
window.onYouTubeIframeAPIReady!();
expect(spy).toHaveBeenCalled();
});
});
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 19669,
"start_byte": 10310,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/youtube-player.spec.ts"
}
|
components/src/youtube-player/youtube-player.spec.ts_19673_28500
|
describe('placeholder behavior', () => {
beforeEach(() => {
TestBed.configureTestingModule({providers: TEST_PROVIDERS});
fixture = TestBed.createComponent(TestApp);
testComponent = fixture.debugElement.componentInstance;
fixture.detectChanges();
});
afterEach(() => {
fixture = testComponent = (window as any).YT = window.onYouTubeIframeAPIReady = undefined!;
});
it('should show a placeholder', () => {
const placeholder = getPlaceholder(fixture);
expect(placeholder).toBeTruthy();
expect(placeholder.style.backgroundImage).toContain(
`https://i.ytimg.com/vi_webp/${VIDEO_ID}/sddefault.webp`,
);
expect(placeholder.style.width).toBe(`${DEFAULT_PLAYER_WIDTH}px`);
expect(placeholder.style.height).toBe(`${DEFAULT_PLAYER_HEIGHT}px`);
expect(placeholder.querySelector('button')).toBeTruthy();
testComponent.videoId = 'foo123';
testComponent.width = 100;
testComponent.height = 50;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(placeholder.style.backgroundImage).toContain(
'https://i.ytimg.com/vi_webp/foo123/sddefault.webp',
);
expect(placeholder.style.width).toBe('100px');
expect(placeholder.style.height).toBe('50px');
});
it('should allow for the placeholder to be disabled', () => {
expect(getPlaceholder(fixture)).toBeTruthy();
testComponent.disablePlaceholder = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(getPlaceholder(fixture)).toBeFalsy();
});
it('should allow for the placeholder button label to be changed', () => {
const button = getPlaceholder(fixture).querySelector('button')!;
expect(button.getAttribute('aria-label')).toBe('Play video');
testComponent.placeholderButtonLabel = 'Play Star Wars';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(button.getAttribute('aria-label')).toBe('Play Star Wars');
});
it('should not show the placeholder if a playlist is assigned', () => {
expect(getPlaceholder(fixture)).toBeTruthy();
testComponent.videoId = undefined;
testComponent.playerVars = {
list: 'some-playlist-id',
listType: 'playlist',
};
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(getPlaceholder(fixture)).toBeFalsy();
});
it('should hide the placeholder and start playing if an autoplaying video is assigned', () => {
expect(getPlaceholder(fixture)).toBeTruthy();
expect(playerCtorSpy).not.toHaveBeenCalled();
testComponent.playerVars = {autoplay: 1};
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
events.onReady({target: playerSpy});
fixture.detectChanges();
expect(getPlaceholder(fixture)).toBeFalsy();
expect(playerCtorSpy).toHaveBeenCalled();
});
it('should allow for the placeholder image quality to be changed', () => {
const placeholder = getPlaceholder(fixture);
expect(placeholder.style.backgroundImage).toContain(
`https://i.ytimg.com/vi_webp/${VIDEO_ID}/sddefault.webp`,
);
testComponent.placeholderImageQuality = 'low';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(placeholder.style.backgroundImage).toContain(
`https://i.ytimg.com/vi/${VIDEO_ID}/hqdefault.jpg`,
);
testComponent.placeholderImageQuality = 'high';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(placeholder.style.backgroundImage).toContain(
`https://i.ytimg.com/vi/${VIDEO_ID}/maxresdefault.jpg`,
);
});
});
it('should pick up static startSeconds and endSeconds values', () => {
TestBed.configureTestingModule({providers: TEST_PROVIDERS});
const staticSecondsApp = TestBed.createComponent(StaticStartEndSecondsApp);
staticSecondsApp.detectChanges();
getPlaceholder(staticSecondsApp).click();
staticSecondsApp.detectChanges();
playerSpy.getPlayerState.and.returnValue(window.YT!.PlayerState.CUED);
events.onReady({target: playerSpy});
expect(playerSpy.cueVideoById).toHaveBeenCalledWith(
jasmine.objectContaining({startSeconds: 42, endSeconds: 1337}),
);
});
it('should be able to subscribe to events after initialization', () => {
TestBed.configureTestingModule({providers: TEST_PROVIDERS});
const noEventsApp = TestBed.createComponent(NoEventsApp);
noEventsApp.detectChanges();
getPlaceholder(noEventsApp).click();
noEventsApp.detectChanges();
events.onReady({target: playerSpy});
noEventsApp.detectChanges();
const player = noEventsApp.componentInstance.player;
const subscriptions: Subscription[] = [];
const readySpy = jasmine.createSpy('ready spy');
const stateChangeSpy = jasmine.createSpy('stateChange spy');
const playbackQualityChangeSpy = jasmine.createSpy('playbackQualityChange spy');
const playbackRateChangeSpy = jasmine.createSpy('playbackRateChange spy');
const errorSpy = jasmine.createSpy('error spy');
const apiChangeSpy = jasmine.createSpy('apiChange spy');
subscriptions.push(player.ready.subscribe(readySpy));
events.onReady({target: playerSpy});
expect(readySpy).toHaveBeenCalledWith({target: playerSpy});
subscriptions.push(player.stateChange.subscribe(stateChangeSpy));
events.onStateChange({target: playerSpy, data: 5});
expect(stateChangeSpy).toHaveBeenCalledWith({target: playerSpy, data: 5});
subscriptions.push(player.playbackQualityChange.subscribe(playbackQualityChangeSpy));
events.onPlaybackQualityChange({target: playerSpy, data: 'large'});
expect(playbackQualityChangeSpy).toHaveBeenCalledWith({target: playerSpy, data: 'large'});
subscriptions.push(player.playbackRateChange.subscribe(playbackRateChangeSpy));
events.onPlaybackRateChange({target: playerSpy, data: 2});
expect(playbackRateChangeSpy).toHaveBeenCalledWith({target: playerSpy, data: 2});
subscriptions.push(player.error.subscribe(errorSpy));
events.onError({target: playerSpy, data: 5});
expect(errorSpy).toHaveBeenCalledWith({target: playerSpy, data: 5});
subscriptions.push(player.apiChange.subscribe(apiChangeSpy));
events.onApiChange({target: playerSpy});
expect(apiChangeSpy).toHaveBeenCalledWith({target: playerSpy});
subscriptions.forEach(subscription => subscription.unsubscribe());
});
});
/** Test component that contains a YouTubePlayer. */
@Component({
selector: 'test-app',
standalone: true,
imports: [YouTubePlayer],
template: `
@if (visible) {
<youtube-player #player
[videoId]="videoId"
[width]="width"
[height]="height"
[startSeconds]="startSeconds"
[endSeconds]="endSeconds"
[suggestedQuality]="suggestedQuality"
[playerVars]="playerVars"
[disableCookies]="disableCookies"
[disablePlaceholder]="disablePlaceholder"
[placeholderButtonLabel]="placeholderButtonLabel"
[placeholderImageQuality]="placeholderImageQuality"
(ready)="onReady($event)"
(stateChange)="onStateChange($event)"
(playbackQualityChange)="onPlaybackQualityChange($event)"
(playbackRateChange)="onPlaybackRateChange($event)"
(error)="onError($event)"
(apiChange)="onApiChange($event)"/>
}
`,
})
class TestApp {
videoId: string | undefined = VIDEO_ID;
disableCookies = false;
visible = true;
disablePlaceholder = false;
placeholderButtonLabel = 'Play video';
placeholderImageQuality: PlaceholderImageQuality = 'standard';
width: number | undefined;
height: number | undefined;
startSeconds: number | undefined;
endSeconds: number | undefined;
suggestedQuality: YT.SuggestedVideoQuality | undefined;
playerVars: YT.PlayerVars | undefined;
onReady = jasmine.createSpy('onReady');
onStateChange = jasmine.createSpy('onStateChange');
onPlaybackQualityChange = jasmine.createSpy('onPlaybackQualityChange');
onPlaybackRateChange = jasmine.createSpy('onPlaybackRateChange');
onError = jasmine.createSpy('onError');
onApiChange = jasmine.createSpy('onApiChange');
@ViewChild('player') youtubePlayer: YouTubePlayer;
}
@Component({
standalone: true,
imports: [YouTubePlayer],
template: `
<youtube-player [videoId]="videoId" [startSeconds]="42" [endSeconds]="1337"/>
`,
})
class StaticStartEndSecondsApp {
videoId = VIDEO_ID;
}
@Component({
standalone: true,
imports: [YouTubePlayer],
template: `<youtube-player [videoId]="videoId"/>`,
})
class NoEventsApp {
@ViewChild(YouTubePlayer) player: YouTubePlayer;
videoId = VIDEO_ID;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 28500,
"start_byte": 19673,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/youtube-player.spec.ts"
}
|
components/src/youtube-player/README.md_0_4964
|
# Angular YouTube Player component
This component provides a simple Angular wrapper around the
[YouTube player API](https://developers.google.com/youtube/iframe_api_reference).
File any bugs against the [angular/components repo](https://github.com/angular/components/issues).
## Installation
To install, run `ng add @angular/youtube-player`.
## Usage
Import the component either by adding the `YouTubePlayerModule` to your app or by importing
`YouTubePlayer` into a standalone component. Then add the `<youtube-player videoId="<your ID>"`
to your template.
## Example
If your video is found at https://www.youtube.com/watch?v=mVjYG9TSN88, then your video id is `mVjYG9TSN88`.
```typescript
import {Component} from '@angular/core';
import {YouTubePlayer} from '@angular/youtube-player';
@Component({
imports: [YouTubePlayer],
template: '<youtube-player videoId="mVjYG9TSN88"/>',
selector: 'youtube-player-example',
})
export class YoutubePlayerExample {}
```
## API reference
Check out the [source](./youtube-player.ts) to read the API.
## YouTube iframe API usage
The `<youtube-player/>` component requires the YouTube `iframe` to work. If the API isn't loaded
by the time the player is initialized, it'll load the API automatically from `https://www.youtube.com/iframe_api`.
If you don't want it to be loaded, you can either control it on a per-component level using the
`loadApi` input:
```html
<youtube-player videoId="mVjYG9TSN88" loadApi="false"/>
```
Or at a global level using the `YOUTUBE_PLAYER_CONFIG` injection token:
```typescript
import {NgModule} from '@angular/core';
import {YouTubePlayer, YOUTUBE_PLAYER_CONFIG} from '@angular/youtube-player';
@NgModule({
imports: [YouTubePlayer],
providers: [{
provide: YOUTUBE_PLAYER_CONFIG,
useValue: {
loadApi: false
}
}]
})
export class YourApp {}
```
## Loading behavior
By default, the `<youtube-player/>` will show a placeholder element instead of loading the API
up-front until the user interacts with it. This speeds up the initial render of the page by not
loading unnecessary JavaScript for a video that might not be played. Once the user clicks on the
video, the API will be loaded and the placeholder will be swapped out with the actual video.
Note that the placeholder won't be shown in the following scenarios:
* Video that plays automatically (e.g. `playerVars` contains `autoplay: 1`).
* The player is showing a playlist (e.g. `playerVars` contains a `list` property).
If you want to disable the placeholder and have the `<youtube-player/>` load the API on
initialization, you can either pass in the `disablePlaceholder` input:
```html
<youtube-player videoId="mVjYG9TSN88" disablePlaceholder/>
```
Or set it at a global level using the `YOUTUBE_PLAYER_CONFIG` injection token:
```typescript
import {NgModule} from '@angular/core';
import {YouTubePlayer, YOUTUBE_PLAYER_CONFIG} from '@angular/youtube-player';
@NgModule({
imports: [YouTubePlayer],
providers: [{
provide: YOUTUBE_PLAYER_CONFIG,
useValue: {
disablePlaceholder: true
}
}]
})
export class YourApp {}
```
### Placeholder image quality
YouTube provides different sizes of placeholder images depending on when the video was uploaded
and the thumbnail that was provided by the uploader. The `<youtube-player/>` defaults to a quality
that should be available for the majority of videos, but if you're seeing a grey placeholder,
consider switching to the `low` quality using the `placeholderImageQuality` input or through the
`YOUTUBE_PLAYER_CONFIG`.
```html
<!-- Default value, should exist for most videos. -->
<youtube-player videoId="mVjYG9TSN88" placeholderImageQuality="standard"/>
<!-- High quality image that should be present for most videos from the past few years. -->
<youtube-player videoId="mVjYG9TSN88" placeholderImageQuality="high"/>
<!-- Very low quality image, but should exist for all videos. -->
<youtube-player videoId="mVjYG9TSN88" placeholderImageQuality="low"/>
```
### Placeholder internationalization
Since the placeholder has an interactive `button` element, it needs an `aria-label` for proper
accessibility. The default label is "Play video", but you can customize it based on your app through
the `placeholderButtonLabel` input or the `YOUTUBE_PLAYER_CONFIG` injection token:
```html
<youtube-player videoId="mVjYG9TSN88" placeholderButtonLabel="Afspil video"/>
```
### Placeholder caveats
There are a couple of considerations when using placeholders:
1. Different videos support different sizes of placeholder images and there's no way to know
ahead of time which one is supported. The `<youtube-player/>` defaults to a value that should
work for most videos, but if you want something higher or lower, you can refer to the
["Placeholder image quality" section](#placeholder-image-quality).
2. Unlike the native YouTube placeholder, the Angular component doesn't show the video's title,
because it isn't known ahead of time.
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 4964,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/README.md"
}
|
components/src/youtube-player/BUILD.bazel_0_1362
|
load(
"//tools:defaults.bzl",
"ng_module",
"ng_package",
"ng_test_library",
"ng_web_test_suite",
"sass_binary",
)
package(default_visibility = ["//visibility:public"])
ng_module(
name = "youtube-player",
srcs = glob(
["**/*.ts"],
exclude = [
"**/*.spec.ts",
"fake-youtube-player.ts",
],
),
assets = [
":youtube_player_placeholder_scss",
],
deps = [
"//src:dev_mode_types",
"@npm//@angular/common",
"@npm//@angular/core",
"@npm//@types/youtube",
"@npm//rxjs",
],
)
sass_binary(
name = "youtube_player_placeholder_scss",
src = "youtube-player-placeholder.scss",
)
ng_package(
name = "npm_package",
srcs = ["package.json"],
nested_packages = ["//src/youtube-player/schematics:npm_package"],
tags = ["release-package"],
deps = [":youtube-player"],
)
ng_test_library(
name = "unit_test_sources",
srcs = ["fake-youtube-player.ts"] + glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":youtube-player",
"@npm//@angular/platform-browser",
"@npm//rxjs",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1362,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/BUILD.bazel"
}
|
components/src/youtube-player/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';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/index.ts"
}
|
components/src/youtube-player/youtube-player-placeholder.scss_0_957
|
.youtube-player-placeholder {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
overflow: hidden;
cursor: pointer;
background-color: #000;
background-position: center center;
background-size: cover;
transition: box-shadow 300ms ease;
// YouTube has a slight drop shadow on the preview that we try to imitate here.
// Note that they use a base64 image, likely for performance reasons. We can't use the
// image, because it can break users with a CSP that doesn't allow `data:` URLs.
box-shadow: inset 0 120px 90px -90px rgba(0, 0, 0, 0.8);
}
.youtube-player-placeholder-button {
transition: opacity 300ms ease;
-moz-appearance: none;
-webkit-appearance: none;
background: none;
border: none;
padding: 0;
display: flex;
svg {
width: 68px;
height: 48px;
}
}
.youtube-player-placeholder-loading {
box-shadow: none;
.youtube-player-placeholder-button {
opacity: 0;
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 957,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/youtube-player-placeholder.scss"
}
|
components/src/youtube-player/fake-youtube-player.ts_0_3286
|
/**
* @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
*/
// A re-creation of YT.PlayerState since enum values cannot be bound to the window object.
const playerState = {
UNSTARTED: -1,
ENDED: 0,
PLAYING: 1,
PAUSED: 2,
BUFFERING: 3,
CUED: 5,
};
// Re-creation of `YT.ModestBranding` since it was changed
// to a plain enum which we can't reference in tests.
const modestBranding = {
Full: 0,
Modest: 1,
};
interface FakeYtNamespace {
playerCtorSpy: jasmine.Spy;
playerSpy: jasmine.SpyObj<YT.Player>;
events: Required<YT.Events>;
namespace: typeof YT;
}
export function createFakeYtNamespace(): FakeYtNamespace {
const playerSpy: jasmine.SpyObj<YT.Player> = jasmine.createSpyObj('Player', [
'getPlayerState',
'destroy',
'cueVideoById',
'loadVideoById',
'pauseVideo',
'stopVideo',
'seekTo',
'isMuted',
'mute',
'unMute',
'getVolume',
'getPlaybackRate',
'getAvailablePlaybackRates',
'getVideoLoadedFraction',
'getPlayerState',
'getCurrentTime',
'getPlaybackQuality',
'getAvailableQualityLevels',
'getDuration',
'getVideoUrl',
'getVideoEmbedCode',
'playVideo',
'setSize',
'setVolume',
'setPlaybackQuality',
'setPlaybackRate',
'addEventListener',
'removeEventListener',
]);
let playerConfig: YT.PlayerOptions | undefined;
const boundListeners = new Map<keyof YT.Events, Set<(event: any) => void>>();
const playerCtorSpy = jasmine.createSpy('Player Constructor');
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
playerCtorSpy.and.callFake(function (_el: Element, config: YT.PlayerOptions) {
playerConfig = config;
return playerSpy;
});
playerSpy.addEventListener.and.callFake((name: keyof YT.Events, listener: (e: any) => any) => {
if (!boundListeners.has(name)) {
boundListeners.set(name, new Set());
}
boundListeners.get(name)!.add(listener);
});
playerSpy.removeEventListener.and.callFake((name: keyof YT.Events, listener: (e: any) => any) => {
if (boundListeners.has(name)) {
boundListeners.get(name)!.delete(listener);
}
});
function eventHandlerFactory(name: keyof YT.Events) {
return (arg: Object = {}) => {
if (!playerConfig) {
throw new Error(`Player not initialized before ${name} called`);
}
if (boundListeners.has(name)) {
boundListeners.get(name)!.forEach(callback => callback(arg));
}
};
}
const events: Required<YT.Events> = {
onReady: eventHandlerFactory('onReady'),
onStateChange: eventHandlerFactory('onStateChange'),
onPlaybackQualityChange: eventHandlerFactory('onPlaybackQualityChange'),
onPlaybackRateChange: eventHandlerFactory('onPlaybackRateChange'),
onError: eventHandlerFactory('onError'),
onApiChange: eventHandlerFactory('onApiChange'),
};
return {
playerCtorSpy,
playerSpy,
events,
namespace: {
'Player': playerCtorSpy as unknown as typeof YT.Player,
'PlayerState': playerState,
'ModestBranding': modestBranding,
} as typeof YT,
};
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 3286,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/fake-youtube-player.ts"
}
|
components/src/youtube-player/schematics/BUILD.bazel_0_900
|
load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin")
load("//tools:defaults.bzl", "pkg_npm", "ts_library")
package(default_visibility = ["//visibility:public"])
copy_to_bin(
name = "schematics_assets",
srcs = glob(["**/*.json"]),
)
ts_library(
name = "schematics",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
# Schematics can not yet run in ESM module. For now we continue to use CommonJS.
# TODO(ESM): remove this once the Angular CLI supports ESM schematics.
devmode_module = "commonjs",
prodmode_module = "commonjs",
deps = [
"@npm//@angular-devkit/schematics",
"@npm//@types/node",
],
)
# This package is intended to be combined into the main @angular/youtube-player package as a dep.
pkg_npm(
name = "npm_package",
deps = [
":schematics",
":schematics_assets",
],
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 900,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/schematics/BUILD.bazel"
}
|
components/src/youtube-player/schematics/ng-add/index.ts_0_455
|
/**
* @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 {Rule} from '@angular-devkit/schematics';
export default function (): Rule {
// Noop schematic so the CLI doesn't throw if users try to `ng add` this package.
// Also allows us to add more functionality in the future.
return () => {};
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 455,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/youtube-player/schematics/ng-add/index.ts"
}
|
components/src/cdk-experimental/public-api.ts_0_231
|
/**
* @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 './version';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 231,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/public-api.ts"
}
|
components/src/cdk-experimental/config.bzl_0_459
|
# List of all entry-points of the Angular cdk-experimental package.
CDK_EXPERIMENTAL_ENTRYPOINTS = [
"column-resize",
"combobox",
"popover-edit",
"scrolling",
"selection",
"table-scroll-container",
]
# List of all entry-point targets of the Angular cdk-experimental package.
CDK_EXPERIMENTAL_TARGETS = ["//src/cdk-experimental"] + \
["//src/cdk-experimental/%s" % ep for ep in CDK_EXPERIMENTAL_ENTRYPOINTS]
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 459,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/config.bzl"
}
|
components/src/cdk-experimental/README.md_0_265
|
# Angular CDK Experimental
This package contains prototypes and experiments in development for Angular CDK. Nothing in
this package is considered stable or production ready. While the package releases with Angular
CDK, breaking changes may occur with any release.
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 265,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/README.md"
}
|
components/src/cdk-experimental/BUILD.bazel_0_481
|
load("//src/cdk-experimental:config.bzl", "CDK_EXPERIMENTAL_TARGETS")
load("//tools:defaults.bzl", "ng_package", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "cdk-experimental",
srcs = glob(
["*.ts"],
exclude = ["**/*.spec.ts"],
),
deps = ["@npm//@angular/core"],
)
ng_package(
name = "npm_package",
srcs = ["package.json"],
tags = ["release-package"],
deps = CDK_EXPERIMENTAL_TARGETS,
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/BUILD.bazel"
}
|
components/src/cdk-experimental/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';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/index.ts"
}
|
components/src/cdk-experimental/version.ts_0_357
|
/**
* @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 {Version} from '@angular/core';
/** Current version of the CDK Experimental package. */
export const VERSION = new Version('0.0.0-PLACEHOLDER');
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 357,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/version.ts"
}
|
components/src/cdk-experimental/table-scroll-container/table-scroll-container.spec.ts_0_8701
|
import {CollectionViewer, DataSource} from '@angular/cdk/collections';
import {Platform} from '@angular/cdk/platform';
import {CdkTable, CdkTableModule} from '@angular/cdk/table';
import {Component, Type, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {BehaviorSubject, combineLatest} from 'rxjs';
import {map} from 'rxjs/operators';
import {CdkTableScrollContainerModule} from './index';
describe('CdkTableScrollContainer', () => {
let fixture: ComponentFixture<any>;
let component: any;
let platform: Platform;
let tableElement: HTMLElement;
let scrollerElement: HTMLElement;
let dataRows: HTMLElement[];
let headerRows: HTMLElement[];
let footerRows: HTMLElement[];
function createComponent<T>(
componentType: Type<T>,
declarations: any[] = [],
): ComponentFixture<T> {
TestBed.configureTestingModule({
imports: [CdkTableModule, CdkTableScrollContainerModule, componentType, ...declarations],
});
return TestBed.createComponent<T>(componentType);
}
function setupTableTestApp(componentType: Type<any>, declarations: any[] = []) {
fixture = createComponent(componentType, declarations);
component = fixture.componentInstance;
fixture.detectChanges();
tableElement = fixture.nativeElement.querySelector('.cdk-table');
scrollerElement = fixture.nativeElement.querySelector('.cdk-table-scroll-container');
}
async function waitForLayout(): Promise<void> {
await new Promise(resolve => setTimeout(resolve));
// In newer versions of Chrome (change was noticed between 114 and 124), the computed
// style of `::-webkit-scrollbar-track` doesn't update until the styles of the container
// have changed. Toggle between a couple of states so that tests get accurate measurements.
scrollerElement.style.color = scrollerElement.style.color ? '' : '#000';
}
beforeEach(() => {
setupTableTestApp(StickyNativeLayoutCdkTableApp);
platform = TestBed.inject(Platform);
headerRows = getHeaderRows(tableElement);
footerRows = getFooterRows(tableElement);
dataRows = getRows(tableElement);
});
it('sets scrollbar track margin for sticky headers', waitForAsync(async () => {
component.stickyHeaders = ['header-1', 'header-3'];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
await waitForLayout();
if (platform.FIREFOX) {
// ::-webkit-scrollbar-track is not recognized by Firefox.
return;
}
const scrollerStyle = window.getComputedStyle(scrollerElement, '::-webkit-scrollbar-track');
expect(scrollerStyle.getPropertyValue('margin-top')).toBe(`${headerRows[0].offsetHeight}px`);
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
component.stickyHeaders = [];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
await waitForLayout();
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
}));
it('sets scrollbar track margin for sticky footers', waitForAsync(async () => {
component.stickyFooters = ['footer-1', 'footer-3'];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
await waitForLayout();
if (platform.FIREFOX) {
// ::-webkit-scrollbar-track is not recognized by Firefox.
return;
}
const scrollerStyle = window.getComputedStyle(scrollerElement, '::-webkit-scrollbar-track');
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe(`${footerRows[2].offsetHeight}px`);
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
component.stickyFooters = [];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
await waitForLayout();
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
}));
it('sets scrollbar track margin for sticky start columns', waitForAsync(async () => {
component.stickyStartColumns = ['column-1', 'column-3'];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
await waitForLayout();
if (platform.FIREFOX) {
// ::-webkit-scrollbar-track is not recognized by Firefox.
return;
}
const scrollerStyle = window.getComputedStyle(scrollerElement, '::-webkit-scrollbar-track');
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe(
`${getCells(dataRows[0])[0].offsetWidth}px`,
);
component.stickyStartColumns = [];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
await waitForLayout();
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
}));
it('sets scrollbar track margin for sticky end columns', waitForAsync(async () => {
component.stickyEndColumns = ['column-4', 'column-6'];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
await waitForLayout();
if (platform.FIREFOX) {
// ::-webkit-scrollbar-track is not recognized by Firefox.
return;
}
const scrollerStyle = window.getComputedStyle(scrollerElement, '::-webkit-scrollbar-track');
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe(
`${getCells(dataRows[0])[5].offsetWidth}px`,
);
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
component.stickyEndColumns = [];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
await waitForLayout();
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
}));
it('sets scrollbar track margin for a combination of sticky rows and columns', waitForAsync(async () => {
component.stickyHeaders = ['header-1'];
component.stickyFooters = ['footer-3'];
component.stickyStartColumns = ['column-1'];
component.stickyEndColumns = ['column-6'];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
await waitForLayout();
if (platform.FIREFOX) {
// ::-webkit-scrollbar-track is not recognized by Firefox.
return;
}
const scrollerStyle = window.getComputedStyle(scrollerElement, '::-webkit-scrollbar-track');
expect(scrollerStyle.getPropertyValue('margin-top')).toBe(`${headerRows[0].offsetHeight}px`);
expect(scrollerStyle.getPropertyValue('margin-right')).toBe(
`${getCells(dataRows[0])[5].offsetWidth}px`,
);
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe(`${footerRows[2].offsetHeight}px`);
expect(scrollerStyle.getPropertyValue('margin-left')).toBe(
`${getCells(dataRows[0])[0].offsetWidth}px`,
);
component.stickyHeaders = [];
component.stickyFooters = [];
component.stickyStartColumns = [];
component.stickyEndColumns = [];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
await waitForLayout();
expect(scrollerStyle.getPropertyValue('margin-top')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-right')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-bottom')).toBe('0px');
expect(scrollerStyle.getPropertyValue('margin-left')).toBe('0px');
}));
});
interface TestData {
a: string;
b: string;
c: string;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 8701,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/table-scroll-container/table-scroll-container.spec.ts"
}
|
components/src/cdk-experimental/table-scroll-container/table-scroll-container.spec.ts_8703_12298
|
class FakeDataSource extends DataSource<TestData> {
isConnected = false;
get data() {
return this._dataChange.getValue();
}
set data(data: TestData[]) {
this._dataChange.next(data);
}
_dataChange = new BehaviorSubject<TestData[]>([]);
constructor() {
super();
for (let i = 0; i < 3; i++) {
this.addData();
}
}
connect(collectionViewer: CollectionViewer) {
this.isConnected = true;
return combineLatest([this._dataChange, collectionViewer.viewChange]).pipe(
map(data => data[0]),
);
}
disconnect() {
this.isConnected = false;
}
addData() {
const nextIndex = this.data.length + 1;
let copiedData = this.data.slice();
copiedData.push({
a: `a_${nextIndex}`,
b: `b_${nextIndex}`,
c: `c_${nextIndex}`,
});
this.data = copiedData;
}
}
@Component({
template: `
<div cdkTableScrollContainer>
<table cdk-table [dataSource]="dataSource">
@for (column of columns; track column) {
<ng-container [cdkColumnDef]="column"
[sticky]="isStuck(stickyStartColumns, column)"
[stickyEnd]="isStuck(stickyEndColumns, column)">
<th cdk-header-cell *cdkHeaderCellDef> Header {{column}} </th>
<td cdk-cell *cdkCellDef="let row"> {{column}} </td>
<td cdk-footer-cell *cdkFooterCellDef> Footer {{column}} </td>
</ng-container>
}
<tr cdk-header-row *cdkHeaderRowDef="columns; sticky: isStuck(stickyHeaders, 'header-1')">
</tr>
<tr cdk-header-row *cdkHeaderRowDef="columns; sticky: isStuck(stickyHeaders, 'header-2')">
</tr>
<tr cdk-header-row *cdkHeaderRowDef="columns; sticky: isStuck(stickyHeaders, 'header-3')">
</tr>
<tr cdk-row *cdkRowDef="let row; columns: columns"></tr>
<tr cdk-footer-row *cdkFooterRowDef="columns; sticky: isStuck(stickyFooters, 'footer-1')">
</tr>
<tr cdk-footer-row *cdkFooterRowDef="columns; sticky: isStuck(stickyFooters, 'footer-2')">
</tr>
<tr cdk-footer-row *cdkFooterRowDef="columns; sticky: isStuck(stickyFooters, 'footer-3')">
</tr>
</table>
</div>
`,
standalone: true,
imports: [CdkTableModule, CdkTableScrollContainerModule],
styles: `
.cdk-header-cell, .cdk-cell, .cdk-footer-cell {
display: block;
width: 20px;
box-sizing: border-box;
}
`,
})
class StickyNativeLayoutCdkTableApp {
dataSource: FakeDataSource = new FakeDataSource();
columns = ['column-1', 'column-2', 'column-3', 'column-4', 'column-5', 'column-6'];
@ViewChild(CdkTable) table: CdkTable<TestData>;
stickyHeaders: string[] = [];
stickyFooters: string[] = [];
stickyStartColumns: string[] = [];
stickyEndColumns: string[] = [];
isStuck(list: string[], id: string) {
return list.indexOf(id) != -1;
}
}
function getElements(element: Element, query: string): HTMLElement[] {
return [].slice.call(element.querySelectorAll(query));
}
function getHeaderRows(tableElement: Element): HTMLElement[] {
return [].slice.call(tableElement.querySelectorAll('.cdk-header-row'));
}
function getFooterRows(tableElement: Element): HTMLElement[] {
return [].slice.call(tableElement.querySelectorAll('.cdk-footer-row'));
}
function getRows(tableElement: Element): HTMLElement[] {
return getElements(tableElement, '.cdk-row');
}
function getCells(row: Element): HTMLElement[] {
if (!row) {
return [];
}
let cells = getElements(row, 'cdk-cell');
if (!cells.length) {
cells = getElements(row, 'td.cdk-cell');
}
return cells;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 12298,
"start_byte": 8703,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/table-scroll-container/table-scroll-container.spec.ts"
}
|
components/src/cdk-experimental/table-scroll-container/public-api.ts_0_295
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './table-scroll-container';
export * from './table-scroll-container-module';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 295,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/table-scroll-container/public-api.ts"
}
|
components/src/cdk-experimental/table-scroll-container/table-scroll-container.ts_0_4780
|
/**
* @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 {CSP_NONCE, Directive, ElementRef, OnDestroy, OnInit, inject} from '@angular/core';
import {DOCUMENT} from '@angular/common';
import {Directionality} from '@angular/cdk/bidi';
import {_getShadowRoot} from '@angular/cdk/platform';
import {
STICKY_POSITIONING_LISTENER,
StickyPositioningListener,
StickySize,
StickyUpdate,
} from '@angular/cdk/table';
let nextId = 0;
/**
* Applies styles to the host element that make its scrollbars match up with
* the non-sticky scrollable portions of the CdkTable contained within.
*
* This visual effect only works in Webkit and Blink based browsers (eg Chrome,
* Safari, Edge). Other browsers such as Firefox will gracefully degrade to
* normal scrollbar appearance.
* Further note: These styles have no effect when the browser is using OS-default
* scrollbars. The easiest way to force them into custom mode is to specify width
* and height for the scrollbar and thumb.
*/
@Directive({
selector: '[cdkTableScrollContainer]',
host: {
'class': 'cdk-table-scroll-container',
},
providers: [{provide: STICKY_POSITIONING_LISTENER, useExisting: CdkTableScrollContainer}],
})
export class CdkTableScrollContainer implements StickyPositioningListener, OnDestroy, OnInit {
private readonly _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly _document = inject<Document>(DOCUMENT);
private readonly _directionality = inject(Directionality, {optional: true});
private readonly _nonce = inject(CSP_NONCE, {optional: true});
private readonly _uniqueClassName = `cdk-table-scroll-container-${++nextId}`;
private _styleRoot!: Node;
private _styleElement?: HTMLStyleElement;
/** The most recent sticky column size values from the CdkTable. */
private _startSizes: StickySize[] = [];
private _endSizes: StickySize[] = [];
private _headerSizes: StickySize[] = [];
private _footerSizes: StickySize[] = [];
ngOnInit() {
this._elementRef.nativeElement.classList.add(this._uniqueClassName);
this._styleRoot = _getShadowRoot(this._elementRef.nativeElement) ?? this._document.head;
}
ngOnDestroy(): void {
this._styleElement?.remove();
this._styleElement = undefined;
}
stickyColumnsUpdated({sizes}: StickyUpdate): void {
this._startSizes = sizes;
this._updateScrollbar();
}
stickyEndColumnsUpdated({sizes}: StickyUpdate): void {
this._endSizes = sizes;
this._updateScrollbar();
}
stickyHeaderRowsUpdated({sizes}: StickyUpdate): void {
this._headerSizes = sizes;
this._updateScrollbar();
}
stickyFooterRowsUpdated({sizes}: StickyUpdate): void {
this._footerSizes = sizes;
this._updateScrollbar();
}
/**
* Set padding on the scrollbar track based on the sticky states from CdkTable.
*/
private _updateScrollbar(): void {
const topMargin = computeMargin(this._headerSizes);
const bottomMargin = computeMargin(this._footerSizes);
const startMargin = computeMargin(this._startSizes);
const endMargin = computeMargin(this._endSizes);
if (topMargin === 0 && bottomMargin === 0 && startMargin === 0 && endMargin === 0) {
this._clearCss();
return;
}
const direction = this._directionality ? this._directionality.value : 'ltr';
const leftMargin = direction === 'rtl' ? endMargin : startMargin;
const rightMargin = direction === 'rtl' ? startMargin : endMargin;
this._applyCss(`${topMargin}px ${rightMargin}px ${bottomMargin}px ${leftMargin}px`);
}
/** Gets the stylesheet for the scrollbar styles and creates it if need be. */
private _getStyleSheet(): CSSStyleSheet {
if (!this._styleElement) {
this._styleElement = this._document.createElement('style');
if (this._nonce) {
this._styleElement.setAttribute('nonce', this._nonce);
}
this._styleRoot.appendChild(this._styleElement);
}
return this._styleElement.sheet as CSSStyleSheet;
}
/** Updates the stylesheet with the specified scrollbar style. */
private _applyCss(value: string) {
this._clearCss();
const selector = `.${this._uniqueClassName}::-webkit-scrollbar-track`;
this._getStyleSheet().insertRule(`${selector} {margin: ${value}}`, 0);
}
private _clearCss() {
const styleSheet = this._getStyleSheet();
if (styleSheet.cssRules.length > 0) {
styleSheet.deleteRule(0);
}
}
}
function computeMargin(sizes: (number | null | undefined)[]): number {
let margin = 0;
for (const size of sizes) {
if (size == null) {
break;
}
margin += size;
}
return margin;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 4780,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/table-scroll-container/table-scroll-container.ts"
}
|
components/src/cdk-experimental/table-scroll-container/table-scroll-container-module.ts_0_449
|
/**
* @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 {CdkTableScrollContainer} from './table-scroll-container';
@NgModule({
imports: [CdkTableScrollContainer],
exports: [CdkTableScrollContainer],
})
export class CdkTableScrollContainerModule {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 449,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/table-scroll-container/table-scroll-container-module.ts"
}
|
components/src/cdk-experimental/table-scroll-container/BUILD.bazel_0_868
|
load(
"//tools:defaults.bzl",
"ng_module",
"ng_test_library",
"ng_web_test_suite",
)
package(default_visibility = ["//visibility:public"])
ng_module(
name = "table-scroll-container",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
deps = [
"//src/cdk/bidi",
"//src/cdk/platform",
"//src/cdk/table",
"@npm//@angular/common",
"@npm//@angular/core",
"@npm//rxjs",
],
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":table-scroll-container",
"//src/cdk/collections",
"//src/cdk/platform",
"//src/cdk/table",
"@npm//rxjs",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 868,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/table-scroll-container/BUILD.bazel"
}
|
components/src/cdk-experimental/table-scroll-container/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';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/table-scroll-container/index.ts"
}
|
components/src/cdk-experimental/combobox/public-api.ts_0_301
|
/**
* @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 './combobox-module';
export * from './combobox';
export * from './combobox-popup';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 301,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/combobox/public-api.ts"
}
|
components/src/cdk-experimental/combobox/combobox-module.ts_0_588
|
/**
* @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 {OverlayModule} from '@angular/cdk/overlay';
import {CdkCombobox} from './combobox';
import {CdkComboboxPopup} from './combobox-popup';
const EXPORTED_DECLARATIONS = [CdkCombobox, CdkComboboxPopup];
@NgModule({
imports: [OverlayModule, ...EXPORTED_DECLARATIONS],
exports: EXPORTED_DECLARATIONS,
})
export class CdkComboboxModule {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 588,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/combobox/combobox-module.ts"
}
|
components/src/cdk-experimental/combobox/BUILD.bazel_0_796
|
load("//tools:defaults.bzl", "ng_module", "ng_test_library", "ng_web_test_suite")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "combobox",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
deps = [
"//src:dev_mode_types",
"//src/cdk/a11y",
"//src/cdk/bidi",
"//src/cdk/collections",
"//src/cdk/overlay",
],
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":combobox",
"//src/cdk/keycodes",
"//src/cdk/testing/private",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 796,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/combobox/BUILD.bazel"
}
|
components/src/cdk-experimental/combobox/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';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/combobox/index.ts"
}
|
components/src/cdk-experimental/combobox/combobox.spec.ts_0_8525
|
import {CdkComboboxPopup} from '@angular/cdk-experimental/combobox/combobox-popup';
import {DOWN_ARROW, ESCAPE} from '@angular/cdk/keycodes';
import {dispatchKeyboardEvent, dispatchMouseEvent} from '@angular/cdk/testing/private';
import {Component, DebugElement, ElementRef, ViewChild, signal} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {CdkCombobox} from './combobox';
import {CdkComboboxModule} from './combobox-module';
describe('Combobox', () => {
describe('with a basic toggle trigger', () => {
let fixture: ComponentFixture<ComboboxToggle>;
let testComponent: ComboboxToggle;
let combobox: DebugElement;
let comboboxInstance: CdkCombobox;
let comboboxElement: HTMLElement;
let dialog: DebugElement;
let dialogInstance: CdkComboboxPopup;
let dialogElement: HTMLElement;
let applyButton: DebugElement;
let applyButtonElement: HTMLElement;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [CdkComboboxModule, ComboboxToggle],
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(ComboboxToggle);
fixture.detectChanges();
testComponent = fixture.debugElement.componentInstance;
combobox = fixture.debugElement.query(By.directive(CdkCombobox));
comboboxInstance = combobox.injector.get<CdkCombobox>(CdkCombobox);
comboboxElement = combobox.nativeElement;
});
it('should have the combobox role', () => {
expect(comboboxElement.getAttribute('role')).toBe('combobox');
});
it('should update the aria disabled attribute', () => {
comboboxInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(comboboxElement.getAttribute('aria-disabled')).toBe('true');
comboboxInstance.disabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(comboboxElement.getAttribute('aria-disabled')).toBe('false');
});
it('should have aria-owns and aria-haspopup attributes', () => {
dispatchMouseEvent(comboboxElement, 'click');
fixture.detectChanges();
dialog = fixture.debugElement.query(By.directive(CdkComboboxPopup));
dialogInstance = dialog.injector.get<CdkComboboxPopup>(CdkComboboxPopup);
expect(comboboxElement.getAttribute('aria-owns')).toBe(dialogInstance.id);
expect(comboboxElement.getAttribute('aria-haspopup')).toBe('dialog');
});
it('should update aria-expanded attribute upon toggle of panel', () => {
expect(comboboxElement.getAttribute('aria-expanded')).toBe('false');
dispatchMouseEvent(comboboxElement, 'click');
fixture.detectChanges();
expect(comboboxElement.getAttribute('aria-expanded')).toBe('true');
comboboxInstance.close();
fixture.detectChanges();
expect(comboboxElement.getAttribute('aria-expanded')).toBe('false');
});
it('should toggle focus upon toggling the panel', () => {
comboboxElement.focus();
testComponent.actions.set('toggle');
fixture.detectChanges();
expect(document.activeElement).toEqual(comboboxElement);
dispatchMouseEvent(comboboxElement, 'click');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeTrue();
dialog = fixture.debugElement.query(By.directive(CdkComboboxPopup));
dialogElement = dialog.nativeElement;
expect(document.activeElement).toBe(dialogElement);
dispatchMouseEvent(comboboxElement, 'click');
fixture.detectChanges();
expect(document.activeElement).not.toEqual(dialogElement);
});
it('should have a panel that is closed by default', () => {
expect(comboboxInstance.hasPanel()).toBeTrue();
expect(comboboxInstance.isOpen()).toBeFalse();
});
it('should have an open action of click by default', () => {
expect(comboboxInstance.isOpen()).toBeFalse();
dispatchMouseEvent(comboboxElement, 'click');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeTrue();
});
it('should not open panel when disabled', () => {
expect(comboboxInstance.isOpen()).toBeFalse();
comboboxInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(comboboxElement, 'click');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeFalse();
});
it('should update textContent on close of panel', () => {
expect(comboboxInstance.isOpen()).toBeFalse();
dispatchMouseEvent(comboboxElement, 'click');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeTrue();
testComponent.inputElement.nativeElement.value = 'testing input';
fixture.detectChanges();
applyButton = fixture.debugElement.query(By.css('#applyButton'));
applyButtonElement = applyButton.nativeElement;
dispatchMouseEvent(applyButtonElement, 'click');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeFalse();
expect(comboboxElement.textContent).toEqual('testing input');
});
it('should close panel on outside click', () => {
expect(comboboxInstance.isOpen()).toBeFalse();
dispatchMouseEvent(comboboxElement, 'click');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeTrue();
const otherDiv = fixture.debugElement.query(By.css('#other-content'));
const otherDivElement = otherDiv.nativeElement;
dispatchMouseEvent(otherDivElement, 'click');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeFalse();
});
it('should clean up the overlay on destroy', () => {
expect(document.querySelectorAll('.cdk-overlay-pane').length).toBe(0);
dispatchMouseEvent(comboboxElement, 'click');
fixture.detectChanges();
expect(document.querySelectorAll('.cdk-overlay-pane').length).toBe(1);
fixture.destroy();
expect(document.querySelectorAll('.cdk-overlay-pane').length).toBe(0);
});
});
describe('with a coerce open action property function', () => {
let fixture: ComponentFixture<ComboboxToggle>;
let testComponent: ComboboxToggle;
let combobox: DebugElement;
let comboboxInstance: CdkCombobox;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [CdkComboboxModule, ComboboxToggle],
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(ComboboxToggle);
fixture.detectChanges();
testComponent = fixture.debugElement.componentInstance;
combobox = fixture.debugElement.query(By.directive(CdkCombobox));
comboboxInstance = combobox.injector.get<CdkCombobox>(CdkCombobox);
});
it('should coerce single string into open action', () => {
const openActions = comboboxInstance.openActions;
expect(openActions.length).toBe(1);
expect(openActions[0]).toBe('click');
});
it('should coerce actions separated by space', () => {
testComponent.actions.set('focus click');
fixture.detectChanges();
const openActions = comboboxInstance.openActions;
expect(openActions.length).toBe(2);
expect(openActions[0]).toBe('focus');
expect(openActions[1]).toBe('click');
});
it('should coerce actions separated by comma', () => {
testComponent.actions.set('focus,click,downKey');
fixture.detectChanges();
const openActions = comboboxInstance.openActions;
expect(openActions.length).toBe(3);
expect(openActions[0]).toBe('focus');
expect(openActions[1]).toBe('click');
expect(openActions[2]).toBe('downKey');
});
it('should coerce actions separated by commas and spaces', () => {
testComponent.actions.set('focus click,downKey');
fixture.detectChanges();
const openActions = comboboxInstance.openActions;
expect(openActions.length).toBe(3);
expect(openActions[0]).toBe('focus');
expect(openActions[1]).toBe('click');
expect(openActions[2]).toBe('downKey');
});
it('should throw error when given invalid open action', () => {
expect(() => {
testComponent.actions.set('invalidAction');
fixture.detectChanges();
}).toThrowError('invalidAction is not a support open action for CdkCombobox');
});
});
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 8525,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/combobox/combobox.spec.ts"
}
|
components/src/cdk-experimental/combobox/combobox.spec.ts_8529_12523
|
describe('with various open actions', () => {
let fixture: ComponentFixture<ComboboxToggle>;
let testComponent: ComboboxToggle;
let combobox: DebugElement;
let comboboxInstance: CdkCombobox;
let comboboxElement: HTMLElement;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [CdkComboboxModule, ComboboxToggle],
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(ComboboxToggle);
fixture.detectChanges();
testComponent = fixture.debugElement.componentInstance;
combobox = fixture.debugElement.query(By.directive(CdkCombobox));
comboboxInstance = combobox.injector.get<CdkCombobox>(CdkCombobox);
comboboxElement = combobox.nativeElement;
});
it('should open panel with focus open action', () => {
testComponent.actions.set('focus');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeFalse();
comboboxElement.focus();
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeTrue();
});
it('should open panel with click open action', () => {
testComponent.actions.set('click');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeFalse();
dispatchMouseEvent(comboboxElement, 'click');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeTrue();
});
it('should open panel with downKey open action', () => {
testComponent.actions.set('downKey');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeFalse();
dispatchKeyboardEvent(comboboxElement, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeTrue();
});
it('should toggle panel with toggle open action', () => {
testComponent.actions.set('toggle');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeFalse();
dispatchMouseEvent(comboboxElement, 'click');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeTrue();
dispatchMouseEvent(comboboxElement, 'click');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeFalse();
});
it('should close panel on escape key', () => {
testComponent.actions.set('click');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeFalse();
dispatchMouseEvent(comboboxElement, 'click');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeTrue();
dispatchKeyboardEvent(comboboxElement, 'keydown', ESCAPE);
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeFalse();
});
it('should handle multiple open actions', () => {
testComponent.actions.set('click downKey');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeFalse();
dispatchMouseEvent(comboboxElement, 'click');
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeTrue();
dispatchKeyboardEvent(comboboxElement, 'keydown', ESCAPE);
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeFalse();
dispatchKeyboardEvent(comboboxElement, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(comboboxInstance.isOpen()).toBeTrue();
});
});
});
@Component({
template: `
<button cdkCombobox #toggleCombobox="cdkCombobox" class="example-combobox"
[cdkComboboxTriggerFor]="panel"
[openActions]="actions()">
No Value
</button>
<div id="other-content"></div>
<ng-template #panel>
<div #dialog cdkComboboxPopup>
<input #input>
<button id="applyButton" (click)="toggleCombobox.updateAndClose(input.value)">Apply</button>
</div>
</ng-template>`,
standalone: true,
imports: [CdkComboboxModule],
})
class ComboboxToggle {
@ViewChild('input') inputElement: ElementRef<HTMLInputElement>;
actions = signal('click');
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 12523,
"start_byte": 8529,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/combobox/combobox.spec.ts"
}
|
components/src/cdk-experimental/combobox/combobox-popup.ts_0_1569
|
/**
* @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, OnInit, inject} from '@angular/core';
import {AriaHasPopupValue, CDK_COMBOBOX, CdkCombobox} from './combobox';
let nextId = 0;
@Directive({
selector: '[cdkComboboxPopup]',
exportAs: 'cdkComboboxPopup',
host: {
'class': 'cdk-combobox-popup',
'[attr.role]': 'role',
'[id]': 'id',
'tabindex': '-1',
'(focus)': 'focusFirstElement()',
},
})
export class CdkComboboxPopup<T = unknown> implements OnInit {
private readonly _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly _combobox = inject<CdkCombobox>(CDK_COMBOBOX);
@Input()
get role(): AriaHasPopupValue {
return this._role;
}
set role(value: AriaHasPopupValue) {
this._role = value;
}
private _role: AriaHasPopupValue = 'dialog';
@Input()
get firstFocus(): HTMLElement {
return this._firstFocusElement;
}
set firstFocus(id: HTMLElement) {
this._firstFocusElement = id;
}
private _firstFocusElement: HTMLElement;
@Input() id = `cdk-combobox-popup-${nextId++}`;
ngOnInit() {
this.registerWithPanel();
}
registerWithPanel(): void {
this._combobox._registerContent(this.id, this._role);
}
focusFirstElement() {
if (this._firstFocusElement) {
this._firstFocusElement.focus();
} else {
this._elementRef.nativeElement.focus();
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1569,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/combobox/combobox-popup.ts"
}
|
components/src/cdk-experimental/combobox/combobox.ts_0_1898
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Directionality} from '@angular/cdk/bidi';
import {BooleanInput, coerceArray, coerceBooleanProperty} from '@angular/cdk/coercion';
import {DOWN_ARROW, ENTER, ESCAPE, TAB} from '@angular/cdk/keycodes';
import {
ConnectedPosition,
FlexibleConnectedPositionStrategy,
Overlay,
OverlayConfig,
OverlayRef,
} from '@angular/cdk/overlay';
import {_getEventTarget} from '@angular/cdk/platform';
import {TemplatePortal} from '@angular/cdk/portal';
import {DOCUMENT} from '@angular/common';
import {
ChangeDetectorRef,
Directive,
ElementRef,
EventEmitter,
InjectionToken,
Injector,
Input,
OnDestroy,
Output,
TemplateRef,
ViewContainerRef,
inject,
} from '@angular/core';
export type AriaHasPopupValue = 'false' | 'true' | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog';
export type OpenAction = 'focus' | 'click' | 'downKey' | 'toggle';
export type OpenActionInput = OpenAction | OpenAction[] | string | null | undefined;
const allowedOpenActions = ['focus', 'click', 'downKey', 'toggle'];
export const CDK_COMBOBOX = new InjectionToken<CdkCombobox>('CDK_COMBOBOX');
@Directive({
selector: '[cdkCombobox]',
exportAs: 'cdkCombobox',
host: {
'role': 'combobox',
'class': 'cdk-combobox',
'(click)': '_handleInteractions("click")',
'(focus)': '_handleInteractions("focus")',
'(keydown)': '_keydown($event)',
'(document:click)': '_attemptClose($event)',
'[attr.aria-disabled]': 'disabled',
'[attr.aria-owns]': 'contentId',
'[attr.aria-haspopup]': 'contentType',
'[attr.aria-expanded]': 'isOpen()',
'[attr.tabindex]': '_getTabIndex()',
},
providers: [{provide: CDK_COMBOBOX, useExisting: CdkCombobox}],
})
export
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1898,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/combobox/combobox.ts"
}
|
components/src/cdk-experimental/combobox/combobox.ts_1899_9726
|
class CdkCombobox<T = unknown> implements OnDestroy {
private readonly _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly _overlay = inject(Overlay);
protected readonly _viewContainerRef = inject(ViewContainerRef);
private readonly _injector = inject(Injector);
private readonly _doc = inject(DOCUMENT);
private readonly _directionality = inject(Directionality, {optional: true});
private _changeDetectorRef = inject(ChangeDetectorRef);
private _overlayRef: OverlayRef;
private _panelPortal: TemplatePortal;
@Input('cdkComboboxTriggerFor')
_panelTemplateRef: TemplateRef<unknown>;
@Input()
value: T | T[];
@Input()
get disabled(): boolean {
return this._disabled;
}
set disabled(value: BooleanInput) {
this._disabled = coerceBooleanProperty(value);
}
private _disabled: boolean = false;
@Input()
get openActions(): OpenAction[] {
return this._openActions;
}
set openActions(action: OpenActionInput) {
this._openActions = this._coerceOpenActionProperty(action);
}
private _openActions: OpenAction[] = ['click'];
/** Whether the textContent is automatically updated upon change of the combobox value. */
@Input()
get autoSetText(): boolean {
return this._autoSetText;
}
set autoSetText(value: BooleanInput) {
this._autoSetText = coerceBooleanProperty(value);
}
private _autoSetText: boolean = true;
@Output('comboboxPanelOpened') readonly opened: EventEmitter<void> = new EventEmitter<void>();
@Output('comboboxPanelClosed') readonly closed: EventEmitter<void> = new EventEmitter<void>();
@Output('panelValueChanged') readonly panelValueChanged: EventEmitter<T[]> = new EventEmitter<
T[]
>();
contentId: string = '';
contentType: AriaHasPopupValue;
ngOnDestroy() {
if (this._overlayRef) {
this._overlayRef.dispose();
}
this.opened.complete();
this.closed.complete();
this.panelValueChanged.complete();
}
_keydown(event: KeyboardEvent) {
const {keyCode} = event;
if (keyCode === DOWN_ARROW) {
if (this.isOpen()) {
// TODO: instead of using a focus function, potentially use cdk/a11y focus trapping
this._doc.getElementById(this.contentId)?.focus();
} else if (this._openActions.indexOf('downKey') !== -1) {
this.open();
}
} else if (keyCode === ENTER) {
if (this._openActions.indexOf('toggle') !== -1) {
this.toggle();
} else if (this._openActions.indexOf('click') !== -1) {
this.open();
}
} else if (keyCode === ESCAPE) {
event.preventDefault();
this.close();
} else if (keyCode === TAB) {
this.close();
}
}
/** Handles click or focus interactions. */
_handleInteractions(interaction: OpenAction) {
if (interaction === 'click') {
if (this._openActions.indexOf('toggle') !== -1) {
this.toggle();
} else if (this._openActions.indexOf('click') !== -1) {
this.open();
}
} else if (interaction === 'focus') {
if (this._openActions.indexOf('focus') !== -1) {
this.open();
}
}
}
/** Given a click in the document, determines if the click was inside a combobox. */
_attemptClose(event: MouseEvent) {
if (this.isOpen()) {
let target = _getEventTarget(event);
while (target instanceof Element) {
if (target.className.indexOf('cdk-combobox') !== -1) {
return;
}
target = target.parentElement;
}
}
this.close();
}
/** Toggles the open state of the panel. */
toggle() {
if (this.hasPanel()) {
this.isOpen() ? this.close() : this.open();
}
}
/** If the combobox is closed and not disabled, opens the panel. */
open() {
if (!this.isOpen() && !this.disabled) {
this.opened.next();
this._overlayRef = this._overlayRef || this._overlay.create(this._getOverlayConfig());
this._overlayRef.attach(this._getPanelContent());
this._changeDetectorRef.markForCheck();
if (!this._isTextTrigger()) {
// TODO: instead of using a focus function, potentially use cdk/a11y focus trapping
this._doc.getElementById(this.contentId)?.focus();
}
}
}
/** If the combobox is open and not disabled, closes the panel. */
close() {
if (this.isOpen() && !this.disabled) {
this.closed.next();
this._overlayRef.detach();
this._changeDetectorRef.markForCheck();
}
}
/** Returns true if panel is currently opened. */
isOpen(): boolean {
return this._overlayRef ? this._overlayRef.hasAttached() : false;
}
/** Returns true if combobox has a child panel. */
hasPanel(): boolean {
return !!this._panelTemplateRef;
}
_getTabIndex(): string | null {
return this.disabled ? null : '0';
}
private _setComboboxValue(value: T | T[]) {
const valueChanged = this.value !== value;
this.value = value;
if (valueChanged) {
this.panelValueChanged.emit(coerceArray(value));
if (this._autoSetText) {
this._setTextContent(value);
}
}
}
updateAndClose(value: T | T[]) {
this._setComboboxValue(value);
this.close();
}
private _setTextContent(content: T | T[]) {
const contentArray = coerceArray(content);
this._elementRef.nativeElement.textContent = contentArray.join(' ');
}
private _isTextTrigger() {
// TODO: Should check if the trigger is contenteditable.
const tagName = this._elementRef.nativeElement.tagName.toLowerCase();
return tagName === 'input' || tagName === 'textarea' ? true : false;
}
private _getOverlayConfig() {
return new OverlayConfig({
positionStrategy: this._getOverlayPositionStrategy(),
scrollStrategy: this._overlay.scrollStrategies.block(),
direction: this._directionality || undefined,
});
}
private _getOverlayPositionStrategy(): FlexibleConnectedPositionStrategy {
return this._overlay
.position()
.flexibleConnectedTo(this._elementRef)
.withPositions(this._getOverlayPositions());
}
private _getOverlayPositions(): ConnectedPosition[] {
return [
{originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top'},
{originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom'},
{originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top'},
{originX: 'end', originY: 'top', overlayX: 'end', overlayY: 'bottom'},
];
}
private _getPanelInjector() {
return this._injector;
}
private _getPanelContent() {
const hasPanelChanged = this._panelTemplateRef !== this._panelPortal?.templateRef;
if (this._panelTemplateRef && (!this._panelPortal || hasPanelChanged)) {
this._panelPortal = new TemplatePortal(
this._panelTemplateRef,
this._viewContainerRef,
undefined,
this._getPanelInjector(),
);
}
return this._panelPortal;
}
private _coerceOpenActionProperty(input: OpenActionInput): OpenAction[] {
let actions = typeof input === 'string' ? input.trim().split(/[ ,]+/) : input;
if (
(typeof ngDevMode === 'undefined' || ngDevMode) &&
actions?.some(a => allowedOpenActions.indexOf(a) === -1)
) {
throw Error(`${input} is not a support open action for CdkCombobox`);
}
return actions as OpenAction[];
}
/** Registers the content's id and the content type with the panel. */
_registerContent(contentId: string, contentType: AriaHasPopupValue) {
if (
(typeof ngDevMode === 'undefined' || ngDevMode) &&
contentType !== 'listbox' &&
contentType !== 'dialog'
) {
throw Error('CdkComboboxPanel currently only supports listbox or dialog content.');
}
this.contentId = contentId;
this.contentType = contentType;
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 9726,
"start_byte": 1899,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/combobox/combobox.ts"
}
|
components/src/cdk-experimental/column-resize/resize-strategy.ts_0_8913
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Injectable, OnDestroy, Provider, CSP_NONCE, inject} from '@angular/core';
import {DOCUMENT} from '@angular/common';
import {coerceCssPixelValue} from '@angular/cdk/coercion';
import {CdkTable, _CoalescedStyleScheduler, _COALESCED_STYLE_SCHEDULER} from '@angular/cdk/table';
import {ColumnResize} from './column-resize';
/**
* Provides an implementation for resizing a column.
* The details of how resizing works for tables for flex mat-tables are quite different.
*/
@Injectable()
export abstract class ResizeStrategy {
protected abstract readonly columnResize: ColumnResize;
protected abstract readonly styleScheduler: _CoalescedStyleScheduler;
protected abstract readonly table: CdkTable<unknown>;
private _pendingResizeDelta: number | null = null;
/** Updates the width of the specified column. */
abstract applyColumnSize(
cssFriendlyColumnName: string,
columnHeader: HTMLElement,
sizeInPx: number,
previousSizeInPx?: number,
): void;
/** Applies a minimum width to the specified column, updating its current width as needed. */
abstract applyMinColumnSize(
cssFriendlyColumnName: string,
columnHeader: HTMLElement,
minSizeInPx: number,
): void;
/** Applies a maximum width to the specified column, updating its current width as needed. */
abstract applyMaxColumnSize(
cssFriendlyColumnName: string,
columnHeader: HTMLElement,
minSizeInPx: number,
): void;
/** Adjusts the width of the table element by the specified delta. */
protected updateTableWidthAndStickyColumns(delta: number): void {
if (this._pendingResizeDelta === null) {
const tableElement = this.columnResize.elementRef.nativeElement;
const tableWidth = getElementWidth(tableElement);
this.styleScheduler.schedule(() => {
tableElement.style.width = coerceCssPixelValue(tableWidth + this._pendingResizeDelta!);
this._pendingResizeDelta = null;
});
this.styleScheduler.scheduleEnd(() => {
this.table.updateStickyColumnStyles();
});
}
this._pendingResizeDelta = (this._pendingResizeDelta ?? 0) + delta;
}
}
/**
* The optimally performing resize strategy for <table> elements with table-layout: fixed.
* Tested against and outperformed:
* CSS selector
* CSS selector w/ CSS variable
* Updating all cell nodes
*/
@Injectable()
export class TableLayoutFixedResizeStrategy extends ResizeStrategy {
protected readonly columnResize = inject(ColumnResize);
protected readonly styleScheduler = inject<_CoalescedStyleScheduler>(_COALESCED_STYLE_SCHEDULER);
protected readonly table = inject<CdkTable<unknown>>(CdkTable);
applyColumnSize(
_: string,
columnHeader: HTMLElement,
sizeInPx: number,
previousSizeInPx?: number,
): void {
const delta = sizeInPx - (previousSizeInPx ?? getElementWidth(columnHeader));
if (delta === 0) {
return;
}
this.styleScheduler.schedule(() => {
columnHeader.style.width = coerceCssPixelValue(sizeInPx);
});
this.updateTableWidthAndStickyColumns(delta);
}
applyMinColumnSize(_: string, columnHeader: HTMLElement, sizeInPx: number): void {
const currentWidth = getElementWidth(columnHeader);
const newWidth = Math.max(currentWidth, sizeInPx);
this.applyColumnSize(_, columnHeader, newWidth, currentWidth);
}
applyMaxColumnSize(_: string, columnHeader: HTMLElement, sizeInPx: number): void {
const currentWidth = getElementWidth(columnHeader);
const newWidth = Math.min(currentWidth, sizeInPx);
this.applyColumnSize(_, columnHeader, newWidth, currentWidth);
}
}
/**
* The optimally performing resize strategy for flex mat-tables.
* Tested against and outperformed:
* CSS selector w/ CSS variable
* Updating all mat-cell nodes
*/
@Injectable()
export class CdkFlexTableResizeStrategy extends ResizeStrategy implements OnDestroy {
protected readonly columnResize = inject(ColumnResize);
protected readonly styleScheduler = inject<_CoalescedStyleScheduler>(_COALESCED_STYLE_SCHEDULER);
protected readonly table = inject<CdkTable<unknown>>(CdkTable);
private readonly _nonce = inject(CSP_NONCE, {optional: true});
private readonly _document = inject(DOCUMENT);
private readonly _columnIndexes = new Map<string, number>();
private readonly _columnProperties = new Map<string, Map<string, string>>();
private _styleElement?: HTMLStyleElement;
private _indexSequence = 0;
protected readonly defaultMinSize = 0;
protected readonly defaultMaxSize = Number.MAX_SAFE_INTEGER;
applyColumnSize(
cssFriendlyColumnName: string,
columnHeader: HTMLElement,
sizeInPx: number,
previousSizeInPx?: number,
): void {
// Optimization: Check applied width first as we probably set it already before reading
// offsetWidth which triggers layout.
const delta =
sizeInPx -
(previousSizeInPx ??
(this._getAppliedWidth(cssFriendlyColumnName) || columnHeader.offsetWidth));
if (delta === 0) {
return;
}
const cssSize = coerceCssPixelValue(sizeInPx);
this._applyProperty(cssFriendlyColumnName, 'flex', `0 0.01 ${cssSize}`);
this.updateTableWidthAndStickyColumns(delta);
}
applyMinColumnSize(cssFriendlyColumnName: string, _: HTMLElement, sizeInPx: number): void {
const cssSize = coerceCssPixelValue(sizeInPx);
this._applyProperty(
cssFriendlyColumnName,
'min-width',
cssSize,
sizeInPx !== this.defaultMinSize,
);
this.updateTableWidthAndStickyColumns(0);
}
applyMaxColumnSize(cssFriendlyColumnName: string, _: HTMLElement, sizeInPx: number): void {
const cssSize = coerceCssPixelValue(sizeInPx);
this._applyProperty(
cssFriendlyColumnName,
'max-width',
cssSize,
sizeInPx !== this.defaultMaxSize,
);
this.updateTableWidthAndStickyColumns(0);
}
protected getColumnCssClass(cssFriendlyColumnName: string): string {
return `cdk-column-${cssFriendlyColumnName}`;
}
ngOnDestroy(): void {
this._styleElement?.remove();
this._styleElement = undefined;
}
private _getPropertyValue(cssFriendlyColumnName: string, key: string): string | undefined {
const properties = this._getColumnPropertiesMap(cssFriendlyColumnName);
return properties.get(key);
}
private _getAppliedWidth(cssFriendslyColumnName: string): number {
return coercePixelsFromFlexValue(this._getPropertyValue(cssFriendslyColumnName, 'flex'));
}
private _applyProperty(
cssFriendlyColumnName: string,
key: string,
value: string,
enable = true,
): void {
const properties = this._getColumnPropertiesMap(cssFriendlyColumnName);
this.styleScheduler.schedule(() => {
if (enable) {
properties.set(key, value);
} else {
properties.delete(key);
}
this._applySizeCss(cssFriendlyColumnName);
});
}
private _getStyleSheet(): CSSStyleSheet {
if (!this._styleElement) {
this._styleElement = this._document.createElement('style');
if (this._nonce) {
this._styleElement.setAttribute('nonce', this._nonce);
}
this._styleElement.appendChild(this._document.createTextNode(''));
this._document.head.appendChild(this._styleElement);
}
return this._styleElement.sheet as CSSStyleSheet;
}
private _getColumnPropertiesMap(cssFriendlyColumnName: string): Map<string, string> {
let properties = this._columnProperties.get(cssFriendlyColumnName);
if (properties === undefined) {
properties = new Map<string, string>();
this._columnProperties.set(cssFriendlyColumnName, properties);
}
return properties;
}
private _applySizeCss(cssFriendlyColumnName: string) {
const properties = this._getColumnPropertiesMap(cssFriendlyColumnName);
const propertyKeys = Array.from(properties.keys());
let index = this._columnIndexes.get(cssFriendlyColumnName);
if (index === undefined) {
if (!propertyKeys.length) {
// Nothing to set or unset.
return;
}
index = this._indexSequence++;
this._columnIndexes.set(cssFriendlyColumnName, index);
} else {
this._getStyleSheet().deleteRule(index);
}
const columnClassName = this.getColumnCssClass(cssFriendlyColumnName);
const tableClassName = this.columnResize.getUniqueCssClass();
const selector = `.${tableClassName} .${columnClassName}`;
const body = propertyKeys.map(key => `${key}:${properties.get(key)}`).join(';');
this._getStyleSheet().insertRule(`${selector} {${body}}`, index!);
}
}
/** Converts CSS pixel values to numbers, eg "123px" to 123. Returns NaN for non pixel values. */
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 8913,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/resize-strategy.ts"
}
|
components/src/cdk-experimental/column-resize/resize-strategy.ts_8914_9909
|
function coercePixelsFromCssValue(cssValue: string): number {
return Number(cssValue.match(/(\d+)px/)?.[1]);
}
/** Gets the style.width pixels on the specified element if present, otherwise its offsetWidth. */
function getElementWidth(element: HTMLElement) {
// Optimization: Check style.width first as we probably set it already before reading
// offsetWidth which triggers layout.
return coercePixelsFromCssValue(element.style.width) || element.offsetWidth;
}
/**
* Converts CSS flex values as set in CdkFlexTableResizeStrategy to numbers,
* eg "0 0.01 123px" to 123.
*/
function coercePixelsFromFlexValue(flexValue: string | undefined): number {
return Number(flexValue?.match(/0 0\.01 (\d+)px/)?.[1]);
}
export const TABLE_LAYOUT_FIXED_RESIZE_STRATEGY_PROVIDER: Provider = {
provide: ResizeStrategy,
useClass: TableLayoutFixedResizeStrategy,
};
export const FLEX_RESIZE_STRATEGY_PROVIDER: Provider = {
provide: ResizeStrategy,
useClass: CdkFlexTableResizeStrategy,
};
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 9909,
"start_byte": 8914,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/resize-strategy.ts"
}
|
components/src/cdk-experimental/column-resize/column-resize.ts_0_4016
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {AfterViewInit, Directive, ElementRef, NgZone, OnDestroy} from '@angular/core';
import {fromEvent, merge, Subject} from 'rxjs';
import {filter, map, mapTo, pairwise, startWith, take, takeUntil} from 'rxjs/operators';
import {_closest} from '@angular/cdk-experimental/popover-edit';
import {ColumnResizeNotifier, ColumnResizeNotifierSource} from './column-resize-notifier';
import {HEADER_CELL_SELECTOR, RESIZE_OVERLAY_SELECTOR} from './selectors';
import {HeaderRowEventDispatcher} from './event-dispatcher';
const HOVER_OR_ACTIVE_CLASS = 'cdk-column-resize-hover-or-active';
const WITH_RESIZED_COLUMN_CLASS = 'cdk-column-resize-with-resized-column';
let nextId = 0;
/**
* Base class for ColumnResize directives which attach to mat-table elements to
* provide common events and services for column resizing.
*/
@Directive()
export abstract class ColumnResize implements AfterViewInit, OnDestroy {
protected readonly destroyed = new Subject<void>();
/* Publicly accessible interface for triggering and being notified of resizes. */
abstract readonly columnResizeNotifier: ColumnResizeNotifier;
/* ElementRef that this directive is attached to. Exposed For use by column-level directives */
abstract readonly elementRef: ElementRef<HTMLElement>;
protected abstract readonly eventDispatcher: HeaderRowEventDispatcher;
protected abstract readonly ngZone: NgZone;
protected abstract readonly notifier: ColumnResizeNotifierSource;
/** Unique ID for this table instance. */
protected readonly selectorId = `${++nextId}`;
/** The id attribute of the table, if specified. */
id?: string;
ngAfterViewInit() {
this.elementRef.nativeElement!.classList.add(this.getUniqueCssClass());
this._listenForRowHoverEvents();
this._listenForResizeActivity();
this._listenForHoverActivity();
}
ngOnDestroy() {
this.destroyed.next();
this.destroyed.complete();
}
/** Gets the unique CSS class name for this table instance. */
getUniqueCssClass() {
return `cdk-column-resize-${this.selectorId}`;
}
/** Called when a column in the table is resized. Applies a css class to the table element. */
setResized() {
this.elementRef.nativeElement!.classList.add(WITH_RESIZED_COLUMN_CLASS);
}
private _listenForRowHoverEvents() {
this.ngZone.runOutsideAngular(() => {
const element = this.elementRef.nativeElement!;
fromEvent<MouseEvent>(element, 'mouseover')
.pipe(
map(event => _closest(event.target, HEADER_CELL_SELECTOR)),
takeUntil(this.destroyed),
)
.subscribe(this.eventDispatcher.headerCellHovered);
fromEvent<MouseEvent>(element, 'mouseleave')
.pipe(
filter(
event =>
!!event.relatedTarget &&
!(event.relatedTarget as Element).matches(RESIZE_OVERLAY_SELECTOR),
),
mapTo(null),
takeUntil(this.destroyed),
)
.subscribe(this.eventDispatcher.headerCellHovered);
});
}
private _listenForResizeActivity() {
merge(
this.eventDispatcher.overlayHandleActiveForCell.pipe(mapTo(undefined)),
this.notifier.triggerResize.pipe(mapTo(undefined)),
this.notifier.resizeCompleted.pipe(mapTo(undefined)),
)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe(() => {
this.setResized();
});
}
private _listenForHoverActivity() {
this.eventDispatcher.headerRowHoveredOrActiveDistinct
.pipe(startWith(null), pairwise(), takeUntil(this.destroyed))
.subscribe(([previousRow, hoveredRow]) => {
if (hoveredRow) {
hoveredRow.classList.add(HOVER_OR_ACTIVE_CLASS);
}
if (previousRow) {
previousRow.classList.remove(HOVER_OR_ACTIVE_CLASS);
}
});
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 4016,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk-experimental/column-resize/column-resize.ts"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.