_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
components/src/material/list/selection-list.spec.ts_20244_29390 | it('should be able to deselect all options, even if they are disabled', () => {
const list: MatSelectionList = selectionList.componentInstance;
list.options.forEach(option => option.toggle());
expect(list.options.toArray().every(option => option.selected)).toBe(true);
list.options.forEach(option => (option.disabled = true));
fixture.detectChanges();
list.deselectAll();
fixture.detectChanges();
expect(list.options.toArray().every(option => option.selected)).toBe(false);
});
it('should update the list value when an item is selected programmatically', () => {
const list: MatSelectionList = selectionList.componentInstance;
expect(list.selectedOptions.isEmpty()).toBe(true);
listOptions[0].componentInstance.selected = true;
listOptions[2].componentInstance.selected = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(list.selectedOptions.isEmpty()).toBe(false);
expect(list.selectedOptions.isSelected(listOptions[0].componentInstance)).toBe(true);
expect(list.selectedOptions.isSelected(listOptions[2].componentInstance)).toBe(true);
});
it('should update the item selected state when it is selected via the model', () => {
const list: MatSelectionList = selectionList.componentInstance;
const item: MatListOption = listOptions[0].componentInstance;
expect(item.selected).toBe(false);
list.selectedOptions.select(item);
fixture.detectChanges();
expect(item.selected).toBe(true);
});
it('should set aria-multiselectable to true on the selection list element', () => {
expect(selectionList.nativeElement.getAttribute('aria-multiselectable')).toBe('true');
});
it('should be able to reach list options that are indirect descendants', () => {
const descendatsFixture = TestBed.createComponent(SelectionListWithIndirectChildOptions);
descendatsFixture.detectChanges();
listOptions = descendatsFixture.debugElement.queryAll(By.directive(MatListOption));
selectionList = descendatsFixture.debugElement.query(By.directive(MatSelectionList))!;
const list: MatSelectionList = selectionList.componentInstance;
expect(list.options.toArray().every(option => option.selected)).toBe(false);
list.selectAll();
descendatsFixture.detectChanges();
expect(list.options.toArray().every(option => option.selected)).toBe(true);
});
it('should disable list item ripples when the ripples on the list have been disabled', fakeAsync(() => {
const rippleTarget = fixture.nativeElement.querySelector(
'.mat-mdc-list-option:not(.mdc-list-item--disabled)',
);
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
// Flush the ripple enter animation.
dispatchFakeEvent(rippleTarget.querySelector('.mat-ripple-element')!, 'transitionend');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected ripples to be enabled by default.')
.toBe(1);
// Flush the ripple exit animation.
dispatchFakeEvent(rippleTarget.querySelector('.mat-ripple-element')!, 'transitionend');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected ripples to go away.')
.toBe(0);
fixture.componentInstance.listRippleDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected no ripples after list ripples are disabled.')
.toBe(0);
}));
it('can bind both selected and value at the same time', () => {
const componentFixture = TestBed.createComponent(SelectionListWithSelectedOptionAndValue);
componentFixture.detectChanges();
const listItemEl = componentFixture.debugElement.query(By.directive(MatListOption))!;
expect(listItemEl.componentInstance.selected).toBe(true);
expect(listItemEl.componentInstance.value).toBe(componentFixture.componentInstance.itemValue);
});
it('should have a focus indicator', () => {
const optionNativeElements = listOptions.map(option => option.nativeElement as HTMLElement);
expect(
optionNativeElements.every(
element => element.querySelector('.mat-focus-indicator') !== null,
),
).toBe(true);
});
it('should hide the internal SVG', () => {
listOptions.forEach(option => {
const svg = option.nativeElement.querySelector('.mdc-checkbox svg');
expect(svg.getAttribute('aria-hidden')).toBe('true');
});
});
});
describe('multiple-selection with list option selected', () => {
let fixture: ComponentFixture<SelectionListWithSelectedOption>;
let listOptionElements: DebugElement[];
let selectionList: DebugElement;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatListModule, SelectionListWithSelectedOption],
});
}));
beforeEach(waitForAsync(() => {
fixture = TestBed.createComponent(SelectionListWithSelectedOption);
listOptionElements = fixture.debugElement.queryAll(By.directive(MatListOption))!;
selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!;
fixture.detectChanges();
}));
it('should set its initial selected state in the selectedOptions', () => {
let options = listOptionElements.map(optionEl =>
optionEl.injector.get<MatListOption>(MatListOption),
);
let selectedOptions = selectionList.componentInstance.selectedOptions;
expect(selectedOptions.isSelected(options[0])).toBeFalse();
expect(selectedOptions.isSelected(options[1])).toBeTrue();
expect(selectedOptions.isSelected(options[2])).toBeTrue();
expect(selectedOptions.isSelected(options[3])).toBeFalse();
});
it('should focus the first selected option on first focus if an item is pre-selected', fakeAsync(() => {
// MDC manages the focus through setting a `tabindex` on the designated list item. We
// assert that the proper tabindex is set on the pre-selected option at index 1, and
// ensure that other options are not reachable through tab.
expect(listOptionElements.map(el => el.nativeElement.tabIndex)).toEqual([-1, 0, -1, -1]);
}));
});
describe('single-selection with list option selected', () => {
let fixture: ComponentFixture<SingleSelectionListWithSelectedOption>;
let listOptionElements: DebugElement[];
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatListModule, SingleSelectionListWithSelectedOption],
});
}));
beforeEach(waitForAsync(() => {
fixture = TestBed.createComponent(SingleSelectionListWithSelectedOption);
listOptionElements = fixture.debugElement.queryAll(By.directive(MatListOption))!;
fixture.detectChanges();
}));
it('displays radio indicators by default', () => {
expect(
listOptionElements[0].nativeElement.querySelector('input[type="radio"]'),
).not.toBeNull();
expect(
listOptionElements[1].nativeElement.querySelector('input[type="radio"]'),
).not.toBeNull();
expect(listOptionElements[0].nativeElement.classList).not.toContain(
'mdc-list-item--selected',
);
expect(listOptionElements[1].nativeElement.classList).not.toContain(
'mdc-list-item--selected',
);
});
});
describe('with token to hide radio indicators', () => {
let fixture: ComponentFixture<SingleSelectionListWithSelectedOption>;
let listOptionElements: DebugElement[];
beforeEach(waitForAsync(() => {
const matListConfig: MatListConfig = {hideSingleSelectionIndicator: true};
TestBed.configureTestingModule({
imports: [MatListModule, SingleSelectionListWithSelectedOption],
providers: [{provide: MAT_LIST_CONFIG, useValue: matListConfig}],
});
}));
beforeEach(waitForAsync(() => {
fixture = TestBed.createComponent(SingleSelectionListWithSelectedOption);
listOptionElements = fixture.debugElement.queryAll(By.directive(MatListOption))!;
fixture.detectChanges();
}));
it('does not display radio indicators', () => {
expect(listOptionElements[0].nativeElement.querySelector('input[type="radio"]')).toBeNull();
expect(listOptionElements[1].nativeElement.querySelector('input[type="radio"]')).toBeNull();
expect(listOptionElements[0].nativeElement.classList).not.toContain(
'mdc-list-item--selected',
);
expect(listOptionElements[1].nativeElement.getAttribute('aria-selected'))
.withContext('Expected second option to be selected')
.toBe('true');
expect(listOptionElements[1].nativeElement.classList).toContain('mdc-list-item--selected');
});
}); | {
"end_byte": 29390,
"start_byte": 20244,
"url": "https://github.com/angular/components/blob/main/src/material/list/selection-list.spec.ts"
} |
components/src/material/list/selection-list.spec.ts_29394_35663 | describe('with option disabled', () => {
let fixture: ComponentFixture<SelectionListWithDisabledOption>;
let listOptionEl: HTMLElement;
let listOption: MatListOption;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatListModule, SelectionListWithDisabledOption],
});
}));
beforeEach(waitForAsync(() => {
fixture = TestBed.createComponent(SelectionListWithDisabledOption);
const listOptionDebug = fixture.debugElement.query(By.directive(MatListOption))!;
listOption = listOptionDebug.componentInstance;
listOptionEl = listOptionDebug.nativeElement;
fixture.detectChanges();
}));
it('should disable ripples for disabled option', () => {
expect(listOption.rippleDisabled)
.withContext('Expected ripples to be enabled by default')
.toBe(false);
fixture.componentInstance.disableItem = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(listOption.rippleDisabled)
.withContext('Expected ripples to be disabled if option is disabled')
.toBe(true);
});
it('should apply the "mat-list-item-disabled" class properly', () => {
expect(listOptionEl.classList).not.toContain('mdc-list-item--disabled');
fixture.componentInstance.disableItem = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(listOptionEl.classList).toContain('mdc-list-item--disabled');
});
});
describe('with list disabled', () => {
let fixture: ComponentFixture<SelectionListWithListDisabled>;
let listOption: DebugElement[];
let selectionList: DebugElement;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
MatListModule,
SelectionListWithListOptions,
SelectionListWithCheckboxPositionAfter,
SelectionListWithListDisabled,
SelectionListWithOnlyOneOption,
],
});
}));
beforeEach(waitForAsync(() => {
fixture = TestBed.createComponent(SelectionListWithListDisabled);
listOption = fixture.debugElement.queryAll(By.directive(MatListOption));
selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!;
fixture.detectChanges();
}));
it('should not allow selection on disabled selection-list', () => {
let testListItem = listOption[2].injector.get<MatListOption>(MatListOption);
let selectList =
selectionList.injector.get<MatSelectionList>(MatSelectionList).selectedOptions;
expect(selectList.selected.length).toBe(0);
dispatchMouseEvent(testListItem._hostElement, 'click');
fixture.detectChanges();
expect(selectList.selected.length).toBe(0);
});
it('should update state of options if list state has changed', () => {
const testOption = listOption[2].componentInstance as MatListOption;
expect(testOption.rippleDisabled)
.withContext('Expected ripples of list option to be disabled')
.toBe(true);
fixture.componentInstance.disabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(testOption.rippleDisabled)
.withContext('Expected ripples of list option to be enabled')
.toBe(false);
});
// when the entire list is disabled, its listitems should always have tabindex="-1"
it('should remove all listitems from the tab order when disabled state is enabled', () => {
fixture.componentInstance.disabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
let testListItem = listOption[2].injector.get<MatListOption>(MatListOption);
testListItem.focus();
fixture.detectChanges();
expect(
listOption.filter(option => option.nativeElement.getAttribute('tabindex') === '0').length,
)
.withContext('Expected at least one list option to be in the tab order')
.toBeGreaterThanOrEqual(1);
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(
listOption.filter(option => option.nativeElement.getAttribute('tabindex') !== '-1').length,
)
.withContext('Expected all list options to be excluded from the tab order')
.toBe(0);
});
it('should not allow focusin event to change the tabindex', () => {
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(
listOption.filter(option => option.nativeElement.getAttribute('tabindex') !== '-1').length,
)
.withContext('Expected all list options to be excluded from the tab order')
.toBe(0);
listOption[1].triggerEventHandler('focusin', {target: listOption[1].nativeElement});
fixture.detectChanges();
expect(
listOption.filter(option => option.nativeElement.getAttribute('tabindex') !== '-1').length,
)
.withContext('Expected all list options to be excluded from the tab order')
.toBe(0);
});
});
describe('with checkbox position after', () => {
let fixture: ComponentFixture<SelectionListWithCheckboxPositionAfter>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
MatListModule,
SelectionListWithListOptions,
SelectionListWithCheckboxPositionAfter,
SelectionListWithListDisabled,
SelectionListWithOnlyOneOption,
],
});
}));
beforeEach(waitForAsync(() => {
fixture = TestBed.createComponent(SelectionListWithCheckboxPositionAfter);
fixture.detectChanges();
}));
it('should be able to customize checkbox position', () => {
expect(fixture.nativeElement.querySelector('.mdc-list-item__end .mdc-checkbox'))
.withContext('Expected checkbox to show up after content.')
.toBeTruthy();
expect(fixture.nativeElement.querySelector('.mdc-list-item__start .mdc-checkbox'))
.withContext('Expected no checkbox to show up before content.')
.toBeFalsy();
});
}); | {
"end_byte": 35663,
"start_byte": 29394,
"url": "https://github.com/angular/components/blob/main/src/material/list/selection-list.spec.ts"
} |
components/src/material/list/selection-list.spec.ts_35667_40959 | describe('with list item elements', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatListModule, SelectionListWithAvatar, SelectionListWithIcon],
});
}));
function expectCheckboxAtPosition(
listItemElement: HTMLElement,
position: MatListOptionTogglePosition,
) {
const containerSelector =
position === 'before' ? '.mdc-list-item__start' : 'mdc-list-item__end';
const checkboxPositionClass =
position === 'before'
? 'mdc-list-item--with-leading-checkbox'
: 'mdc-list-item--with-trailing-checkbox';
expect(listItemElement.querySelector(`${containerSelector} .mdc-checkbox`))
.withContext(`Expected checkbox to be aligned ${position}`)
.toBeDefined();
expect(listItemElement.classList).toContain(checkboxPositionClass);
}
/**
* Expects an icon to be shown at the given position. Also
* ensures no avatar is shown at the specified position.
*/
function expectIconAt(item: HTMLElement, position: 'before' | 'after') {
const icon = item.querySelector('.mat-mdc-list-item-icon')!;
expect(item.classList).not.toContain('mdc-list-item--with-leading-avatar');
expect(item.classList).not.toContain('mat-mdc-list-option-with-trailing-avatar');
if (position === 'before') {
expect(icon.classList).toContain('mdc-list-item__start');
expect(item.classList).toContain('mdc-list-item--with-leading-icon');
expect(item.classList).not.toContain('mdc-list-item--with-trailing-icon');
} else {
expect(icon.classList).toContain('mdc-list-item__end');
expect(item.classList).toContain('mdc-list-item--with-trailing-icon');
expect(item.classList).not.toContain('mdc-list-item--with-leading-icon');
}
}
/**
* Expects an avatar to be shown at the given position. Also
* ensures that no icon is shown at the specified position.
*/
function expectAvatarAt(item: HTMLElement, position: 'before' | 'after') {
const avatar = item.querySelector('.mat-mdc-list-item-avatar')!;
expect(item.classList).not.toContain('mdc-list-item--with-leading-icon');
expect(item.classList).not.toContain('mdc-list-item--with-trailing-icon');
if (position === 'before') {
expect(avatar.classList).toContain('mdc-list-item__start');
expect(item.classList).toContain('mdc-list-item--with-leading-avatar');
expect(item.classList).not.toContain('mat-mdc-list-option-with-trailing-avatar');
} else {
expect(avatar.classList).toContain('mdc-list-item__end');
expect(item.classList).toContain('mat-mdc-list-option-with-trailing-avatar');
expect(item.classList).not.toContain('mdc-list-item--with-leading-avatar');
}
}
it('should add a class to reflect that it has an avatar', () => {
const fixture = TestBed.createComponent(SelectionListWithAvatar);
fixture.detectChanges();
const listOption = fixture.nativeElement.querySelector('.mat-mdc-list-option');
expect(listOption.classList).toContain('mdc-list-item--with-leading-avatar');
});
it('should add a class to reflect that it has an icon', () => {
const fixture = TestBed.createComponent(SelectionListWithIcon);
fixture.detectChanges();
const listOption = fixture.nativeElement.querySelector('.mat-mdc-list-option');
expect(listOption.classList).toContain('mdc-list-item--with-leading-icon');
});
it('should align icons properly together with checkbox', () => {
const fixture = TestBed.createComponent(SelectionListWithIcon);
fixture.detectChanges();
const listOption = fixture.nativeElement.querySelector(
'.mat-mdc-list-option',
)! as HTMLElement;
expectCheckboxAtPosition(listOption, 'after');
expectIconAt(listOption, 'before');
fixture.componentInstance.togglePosition = 'before';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expectCheckboxAtPosition(listOption, 'before');
expectIconAt(listOption, 'after');
fixture.componentInstance.togglePosition = 'after';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expectCheckboxAtPosition(listOption, 'after');
expectIconAt(listOption, 'before');
});
it('should align avatars properly together with checkbox', () => {
const fixture = TestBed.createComponent(SelectionListWithAvatar);
fixture.detectChanges();
const listOption = fixture.nativeElement.querySelector(
'.mat-mdc-list-option',
)! as HTMLElement;
expectCheckboxAtPosition(listOption, 'after');
expectAvatarAt(listOption, 'before');
fixture.componentInstance.togglePosition = 'before';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expectCheckboxAtPosition(listOption, 'before');
expectAvatarAt(listOption, 'after');
fixture.componentInstance.togglePosition = 'after';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expectCheckboxAtPosition(listOption, 'after');
expectAvatarAt(listOption, 'before');
});
}); | {
"end_byte": 40959,
"start_byte": 35667,
"url": "https://github.com/angular/components/blob/main/src/material/list/selection-list.spec.ts"
} |
components/src/material/list/selection-list.spec.ts_40963_46898 | describe('with single selection', () => {
let fixture: ComponentFixture<SelectionListWithListOptions>;
let listOptions: DebugElement[];
let selectionList: DebugElement;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatListModule, SelectionListWithListOptions],
});
fixture = TestBed.createComponent(SelectionListWithListOptions);
fixture.componentInstance.multiple = false;
fixture.changeDetectorRef.markForCheck();
listOptions = fixture.debugElement.queryAll(By.directive(MatListOption));
selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!;
fixture.detectChanges();
}));
function getFocusIndex() {
return listOptions.findIndex(o => document.activeElement === o.nativeElement);
}
it('should select one option at a time', () => {
const testListItem1 = listOptions[1].injector.get<MatListOption>(MatListOption);
const testListItem2 = listOptions[2].injector.get<MatListOption>(MatListOption);
const selectList =
selectionList.injector.get<MatSelectionList>(MatSelectionList).selectedOptions;
expect(selectList.selected.length).toBe(0);
dispatchMouseEvent(testListItem1._hostElement, 'click');
fixture.detectChanges();
expect(selectList.selected).toEqual([testListItem1]);
expect(listOptions[1].nativeElement.getAttribute('aria-selected')).toBe('true');
dispatchMouseEvent(testListItem2._hostElement, 'click');
fixture.detectChanges();
expect(selectList.selected).toEqual([testListItem2]);
expect(listOptions[1].nativeElement.getAttribute('aria-selected')).toBe('false');
expect(listOptions[2].nativeElement.getAttribute('aria-selected')).toBe('true');
});
it('should not show check boxes', () => {
expect(fixture.nativeElement.querySelector('mat-pseudo-checkbox')).toBeFalsy();
});
it('should not deselect the target option on click', () => {
const testListItem1 = listOptions[1].injector.get<MatListOption>(MatListOption);
const selectList =
selectionList.injector.get<MatSelectionList>(MatSelectionList).selectedOptions;
expect(selectList.selected.length).toBe(0);
dispatchMouseEvent(testListItem1._hostElement, 'click');
fixture.detectChanges();
expect(selectList.selected).toEqual([testListItem1]);
dispatchMouseEvent(testListItem1._hostElement, 'click');
fixture.detectChanges();
expect(selectList.selected).toEqual([testListItem1]);
});
it('throws an exception when toggling single/multiple mode after bootstrap', () => {
fixture.componentInstance.multiple = true;
fixture.changeDetectorRef.markForCheck();
expect(() => fixture.detectChanges()).toThrow(
new Error('Cannot change `multiple` mode of mat-selection-list after initialization.'),
);
});
it('should do nothing when pressing ctrl + a', () => {
const event = createKeyboardEvent('keydown', A, undefined, {control: true});
expect(listOptions.every(option => !option.componentInstance.selected)).toBe(true);
dispatchEvent(selectionList.nativeElement, event);
fixture.detectChanges();
expect(listOptions.every(option => !option.componentInstance.selected)).toBe(true);
});
it(
'should focus, but not toggle, the next item when pressing SHIFT + UP_ARROW in single ' +
'selection mode',
() => {
listOptions[3].nativeElement.focus();
expect(getFocusIndex()).toBe(3);
expect(listOptions[1].componentInstance.selected).toBe(false);
expect(listOptions[2].componentInstance.selected).toBe(false);
dispatchKeyboardEvent(listOptions[3].nativeElement, 'keydown', UP_ARROW, undefined, {
shift: true,
});
fixture.detectChanges();
expect(listOptions[1].componentInstance.selected).toBe(false);
expect(listOptions[2].componentInstance.selected).toBe(false);
},
);
it(
'should focus, but not toggle, the next item when pressing SHIFT + DOWN_ARROW ' +
'in single selection mode',
() => {
listOptions[3].nativeElement.focus();
expect(getFocusIndex()).toBe(3);
expect(listOptions[1].componentInstance.selected).toBe(false);
expect(listOptions[2].componentInstance.selected).toBe(false);
dispatchKeyboardEvent(listOptions[3].nativeElement, 'keydown', DOWN_ARROW, undefined, {
shift: true,
});
fixture.detectChanges();
expect(listOptions[1].componentInstance.selected).toBe(false);
expect(listOptions[2].componentInstance.selected).toBe(false);
},
);
});
describe('with single selection', () => {
let fixture: ComponentFixture<ListOptionWithTwoWayBinding>;
let optionElement: HTMLElement;
let option: MatListOption;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatListModule, ListOptionWithTwoWayBinding],
});
fixture = TestBed.createComponent(ListOptionWithTwoWayBinding);
fixture.detectChanges();
const optionDebug = fixture.debugElement.query(By.directive(MatListOption));
option = optionDebug.componentInstance;
optionElement = optionDebug.nativeElement;
}));
it('should sync the value from the view to the option', () => {
expect(option.selected).toBe(false);
fixture.componentInstance.selected = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(option.selected).toBe(true);
});
it('should sync the value from the option to the view', () => {
expect(fixture.componentInstance.selected).toBe(false);
optionElement.click();
fixture.detectChanges();
expect(fixture.componentInstance.selected).toBe(true);
});
});
}); | {
"end_byte": 46898,
"start_byte": 40963,
"url": "https://github.com/angular/components/blob/main/src/material/list/selection-list.spec.ts"
} |
components/src/material/list/selection-list.spec.ts_46900_55667 | describe('MatSelectionList with forms', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
MatListModule,
FormsModule,
ReactiveFormsModule,
SelectionListWithModel,
SelectionListWithFormControl,
SelectionListWithPreselectedOption,
SelectionListWithPreselectedOptionAndModel,
SelectionListWithPreselectedFormControlOnPush,
SelectionListWithCustomComparator,
],
});
}));
describe('and ngModel', () => {
let fixture: ComponentFixture<SelectionListWithModel>;
let selectionListDebug: DebugElement;
let listOptions: MatListOption[];
let ngModel: NgModel;
beforeEach(() => {
fixture = TestBed.createComponent(SelectionListWithModel);
fixture.detectChanges();
selectionListDebug = fixture.debugElement.query(By.directive(MatSelectionList))!;
ngModel = selectionListDebug.injector.get<NgModel>(NgModel);
listOptions = fixture.debugElement
.queryAll(By.directive(MatListOption))
.map(optionDebugEl => optionDebugEl.componentInstance);
});
it('should update the model if an option got selected programmatically', fakeAsync(() => {
expect(fixture.componentInstance.selectedOptions.length)
.withContext('Expected no options to be selected by default')
.toBe(0);
listOptions[0].toggle();
fixture.detectChanges();
tick();
expect(fixture.componentInstance.selectedOptions.length)
.withContext('Expected first list option to be selected')
.toBe(1);
}));
it('should update the model if an option got clicked', fakeAsync(() => {
expect(fixture.componentInstance.selectedOptions.length)
.withContext('Expected no options to be selected by default')
.toBe(0);
dispatchMouseEvent(listOptions[0]._hostElement, 'click');
fixture.detectChanges();
tick();
expect(fixture.componentInstance.selectedOptions.length)
.withContext('Expected first list option to be selected')
.toBe(1);
}));
it('should update the options if a model value is set', fakeAsync(() => {
expect(fixture.componentInstance.selectedOptions.length)
.withContext('Expected no options to be selected by default')
.toBe(0);
fixture.componentInstance.selectedOptions = ['opt3'];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(fixture.componentInstance.selectedOptions.length)
.withContext('Expected first list option to be selected')
.toBe(1);
}));
it('should focus the first option when the list items are changed', fakeAsync(() => {
fixture.componentInstance.options = ['first option', 'second option'];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
const listElements = fixture.debugElement
.queryAll(By.directive(MatListOption))
.map(optionDebugEl => optionDebugEl.nativeElement);
expect(listElements.length).toBe(2);
expect(listElements[0].tabIndex).toBe(0);
expect(listElements[1].tabIndex).toBe(-1);
}));
it('should not mark the model as touched when the list is blurred', fakeAsync(() => {
expect(ngModel.touched)
.withContext('Expected the selection-list to be untouched by default.')
.toBe(false);
dispatchFakeEvent(selectionListDebug.nativeElement, 'blur');
fixture.detectChanges();
tick();
expect(ngModel.touched)
.withContext('Expected the selection-list to remain untouched.')
.toBe(false);
}));
it('should mark the model as touched when a list item is blurred', fakeAsync(() => {
expect(ngModel.touched)
.withContext('Expected the selection-list to be untouched by default.')
.toBe(false);
dispatchFakeEvent(fixture.nativeElement.querySelector('.mat-mdc-list-option'), 'blur');
fixture.detectChanges();
tick();
expect(ngModel.touched)
.withContext('Expected the selection-list to be touched after an item is blurred.')
.toBe(true);
}));
it('should be pristine by default', fakeAsync(() => {
fixture = TestBed.createComponent(SelectionListWithModel);
fixture.componentInstance.selectedOptions = ['opt2'];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
ngModel = fixture.debugElement
.query(By.directive(MatSelectionList))!
.injector.get<NgModel>(NgModel);
listOptions = fixture.debugElement
.queryAll(By.directive(MatListOption))
.map(optionDebugEl => optionDebugEl.componentInstance);
// Flush the initial tick to ensure that every action from the ControlValueAccessor
// happened before the actual test starts.
tick();
expect(ngModel.pristine)
.withContext('Expected the selection-list to be pristine by default.')
.toBe(true);
listOptions[1].toggle();
fixture.detectChanges();
tick();
expect(ngModel.pristine)
.withContext('Expected the selection-list to be dirty after state change.')
.toBe(false);
}));
it('should remove a selected option from the value on destroy', fakeAsync(() => {
listOptions[1].selected = true;
listOptions[2].selected = true;
fixture.detectChanges();
expect(fixture.componentInstance.selectedOptions).toEqual(['opt2', 'opt3']);
fixture.componentInstance.options.pop();
fixture.detectChanges();
tick();
expect(fixture.componentInstance.selectedOptions).toEqual(['opt2']);
}));
it('should update the model if an option got selected via the model', fakeAsync(() => {
expect(fixture.componentInstance.selectedOptions).toEqual([]);
selectionListDebug.componentInstance.selectedOptions.select(listOptions[0]);
fixture.detectChanges();
tick();
expect(fixture.componentInstance.selectedOptions).toEqual(['opt1']);
}));
it('should not dispatch the model change event if nothing changed using selectAll', () => {
expect(fixture.componentInstance.modelChangeSpy).not.toHaveBeenCalled();
selectionListDebug.componentInstance.selectAll();
fixture.detectChanges();
expect(fixture.componentInstance.modelChangeSpy).toHaveBeenCalledTimes(1);
selectionListDebug.componentInstance.selectAll();
fixture.detectChanges();
expect(fixture.componentInstance.modelChangeSpy).toHaveBeenCalledTimes(1);
});
it('should not dispatch the model change event if nothing changed using selectAll', () => {
expect(fixture.componentInstance.modelChangeSpy).not.toHaveBeenCalled();
selectionListDebug.componentInstance.deselectAll();
fixture.detectChanges();
expect(fixture.componentInstance.modelChangeSpy).not.toHaveBeenCalled();
});
it('should be able to programmatically set an array with duplicate values', fakeAsync(() => {
fixture.componentInstance.options = ['one', 'two', 'two', 'two', 'three'];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
listOptions = fixture.debugElement
.queryAll(By.directive(MatListOption))
.map(optionDebugEl => optionDebugEl.componentInstance);
fixture.componentInstance.selectedOptions = ['one', 'two', 'two'];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(listOptions.map(option => option.selected)).toEqual([true, true, true, false, false]);
}));
it('should dispatch one change event per change when updating a single-selection list', fakeAsync(() => {
fixture.destroy();
fixture = TestBed.createComponent(SelectionListWithModel);
fixture.componentInstance.multiple = false;
fixture.componentInstance.selectedOptions = ['opt3'];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const options = fixture.debugElement
.queryAll(By.directive(MatListOption))
.map(optionDebugEl => optionDebugEl.nativeElement);
expect(fixture.componentInstance.modelChangeSpy).not.toHaveBeenCalled();
options[0].click();
fixture.detectChanges();
tick();
expect(fixture.componentInstance.modelChangeSpy).toHaveBeenCalledTimes(1);
expect(fixture.componentInstance.selectedOptions).toEqual(['opt1']);
options[1].click();
fixture.detectChanges();
tick();
expect(fixture.componentInstance.modelChangeSpy).toHaveBeenCalledTimes(2);
expect(fixture.componentInstance.selectedOptions).toEqual(['opt2']);
}));
}); | {
"end_byte": 55667,
"start_byte": 46900,
"url": "https://github.com/angular/components/blob/main/src/material/list/selection-list.spec.ts"
} |
components/src/material/list/selection-list.spec.ts_55671_65517 | describe('and formControl', () => {
let fixture: ComponentFixture<SelectionListWithFormControl>;
let listOptions: MatListOption[];
let selectionList: MatSelectionList;
beforeEach(() => {
fixture = TestBed.createComponent(SelectionListWithFormControl);
fixture.detectChanges();
selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!.componentInstance;
listOptions = fixture.debugElement
.queryAll(By.directive(MatListOption))
.map(optionDebugEl => optionDebugEl.componentInstance);
});
it('should be able to disable options from the control', () => {
selectionList.focus();
expect(selectionList.disabled)
.withContext('Expected the selection list to be enabled.')
.toBe(false);
expect(listOptions.every(option => !option.disabled))
.withContext('Expected every list option to be enabled.')
.toBe(true);
expect(
listOptions.some(
option => option._elementRef.nativeElement.getAttribute('tabindex') === '0',
),
)
.withContext('Expected one list item to be in the tab order')
.toBe(true);
fixture.componentInstance.formControl.disable();
fixture.detectChanges();
expect(selectionList.disabled)
.withContext('Expected the selection list to be disabled.')
.toBe(true);
expect(listOptions.every(option => option.disabled))
.withContext('Expected every list option to be disabled.')
.toBe(true);
expect(
listOptions.every(
option => option._elementRef.nativeElement.getAttribute('tabindex') === '-1',
),
)
.withContext('Expected every list option to be removed from the tab order')
.toBe(true);
});
it('should be able to update the disabled property after form control disabling', () => {
expect(listOptions.every(option => !option.disabled))
.withContext('Expected every list option to be enabled.')
.toBe(true);
fixture.componentInstance.formControl.disable();
fixture.detectChanges();
expect(listOptions.every(option => option.disabled))
.withContext('Expected every list option to be disabled.')
.toBe(true);
// Previously the selection list has been disabled through FormControl#disable. Now we
// want to verify that we can still change the disabled state through updating the disabled
// property. Calling FormControl#disable should not lock the disabled property.
// See: https://github.com/angular/material2/issues/12107
selectionList.disabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(listOptions.every(option => !option.disabled))
.withContext('Expected every list option to be enabled.')
.toBe(true);
});
it('should be able to set the value through the form control', () => {
expect(listOptions.every(option => !option.selected))
.withContext('Expected every list option to be unselected.')
.toBe(true);
fixture.componentInstance.formControl.setValue(['opt2', 'opt3']);
fixture.detectChanges();
expect(listOptions[1].selected)
.withContext('Expected second option to be selected.')
.toBe(true);
expect(listOptions[2].selected)
.withContext('Expected third option to be selected.')
.toBe(true);
fixture.componentInstance.formControl.setValue(null);
fixture.detectChanges();
expect(listOptions.every(option => !option.selected))
.withContext('Expected every list option to be unselected.')
.toBe(true);
});
it('should deselect option whose value no longer matches', () => {
const option = listOptions[1];
fixture.componentInstance.formControl.setValue(['opt2']);
fixture.detectChanges();
expect(option.selected).withContext('Expected option to be selected.').toBe(true);
option.value = 'something-different';
fixture.detectChanges();
expect(option.selected).withContext('Expected option not to be selected.').toBe(false);
expect(fixture.componentInstance.formControl.value).toEqual([]);
});
it('should mark options as selected when the value is set before they are initialized', () => {
fixture.destroy();
fixture = TestBed.createComponent(SelectionListWithFormControl);
fixture.componentInstance.formControl.setValue(['opt2', 'opt3']);
fixture.detectChanges();
listOptions = fixture.debugElement
.queryAll(By.directive(MatListOption))
.map(optionDebugEl => optionDebugEl.componentInstance);
expect(listOptions[1].selected)
.withContext('Expected second option to be selected.')
.toBe(true);
expect(listOptions[2].selected)
.withContext('Expected third option to be selected.')
.toBe(true);
});
it('should not clear the form control when the list is destroyed', fakeAsync(() => {
const option = listOptions[1];
option.selected = true;
fixture.detectChanges();
expect(fixture.componentInstance.formControl.value).toEqual(['opt2']);
fixture.componentInstance.renderList = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(fixture.componentInstance.formControl.value).toEqual(['opt2']);
}));
it('should mark options added at a later point as selected', () => {
fixture.componentInstance.formControl.setValue(['opt4']);
fixture.detectChanges();
fixture.componentInstance.renderExtraOption = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
listOptions = fixture.debugElement
.queryAll(By.directive(MatListOption))
.map(optionDebugEl => optionDebugEl.componentInstance);
expect(listOptions.length).toBe(4);
expect(listOptions[3].selected).toBe(true);
});
});
describe('preselected values', () => {
it('should add preselected options to the model value', fakeAsync(() => {
const fixture = TestBed.createComponent(SelectionListWithPreselectedOption);
const listOptions = fixture.debugElement
.queryAll(By.directive(MatListOption))
.map(optionDebugEl => optionDebugEl.componentInstance);
fixture.detectChanges();
tick();
expect(listOptions[1].selected).toBe(true);
expect(fixture.componentInstance.selectedOptions).toEqual(['opt2']);
}));
it('should handle preselected option both through the model and the view', fakeAsync(() => {
const fixture = TestBed.createComponent(SelectionListWithPreselectedOptionAndModel);
const listOptions = fixture.debugElement
.queryAll(By.directive(MatListOption))
.map(optionDebugEl => optionDebugEl.componentInstance);
fixture.detectChanges();
tick();
expect(listOptions[0].selected).toBe(true);
expect(listOptions[1].selected).toBe(true);
expect(fixture.componentInstance.selectedOptions).toEqual(['opt1', 'opt2']);
}));
it('should show the item as selected when preselected inside OnPush parent', fakeAsync(() => {
const fixture = TestBed.createComponent(SelectionListWithPreselectedFormControlOnPush);
fixture.detectChanges();
const option = fixture.debugElement.queryAll(By.directive(MatListOption))[1];
const checkbox = option.nativeElement.querySelector(
'.mdc-checkbox__native-control',
) as HTMLInputElement;
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(option.componentInstance.selected).toBe(true);
expect(checkbox.checked).toBe(true);
}));
});
describe('with custom compare function', () => {
it('should use a custom comparator to determine which options are selected', fakeAsync(() => {
const fixture = TestBed.createComponent(SelectionListWithCustomComparator);
const testComponent = fixture.componentInstance;
testComponent.compareWith = jasmine
.createSpy('comparator', (o1: any, o2: any) => {
return o1 && o2 && o1.id === o2.id;
})
.and.callThrough();
testComponent.selectedOptions = [{id: 2, label: 'Two'}];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(testComponent.compareWith).toHaveBeenCalled();
expect(testComponent.optionInstances.toArray()[1].selected).toBe(true);
}));
});
});
@Component({
template: `
<mat-selection-list
id="selection-list-1"
(selectionChange)="onSelectionChange($event)"
[disableRipple]="listRippleDisabled"
[color]="selectionListColor"
[multiple]="multiple">
<mat-list-option togglePosition="before" disabled="true" value="inbox"
[color]="firstOptionColor">
Inbox (disabled selection-option)
</mat-list-option>
<mat-list-option id="testSelect" togglePosition="before" class="test-native-focus"
value="starred">
Starred
</mat-list-option>
<mat-list-option togglePosition="before" value="sent-mail">
Sent Mail
</mat-list-option>
<mat-list-option togglePosition="before" value="archive">
Archive
</mat-list-option>
@if (showLastOption) {
<mat-list-option togglePosition="before" value="drafts">
Drafts
</mat-list-option>
}
</mat-selection-list>`,
standalone: true,
imports: [MatListModule],
})
class SelectionListWithListOptions {
showLastOption = true;
listRippleDisabled = false;
multiple = true;
selectionListColor: ThemePalette;
firstOptionColor: ThemePalette;
onSelectionChange(_change: MatSelectionListChange) {}
} | {
"end_byte": 65517,
"start_byte": 55671,
"url": "https://github.com/angular/components/blob/main/src/material/list/selection-list.spec.ts"
} |
components/src/material/list/selection-list.spec.ts_65519_73046 | @Component({
template: `
<mat-selection-list id="selection-list-2">
<mat-list-option togglePosition="after">
Inbox (disabled selection-option)
</mat-list-option>
<mat-list-option id="testSelect" togglePosition="after">
Starred
</mat-list-option>
<mat-list-option togglePosition="after">
Sent Mail
</mat-list-option>
<mat-list-option togglePosition="after">
Drafts
</mat-list-option>
</mat-selection-list>`,
standalone: true,
imports: [MatListModule],
})
class SelectionListWithCheckboxPositionAfter {}
@Component({
template: `
<mat-selection-list id="selection-list-3" [disabled]="disabled">
<mat-list-option togglePosition="after">
Inbox (disabled selection-option)
</mat-list-option>
<mat-list-option id="testSelect" togglePosition="after">
Starred
</mat-list-option>
<mat-list-option togglePosition="after">
Sent Mail
</mat-list-option>
<mat-list-option togglePosition="after">
Drafts
</mat-list-option>
</mat-selection-list>`,
standalone: true,
imports: [MatListModule],
})
class SelectionListWithListDisabled {
disabled: boolean = true;
}
@Component({
template: `
<mat-selection-list>
<mat-list-option [disabled]="disableItem">Item</mat-list-option>
</mat-selection-list>
`,
standalone: true,
imports: [MatListModule],
})
class SelectionListWithDisabledOption {
disableItem: boolean = false;
}
@Component({
template: `
<mat-selection-list>
<mat-list-option>Not selected - Item #1</mat-list-option>
<mat-list-option [selected]="true">Pre-selected - Item #2</mat-list-option>
<mat-list-option [selected]="true">Pre-selected - Item #3</mat-list-option>
<mat-list-option>Not selected - Item #4</mat-list-option>
</mat-selection-list>`,
standalone: true,
imports: [MatListModule],
})
class SelectionListWithSelectedOption {}
@Component({
template: `
<mat-selection-list [multiple]="false">
<mat-list-option>Not selected - Item #1</mat-list-option>
<mat-list-option [selected]="true">Pre-selected - Item #2</mat-list-option>
</mat-selection-list>`,
standalone: true,
imports: [MatListModule],
})
class SingleSelectionListWithSelectedOption {}
@Component({
template: `
<mat-selection-list>
<mat-list-option [selected]="true" [value]="itemValue">Item</mat-list-option>
</mat-selection-list>`,
standalone: true,
imports: [MatListModule],
})
class SelectionListWithSelectedOptionAndValue {
itemValue = 'item1';
}
@Component({
template: `
<mat-selection-list id="selection-list-4">
<mat-list-option togglePosition="after" class="test-focus" id="123">
Inbox
</mat-list-option>
</mat-selection-list>`,
standalone: true,
imports: [MatListModule],
})
class SelectionListWithOnlyOneOption {}
@Component({
template: `
<mat-selection-list
[(ngModel)]="selectedOptions"
(ngModelChange)="modelChangeSpy()"
[multiple]="multiple">
@for (option of options; track option) {
<mat-list-option [value]="option">{{option}}</mat-list-option>
}
</mat-selection-list>`,
standalone: true,
imports: [MatListModule, FormsModule, ReactiveFormsModule],
})
class SelectionListWithModel {
modelChangeSpy = jasmine.createSpy('model change spy');
selectedOptions: string[] = [];
multiple = true;
options = ['opt1', 'opt2', 'opt3'];
}
@Component({
template: `
@if (renderList) {
<mat-selection-list [formControl]="formControl">
<mat-list-option value="opt1">Option 1</mat-list-option>
<mat-list-option value="opt2">Option 2</mat-list-option>
<mat-list-option value="opt3">Option 3</mat-list-option>
@if (renderExtraOption) {
<mat-list-option value="opt4">Option 4</mat-list-option>
}
</mat-selection-list>
}
`,
standalone: true,
imports: [MatListModule, FormsModule, ReactiveFormsModule],
})
class SelectionListWithFormControl {
formControl = new FormControl([] as string[]);
renderList = true;
renderExtraOption = false;
}
@Component({
template: `
<mat-selection-list [(ngModel)]="selectedOptions">
<mat-list-option value="opt1">Option 1</mat-list-option>
<mat-list-option value="opt2" selected>Option 2</mat-list-option>
</mat-selection-list>`,
standalone: true,
imports: [MatListModule, FormsModule, ReactiveFormsModule],
})
class SelectionListWithPreselectedOption {
selectedOptions: string[];
}
@Component({
template: `
<mat-selection-list [(ngModel)]="selectedOptions">
<mat-list-option value="opt1">Option 1</mat-list-option>
<mat-list-option value="opt2" selected>Option 2</mat-list-option>
</mat-selection-list>`,
standalone: true,
imports: [MatListModule, FormsModule, ReactiveFormsModule],
})
class SelectionListWithPreselectedOptionAndModel {
selectedOptions = ['opt1'];
}
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<mat-selection-list [formControl]="formControl">
@for (opt of opts; track opt) {
<mat-list-option [value]="opt">{{opt}}</mat-list-option>
}
</mat-selection-list>
`,
standalone: true,
imports: [MatListModule, FormsModule, ReactiveFormsModule],
})
class SelectionListWithPreselectedFormControlOnPush {
opts = ['opt1', 'opt2', 'opt3'];
formControl = new FormControl(['opt2']);
}
@Component({
template: `
<mat-selection-list [(ngModel)]="selectedOptions" [compareWith]="compareWith">
@for (option of options; track option) {
<mat-list-option [value]="option">{{option.label}}</mat-list-option>
}
</mat-selection-list>`,
standalone: true,
imports: [MatListModule, FormsModule, ReactiveFormsModule],
})
class SelectionListWithCustomComparator {
@ViewChildren(MatListOption) optionInstances: QueryList<MatListOption>;
selectedOptions: {id: number; label: string}[] = [];
compareWith?: (o1: any, o2: any) => boolean;
options = [
{id: 1, label: 'One'},
{id: 2, label: 'Two'},
{id: 3, label: 'Three'},
];
}
@Component({
template: `
<mat-selection-list>
<mat-list-option [togglePosition]="togglePosition">
<div matListItemAvatar>I</div>
Inbox
</mat-list-option>
</mat-selection-list>
`,
standalone: true,
imports: [MatListModule],
})
class SelectionListWithAvatar {
togglePosition: MatListOptionTogglePosition | undefined;
}
@Component({
template: `
<mat-selection-list>
<mat-list-option [togglePosition]="togglePosition">
<div matListItemIcon>I</div>
Inbox
</mat-list-option>
</mat-selection-list>
`,
standalone: true,
imports: [MatListModule],
})
class SelectionListWithIcon {
togglePosition: MatListOptionTogglePosition | undefined;
}
@Component({
// Note the blank `@if` which we need in order to hit the bug that we're testing.
template: `
<mat-selection-list>
@if (true) {
<mat-list-option [value]="1">One</mat-list-option>
<mat-list-option [value]="2">Two</mat-list-option>
}
</mat-selection-list>`,
standalone: true,
imports: [MatListModule],
})
class SelectionListWithIndirectChildOptions {
@ViewChildren(MatListOption) optionInstances: QueryList<MatListOption>;
}
@Component({
template: `
<mat-selection-list>
<mat-list-option [(selected)]="selected">Item</mat-list-option>
</mat-selection-list>
`,
standalone: true,
imports: [MatListModule],
})
class ListOptionWithTwoWayBinding {
selected = false;
} | {
"end_byte": 73046,
"start_byte": 65519,
"url": "https://github.com/angular/components/blob/main/src/material/list/selection-list.spec.ts"
} |
components/src/material/list/list.ts_0_3521 | /**
* @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,
ContentChildren,
ElementRef,
QueryList,
ViewChild,
ViewEncapsulation,
InjectionToken,
} from '@angular/core';
import {MatListBase, MatListItemBase} from './list-base';
import {MatListItemLine, MatListItemMeta, MatListItemTitle} from './list-item-sections';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {CdkObserveContent} from '@angular/cdk/observers';
/**
* Injection token that can be used to inject instances of `MatList`. It serves as
* alternative token to the actual `MatList` class which could cause unnecessary
* retention of the class and its component metadata.
*/
export const MAT_LIST = new InjectionToken<MatList>('MatList');
@Component({
selector: 'mat-list',
exportAs: 'matList',
template: '<ng-content></ng-content>',
host: {
'class': 'mat-mdc-list mat-mdc-list-base mdc-list',
},
styleUrl: 'list.css',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [{provide: MatListBase, useExisting: MatList}],
})
export class MatList extends MatListBase {}
@Component({
selector: 'mat-list-item, a[mat-list-item], button[mat-list-item]',
exportAs: 'matListItem',
host: {
'class': 'mat-mdc-list-item mdc-list-item',
'[class.mdc-list-item--activated]': 'activated',
'[class.mdc-list-item--with-leading-avatar]': '_avatars.length !== 0',
'[class.mdc-list-item--with-leading-icon]': '_icons.length !== 0',
'[class.mdc-list-item--with-trailing-meta]': '_meta.length !== 0',
// Utility class that makes it easier to target the case where there's both a leading
// and a trailing icon. Avoids having to write out all the combinations.
'[class.mat-mdc-list-item-both-leading-and-trailing]': '_hasBothLeadingAndTrailing()',
'[class._mat-animation-noopable]': '_noopAnimations',
'[attr.aria-current]': '_getAriaCurrent()',
},
templateUrl: 'list-item.html',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [CdkObserveContent],
})
export class MatListItem extends MatListItemBase {
@ContentChildren(MatListItemLine, {descendants: true}) _lines: QueryList<MatListItemLine>;
@ContentChildren(MatListItemTitle, {descendants: true}) _titles: QueryList<MatListItemTitle>;
@ContentChildren(MatListItemMeta, {descendants: true}) _meta: QueryList<MatListItemMeta>;
@ViewChild('unscopedContent') _unscopedContent: ElementRef<HTMLSpanElement>;
@ViewChild('text') _itemText: ElementRef<HTMLElement>;
/** Indicates whether an item in a `<mat-nav-list>` is the currently active page. */
@Input()
get activated(): boolean {
return this._activated;
}
set activated(activated) {
this._activated = coerceBooleanProperty(activated);
}
_activated = false;
/**
* Determine the value of `aria-current`. Return 'page' if this item is an activated anchor tag.
* Otherwise, return `null`. This method is safe to use with server-side rendering.
*/
_getAriaCurrent(): string | null {
return this._hostElement.nodeName === 'A' && this._activated ? 'page' : null;
}
protected _hasBothLeadingAndTrailing(): boolean {
return this._meta.length !== 0 && (this._avatars.length !== 0 || this._icons.length !== 0);
}
}
| {
"end_byte": 3521,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/list/list.ts"
} |
components/src/material/list/list.spec.ts_0_357 | import {dispatchFakeEvent, dispatchMouseEvent} from '@angular/cdk/testing/private';
import {Component, QueryList, ViewChild, ViewChildren} from '@angular/core';
import {TestBed, fakeAsync, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {MatListItem, MatListModule} from './index';
describe('MatList', () => | {
"end_byte": 357,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/list/list.spec.ts"
} |
components/src/material/list/list.spec.ts_358_10119 | {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
MatListModule,
ListWithOneAnchorItem,
ListWithOneItem,
ListWithTwoLineItem,
ListWithThreeLineItem,
ListWithAvatar,
ListWithItemWithCssClass,
ListWithDynamicNumberOfLines,
ListWithMultipleItems,
NavListWithOneAnchorItem,
NavListWithActivatedItem,
ActionListWithoutType,
ActionListWithType,
ActionListWithDisabledList,
ActionListWithDisabledItem,
ListWithDisabledItems,
StandaloneListItem,
],
});
}));
it('should apply an additional class to lists without lines', () => {
const fixture = TestBed.createComponent(ListWithOneItem);
const listItem = fixture.debugElement.query(By.css('mat-list-item'))!;
fixture.detectChanges();
expect(listItem.nativeElement.classList).toContain('mat-mdc-list-item');
expect(listItem.nativeElement.classList).toContain('mdc-list-item');
expect(listItem.nativeElement.classList).toContain('mdc-list-item--with-one-line');
});
it('should apply a particular class to lists with two lines', () => {
const fixture = TestBed.createComponent(ListWithTwoLineItem);
fixture.detectChanges();
const listItems = fixture.debugElement.children[0].queryAll(By.css('mat-list-item'));
expect(listItems[0].nativeElement.className).toContain('mdc-list-item--with-two-lines');
});
it('should apply a particular class to lists with three lines', () => {
const fixture = TestBed.createComponent(ListWithThreeLineItem);
fixture.detectChanges();
const listItems = fixture.debugElement.children[0].queryAll(By.css('mat-list-item'));
expect(listItems[0].nativeElement.className).toContain('mdc-list-item--with-three-lines');
});
it('should apply a class to list items with avatars', () => {
const fixture = TestBed.createComponent(ListWithAvatar);
fixture.detectChanges();
const listItems = fixture.debugElement.children[0].queryAll(By.css('mat-list-item'));
expect(listItems[0].nativeElement.className).toContain('mdc-list-item--with-leading-avatar');
expect(listItems[1].nativeElement.className).not.toContain(
'mdc-list-item--with-leading-avatar',
);
});
it('should have a strong focus indicator configured for all list-items', () => {
const fixture = TestBed.createComponent(ListWithThreeLineItem);
fixture.detectChanges();
const listItems = fixture.debugElement.children[0]
.queryAll(By.css('mat-list-item'))
.map(debugEl => debugEl.nativeElement as HTMLElement);
expect(listItems.every(i => i.querySelector('.mat-focus-indicator') !== null))
.withContext('Expected all list items to have a strong focus indicator element.')
.toBe(true);
});
it('should not clear custom classes provided by user', () => {
const fixture = TestBed.createComponent(ListWithItemWithCssClass);
fixture.detectChanges();
const listItems = fixture.debugElement.children[0].queryAll(By.css('mat-list-item'));
expect(listItems[0].nativeElement.classList.contains('test-class')).toBe(true);
});
it('should update classes if number of lines change', () => {
const fixture = TestBed.createComponent(ListWithDynamicNumberOfLines);
fixture.debugElement.componentInstance.showThirdLine = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const listItem = fixture.debugElement.children[0].query(By.css('mat-list-item'))!;
expect(listItem.nativeElement.classList).toContain('mdc-list-item--with-two-lines');
expect(listItem.nativeElement.classList).toContain('mat-mdc-list-item');
expect(listItem.nativeElement.classList).toContain('mdc-list-item');
fixture.debugElement.componentInstance.showThirdLine = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(listItem.nativeElement.className).toContain('mdc-list-item--with-three-lines');
});
it('should not apply aria roles to mat-list', () => {
const fixture = TestBed.createComponent(ListWithMultipleItems);
fixture.detectChanges();
const list = fixture.debugElement.children[0];
const listItem = fixture.debugElement.children[0].query(By.css('mat-list-item'))!;
expect(list.nativeElement.getAttribute('role'))
.withContext('Expect mat-list no role')
.toBeNull();
expect(listItem.nativeElement.getAttribute('role'))
.withContext('Expect mat-list-item no role')
.toBeNull();
});
it('should apply role="navigation" to mat-nav-list', () => {
const fixture = TestBed.createComponent(NavListWithOneAnchorItem);
fixture.detectChanges();
const list = fixture.debugElement.children[0];
expect(list.nativeElement.getAttribute('role'))
.withContext('Expect mat-nav-list to have navigation role')
.toBe('navigation');
});
it('should apply role="group" to mat-action-list', () => {
const fixture = TestBed.createComponent(ActionListWithoutType);
fixture.detectChanges();
const list = fixture.debugElement.children[0];
expect(list.nativeElement.getAttribute('role'))
.withContext('Expect mat-action-list to have group role')
.toBe('group');
});
it('should apply aria-current="page" to activated list items', () => {
const fixture = TestBed.createComponent(NavListWithActivatedItem);
fixture.detectChanges();
const items = fixture.componentInstance.listItems;
expect(items.length)
.withContext('expected list to have at least two items')
.toBeGreaterThanOrEqual(2);
const inactiveItem = items.get(0)!._elementRef.nativeElement;
const activeItem = items.get(1)!._elementRef.nativeElement;
expect(inactiveItem.hasAttribute('aria-current')).toBe(false);
expect(activeItem.getAttribute('aria-current')).toBe('page');
});
it('should not show ripples for non-nav lists', fakeAsync(() => {
const fixture = TestBed.createComponent(ListWithOneAnchorItem);
fixture.detectChanges();
const items: QueryList<MatListItem> = fixture.debugElement.componentInstance.listItems;
expect(items.length).toBeGreaterThan(0);
items.forEach(item => {
dispatchMouseEvent(item._hostElement, 'mousedown');
expect(fixture.nativeElement.querySelector('.mat-ripple-element')).toBe(null);
});
}));
it('should allow disabling ripples for specific nav-list items', () => {
const fixture = TestBed.createComponent(NavListWithOneAnchorItem);
fixture.detectChanges();
const items = fixture.componentInstance.listItems;
expect(items.length).toBeGreaterThan(0);
// Ripples should be enabled by default, and can be disabled with a binding.
items.forEach(item => expect(item.rippleDisabled).toBe(false));
fixture.componentInstance.disableItemRipple = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
items.forEach(item => expect(item.rippleDisabled).toBe(true));
});
it('should create an action list', () => {
const fixture = TestBed.createComponent(ActionListWithoutType);
fixture.detectChanges();
const items = fixture.componentInstance.listItems;
expect(items.length).toBeGreaterThan(0);
});
it('should set the proper class on the action list host', () => {
const fixture = TestBed.createComponent(ActionListWithoutType);
fixture.detectChanges();
const host = fixture.nativeElement.querySelector('mat-action-list');
expect(host.classList).toContain('mat-mdc-action-list');
});
it('should enable ripples for action lists by default', () => {
const fixture = TestBed.createComponent(ActionListWithoutType);
fixture.detectChanges();
const items = fixture.componentInstance.listItems;
expect(items.toArray().every(item => !item.rippleDisabled)).toBe(true);
});
it('should allow disabling ripples for specific action list items', () => {
const fixture = TestBed.createComponent(ActionListWithoutType);
fixture.detectChanges();
const items = fixture.componentInstance.listItems.toArray();
expect(items.length).toBeGreaterThan(0);
expect(items.every(item => !item.rippleDisabled)).toBe(true);
fixture.componentInstance.disableItemRipple = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(items.every(item => item.rippleDisabled)).toBe(true);
});
it('should set default type attribute to button for action list', () => {
const fixture = TestBed.createComponent(ActionListWithoutType);
fixture.detectChanges();
const listItemEl = fixture.debugElement.query(By.css('.mat-mdc-list-item'))!;
expect(listItemEl.nativeElement.getAttribute('type')).toBe('button');
});
it('should not change type attribute if it is already specified', () => {
const fixture = TestBed.createComponent(ActionListWithType);
fixture.detectChanges();
const listItemEl = fixture.debugElement.query(By.css('.mat-mdc-list-item'))!;
expect(listItemEl.nativeElement.getAttribute('type')).toBe('submit');
});
it('should allow disabling ripples for the whole nav-list', () => {
const fixture = TestBed.createComponent(NavListWithOneAnchorItem);
fixture.detectChanges();
const items = fixture.componentInstance.listItems;
expect(items.length).toBeGreaterThan(0);
// Ripples should be enabled by default, and can be disabled with a binding.
items.forEach(item => expect(item.rippleDisabled).toBe(false));
fixture.componentInstance.disableListRipple = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
items.forEach(item => expect(item.rippleDisabled).toBe(true));
}); | {
"end_byte": 10119,
"start_byte": 358,
"url": "https://github.com/angular/components/blob/main/src/material/list/list.spec.ts"
} |
components/src/material/list/list.spec.ts_10123_18840 | it('should allow disabling ripples for the entire action list', () => {
const fixture = TestBed.createComponent(ActionListWithoutType);
fixture.detectChanges();
const items = fixture.componentInstance.listItems.toArray();
expect(items.length).toBeGreaterThan(0);
expect(items.every(item => !item.rippleDisabled)).toBe(true);
fixture.componentInstance.disableListRipple = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(items.every(item => item.rippleDisabled)).toBe(true);
});
it('should disable item ripples when list ripples are disabled via the input in nav list', fakeAsync(() => {
const fixture = TestBed.createComponent(NavListWithOneAnchorItem);
fixture.detectChanges();
const rippleTarget = fixture.nativeElement.querySelector('.mat-mdc-list-item');
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
// Flush the ripple enter animation.
dispatchFakeEvent(rippleTarget.querySelector('.mat-ripple-element')!, 'transitionend');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected ripples to be enabled by default.')
.toBe(1);
// Flush the ripple exit animation.
dispatchFakeEvent(rippleTarget.querySelector('.mat-ripple-element')!, 'transitionend');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected ripples to go away.')
.toBe(0);
fixture.componentInstance.disableListRipple = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected no ripples after list ripples are disabled.')
.toBe(0);
}));
it('should disable item ripples when list ripples are disabled via the input in an action list', fakeAsync(() => {
const fixture = TestBed.createComponent(ActionListWithoutType);
fixture.detectChanges();
const rippleTarget = fixture.nativeElement.querySelector('.mat-mdc-list-item');
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
// Flush the ripple enter animation.
dispatchFakeEvent(rippleTarget.querySelector('.mat-ripple-element')!, 'transitionend');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected ripples to be enabled by default.')
.toBe(1);
// Flush the ripple exit animation.
dispatchFakeEvent(rippleTarget.querySelector('.mat-ripple-element')!, 'transitionend');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected ripples to go away.')
.toBe(0);
fixture.componentInstance.disableListRipple = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected no ripples after list ripples are disabled.')
.toBe(0);
}));
it('should be able to disable a single list item', () => {
const fixture = TestBed.createComponent(ListWithDisabledItems);
const listItems: HTMLElement[] = Array.from(
fixture.nativeElement.querySelectorAll('mat-list-item'),
);
fixture.detectChanges();
expect(
listItems.map(item => {
return item.classList.contains('mdc-list-item--disabled');
}),
).toEqual([false, false, false]);
fixture.componentInstance.firstItemDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(
listItems.map(item => {
return item.classList.contains('mdc-list-item--disabled');
}),
).toEqual([true, false, false]);
});
it('should be able to disable the entire list', () => {
const fixture = TestBed.createComponent(ListWithDisabledItems);
const listItems: HTMLElement[] = Array.from(
fixture.nativeElement.querySelectorAll('mat-list-item'),
);
fixture.detectChanges();
expect(listItems.every(item => item.classList.contains('mdc-list-item--disabled'))).toBe(false);
fixture.componentInstance.listDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(listItems.every(item => item.classList.contains('mdc-list-item--disabled'))).toBe(true);
});
it('should allow a list item outside of a list', () => {
expect(() => {
const fixture = TestBed.createComponent(StandaloneListItem);
fixture.detectChanges();
}).not.toThrow();
});
it('should be able to disable and enable the entire action list', () => {
const fixture = TestBed.createComponent(ActionListWithDisabledList);
const listItems: HTMLElement[] = Array.from(
fixture.nativeElement.querySelectorAll('[mat-list-item]'),
);
fixture.detectChanges();
expect(listItems.every(listItem => listItem.hasAttribute('disabled'))).toBe(true);
fixture.componentInstance.disableList = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(listItems.every(listItem => !listItem.hasAttribute('disabled'))).toBe(true);
});
it('should be able to disable and enable button item', () => {
const fixture = TestBed.createComponent(ActionListWithDisabledItem);
const buttonItem: HTMLButtonElement = fixture.nativeElement.querySelector('[mat-list-item]');
fixture.detectChanges();
expect(buttonItem.hasAttribute('disabled')).toBe(true);
fixture.componentInstance.buttonItem.disabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonItem.hasAttribute('disabled')).toBe(false);
});
});
class BaseTestList {
items: any[] = [
{'name': 'Paprika', 'description': 'A seasoning'},
{'name': 'Pepper', 'description': 'Another seasoning'},
];
showThirdLine: boolean = false;
}
@Component({
template: `
<mat-list>
<a mat-list-item>
Paprika
</a>
</mat-list>`,
standalone: true,
imports: [MatListModule],
})
class ListWithOneAnchorItem extends BaseTestList {
// This needs to be declared directly on the class; if declared on the BaseTestList superclass,
// it doesn't get populated.
@ViewChildren(MatListItem) listItems: QueryList<MatListItem>;
}
@Component({
template: `
<mat-nav-list [disableRipple]="disableListRipple">
<a mat-list-item [disableRipple]="disableItemRipple">
Paprika
</a>
</mat-nav-list>`,
standalone: true,
imports: [MatListModule],
})
class NavListWithOneAnchorItem extends BaseTestList {
@ViewChildren(MatListItem) listItems: QueryList<MatListItem>;
disableItemRipple: boolean = false;
disableListRipple: boolean = false;
}
@Component({
template: `
<mat-nav-list [disableRipple]="disableListRipple">
@for (item of items; track item; let index = $index) {
<a mat-list-item [disableRipple]="disableItemRipple"
[activated]="index === activatedIndex">
{{item.name}}
</a>
}
</mat-nav-list>`,
standalone: true,
imports: [MatListModule],
})
class NavListWithActivatedItem extends BaseTestList {
@ViewChildren(MatListItem) listItems: QueryList<MatListItem>;
disableItemRipple: boolean = false;
disableListRipple: boolean = false;
/** Index of the activated list item in `this.items`. Set to -1 if no item is selected. */
activatedIndex = 1;
}
@Component({
template: `
<mat-action-list [disableRipple]="disableListRipple">
<button mat-list-item [disableRipple]="disableItemRipple">
Paprika
</button>
</mat-action-list>`,
standalone: true,
imports: [MatListModule],
})
class ActionListWithoutType extends BaseTestList {
@ViewChildren(MatListItem) listItems: QueryList<MatListItem>;
disableListRipple = false;
disableItemRipple = false;
}
@Component({
template: `
<mat-action-list>
<button mat-list-item type="submit">
Paprika
</button>
</mat-action-list>`,
standalone: true,
imports: [MatListModule],
})
class ActionListWithType extends BaseTestList {
@ViewChildren(MatListItem) listItems: QueryList<MatListItem>;
}
@Component({
template: `
<mat-action-list [disabled]="disableList">
@for (item of items; track item) {
<button mat-list-item>{{item.name}}</button>
}
</mat-action-list>`,
standalone: true,
imports: [MatListModule],
})
class ActionListWithDisabledList extends BaseTestList {
disableList = true;
} | {
"end_byte": 18840,
"start_byte": 10123,
"url": "https://github.com/angular/components/blob/main/src/material/list/list.spec.ts"
} |
components/src/material/list/list.spec.ts_18842_22030 | @Component({
template: `
<mat-action-list>
<button mat-list-item [disabled]="disableItem">
Paprika
</button>
</mat-action-list>`,
standalone: true,
imports: [MatListModule],
})
class ActionListWithDisabledItem extends BaseTestList {
@ViewChild(MatListItem) buttonItem: MatListItem;
disableItem = true;
}
@Component({
template: `
<mat-list>
<mat-list-item>
Paprika
</mat-list-item>
</mat-list>`,
standalone: true,
imports: [MatListModule],
})
class ListWithOneItem extends BaseTestList {}
@Component({
template: `
<mat-list>
@for (item of items; track item) {
<mat-list-item>
<img src="">
<h3 matListItemTitle>{{item.name}}</h3>
<p matListItemLine>{{item.description}}</p>
</mat-list-item>
}
</mat-list>`,
standalone: true,
imports: [MatListModule],
})
class ListWithTwoLineItem extends BaseTestList {}
@Component({
template: `
<mat-list>
@for (item of items; track item) {
<mat-list-item>
<h3 matListItemTitle>{{item.name}}</h3>
<p matListItemLine>{{item.description}}</p>
<p matListItemLine>Some other text</p>
</mat-list-item>
}
</mat-list>`,
standalone: true,
imports: [MatListModule],
})
class ListWithThreeLineItem extends BaseTestList {}
@Component({
template: `
<mat-list>
<mat-list-item>
<img src="" matListItemAvatar>
Paprika
</mat-list-item>
<mat-list-item>
Pepper
</mat-list-item>
</mat-list>`,
standalone: true,
imports: [MatListModule],
})
class ListWithAvatar extends BaseTestList {}
@Component({
template: `
<mat-list>
@for (item of items; track item) {
<mat-list-item class="test-class">
<h3 matListItemTitle>{{item.name}}</h3>
<p matListItemLine>{{item.description}}</p>
</mat-list-item>
}
</mat-list>`,
standalone: true,
imports: [MatListModule],
})
class ListWithItemWithCssClass extends BaseTestList {}
@Component({
template: `
<mat-list>
@for (item of items; track item) {
<mat-list-item>
<h3 matListItemTitle>{{item.name}}</h3>
<p matListItemLine>{{item.description}}</p>
@if (showThirdLine) {
<p matListItemLine>Some other text</p>
}
</mat-list-item>
}
</mat-list>`,
standalone: true,
imports: [MatListModule],
})
class ListWithDynamicNumberOfLines extends BaseTestList {}
@Component({
template: `
<mat-list>
@for (item of items; track item) {
<mat-list-item>{{item.name}}</mat-list-item>
}
</mat-list>`,
standalone: true,
imports: [MatListModule],
})
class ListWithMultipleItems extends BaseTestList {}
@Component({
template: `
<mat-list [disabled]="listDisabled">
<mat-list-item [disabled]="firstItemDisabled">One</mat-list-item>
<mat-list-item>Two</mat-list-item>
<mat-list-item>Three</mat-list-item>
</mat-list>`,
standalone: true,
imports: [MatListModule],
})
class ListWithDisabledItems {
firstItemDisabled = false;
listDisabled = false;
}
@Component({
template: `<mat-list-item></mat-list-item>`,
standalone: true,
imports: [MatListModule],
})
class StandaloneListItem {} | {
"end_byte": 22030,
"start_byte": 18842,
"url": "https://github.com/angular/components/blob/main/src/material/list/list.spec.ts"
} |
components/src/material/list/list-option.html_0_3105 | <!--
Save icons and the pseudo checkbox/radio so that they can be re-used in the template without
duplication. Also content can only be injected once so we need to extract icons/avatars
into a template since we use it in multiple places.
-->
<ng-template #icons>
<ng-content select="[matListItemAvatar],[matListItemIcon]">
</ng-content>
</ng-template>
<ng-template #checkbox>
<div class="mdc-checkbox" [class.mdc-checkbox--disabled]="disabled">
<input type="checkbox" class="mdc-checkbox__native-control"
[checked]="selected" [disabled]="disabled"/>
<div class="mdc-checkbox__background">
<svg class="mdc-checkbox__checkmark"
viewBox="0 0 24 24"
aria-hidden="true">
<path class="mdc-checkbox__checkmark-path"
fill="none"
d="M1.73,12.91 8.1,19.28 22.79,4.59"/>
</svg>
<div class="mdc-checkbox__mixedmark"></div>
</div>
</div>
</ng-template>
<ng-template #radio>
<div class="mdc-radio" [class.mdc-radio--disabled]="disabled">
<input type="radio" class="mdc-radio__native-control"
[checked]="selected" [disabled]="disabled"/>
<div class="mdc-radio__background">
<div class="mdc-radio__outer-circle"></div>
<div class="mdc-radio__inner-circle"></div>
</div>
</div>
</ng-template>
@if (_hasCheckboxAt('before')) {
<!-- Container for the checkbox at start. -->
<span class="mdc-list-item__start mat-mdc-list-option-checkbox-before">
<ng-template [ngTemplateOutlet]="checkbox"></ng-template>
</span>
} @else if (_hasRadioAt('before')) {
<!-- Container for the radio at the start. -->
<span class="mdc-list-item__start mat-mdc-list-option-radio-before">
<ng-template [ngTemplateOutlet]="radio"></ng-template>
</span>
}
<!-- Conditionally renders icons/avatars before the list item text. -->
@if (_hasIconsOrAvatarsAt('before')) {
<ng-template [ngTemplateOutlet]="icons"></ng-template>
}
<!-- Text -->
<span class="mdc-list-item__content">
<ng-content select="[matListItemTitle]"></ng-content>
<ng-content select="[matListItemLine]"></ng-content>
<span #unscopedContent class="mat-mdc-list-item-unscoped-content"
(cdkObserveContent)="_updateItemLines(true)">
<ng-content></ng-content>
</span>
</span>
@if (_hasCheckboxAt('after')) {
<!-- Container for the checkbox at the end. -->
<span class="mdc-list-item__end">
<ng-template [ngTemplateOutlet]="checkbox"></ng-template>
</span>
} @else if (_hasRadioAt('after')) {
<!-- Container for the radio at the end. -->
<span class="mdc-list-item__end">
<ng-template [ngTemplateOutlet]="radio"></ng-template>
</span>
}
<!-- Conditionally renders icons/avatars after the list item text. -->
@if (_hasIconsOrAvatarsAt('after')) {
<ng-template [ngTemplateOutlet]="icons"></ng-template>
}
<!-- Divider -->
<ng-content select="mat-divider"></ng-content>
<!--
Strong focus indicator element. MDC uses the `::before` pseudo element for the default
focus/hover/selected state, so we need a separate element.
-->
<div class="mat-focus-indicator"></div>
| {
"end_byte": 3105,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/list/list-option.html"
} |
components/src/material/list/testing/public-api.ts_0_492 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './action-list-harness';
export * from './list-harness';
export * from './list-harness-filters';
export * from './nav-list-harness';
export * from './selection-list-harness';
export {MatListItemSection, MatSubheaderHarness, MatListItemType} from './list-item-harness-base';
| {
"end_byte": 492,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/public-api.ts"
} |
components/src/material/list/testing/action-list-harness.ts_0_2700 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ComponentHarnessConstructor, HarnessPredicate} from '@angular/cdk/testing';
import {MatListHarnessBase} from './list-harness-base';
import {ActionListHarnessFilters, ActionListItemHarnessFilters} from './list-harness-filters';
import {getListItemPredicate, MatListItemHarnessBase} from './list-item-harness-base';
/** Harness for interacting with a action-list in tests. */
export class MatActionListHarness extends MatListHarnessBase<
typeof MatActionListItemHarness,
MatActionListItemHarness,
ActionListItemHarnessFilters
> {
/** The selector for the host element of a `MatActionList` instance. */
static hostSelector = '.mat-mdc-action-list';
/**
* Gets a `HarnessPredicate` that can be used to search for an action list with specific
* attributes.
* @param options Options for filtering which action list instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatActionListHarness>(
this: ComponentHarnessConstructor<T>,
options: ActionListHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options);
}
override _itemHarness = MatActionListItemHarness;
}
/** Harness for interacting with an action list item. */
export class MatActionListItemHarness extends MatListItemHarnessBase {
/** The selector for the host element of a `MatListItem` instance. */
static hostSelector = `${MatActionListHarness.hostSelector} .mat-mdc-list-item`;
/**
* Gets a `HarnessPredicate` that can be used to search for a list item with specific
* attributes.
* @param options Options for filtering which action list item instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatActionListItemHarness>(
this: ComponentHarnessConstructor<T>,
options: ActionListItemHarnessFilters = {},
): HarnessPredicate<T> {
return getListItemPredicate(this, options);
}
/** Clicks on the action list item. */
async click(): Promise<void> {
return (await this.host()).click();
}
/** Focuses the action list item. */
async focus(): Promise<void> {
return (await this.host()).focus();
}
/** Blurs the action list item. */
async blur(): Promise<void> {
return (await this.host()).blur();
}
/** Whether the action list item is focused. */
async isFocused(): Promise<boolean> {
return (await this.host()).isFocused();
}
}
| {
"end_byte": 2700,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/action-list-harness.ts"
} |
components/src/material/list/testing/list-harness-base.ts_0_6808 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ComponentHarness,
ComponentHarnessConstructor,
HarnessPredicate,
parallel,
} from '@angular/cdk/testing';
import {DividerHarnessFilters, MatDividerHarness} from '@angular/material/divider/testing';
import {BaseListItemHarnessFilters, SubheaderHarnessFilters} from './list-harness-filters';
import {MatSubheaderHarness} from './list-item-harness-base';
/** Represents a section of a list falling under a specific header. */
export interface ListSection<I> {
/** The heading for this list section. `undefined` if there is no heading. */
heading?: string;
/** The items in this list section. */
items: I[];
}
/**
* Shared behavior among the harnesses for the various `MatList` flavors.
* @template T A constructor type for a list item harness type used by this list harness.
* @template C The list item harness type that `T` constructs.
* @template F The filter type used filter list item harness of type `C`.
* @docs-private
*/
export abstract class MatListHarnessBase<
T extends ComponentHarnessConstructor<C> & {with: (options?: F) => HarnessPredicate<C>},
C extends ComponentHarness,
F extends BaseListItemHarnessFilters,
> extends ComponentHarness {
protected _itemHarness: T;
/**
* Gets a list of harnesses representing the items in this list.
* @param filters Optional filters used to narrow which harnesses are included
* @return The list of items matching the given filters.
*/
async getItems(filters?: F): Promise<C[]> {
return this.locatorForAll(this._itemHarness.with(filters))();
}
/**
* Gets a list of `ListSection` representing the list items grouped by subheaders. If the list has
* no subheaders it is represented as a single `ListSection` with an undefined `heading` property.
* @param filters Optional filters used to narrow which list item harnesses are included
* @return The list of items matching the given filters, grouped into sections by subheader.
*/
async getItemsGroupedBySubheader(filters?: F): Promise<ListSection<C>[]> {
type Section = {items: C[]; heading?: Promise<string>};
const listSections: Section[] = [];
let currentSection: Section = {items: []};
const itemsAndSubheaders = await this.getItemsWithSubheadersAndDividers({
item: filters,
divider: false,
});
for (const itemOrSubheader of itemsAndSubheaders) {
if (itemOrSubheader instanceof MatSubheaderHarness) {
if (currentSection.heading !== undefined || currentSection.items.length) {
listSections.push(currentSection);
}
currentSection = {heading: itemOrSubheader.getText(), items: []};
} else {
currentSection.items.push(itemOrSubheader);
}
}
if (
currentSection.heading !== undefined ||
currentSection.items.length ||
!listSections.length
) {
listSections.push(currentSection);
}
// Concurrently wait for all sections to resolve their heading if present.
return parallel(() =>
listSections.map(async s => ({items: s.items, heading: await s.heading})),
);
}
/**
* Gets a list of sub-lists representing the list items grouped by dividers. If the list has no
* dividers it is represented as a list with a single sub-list.
* @param filters Optional filters used to narrow which list item harnesses are included
* @return The list of items matching the given filters, grouped into sub-lists by divider.
*/
async getItemsGroupedByDividers(filters?: F): Promise<C[][]> {
const listSections: C[][] = [[]];
const itemsAndDividers = await this.getItemsWithSubheadersAndDividers({
item: filters,
subheader: false,
});
for (const itemOrDivider of itemsAndDividers) {
if (itemOrDivider instanceof MatDividerHarness) {
listSections.push([]);
} else {
listSections[listSections.length - 1].push(itemOrDivider);
}
}
return listSections;
}
/**
* Gets a list of harnesses representing all of the items, subheaders, and dividers
* (in the order they appear in the list). Use `instanceof` to check which type of harness a given
* item is.
* @param filters Optional filters used to narrow which list items, subheaders, and dividers are
* included. A value of `false` for the `item`, `subheader`, or `divider` properties indicates
* that the respective harness type should be omitted completely.
* @return The list of harnesses representing the items, subheaders, and dividers matching the
* given filters.
*/
getItemsWithSubheadersAndDividers(filters: {
item: false;
subheader: false;
divider: false;
}): Promise<[]>;
getItemsWithSubheadersAndDividers(filters: {
item?: F | false;
subheader: false;
divider: false;
}): Promise<C[]>;
getItemsWithSubheadersAndDividers(filters: {
item: false;
subheader?: SubheaderHarnessFilters | false;
divider: false;
}): Promise<MatSubheaderHarness[]>;
getItemsWithSubheadersAndDividers(filters: {
item: false;
subheader: false;
divider?: DividerHarnessFilters | false;
}): Promise<MatDividerHarness[]>;
getItemsWithSubheadersAndDividers(filters: {
item?: F | false;
subheader?: SubheaderHarnessFilters | false;
divider: false;
}): Promise<(C | MatSubheaderHarness)[]>;
getItemsWithSubheadersAndDividers(filters: {
item?: F | false;
subheader: false;
divider?: false | DividerHarnessFilters;
}): Promise<(C | MatDividerHarness)[]>;
getItemsWithSubheadersAndDividers(filters: {
item: false;
subheader?: false | SubheaderHarnessFilters;
divider?: false | DividerHarnessFilters;
}): Promise<(MatSubheaderHarness | MatDividerHarness)[]>;
getItemsWithSubheadersAndDividers(filters?: {
item?: F | false;
subheader?: SubheaderHarnessFilters | false;
divider?: DividerHarnessFilters | false;
}): Promise<(C | MatSubheaderHarness | MatDividerHarness)[]>;
async getItemsWithSubheadersAndDividers(
filters: {
item?: F | false;
subheader?: SubheaderHarnessFilters | false;
divider?: DividerHarnessFilters | false;
} = {},
): Promise<(C | MatSubheaderHarness | MatDividerHarness)[]> {
const query = [];
if (filters.item !== false) {
query.push(this._itemHarness.with(filters.item || ({} as F)));
}
if (filters.subheader !== false) {
query.push(MatSubheaderHarness.with(filters.subheader));
}
if (filters.divider !== false) {
query.push(MatDividerHarness.with(filters.divider));
}
return this.locatorForAll(...query)();
}
}
| {
"end_byte": 6808,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/list-harness-base.ts"
} |
components/src/material/list/testing/list-harness.spec.ts_0_1596 | import {
BaseHarnessFilters,
ComponentHarness,
ComponentHarnessConstructor,
HarnessPredicate,
parallel,
} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component, Type, WritableSignal, signal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MatDividerHarness} from '@angular/material/divider/testing';
import {MatListModule} from '@angular/material/list';
import {MatActionListHarness, MatActionListItemHarness} from './action-list-harness';
import {MatListHarness, MatListItemHarness} from './list-harness';
import {
MatListItemHarnessBase,
MatListItemSection,
MatSubheaderHarness,
} from './list-item-harness-base';
import {MatNavListHarness, MatNavListItemHarness} from './nav-list-harness';
import {MatListOptionHarness, MatSelectionListHarness} from './selection-list-harness';
import {MatListHarnessBase} from './list-harness-base';
import {BaseListItemHarnessFilters} from './list-harness-filters';
/** Tests that apply to all types of the MDC-based mat-list. */
function runBaseListFunctionalityTests<
L extends MatListHarnessBase<
ComponentHarnessConstructor<I> & {with: (x?: any) => HarnessPredicate<I>},
I,
BaseListItemHarnessFilters
>,
I extends MatListItemHarnessBase,
F extends {disableThirdItem: WritableSignal<boolean>},
>(
testComponentFn: () => Type<F>,
listHarness: ComponentHarnessConstructor<L> & {
with: (config?: BaseHarnessFilters) => HarnessPredicate<L>;
},
listItemHarnessBase: ComponentHarnessConstructor<I>,
) | {
"end_byte": 1596,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/list-harness.spec.ts"
} |
components/src/material/list/testing/list-harness.spec.ts_1597_10023 | {
describe('base list functionality', () => {
let simpleListHarness: L;
let emptyListHarness: L;
let fixture: ComponentFixture<F>;
beforeEach(async () => {
const testComponent = testComponentFn();
TestBed.configureTestingModule({
imports: [MatListModule, testComponent],
});
fixture = TestBed.createComponent(testComponent);
fixture.detectChanges();
const loader = TestbedHarnessEnvironment.loader(fixture);
simpleListHarness = await loader.getHarness(
listHarness.with({selector: '.test-base-list-functionality'}),
);
emptyListHarness = await loader.getHarness(listHarness.with({selector: '.test-empty'}));
});
it('should get all items', async () => {
const items = await simpleListHarness.getItems();
expect(await parallel(() => items.map(i => i.getFullText()))).toEqual([
'Item 1',
'Item 2',
'Item 3',
jasmine.stringMatching(/^Title/),
jasmine.stringMatching(/^Item 5/),
]);
});
it('should get all items matching full text (deprecated filter)', async () => {
const items = await simpleListHarness.getItems({text: /[13]/});
expect(await parallel(() => items.map(i => i.getText()))).toEqual(['Item 1', 'Item 3']);
});
it('should get all items matching full text', async () => {
const items = await simpleListHarness.getItems({fullText: /[13]/});
expect(await parallel(() => items.map(i => i.getFullText()))).toEqual(['Item 1', 'Item 3']);
});
it('should get all items matching title', async () => {
const items = await simpleListHarness.getItems({title: 'Title'});
expect(await parallel(() => items.map(i => i.getTitle()))).toEqual(['Title']);
});
it('should get all items matching secondary text', async () => {
const items = await simpleListHarness.getItems({secondaryText: 'Secondary Text'});
expect(await parallel(() => items.map(i => i.getSecondaryText()))).toEqual([
'Secondary Text',
]);
const itemsWithoutSecondaryText = await simpleListHarness.getItems({secondaryText: null});
expect(await parallel(() => itemsWithoutSecondaryText.map(i => i.getFullText()))).toEqual([
'Item 2',
'Item 3',
]);
});
it('should get all items matching tertiary text', async () => {
const items = await simpleListHarness.getItems({tertiaryText: 'Tertiary Text'});
expect(await parallel(() => items.map(i => i.getTertiaryText()))).toEqual(['Tertiary Text']);
const itemsWithoutTertiaryText = await simpleListHarness.getItems({tertiaryText: null});
expect(await parallel(() => itemsWithoutTertiaryText.map(i => i.getFullText()))).toEqual([
'Item 1',
'Item 2',
'Item 3',
'TitleText that will wrap into the third line.',
]);
});
it('should get all items of empty list', async () => {
expect((await emptyListHarness.getItems()).length).toBe(0);
});
it('should get items by subheader', async () => {
const sections = await simpleListHarness.getItemsGroupedBySubheader();
expect(sections.length).toBe(4);
expect(sections[0].heading).toBeUndefined();
expect(await parallel(() => sections[0].items.map(i => i.getFullText()))).toEqual(['Item 1']);
expect(sections[1].heading).toBe('Section 1');
expect(await parallel(() => sections[1].items.map(i => i.getFullText()))).toEqual([
'Item 2',
'Item 3',
]);
expect(sections[2].heading).toBe('Section 2');
expect(await parallel(() => sections[2].items.map(i => i.getFullText()))).toEqual([
jasmine.stringMatching(/^Title/),
jasmine.stringMatching(/^Item 5/),
]);
expect(sections[3].heading).toBe('Section 3');
expect(sections[3].items.length).toBe(0);
});
it('should get items by subheader for an empty list', async () => {
const sections = await emptyListHarness.getItemsGroupedBySubheader();
expect(sections.length).toBe(1);
expect(sections[0].heading).toBeUndefined();
expect(sections[0].items.length).toBe(0);
});
it('should get items grouped by divider', async () => {
const sections = await simpleListHarness.getItemsGroupedByDividers();
expect(sections.length).toBe(3);
expect(await parallel(() => sections[0].map(i => i.getFullText()))).toEqual(['Item 1']);
expect(await parallel(() => sections[1].map(i => i.getFullText()))).toEqual([
'Item 2',
'Item 3',
]);
expect(sections[2].length).toBe(2);
});
it('should get items grouped by divider for an empty list', async () => {
const sections = await emptyListHarness.getItemsGroupedByDividers();
expect(sections.length).toBe(1);
expect(sections[0].length).toBe(0);
});
it('should get all items, subheaders, and dividers', async () => {
const itemsSubheadersAndDividers =
await simpleListHarness.getItemsWithSubheadersAndDividers();
expect(itemsSubheadersAndDividers.length).toBe(10);
expect(itemsSubheadersAndDividers[0] instanceof listItemHarnessBase).toBe(true);
expect(await (itemsSubheadersAndDividers[0] as MatListItemHarnessBase).getFullText()).toBe(
'Item 1',
);
expect(itemsSubheadersAndDividers[1] instanceof MatSubheaderHarness).toBe(true);
expect(await (itemsSubheadersAndDividers[1] as MatSubheaderHarness).getText()).toBe(
'Section 1',
);
expect(itemsSubheadersAndDividers[2] instanceof MatDividerHarness).toBe(true);
expect(itemsSubheadersAndDividers[3] instanceof listItemHarnessBase).toBe(true);
expect(await (itemsSubheadersAndDividers[3] as MatListItemHarnessBase).getFullText()).toBe(
'Item 2',
);
expect(itemsSubheadersAndDividers[4] instanceof listItemHarnessBase).toBe(true);
expect(await (itemsSubheadersAndDividers[4] as MatListItemHarnessBase).getFullText()).toBe(
'Item 3',
);
expect(itemsSubheadersAndDividers[5] instanceof MatSubheaderHarness).toBe(true);
expect(await (itemsSubheadersAndDividers[5] as MatSubheaderHarness).getText()).toBe(
'Section 2',
);
expect(itemsSubheadersAndDividers[6] instanceof MatDividerHarness).toBe(true);
expect(await (itemsSubheadersAndDividers[9] as MatSubheaderHarness).getText()).toBe(
'Section 3',
);
});
it('should get all items, subheaders, and dividers excluding some harness types', async () => {
const items = await simpleListHarness.getItemsWithSubheadersAndDividers({
subheader: false,
divider: false,
});
const subheaders = await simpleListHarness.getItemsWithSubheadersAndDividers({
item: false,
divider: false,
});
const dividers = await simpleListHarness.getItemsWithSubheadersAndDividers({
item: false,
subheader: false,
});
expect(await parallel(() => items.map(i => i.getFullText()))).toEqual([
'Item 1',
'Item 2',
'Item 3',
'TitleText that will wrap into the third line.',
'Item 5Secondary TextTertiary Text',
]);
expect(await parallel(() => subheaders.map(s => s.getText()))).toEqual([
'Section 1',
'Section 2',
'Section 3',
]);
expect(await parallel(() => dividers.map(d => d.getOrientation()))).toEqual([
'horizontal',
'horizontal',
]);
});
it('should get all items, subheaders, and dividers with filters', async () => {
const itemsSubheadersAndDividers = await simpleListHarness.getItemsWithSubheadersAndDividers({
item: {fullText: /1/},
subheader: {text: /2/},
});
expect(itemsSubheadersAndDividers.length).toBe(4);
expect(itemsSubheadersAndDividers[0] instanceof listItemHarnessBase).toBe(true);
expect(await (itemsSubheadersAndDividers[0] as MatListItemHarnessBase).getFullText()).toBe(
'Item 1',
);
expect(itemsSubheadersAndDividers[1] instanceof MatDividerHarness).toBe(true);
expect(itemsSubheadersAndDividers[2] instanceof MatSubheaderHarness).toBe(true);
expect(await (itemsSubheadersAndDividers[2] as MatSubheaderHarness).getText()).toBe(
'Section 2',
);
expect(itemsSubheadersAndDividers[3] instanceof MatDividerHarness).toBe(true);
}); | {
"end_byte": 10023,
"start_byte": 1597,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/list-harness.spec.ts"
} |
components/src/material/list/testing/list-harness.spec.ts_10029_16697 | it('should get list item text, title, secondary and tertiary text', async () => {
const items = await simpleListHarness.getItems();
expect(items.length).toBe(5);
expect(await items[0].getFullText()).toBe('Item 1');
expect(await items[0].getTitle()).toBe('Item');
expect(await items[0].getSecondaryText()).toBe('1');
expect(await items[0].getTertiaryText()).toBe(null);
expect(await items[1].getFullText()).toBe('Item 2');
expect(await items[1].getTitle()).toBe('Item 2');
expect(await items[1].getSecondaryText()).toBe(null);
expect(await items[1].getTertiaryText()).toBe(null);
expect(await items[2].getFullText()).toBe('Item 3');
expect(await items[2].getTitle()).toBe('Item 3');
expect(await items[2].getSecondaryText()).toBe(null);
expect(await items[2].getTertiaryText()).toBe(null);
expect(await items[3].getFullText()).toBe('TitleText that will wrap into the third line.');
expect(await items[3].getTitle()).toBe('Title');
expect(await items[3].getSecondaryText()).toBe('Text that will wrap into the third line.');
expect(await items[3].getTertiaryText()).toBe(null);
expect(await items[4].getFullText()).toBe('Item 5Secondary TextTertiary Text');
expect(await items[4].getTitle()).toBe('Item 5');
expect(await items[4].getSecondaryText()).toBe('Secondary Text');
expect(await items[4].getTertiaryText()).toBe('Tertiary Text');
});
it('should check list item icons and avatars', async () => {
const items = await simpleListHarness.getItems();
expect(items.length).toBe(5);
expect(await items[0].hasIcon()).toBe(true);
expect(await items[0].hasAvatar()).toBe(true);
expect(await items[1].hasIcon()).toBe(false);
expect(await items[1].hasAvatar()).toBe(false);
expect(await items[2].hasIcon()).toBe(false);
expect(await items[2].hasAvatar()).toBe(false);
expect(await items[3].hasIcon()).toBe(false);
expect(await items[3].hasAvatar()).toBe(false);
expect(await items[4].hasIcon()).toBe(false);
expect(await items[4].hasAvatar()).toBe(false);
});
it('should get harness loader for list item content', async () => {
const items = await simpleListHarness.getItems();
expect(items.length).toBe(5);
const childHarness = await items[1].getHarness(TestItemContentHarness);
expect(childHarness).not.toBeNull();
});
it('should be able to get content harness loader of list item', async () => {
const items = await simpleListHarness.getItems();
expect(items.length).toBe(5);
const loader = await items[1].getChildLoader(MatListItemSection.CONTENT);
await expectAsync(loader.getHarness(TestItemContentHarness)).toBeResolved();
});
it('should check disabled state of items', async () => {
fixture.componentInstance.disableThirdItem.set(true);
const items = await simpleListHarness.getItems();
expect(items.length).toBe(5);
expect(await items[0].isDisabled()).toBe(false);
expect(await items[2].isDisabled()).toBe(true);
});
});
}
describe('MatListHarness', () => {
runBaseListFunctionalityTests(() => ListHarnessTest, MatListHarness, MatListItemHarness);
});
describe('MatActionListHarness', () => {
runBaseListFunctionalityTests(
() => ActionListHarnessTest,
MatActionListHarness,
MatActionListItemHarness,
);
describe('additional functionality', () => {
let harness: MatActionListHarness;
let fixture: ComponentFixture<ActionListHarnessTest>;
beforeEach(async () => {
TestBed.configureTestingModule({
imports: [MatListModule, ActionListHarnessTest],
});
fixture = TestBed.createComponent(ActionListHarnessTest);
fixture.detectChanges();
const loader = TestbedHarnessEnvironment.loader(fixture);
harness = await loader.getHarness(
MatActionListHarness.with({selector: '.test-base-list-functionality'}),
);
});
it('should click items', async () => {
const items = await harness.getItems();
expect(items.length).toBe(5);
await items[0].click();
expect(fixture.componentInstance.lastClicked).toBe('Item 1');
await items[1].click();
expect(fixture.componentInstance.lastClicked).toBe('Item 2');
await items[2].click();
expect(fixture.componentInstance.lastClicked).toBe('Item 3');
});
});
});
describe('MatNavListHarness', () => {
runBaseListFunctionalityTests(() => NavListHarnessTest, MatNavListHarness, MatNavListItemHarness);
describe('additional functionality', () => {
let harness: MatNavListHarness;
let fixture: ComponentFixture<NavListHarnessTest>;
beforeEach(async () => {
TestBed.configureTestingModule({
imports: [MatListModule, NavListHarnessTest],
});
fixture = TestBed.createComponent(NavListHarnessTest);
fixture.detectChanges();
const loader = TestbedHarnessEnvironment.loader(fixture);
harness = await loader.getHarness(
MatNavListHarness.with({selector: '.test-base-list-functionality'}),
);
});
it('should click items', async () => {
const items = await harness.getItems();
expect(items.length).toBe(5);
await items[0].click();
expect(fixture.componentInstance.lastClicked).toBe('Item 1');
await items[1].click();
expect(fixture.componentInstance.lastClicked).toBe('Item 2');
await items[2].click();
expect(fixture.componentInstance.lastClicked).toBe('Item 3');
});
it('should get href', async () => {
const items = await harness.getItems();
expect(await parallel(() => items.map(i => i.getHref()))).toEqual([
null,
'',
'/somestuff',
null,
null,
]);
});
it('should get item harness by href', async () => {
const items = await harness.getItems({href: /stuff/});
expect(items.length).toBe(1);
expect(await items[0].getHref()).toBe('/somestuff');
});
it('should get activated state', async () => {
const items = await harness.getItems();
const activated = await parallel(() => items.map(item => item.isActivated()));
expect(activated).toEqual([false, true, false, false, false]);
});
it('should get item harness by activated state', async () => {
const activatedItems = await harness.getItems({activated: true});
const activatedItemsText = await parallel(() =>
activatedItems.map(item => item.getFullText()),
);
expect(activatedItemsText).toEqual(['Item 2']);
});
});
}); | {
"end_byte": 16697,
"start_byte": 10029,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/list-harness.spec.ts"
} |
components/src/material/list/testing/list-harness.spec.ts_16699_24638 | describe('MatSelectionListHarness', () => {
runBaseListFunctionalityTests(
() => SelectionListHarnessTest,
MatSelectionListHarness,
MatListOptionHarness,
);
describe('additional functionality', () => {
let harness: MatSelectionListHarness;
let emptyHarness: MatSelectionListHarness;
let fixture: ComponentFixture<SelectionListHarnessTest>;
beforeEach(async () => {
TestBed.configureTestingModule({
imports: [MatListModule, SelectionListHarnessTest],
});
fixture = TestBed.createComponent(SelectionListHarnessTest);
fixture.detectChanges();
const loader = TestbedHarnessEnvironment.loader(fixture);
harness = await loader.getHarness(
MatSelectionListHarness.with({selector: '.test-base-list-functionality'}),
);
emptyHarness = await loader.getHarness(
MatSelectionListHarness.with({selector: '.test-empty'}),
);
});
it('should check disabled state of list', async () => {
expect(await harness.isDisabled()).toBe(false);
expect(await emptyHarness.isDisabled()).toBe(true);
});
it('should get all selected options', async () => {
expect((await harness.getItems({selected: true})).length).toBe(0);
const items = await harness.getItems();
await parallel(() => items.map(item => item.select()));
expect((await harness.getItems({selected: true})).length).toBe(5);
});
it('should check multiple options', async () => {
expect((await harness.getItems({selected: true})).length).toBe(0);
await harness.selectItems({fullText: /1/}, {fullText: /3/});
const selected = await harness.getItems({selected: true});
expect(await parallel(() => selected.map(item => item.getFullText()))).toEqual([
'Item 1',
'Item 3',
]);
});
it('should uncheck multiple options', async () => {
await harness.selectItems();
expect((await harness.getItems({selected: true})).length).toBe(5);
await harness.deselectItems({fullText: /1/}, {fullText: /3/});
const selected = await harness.getItems({selected: true});
expect(await parallel(() => selected.map(item => item.getFullText()))).toEqual([
'Item 2',
jasmine.stringMatching(/^Title/),
jasmine.stringMatching(/^Item 5/),
]);
});
it('should get option checkbox position', async () => {
const items = await harness.getItems();
expect(items.length).toBe(5);
expect(await items[0].getCheckboxPosition()).toBe('before');
expect(await items[1].getCheckboxPosition()).toBe('after');
});
it('should toggle option selection', async () => {
const items = await harness.getItems();
expect(items.length).toBe(5);
expect(await items[0].isSelected()).toBe(false);
await items[0].toggle();
expect(await items[0].isSelected()).toBe(true);
await items[0].toggle();
expect(await items[0].isSelected()).toBe(false);
});
it('should check single option', async () => {
const items = await harness.getItems();
expect(items.length).toBe(5);
expect(await items[0].isSelected()).toBe(false);
await items[0].select();
expect(await items[0].isSelected()).toBe(true);
await items[0].select();
expect(await items[0].isSelected()).toBe(true);
});
it('should uncheck single option', async () => {
const items = await harness.getItems();
expect(items.length).toBe(5);
await items[0].select();
expect(await items[0].isSelected()).toBe(true);
await items[0].deselect();
expect(await items[0].isSelected()).toBe(false);
await items[0].deselect();
expect(await items[0].isSelected()).toBe(false);
});
});
});
@Component({
template: `
<mat-list class="test-base-list-functionality">
<mat-list-item>
<div matListItemTitle>Item </div>
<div matListItemLine>1</div>
<div matListItemIcon>icon</div>
<div matListItemAvatar>Avatar</div>
</mat-list-item>
<div matSubheader>Section 1</div>
<mat-divider></mat-divider>
<a mat-list-item>
<span class="test-item-content">Item 2</span>
</a>
<button mat-list-item [disabled]="disableThirdItem()">Item 3</button>
<div matSubheader>Section 2</div>
<mat-divider></mat-divider>
<mat-list-item lines="3">
<span matListItemTitle>Title</span>
<span>Text that will wrap into the third line.</span>
</mat-list-item>
<mat-list-item>
<span matListItemTitle>Item 5</span>
<span matListItemLine>Secondary Text</span>
<span matListItemLine>Tertiary Text</span>
</mat-list-item>
<div matSubheader>Section 3</div>
</mat-list>
<mat-list class="test-empty"></mat-list>
`,
standalone: true,
imports: [MatListModule],
})
class ListHarnessTest {
disableThirdItem = signal(false);
}
@Component({
template: `
<mat-action-list class="test-base-list-functionality">
<mat-list-item (click)="lastClicked = 'Item 1'">
<div matListItemTitle>Item </div>
<div matListItemLine>1</div>
<div matListItemIcon>icon</div>
<div matListItemAvatar>Avatar</div>
</mat-list-item>
<div matSubheader>Section 1</div>
<mat-divider></mat-divider>
<a mat-list-item (click)="lastClicked = 'Item 2'">
<span class="test-item-content">Item 2</span>
</a>
<button
mat-list-item
(click)="lastClicked = 'Item 3'"
[disabled]="disableThirdItem()">Item 3</button>
<div matSubheader>Section 2</div>
<mat-divider></mat-divider>
<button mat-list-item lines="3">
<span matListItemTitle>Title</span>
<span>Text that will wrap into the third line.</span>
</button>
<button mat-list-item>
<span matListItemTitle>Item 5</span>
<span matListItemLine>Secondary Text</span>
<span matListItemLine>Tertiary Text</span>
</button>
<div matSubheader>Section 3</div>
</mat-action-list>
<mat-action-list class="test-empty"></mat-action-list>
`,
standalone: true,
imports: [MatListModule],
})
class ActionListHarnessTest {
lastClicked: string;
disableThirdItem = signal(false);
}
@Component({
template: `
<mat-nav-list class="test-base-list-functionality">
<a mat-list-item (click)="onClick($event, 'Item 1')">
<div matListItemTitle>Item </div>
<div matListItemLine>1</div>
<div matListItemIcon>icon</div>
<div matListItemAvatar>Avatar</div>
</a>
<div matSubheader>Section 1</div>
<mat-divider></mat-divider>
<a mat-list-item activated href (click)="onClick($event, 'Item 2')">
<span class="test-item-content">Item 2</span>
</a>
<a
mat-list-item
href="/somestuff"
(click)="onClick($event, 'Item 3')"
[disabled]="disableThirdItem()">Item 3</a>
<div matSubheader>Section 2</div>
<mat-divider></mat-divider>
<a mat-list-item lines="3">
<span matListItemTitle>Title</span>
<span>Text that will wrap into the third line.</span>
</a>
<a mat-list-item>
<span matListItemTitle>Item 5</span>
<span matListItemLine>Secondary Text</span>
<span matListItemLine>Tertiary Text</span>
</a>
<div matSubheader>Section 3</div>
</mat-nav-list>
<mat-nav-list class="test-empty"></mat-nav-list>
`,
standalone: true,
imports: [MatListModule],
})
class NavListHarnessTest {
lastClicked: string;
disableThirdItem = signal(false);
onClick(event: Event, value: string) {
event.preventDefault();
this.lastClicked = value;
}
} | {
"end_byte": 24638,
"start_byte": 16699,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/list-harness.spec.ts"
} |
components/src/material/list/testing/list-harness.spec.ts_24640_26030 | @Component({
template: `
<mat-selection-list class="test-base-list-functionality">
<mat-list-option togglePosition="before">
<div matListItemTitle>Item </div>
<div matListItemLine>1</div>
<div matListItemIcon>icon</div>
<div matListItemAvatar>Avatar</div>
</mat-list-option>
<div matSubheader>Section 1</div>
<mat-divider></mat-divider>
<mat-list-option>
<span class="test-item-content">Item 2</span>
</mat-list-option>
<mat-list-option [disabled]="disableThirdItem()">Item 3</mat-list-option>
<div matSubheader>Section 2</div>
<mat-divider></mat-divider>
<mat-list-option lines="3">
<span matListItemTitle>Title</span>
<span>Text that will wrap into the third line.</span>
</mat-list-option>
<mat-list-option>
<span matListItemTitle>Item 5</span>
<span matListItemLine>Secondary Text</span>
<span matListItemLine>Tertiary Text</span>
</mat-list-option>
<div matSubheader>Section 3</div>
</mat-selection-list>
<mat-selection-list class="test-empty" disabled></mat-selection-list>
`,
standalone: true,
imports: [MatListModule],
})
class SelectionListHarnessTest {
disableThirdItem = signal(false);
}
class TestItemContentHarness extends ComponentHarness {
static hostSelector = '.test-item-content';
} | {
"end_byte": 26030,
"start_byte": 24640,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/list-harness.spec.ts"
} |
components/src/material/list/testing/BUILD.bazel_0_836 | load("//tools:defaults.bzl", "ng_test_library", "ng_web_test_suite", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "testing",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
deps = [
"//src/cdk/coercion",
"//src/cdk/testing",
"//src/material/divider/testing",
"//src/material/list",
],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
ng_test_library(
name = "unit_tests_lib",
srcs = glob(["**/*.spec.ts"]),
deps = [
":testing",
"//src/cdk/testing",
"//src/cdk/testing/testbed",
"//src/material/divider/testing",
"//src/material/list",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":unit_tests_lib",
],
)
| {
"end_byte": 836,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/BUILD.bazel"
} |
components/src/material/list/testing/list-harness.ts_0_2074 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ComponentHarnessConstructor, HarnessPredicate} from '@angular/cdk/testing';
import {MatListHarnessBase} from './list-harness-base';
import {ListHarnessFilters, ListItemHarnessFilters} from './list-harness-filters';
import {getListItemPredicate, MatListItemHarnessBase} from './list-item-harness-base';
/** Harness for interacting with a list in tests. */
export class MatListHarness extends MatListHarnessBase<
typeof MatListItemHarness,
MatListItemHarness,
ListItemHarnessFilters
> {
/** The selector for the host element of a `MatList` instance. */
static hostSelector = '.mat-mdc-list';
/**
* Gets a `HarnessPredicate` that can be used to search for a list with specific attributes.
* @param options Options for filtering which list instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatListHarness>(
this: ComponentHarnessConstructor<T>,
options: ListHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options);
}
override _itemHarness = MatListItemHarness;
}
/** Harness for interacting with a list item. */
export class MatListItemHarness extends MatListItemHarnessBase {
/** The selector for the host element of a `MatListItem` instance. */
static hostSelector = `${MatListHarness.hostSelector} .mat-mdc-list-item`;
/**
* Gets a `HarnessPredicate` that can be used to search for a list item with specific attributes.
* @param options Options for filtering which list item instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatListItemHarness>(
this: ComponentHarnessConstructor<T>,
options: ListItemHarnessFilters = {},
): HarnessPredicate<T> {
return getListItemPredicate(this, options);
}
}
| {
"end_byte": 2074,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/list-harness.ts"
} |
components/src/material/list/testing/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public-api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/index.ts"
} |
components/src/material/list/testing/list-harness-filters.ts_0_1388 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {BaseHarnessFilters} from '@angular/cdk/testing';
export interface ListHarnessFilters extends BaseHarnessFilters {}
export interface ActionListHarnessFilters extends BaseHarnessFilters {}
export interface NavListHarnessFilters extends BaseHarnessFilters {}
export interface SelectionListHarnessFilters extends BaseHarnessFilters {}
export interface BaseListItemHarnessFilters extends BaseHarnessFilters {
title?: string | RegExp;
secondaryText?: string | RegExp | null;
tertiaryText?: string | RegExp | null;
fullText?: string | RegExp;
/**
* @deprecated Use the `fullText` filter instead.
* @breaking-change 16.0.0
*/
text?: string | RegExp;
}
export interface ListItemHarnessFilters extends BaseListItemHarnessFilters {}
export interface ActionListItemHarnessFilters extends BaseListItemHarnessFilters {}
export interface NavListItemHarnessFilters extends BaseListItemHarnessFilters {
href?: string | RegExp | null;
activated?: boolean;
}
export interface ListOptionHarnessFilters extends BaseListItemHarnessFilters {
selected?: boolean;
}
export interface SubheaderHarnessFilters extends BaseHarnessFilters {
text?: string | RegExp;
}
| {
"end_byte": 1388,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/list-harness-filters.ts"
} |
components/src/material/list/testing/list-item-harness-base.ts_0_6804 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ComponentHarness,
ComponentHarnessConstructor,
ContentContainerComponentHarness,
HarnessPredicate,
parallel,
} from '@angular/cdk/testing';
import {BaseListItemHarnessFilters, SubheaderHarnessFilters} from './list-harness-filters';
const iconSelector = '.mat-mdc-list-item-icon';
const avatarSelector = '.mat-mdc-list-item-avatar';
/**
* Gets a `HarnessPredicate` that applies the given `BaseListItemHarnessFilters` to the given
* list item harness.
* @template H The type of list item harness to create a predicate for.
* @param harnessType A constructor for a list item harness.
* @param options An instance of `BaseListItemHarnessFilters` to apply.
* @return A `HarnessPredicate` for the given harness type with the given options applied.
*/
export function getListItemPredicate<H extends MatListItemHarnessBase>(
harnessType: ComponentHarnessConstructor<H>,
options: BaseListItemHarnessFilters,
): HarnessPredicate<H> {
return new HarnessPredicate(harnessType, options)
.addOption('text', options.text, (harness, text) =>
HarnessPredicate.stringMatches(harness.getText(), text),
)
.addOption('fullText', options.fullText, (harness, fullText) =>
HarnessPredicate.stringMatches(harness.getFullText(), fullText),
)
.addOption('title', options.title, (harness, title) =>
HarnessPredicate.stringMatches(harness.getTitle(), title),
)
.addOption('secondaryText', options.secondaryText, (harness, secondaryText) =>
HarnessPredicate.stringMatches(harness.getSecondaryText(), secondaryText),
)
.addOption('tertiaryText', options.tertiaryText, (harness, tertiaryText) =>
HarnessPredicate.stringMatches(harness.getTertiaryText(), tertiaryText),
);
}
/** Harness for interacting with a list subheader. */
export class MatSubheaderHarness extends ComponentHarness {
static hostSelector = '.mat-mdc-subheader';
static with(options: SubheaderHarnessFilters = {}): HarnessPredicate<MatSubheaderHarness> {
return new HarnessPredicate(MatSubheaderHarness, options).addOption(
'text',
options.text,
(harness, text) => HarnessPredicate.stringMatches(harness.getText(), text),
);
}
/** Gets the full text content of the list item (including text from any font icons). */
async getText(): Promise<string> {
return (await this.host()).text();
}
}
/** Selectors for the various list item sections that may contain user content. */
export enum MatListItemSection {
CONTENT = '.mdc-list-item__content',
}
/** Enum describing the possible variants of a list item. */
export enum MatListItemType {
ONE_LINE_ITEM,
TWO_LINE_ITEM,
THREE_LINE_ITEM,
}
/**
* Shared behavior among the harnesses for the various `MatListItem` flavors.
* @docs-private
*/
export abstract class MatListItemHarnessBase extends ContentContainerComponentHarness<MatListItemSection> {
private _lines = this.locatorForAll('.mat-mdc-list-item-line');
private _primaryText = this.locatorFor('.mdc-list-item__primary-text');
private _avatar = this.locatorForOptional('.mat-mdc-list-item-avatar');
private _icon = this.locatorForOptional('.mat-mdc-list-item-icon');
private _unscopedTextContent = this.locatorFor('.mat-mdc-list-item-unscoped-content');
/** Gets the type of the list item, currently describing how many lines there are. */
async getType(): Promise<MatListItemType> {
const host = await this.host();
const [isOneLine, isTwoLine] = await parallel(() => [
host.hasClass('mdc-list-item--with-one-line'),
host.hasClass('mdc-list-item--with-two-lines'),
]);
if (isOneLine) {
return MatListItemType.ONE_LINE_ITEM;
} else if (isTwoLine) {
return MatListItemType.TWO_LINE_ITEM;
} else {
return MatListItemType.THREE_LINE_ITEM;
}
}
/**
* Gets the full text content of the list item, excluding text
* from icons and avatars.
*
* @deprecated Use the `getFullText` method instead.
* @breaking-change 16.0.0
*/
async getText(): Promise<string> {
return this.getFullText();
}
/**
* Gets the full text content of the list item, excluding text
* from icons and avatars.
*/
async getFullText(): Promise<string> {
return (await this.host()).text({exclude: `${iconSelector}, ${avatarSelector}`});
}
/** Gets the title of the list item. */
async getTitle(): Promise<string> {
return (await this._primaryText()).text();
}
/** Whether the list item is disabled. */
async isDisabled(): Promise<boolean> {
return (await this.host()).hasClass('mdc-list-item--disabled');
}
/**
* Gets the secondary line text of the list item. Null if the list item
* does not have a secondary line.
*/
async getSecondaryText(): Promise<string | null> {
const type = await this.getType();
if (type === MatListItemType.ONE_LINE_ITEM) {
return null;
}
const [lines, unscopedTextContent] = await parallel(() => [
this._lines(),
this._unscopedTextContent(),
]);
// If there is no explicit line for the secondary text, the unscoped text content
// is rendered as the secondary text (with potential text wrapping enabled).
if (lines.length >= 1) {
return lines[0].text();
} else {
return unscopedTextContent.text();
}
}
/**
* Gets the tertiary line text of the list item. Null if the list item
* does not have a tertiary line.
*/
async getTertiaryText(): Promise<string | null> {
const type = await this.getType();
if (type !== MatListItemType.THREE_LINE_ITEM) {
return null;
}
const [lines, unscopedTextContent] = await parallel(() => [
this._lines(),
this._unscopedTextContent(),
]);
// First we check if there is an explicit line for the tertiary text. If so, we return it.
// If there is at least an explicit secondary line though, then we know that the unscoped
// text content corresponds to the tertiary line. If there are no explicit lines at all,
// we know that the unscoped text content from the secondary text just wraps into the third
// line, but there *no* actual dedicated tertiary text.
if (lines.length === 2) {
return lines[1].text();
} else if (lines.length === 1) {
return unscopedTextContent.text();
}
return null;
}
/** Whether this list item has an avatar. */
async hasAvatar(): Promise<boolean> {
return !!(await this._avatar());
}
/** Whether this list item has an icon. */
async hasIcon(): Promise<boolean> {
return !!(await this._icon());
}
}
| {
"end_byte": 6804,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/list-item-harness-base.ts"
} |
components/src/material/list/testing/nav-list-harness.ts_0_3278 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ComponentHarnessConstructor, HarnessPredicate} from '@angular/cdk/testing';
import {MatListHarnessBase} from './list-harness-base';
import {NavListHarnessFilters, NavListItemHarnessFilters} from './list-harness-filters';
import {getListItemPredicate, MatListItemHarnessBase} from './list-item-harness-base';
/** Harness for interacting with a mat-nav-list in tests. */
export class MatNavListHarness extends MatListHarnessBase<
typeof MatNavListItemHarness,
MatNavListItemHarness,
NavListItemHarnessFilters
> {
/** The selector for the host element of a `MatNavList` instance. */
static hostSelector = '.mat-mdc-nav-list';
/**
* Gets a `HarnessPredicate` that can be used to search for a nav list with specific
* attributes.
* @param options Options for filtering which nav list instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatNavListHarness>(
this: ComponentHarnessConstructor<T>,
options: NavListHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options);
}
override _itemHarness = MatNavListItemHarness;
}
/** Harness for interacting with a nav-list item. */
export class MatNavListItemHarness extends MatListItemHarnessBase {
/** The selector for the host element of a `MatListItem` instance. */
static hostSelector = `${MatNavListHarness.hostSelector} .mat-mdc-list-item`;
/**
* Gets a `HarnessPredicate` that can be used to search for a nav list item with specific
* attributes.
* @param options Options for filtering which nav list item instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatNavListItemHarness>(
this: ComponentHarnessConstructor<T>,
options: NavListItemHarnessFilters = {},
): HarnessPredicate<T> {
return getListItemPredicate(this, options)
.addOption('href', options.href, async (harness, href) =>
HarnessPredicate.stringMatches(harness.getHref(), href),
)
.addOption(
'activated',
options.activated,
async (harness, activated) => (await harness.isActivated()) === activated,
);
}
/** Gets the href for this nav list item. */
async getHref(): Promise<string | null> {
return (await this.host()).getAttribute('href');
}
/** Clicks on the nav list item. */
async click(): Promise<void> {
return (await this.host()).click();
}
/** Focuses the nav list item. */
async focus(): Promise<void> {
return (await this.host()).focus();
}
/** Blurs the nav list item. */
async blur(): Promise<void> {
return (await this.host()).blur();
}
/** Whether the nav list item is focused. */
async isFocused(): Promise<boolean> {
return (await this.host()).isFocused();
}
/** Whether the list item is activated. Should only be used for nav list items. */
async isActivated(): Promise<boolean> {
return (await this.host()).hasClass('mdc-list-item--activated');
}
}
| {
"end_byte": 3278,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/nav-list-harness.ts"
} |
components/src/material/list/testing/selection-list-harness.ts_0_5465 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ComponentHarnessConstructor, HarnessPredicate, parallel} from '@angular/cdk/testing';
import {MatListOptionTogglePosition} from '@angular/material/list';
import {MatListHarnessBase} from './list-harness-base';
import {
ListItemHarnessFilters,
ListOptionHarnessFilters,
SelectionListHarnessFilters,
} from './list-harness-filters';
import {getListItemPredicate, MatListItemHarnessBase} from './list-item-harness-base';
/** Harness for interacting with a selection-list in tests. */
export class MatSelectionListHarness extends MatListHarnessBase<
typeof MatListOptionHarness,
MatListOptionHarness,
ListOptionHarnessFilters
> {
/** The selector for the host element of a `MatSelectionList` instance. */
static hostSelector = '.mat-mdc-selection-list';
/**
* Gets a `HarnessPredicate` that can be used to search for a selection list with specific
* attributes.
* @param options Options for filtering which selection list instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatSelectionListHarness>(
this: ComponentHarnessConstructor<T>,
options: SelectionListHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options);
}
override _itemHarness = MatListOptionHarness;
/** Whether the selection list is disabled. */
async isDisabled(): Promise<boolean> {
return (await (await this.host()).getAttribute('aria-disabled')) === 'true';
}
/**
* Selects all items matching any of the given filters.
* @param filters Filters that specify which items should be selected.
*/
async selectItems(...filters: ListOptionHarnessFilters[]): Promise<void> {
const items = await this._getItems(filters);
await parallel(() => items.map(item => item.select()));
}
/**
* Deselects all items matching any of the given filters.
* @param filters Filters that specify which items should be deselected.
*/
async deselectItems(...filters: ListItemHarnessFilters[]): Promise<void> {
const items = await this._getItems(filters);
await parallel(() => items.map(item => item.deselect()));
}
/** Gets all items matching the given list of filters. */
private async _getItems(filters: ListOptionHarnessFilters[]): Promise<MatListOptionHarness[]> {
if (!filters.length) {
return this.getItems();
}
const matches = await parallel(() =>
filters.map(filter => this.locatorForAll(MatListOptionHarness.with(filter))()),
);
return matches.reduce((result, current) => [...result, ...current], []);
}
}
/** Harness for interacting with a list option. */
export class MatListOptionHarness extends MatListItemHarnessBase {
/** The selector for the host element of a `MatListOption` instance. */
static hostSelector = '.mat-mdc-list-option';
/**
* Gets a `HarnessPredicate` that can be used to search for a list option with specific
* attributes.
* @param options Options for filtering which list option instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatListOptionHarness>(
this: ComponentHarnessConstructor<T>,
options: ListOptionHarnessFilters = {},
): HarnessPredicate<T> {
return getListItemPredicate(this, options).addOption(
'is selected',
options.selected,
async (harness, selected) => (await harness.isSelected()) === selected,
);
}
private _beforeCheckbox = this.locatorForOptional('.mdc-list-item__start .mdc-checkbox');
private _beforeRadio = this.locatorForOptional('.mdc-list-item__start .mdc-radio');
/** Gets the position of the checkbox relative to the list option content. */
async getCheckboxPosition(): Promise<MatListOptionTogglePosition> {
return (await this._beforeCheckbox()) !== null ? 'before' : 'after';
}
/** Gets the position of the radio relative to the list option content. */
async getRadioPosition(): Promise<MatListOptionTogglePosition> {
return (await this._beforeRadio()) !== null ? 'before' : 'after';
}
/** Whether the list option is selected. */
async isSelected(): Promise<boolean> {
return (await (await this.host()).getAttribute('aria-selected')) === 'true';
}
/** Focuses the list option. */
async focus(): Promise<void> {
return (await this.host()).focus();
}
/** Blurs the list option. */
async blur(): Promise<void> {
return (await this.host()).blur();
}
/** Whether the list option is focused. */
async isFocused(): Promise<boolean> {
return (await this.host()).isFocused();
}
/** Toggles the checked state of the checkbox. */
async toggle() {
return (await this.host()).click();
}
/**
* Puts the list option in a checked state by toggling it if it is currently
* unchecked, or doing nothing if it is already checked.
*/
async select() {
if (!(await this.isSelected())) {
return this.toggle();
}
}
/**
* Puts the list option in an unchecked state by toggling it if it is currently
* checked, or doing nothing if it is already unchecked.
*/
async deselect() {
if (await this.isSelected()) {
return this.toggle();
}
}
}
| {
"end_byte": 5465,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/list/testing/selection-list-harness.ts"
} |
components/src/material/divider/_divider-offset.scss_0_420 | // This mixin provides the correct offset for an inset divider based on the
// size of the parent class (e.g. avatar vs icon)
@mixin inset-divider-offset($offset, $padding) {
$mat-inset-divider-offset: #{(2 * $padding) + $offset};
margin-left: $mat-inset-divider-offset;
width: calc(100% - #{$mat-inset-divider-offset});
[dir='rtl'] & {
margin-left: auto;
margin-right: $mat-inset-divider-offset;
}
}
| {
"end_byte": 420,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/_divider-offset.scss"
} |
components/src/material/divider/public-api.ts_0_265 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './divider';
export * from './divider-module';
| {
"end_byte": 265,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/public-api.ts"
} |
components/src/material/divider/README.md_0_97 | Please see the official documentation at https://material.angular.io/components/component/divider | {
"end_byte": 97,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/README.md"
} |
components/src/material/divider/divider.scss_0_825 | @use '../core/tokens/token-utils';
@use '../core/tokens/m2/mat/divider' as tokens-mat-divider;
$inset-margin: 80px;
.mat-divider {
display: block;
margin: 0;
border-top-style: solid;
@include token-utils.use-tokens(
tokens-mat-divider.$prefix, tokens-mat-divider.get-token-slots()) {
@include token-utils.create-token-slot(border-top-color, color);
@include token-utils.create-token-slot(border-top-width, width);
&.mat-divider-vertical {
border-top: 0;
border-right-style: solid;
@include token-utils.create-token-slot(border-right-color, color);
@include token-utils.create-token-slot(border-right-width, width);
}
}
&.mat-divider-inset {
margin-left: $inset-margin;
[dir='rtl'] & {
margin-left: auto;
margin-right: $inset-margin;
}
}
}
| {
"end_byte": 825,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/divider.scss"
} |
components/src/material/divider/divider.ts_0_1348 | /**
* @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';
import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion';
@Component({
selector: 'mat-divider',
host: {
'role': 'separator',
'[attr.aria-orientation]': 'vertical ? "vertical" : "horizontal"',
'[class.mat-divider-vertical]': 'vertical',
'[class.mat-divider-horizontal]': '!vertical',
'[class.mat-divider-inset]': 'inset',
'class': 'mat-divider',
},
template: '',
styleUrl: 'divider.css',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatDivider {
/** Whether the divider is vertically aligned. */
@Input()
get vertical(): boolean {
return this._vertical;
}
set vertical(value: BooleanInput) {
this._vertical = coerceBooleanProperty(value);
}
private _vertical: boolean = false;
/** Whether the divider is an inset divider. */
@Input()
get inset(): boolean {
return this._inset;
}
set inset(value: BooleanInput) {
this._inset = coerceBooleanProperty(value);
}
private _inset: boolean = false;
}
| {
"end_byte": 1348,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/divider.ts"
} |
components/src/material/divider/_divider-theme.scss_0_2623 | @use 'sass:map';
@use '../core/style/sass-utils';
@use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/tokens/token-utils';
@use '../core/tokens/m2/mat/divider' as tokens-mat-divider;
@mixin base($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, base));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-divider.$prefix,
tokens-mat-divider.get-unthemable-tokens()
);
}
}
}
@mixin color($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, color));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-divider.$prefix,
tokens-mat-divider.get-color-tokens($theme)
);
}
}
}
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
}
}
@mixin density($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, density));
} @else {
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
@return (
(
namespace: tokens-mat-divider.$prefix,
tokens: tokens-mat-divider.get-token-slots(),
),
);
}
@mixin overrides($tokens: ()) {
@include token-utils.batch-create-token-values($tokens, _define-overrides()...);
}
@mixin theme($theme) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-divider') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme));
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
@if ($tokens != ()) {
@include token-utils.create-token-values(
tokens-mat-divider.$prefix,
map.get($tokens, tokens-mat-divider.$prefix)
);
}
}
| {
"end_byte": 2623,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/_divider-theme.scss"
} |
components/src/material/divider/BUILD.bazel_0_1341 | load(
"//tools:defaults.bzl",
"extract_tokens",
"markdown_to_html",
"ng_module",
"ng_test_library",
"ng_web_test_suite",
"sass_binary",
"sass_library",
)
package(default_visibility = ["//visibility:public"])
ng_module(
name = "divider",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = [":divider.css"] + glob(["**/*.html"]),
deps = [
"//src/cdk/coercion",
"//src/material/core",
"@npm//@angular/core",
],
)
sass_library(
name = "divider_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = ["//src/material/core:core_scss_lib"],
)
sass_binary(
name = "divider_scss",
src = "divider.scss",
deps = [
":divider_scss_lib",
"//src/material/core:core_scss_lib",
],
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":divider",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
markdown_to_html(
name = "overview",
srcs = [":divider.md"],
)
extract_tokens(
name = "tokens",
srcs = [":divider_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1341,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/BUILD.bazel"
} |
components/src/material/divider/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public-api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/index.ts"
} |
components/src/material/divider/divider-module.ts_0_471 | /**
* @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 {MatDivider} from './divider';
@NgModule({
imports: [MatCommonModule, MatDivider],
exports: [MatDivider, MatCommonModule],
})
export class MatDividerModule {}
| {
"end_byte": 471,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/divider-module.ts"
} |
components/src/material/divider/divider.spec.ts_0_2639 | import {ComponentFixture, TestBed} from '@angular/core/testing';
import {Component} from '@angular/core';
import {By} from '@angular/platform-browser';
import {MatDividerModule} from './divider-module';
describe('MatDivider', () => {
let fixture: ComponentFixture<MatDividerTestComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatDividerModule, MatDividerTestComponent],
});
fixture = TestBed.createComponent(MatDividerTestComponent);
});
it('should apply vertical class to vertical divider', () => {
fixture.componentInstance.vertical = true;
fixture.detectChanges();
const divider = fixture.debugElement.query(By.css('mat-divider'))!;
expect(divider.nativeElement.classList).toContain('mat-divider');
expect(divider.nativeElement.classList).toContain('mat-divider-vertical');
});
it('should apply horizontal class to horizontal divider', () => {
fixture.componentInstance.vertical = false;
fixture.detectChanges();
const divider = fixture.debugElement.query(By.css('mat-divider'))!;
expect(divider.nativeElement.classList).toContain('mat-divider');
expect(divider.nativeElement.classList).not.toContain('mat-divider-vertical');
expect(divider.nativeElement.classList).toContain('mat-divider-horizontal');
});
it('should apply inset class to inset divider', () => {
fixture.componentInstance.inset = true;
fixture.detectChanges();
const divider = fixture.debugElement.query(By.css('mat-divider'))!;
expect(divider.nativeElement.classList).toContain('mat-divider');
expect(divider.nativeElement.classList).toContain('mat-divider-inset');
});
it('should apply inset and vertical classes to vertical inset divider', () => {
fixture.componentInstance.vertical = true;
fixture.componentInstance.inset = true;
fixture.detectChanges();
const divider = fixture.debugElement.query(By.css('mat-divider'))!;
expect(divider.nativeElement.classList).toContain('mat-divider');
expect(divider.nativeElement.classList).toContain('mat-divider-inset');
expect(divider.nativeElement.classList).toContain('mat-divider-vertical');
});
it('should add aria roles properly', () => {
fixture.detectChanges();
const divider = fixture.debugElement.query(By.css('mat-divider'))!;
expect(divider.nativeElement.getAttribute('role')).toBe('separator');
});
});
@Component({
template: `<mat-divider [vertical]="vertical" [inset]="inset"></mat-divider>`,
standalone: true,
imports: [MatDividerModule],
})
class MatDividerTestComponent {
vertical: boolean;
inset: boolean;
}
| {
"end_byte": 2639,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/divider.spec.ts"
} |
components/src/material/divider/divider.md_0_1959 | `<mat-divider>` is a component that allows for Material styling of a line separator with various orientation options.
<!-- example(divider-overview) -->
### Simple divider
A `<mat-divider>` element can be used on its own to create a horizontal or vertical line styled with a Material theme
```html
<mat-divider></mat-divider>
```
### Inset divider
Add the `inset` attribute in order to set whether or not the divider is an inset divider.
```html
<mat-divider [inset]="true"></mat-divider>
```
### Vertical divider
Add the `vertical` attribute in order to set whether or not the divider is vertically-oriented.
```html
<mat-divider [vertical]="true"></mat-divider>
```
### Lists with inset dividers
Dividers can be added to lists as a means of separating content into distinct sections.
Inset dividers can also be added to provide the appearance of distinct elements in a list without cluttering content
like avatar images or icons. Make sure to avoid adding an inset divider to the last element
in a list, because it will overlap with the section divider.
```html
<mat-list>
<h3 mat-subheader>Folders</h3>
@for (folder of folders; track folder) {
<mat-list-item>
<mat-icon mat-list-icon>folder</mat-icon>
<h4 mat-line>{{folder.name}}</h4>
<p mat-line class="demo-2">{{folder.updated}}</p>
@if (!$last) {
<mat-divider [inset]="true"></mat-divider>
}
</mat-list-item>
}
<mat-divider></mat-divider>
<h3 mat-subheader>Notes</h3>
@for (note of notes; track node) {
<mat-list-item>
<mat-icon mat-list-icon>note</mat-icon>
<h4 mat-line>{{note.name}}</h4>
<p mat-line class="demo-2"> {{note.updated}} </p>
</mat-list-item>
}
</mat-list>
```
### Accessibility
`MatDivider` applies the ARIA `role="separator"` attribute, exclusively implementing the
non-focusable style of separator that distinguishes sections of content.
| {
"end_byte": 1959,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/divider.md"
} |
components/src/material/divider/testing/divider-harness-filters.ts_0_331 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {BaseHarnessFilters} from '@angular/cdk/testing';
export interface DividerHarnessFilters extends BaseHarnessFilters {}
| {
"end_byte": 331,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/testing/divider-harness-filters.ts"
} |
components/src/material/divider/testing/public-api.ts_0_282 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './divider-harness';
export * from './divider-harness-filters';
| {
"end_byte": 282,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/testing/public-api.ts"
} |
components/src/material/divider/testing/divider-harness.ts_0_903 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ComponentHarness, HarnessPredicate} from '@angular/cdk/testing';
import {DividerHarnessFilters} from './divider-harness-filters';
/** Harness for interacting with a `mat-divider`. */
export class MatDividerHarness extends ComponentHarness {
static hostSelector = '.mat-divider';
static with(options: DividerHarnessFilters = {}) {
return new HarnessPredicate(MatDividerHarness, options);
}
async getOrientation(): Promise<'horizontal' | 'vertical'> {
return (await this.host()).getAttribute('aria-orientation') as Promise<
'horizontal' | 'vertical'
>;
}
async isInset(): Promise<boolean> {
return (await this.host()).hasClass('mat-divider-inset');
}
}
| {
"end_byte": 903,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/testing/divider-harness.ts"
} |
components/src/material/divider/testing/BUILD.bazel_0_722 | load("//tools:defaults.bzl", "ng_test_library", "ng_web_test_suite", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "testing",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
deps = [
"//src/cdk/testing",
],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
ng_test_library(
name = "unit_tests_lib",
srcs = glob(["**/*.spec.ts"]),
deps = [
":testing",
"//src/cdk/testing",
"//src/cdk/testing/testbed",
"//src/material/divider",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_tests_lib"],
)
| {
"end_byte": 722,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/testing/BUILD.bazel"
} |
components/src/material/divider/testing/divider-harness.spec.ts_0_1609 | import {Component} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {MatDividerModule} from '@angular/material/divider';
import {MatDividerHarness} from './divider-harness';
describe('MatLegacyButtonHarness', () => {
let fixture: ComponentFixture<DividerHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatDividerModule, DividerHarnessTest],
});
fixture = TestBed.createComponent(DividerHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all divider harnesses', async () => {
const dividers = await loader.getAllHarnesses(MatDividerHarness);
expect(dividers.length).toBe(2);
});
it('should check if divider is inset', async () => {
const dividers = await loader.getAllHarnesses(MatDividerHarness);
expect(await dividers[0].isInset()).toBe(false);
expect(await dividers[1].isInset()).toBe(true);
});
it('should get divider orientation', async () => {
const dividers = await loader.getAllHarnesses(MatDividerHarness);
expect(await dividers[0].getOrientation()).toBe('horizontal');
expect(await dividers[1].getOrientation()).toBe('vertical');
});
});
@Component({
template: `
<mat-divider></mat-divider>
<mat-divider inset vertical></mat-divider>
`,
standalone: true,
imports: [MatDividerModule],
})
class DividerHarnessTest {}
| {
"end_byte": 1609,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/testing/divider-harness.spec.ts"
} |
components/src/material/divider/testing/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public-api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/divider/testing/index.ts"
} |
components/src/material/menu/menu-errors.ts_0_1279 | /**
* @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
*/
/**
* Throws an exception for the case when menu's x-position value isn't valid.
* In other words, it doesn't match 'before' or 'after'.
* @docs-private
*/
export function throwMatMenuInvalidPositionX() {
throw Error(`xPosition value must be either 'before' or after'.
Example: <mat-menu xPosition="before" #menu="matMenu"></mat-menu>`);
}
/**
* Throws an exception for the case when menu's y-position value isn't valid.
* In other words, it doesn't match 'above' or 'below'.
* @docs-private
*/
export function throwMatMenuInvalidPositionY() {
throw Error(`yPosition value must be either 'above' or below'.
Example: <mat-menu yPosition="above" #menu="matMenu"></mat-menu>`);
}
/**
* Throws an exception for the case when a menu is assigned
* to a trigger that is placed inside the same menu.
* @docs-private
*/
export function throwMatMenuRecursiveError() {
throw Error(
`matMenuTriggerFor: menu cannot contain its own trigger. Assign a menu that is ` +
`not a parent of the trigger or move the trigger outside of the menu.`,
);
}
| {
"end_byte": 1279,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu-errors.ts"
} |
components/src/material/menu/menu.md_0_4612 | `<mat-menu>` is a floating panel containing list of options.
<!-- example(menu-overview) -->
By itself, the `<mat-menu>` element does not render anything. The menu is attached to and opened
via application of the `matMenuTriggerFor` directive:
<!-- example({"example": "menu-overview",
"file": "menu-overview-example.html",
"region": "mat-menu-trigger-for"}) -->
### Toggling the menu programmatically
The menu exposes an API to open/close programmatically. Please note that in this case, an
`matMenuTriggerFor` directive is still necessary to attach the menu to a trigger element in the DOM.
```ts
class MyComponent {
@ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;
someMethod() {
this.trigger.openMenu();
}
}
```
### Icons
Menus support displaying `mat-icon` elements before the menu item text.
<!-- example({"example": "menu-icons",
"file": "menu-icons-example.html"}) -->
### Customizing menu position
By default, the menu will display below (y-axis), after (x-axis), without overlapping
its trigger. The position can be changed using the `xPosition` (`before | after`) and `yPosition`
(`above | below`) attributes. The menu can be forced to overlap the trigger using the
`overlapTrigger` attribute.
<!-- example({"example": "menu-position",
"file": "menu-position-example.html",
"region": "menu-position"}) -->
### Nested menu
Material supports the ability for an `mat-menu-item` to open a sub-menu. To do so, you have to define
your root menu and sub-menus, in addition to setting the `[matMenuTriggerFor]` on the `mat-menu-item`
that should trigger the sub-menu:
<!-- example({"example": "menu-nested",
"file": "menu-nested-example.html",
"region": "sub-menu"}) -->
### Lazy rendering
By default, the menu content will be initialized even when the panel is closed. To defer
initialization until the menu is open, the content can be provided as an `ng-template`
with the `matMenuContent` attribute:
```html
<mat-menu #appMenu="matMenu">
<ng-template matMenuContent>
<button mat-menu-item>Settings</button>
<button mat-menu-item>Help</button>
</ng-template>
</mat-menu>
<button mat-icon-button [matMenuTriggerFor]="appMenu">
<mat-icon>more_vert</mat-icon>
</button>
```
### Passing in data to a menu
When using lazy rendering, additional context data can be passed to the menu panel via
the `matMenuTriggerData` input. This allows for a single menu instance to be rendered
with a different set of data, depending on the trigger that opened it:
```html
<mat-menu #appMenu="matMenu">
<ng-template matMenuContent let-name="name">
<button mat-menu-item>Settings</button>
<button mat-menu-item>Log off {{name}}</button>
</ng-template>
</mat-menu>
<button mat-icon-button [matMenuTriggerFor]="appMenu" [matMenuTriggerData]="{name: 'Sally'}">
<mat-icon>more_vert</mat-icon>
</button>
<button mat-icon-button [matMenuTriggerFor]="appMenu" [matMenuTriggerData]="{name: 'Bob'}">
<mat-icon>more_vert</mat-icon>
</button>
```
### Keyboard interaction
| Keyboard shortcut | Action |
|------------------------|---------------------------------------------|
| <kbd>Down Arrow</kbd> | Focus the next menu item. |
| <kbd>Up Arrow</kbd> | Focus the previous menu item. |
| <kbd>Left Arrow</kbd> | Close the current menu if it is a sub-menu. |
| <kbd>Right Arrow</kbd> | Opens the current menu item's sub-menu. |
| <kbd>Enter</kbd> | Activate the focused menu item. |
| <kbd>Escape</kbd> | Close all open menus. |
### Accessibility
Angular Material's menu component consists of two connected parts: the trigger and the pop-up menu.
The menu trigger is a standard button element augmented with `aria-haspopup`, `aria-expanded`, and
`aria-controls` to create the relationship to the pop-up panel.
The pop-up menu implements the `role="menu"` pattern, handling keyboard interaction and focus
management. Upon opening, the trigger will focus the first focusable menu item. Upon close, the menu
will return focus to its trigger. Avoid creating a menu in which all items are disabled, instead
hiding or disabling the menu trigger.
Angular Material does not support the `menuitemcheckbox` or `menuitemradio` roles.
Always provide an accessible label via `aria-label` or `aria-labelledby` for any menu
triggers or menu items without descriptive text content.
MatMenu should not contain any interactive controls aside from MatMenuItem.
| {
"end_byte": 4612,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.md"
} |
components/src/material/menu/module.ts_0_1026 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {MatCommonModule, MatRippleModule} from '@angular/material/core';
import {OverlayModule} from '@angular/cdk/overlay';
import {CdkScrollableModule} from '@angular/cdk/scrolling';
import {MatMenu} from './menu';
import {MatMenuItem} from './menu-item';
import {MatMenuContent} from './menu-content';
import {MAT_MENU_SCROLL_STRATEGY_FACTORY_PROVIDER, MatMenuTrigger} from './menu-trigger';
@NgModule({
imports: [
MatRippleModule,
MatCommonModule,
OverlayModule,
MatMenu,
MatMenuItem,
MatMenuContent,
MatMenuTrigger,
],
exports: [
CdkScrollableModule,
MatMenu,
MatCommonModule,
MatMenuItem,
MatMenuContent,
MatMenuTrigger,
],
providers: [MAT_MENU_SCROLL_STRATEGY_FACTORY_PROVIDER],
})
export class MatMenuModule {}
| {
"end_byte": 1026,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/module.ts"
} |
components/src/material/menu/menu.scss_0_7907 | @use '@angular/cdk';
@use '../core/tokens/m2/mat/menu' as tokens-mat-menu;
@use '../core/tokens/token-utils';
@use '../core/style/menu-common';
@use '../core/style/button-common';
@use '../core/style/vendor-prefixes';
// Prevent rendering mat-menu as it can affect the flex layout.
mat-menu {
display: none;
}
.mat-mdc-menu-content {
margin: 0;
padding: 8px 0;
outline: 0;
&,
.mat-mdc-menu-item .mat-mdc-menu-item-text {
@include vendor-prefixes.smooth-font();
flex: 1;
white-space: normal;
@include token-utils.use-tokens(tokens-mat-menu.$prefix, tokens-mat-menu.get-token-slots()) {
@include token-utils.create-token-slot(font-family, item-label-text-font);
@include token-utils.create-token-slot(line-height, item-label-text-line-height);
@include token-utils.create-token-slot(font-size, item-label-text-size);
@include token-utils.create-token-slot(letter-spacing, item-label-text-tracking);
@include token-utils.create-token-slot(font-weight, item-label-text-weight);
}
}
}
.mat-mdc-menu-panel {
@include menu-common.base;
box-sizing: border-box;
outline: 0;
@include token-utils.use-tokens(tokens-mat-menu.$prefix, tokens-mat-menu.get-token-slots()) {
@include token-utils.create-token-slot(border-radius, container-shape);
@include token-utils.create-token-slot(background-color, container-color);
}
// TODO(crisbeto): we don't need this for anything, but it was there when
// we used MDC's structural styles and removing it leads to sub-pixels
// differences in text rendering which break a lot of screenshots internally.
// We should clean it up eventually and re-approve all the screenshots.
will-change: transform, opacity;
// Prevent users from interacting with the panel while it's animating. Note that
// people won't be able to click through it, because the overlay pane will catch the click.
// This fixes the following issues:
// * Users accidentally opening sub-menus when the `overlapTrigger` option is enabled.
// * Users accidentally tapping on content inside the sub-menu on touch devices, if the
// sub-menu overlaps the trigger. The issue is due to touch devices emulating the
// `mouseenter` event by dispatching it on tap.
&.ng-animating {
pointer-events: none;
// If the same menu is assigned to multiple triggers and the user moves quickly between them
// (e.g. in a nested menu), the panel for the old menu may show up as empty while it's
// animating away. Hide such cases since they can look off to users.
&:has(.mat-mdc-menu-content:empty) {
display: none;
}
}
@include cdk.high-contrast {
outline: solid 1px;
}
.mat-divider {
// Use margin instead of padding since divider uses border-top to render out the line.
@include token-utils.use-tokens(
tokens-mat-menu.$prefix,
tokens-mat-menu.get-token-slots()
) {
color: token-utils.get-token-variable(divider-color);
margin-bottom: token-utils.get-token-variable(divider-bottom-spacing);
margin-top: token-utils.get-token-variable(divider-top-spacing);
}
}
}
.mat-mdc-menu-item {
display: flex;
position: relative;
align-items: center;
justify-content: flex-start;
overflow: hidden;
padding: 0;
// MDC's menu items are `<li>` nodes which don't need resets, however ours
// can be anything, including buttons, so we need to do the reset ourselves.
cursor: pointer;
width: 100%;
text-align: left;
box-sizing: border-box;
color: inherit;
font-size: inherit;
background: none;
text-decoration: none;
margin: 0; // Resolves an issue where buttons have an extra 2px margin on Safari.
min-height: 48px;
@include token-utils.use-tokens(tokens-mat-menu.$prefix, tokens-mat-menu.get-token-slots()) {
@include token-utils.create-token-slot(padding-left, item-leading-spacing);
@include token-utils.create-token-slot(padding-right, item-trailing-spacing);
}
@include button-common.reset;
@include token-utils.use-tokens(tokens-mat-menu.$prefix, tokens-mat-menu.get-token-slots()) {
$icons-selector: '.material-icons, mat-icon, [matButtonIcon]';
[dir='rtl'] & {
@include token-utils.create-token-slot(padding-left, item-trailing-spacing);
@include token-utils.create-token-slot(padding-right, item-leading-spacing);
}
&:has(#{$icons-selector}) {
@include token-utils.create-token-slot(padding-left, item-with-icon-leading-spacing);
@include token-utils.create-token-slot(padding-right, item-with-icon-trailing-spacing);
}
[dir='rtl'] &:has(#{$icons-selector}) {
@include token-utils.create-token-slot(padding-left, item-with-icon-trailing-spacing);
@include token-utils.create-token-slot(padding-right, item-with-icon-leading-spacing);
}
}
@include token-utils.use-tokens(tokens-mat-menu.$prefix, tokens-mat-menu.get-token-slots()) {
// The class selector isn't specific enough to overide the link pseudo selectors so we need
// to target them specifically, otherwise the item color might be overwritten by the user
// agent resets of the app.
&, &:visited, &:link {
@include token-utils.create-token-slot(color, item-label-text-color);
}
.mat-icon-no-color,
.mat-mdc-menu-submenu-icon {
@include token-utils.create-token-slot(color, item-icon-color);
}
}
&[disabled] {
cursor: default;
opacity: 0.38;
// The browser prevents clicks on disabled buttons from propagating which prevents the menu
// from closing, but clicks on child nodes still propagate which is inconsistent (see #16694).
// In order to keep the behavior consistent and prevent the menu from closing, we add an overlay
// on top of the content that will catch all the clicks while disabled.
&::after {
display: block;
position: absolute;
content: '';
top: 0;
left: 0;
bottom: 0;
right: 0;
}
}
// Inherited from MDC and necessary for some internal tests.
&:focus {
outline: 0;
}
.mat-icon {
flex-shrink: 0;
@include token-utils.use-tokens(tokens-mat-menu.$prefix, tokens-mat-menu.get-token-slots()) {
margin-right: token-utils.get-token-variable(item-spacing);
height: token-utils.get-token-variable(item-icon-size);
width: token-utils.get-token-variable(item-icon-size);
}
}
[dir='rtl'] & {
text-align: right;
.mat-icon {
margin-right: 0;
@include token-utils.use-tokens(tokens-mat-menu.$prefix, tokens-mat-menu.get-token-slots()) {
margin-left: token-utils.get-token-variable(item-spacing);
}
}
}
&:not([disabled]) {
@include token-utils.use-tokens(tokens-mat-menu.$prefix, tokens-mat-menu.get-token-slots()) {
&:hover {
@include token-utils.create-token-slot(background-color, item-hover-state-layer-color);
}
&.cdk-program-focused,
&.cdk-keyboard-focused,
&.mat-mdc-menu-item-highlighted {
@include token-utils.create-token-slot(background-color, item-focus-state-layer-color);
}
}
}
@include cdk.high-contrast {
$outline-width: 1px;
// We need to move the item 1px down, because Firefox seems to have
// an issue rendering the top part of the outline (see #21524).
margin-top: $outline-width;
}
}
.mat-mdc-menu-submenu-icon {
@include token-utils.use-tokens(tokens-mat-menu.$prefix, tokens-mat-menu.get-token-slots()) {
@include menu-common.item-submenu-icon(
token-utils.get-token-variable(item-spacing),
token-utils.get-token-variable(item-icon-size)
);
}
}
// Increase specificity because ripple styles are part of the `mat-core` mixin and can
// potentially overwrite the absolute position of the container.
.mat-mdc-menu-item .mat-mdc-menu-ripple {
@include menu-common.item-ripple;
}
| {
"end_byte": 7907,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.scss"
} |
components/src/material/menu/public-api.ts_0_639 | /**
* @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 {MatMenu, MAT_MENU_DEFAULT_OPTIONS, MatMenuDefaultOptions, MenuCloseReason} from './menu';
export * from './menu-item';
export * from './menu-content';
export {
MatMenuTrigger,
MAT_MENU_SCROLL_STRATEGY,
MAT_MENU_SCROLL_STRATEGY_FACTORY_PROVIDER,
MENU_PANEL_TOP_PADDING,
} from './menu-trigger';
export * from './module';
export * from './menu-animations';
export * from './menu-positions';
export * from './menu-panel';
| {
"end_byte": 639,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/public-api.ts"
} |
components/src/material/menu/menu.html_0_638 | <ng-template>
<div
class="mat-mdc-menu-panel mat-mdc-elevation-specific"
[id]="panelId"
[class]="_classList"
(keydown)="_handleKeydown($event)"
(click)="closed.emit('click')"
[@transformMenu]="_panelAnimationState"
(@transformMenu.start)="_onAnimationStart($event)"
(@transformMenu.done)="_onAnimationDone($event)"
tabindex="-1"
role="menu"
[attr.aria-label]="ariaLabel || null"
[attr.aria-labelledby]="ariaLabelledby || null"
[attr.aria-describedby]="ariaDescribedby || null">
<div class="mat-mdc-menu-content">
<ng-content></ng-content>
</div>
</div>
</ng-template>
| {
"end_byte": 638,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.html"
} |
components/src/material/menu/menu.ts_0_3163 | /**
* @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 {
AfterContentInit,
ChangeDetectionStrategy,
Component,
ContentChild,
ContentChildren,
ElementRef,
EventEmitter,
InjectionToken,
Input,
OnDestroy,
Output,
TemplateRef,
QueryList,
ViewChild,
ViewEncapsulation,
OnInit,
ChangeDetectorRef,
booleanAttribute,
afterNextRender,
AfterRenderRef,
inject,
Injector,
} from '@angular/core';
import {AnimationEvent} from '@angular/animations';
import {FocusKeyManager, FocusOrigin} from '@angular/cdk/a11y';
import {Direction} from '@angular/cdk/bidi';
import {
ESCAPE,
LEFT_ARROW,
RIGHT_ARROW,
DOWN_ARROW,
UP_ARROW,
hasModifierKey,
} from '@angular/cdk/keycodes';
import {merge, Observable, Subject} from 'rxjs';
import {startWith, switchMap} from 'rxjs/operators';
import {MatMenuItem} from './menu-item';
import {MatMenuPanel, MAT_MENU_PANEL} from './menu-panel';
import {MenuPositionX, MenuPositionY} from './menu-positions';
import {throwMatMenuInvalidPositionX, throwMatMenuInvalidPositionY} from './menu-errors';
import {MatMenuContent, MAT_MENU_CONTENT} from './menu-content';
import {matMenuAnimations} from './menu-animations';
let menuPanelUid = 0;
/** Reason why the menu was closed. */
export type MenuCloseReason = void | 'click' | 'keydown' | 'tab';
/** Default `mat-menu` options that can be overridden. */
export interface MatMenuDefaultOptions {
/** The x-axis position of the menu. */
xPosition: MenuPositionX;
/** The y-axis position of the menu. */
yPosition: MenuPositionY;
/** Whether the menu should overlap the menu trigger. */
overlapTrigger: boolean;
/** Class to be applied to the menu's backdrop. */
backdropClass: string;
/** Class or list of classes to be applied to the menu's overlay panel. */
overlayPanelClass?: string | string[];
/** Whether the menu has a backdrop. */
hasBackdrop?: boolean;
}
/** Injection token to be used to override the default options for `mat-menu`. */
export const MAT_MENU_DEFAULT_OPTIONS = new InjectionToken<MatMenuDefaultOptions>(
'mat-menu-default-options',
{
providedIn: 'root',
factory: MAT_MENU_DEFAULT_OPTIONS_FACTORY,
},
);
/** @docs-private */
export function MAT_MENU_DEFAULT_OPTIONS_FACTORY(): MatMenuDefaultOptions {
return {
overlapTrigger: false,
xPosition: 'after',
yPosition: 'below',
backdropClass: 'cdk-overlay-transparent-backdrop',
};
}
@Component({
selector: 'mat-menu',
templateUrl: 'menu.html',
styleUrl: 'menu.css',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
exportAs: 'matMenu',
host: {
'[attr.aria-label]': 'null',
'[attr.aria-labelledby]': 'null',
'[attr.aria-describedby]': 'null',
},
animations: [matMenuAnimations.transformMenu, matMenuAnimations.fadeInItems],
providers: [{provide: MAT_MENU_PANEL, useExisting: MatMenu}],
})
export class MatMenu implements AfterContentInit, MatMenuPanel<MatMenuItem>, OnInit, OnDestroy | {
"end_byte": 3163,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.ts"
} |
components/src/material/menu/menu.ts_3164_11406 | {
private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private _changeDetectorRef = inject(ChangeDetectorRef);
private _keyManager: FocusKeyManager<MatMenuItem>;
private _xPosition: MenuPositionX;
private _yPosition: MenuPositionY;
private _firstItemFocusRef?: AfterRenderRef;
private _previousElevation: string;
private _elevationPrefix = 'mat-elevation-z';
private _baseElevation: number | null = null;
/** All items inside the menu. Includes items nested inside another menu. */
@ContentChildren(MatMenuItem, {descendants: true}) _allItems: QueryList<MatMenuItem>;
/** Only the direct descendant menu items. */
_directDescendantItems = new QueryList<MatMenuItem>();
/** Classes to be applied to the menu panel. */
_classList: {[key: string]: boolean} = {};
/** Current state of the panel animation. */
_panelAnimationState: 'void' | 'enter' = 'void';
/** Emits whenever an animation on the menu completes. */
readonly _animationDone = new Subject<AnimationEvent>();
/** Whether the menu is animating. */
_isAnimating: boolean;
/** Parent menu of the current menu panel. */
parentMenu: MatMenuPanel | undefined;
/** Layout direction of the menu. */
direction: Direction;
/** Class or list of classes to be added to the overlay panel. */
overlayPanelClass: string | string[];
/** Class to be added to the backdrop element. */
@Input() backdropClass: string;
/** aria-label for the menu panel. */
@Input('aria-label') ariaLabel: string;
/** aria-labelledby for the menu panel. */
@Input('aria-labelledby') ariaLabelledby: string;
/** aria-describedby for the menu panel. */
@Input('aria-describedby') ariaDescribedby: string;
/** Position of the menu in the X axis. */
@Input()
get xPosition(): MenuPositionX {
return this._xPosition;
}
set xPosition(value: MenuPositionX) {
if (
value !== 'before' &&
value !== 'after' &&
(typeof ngDevMode === 'undefined' || ngDevMode)
) {
throwMatMenuInvalidPositionX();
}
this._xPosition = value;
this.setPositionClasses();
}
/** Position of the menu in the Y axis. */
@Input()
get yPosition(): MenuPositionY {
return this._yPosition;
}
set yPosition(value: MenuPositionY) {
if (value !== 'above' && value !== 'below' && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throwMatMenuInvalidPositionY();
}
this._yPosition = value;
this.setPositionClasses();
}
/** @docs-private */
@ViewChild(TemplateRef) templateRef: TemplateRef<any>;
/**
* List of the items inside of a menu.
* @deprecated
* @breaking-change 8.0.0
*/
@ContentChildren(MatMenuItem, {descendants: false}) items: QueryList<MatMenuItem>;
/**
* Menu content that will be rendered lazily.
* @docs-private
*/
@ContentChild(MAT_MENU_CONTENT) lazyContent: MatMenuContent;
/** Whether the menu should overlap its trigger. */
@Input({transform: booleanAttribute}) overlapTrigger: boolean;
/** Whether the menu has a backdrop. */
@Input({transform: (value: any) => (value == null ? null : booleanAttribute(value))})
hasBackdrop?: boolean;
/**
* This method takes classes set on the host mat-menu element and applies them on the
* menu template that displays in the overlay container. Otherwise, it's difficult
* to style the containing menu from outside the component.
* @param classes list of class names
*/
@Input('class')
set panelClass(classes: string) {
const previousPanelClass = this._previousPanelClass;
const newClassList = {...this._classList};
if (previousPanelClass && previousPanelClass.length) {
previousPanelClass.split(' ').forEach((className: string) => {
newClassList[className] = false;
});
}
this._previousPanelClass = classes;
if (classes && classes.length) {
classes.split(' ').forEach((className: string) => {
newClassList[className] = true;
});
this._elementRef.nativeElement.className = '';
}
this._classList = newClassList;
}
private _previousPanelClass: string;
/**
* This method takes classes set on the host mat-menu element and applies them on the
* menu template that displays in the overlay container. Otherwise, it's difficult
* to style the containing menu from outside the component.
* @deprecated Use `panelClass` instead.
* @breaking-change 8.0.0
*/
@Input()
get classList(): string {
return this.panelClass;
}
set classList(classes: string) {
this.panelClass = classes;
}
/** Event emitted when the menu is closed. */
@Output() readonly closed: EventEmitter<MenuCloseReason> = new EventEmitter<MenuCloseReason>();
/**
* Event emitted when the menu is closed.
* @deprecated Switch to `closed` instead
* @breaking-change 8.0.0
*/
@Output() readonly close: EventEmitter<MenuCloseReason> = this.closed;
readonly panelId = `mat-menu-panel-${menuPanelUid++}`;
private _injector = inject(Injector);
constructor(...args: unknown[]);
constructor() {
const defaultOptions = inject<MatMenuDefaultOptions>(MAT_MENU_DEFAULT_OPTIONS);
this.overlayPanelClass = defaultOptions.overlayPanelClass || '';
this._xPosition = defaultOptions.xPosition;
this._yPosition = defaultOptions.yPosition;
this.backdropClass = defaultOptions.backdropClass;
this.overlapTrigger = defaultOptions.overlapTrigger;
this.hasBackdrop = defaultOptions.hasBackdrop;
}
ngOnInit() {
this.setPositionClasses();
}
ngAfterContentInit() {
this._updateDirectDescendants();
this._keyManager = new FocusKeyManager(this._directDescendantItems)
.withWrap()
.withTypeAhead()
.withHomeAndEnd();
this._keyManager.tabOut.subscribe(() => this.closed.emit('tab'));
// If a user manually (programmatically) focuses a menu item, we need to reflect that focus
// change back to the key manager. Note that we don't need to unsubscribe here because _focused
// is internal and we know that it gets completed on destroy.
this._directDescendantItems.changes
.pipe(
startWith(this._directDescendantItems),
switchMap(items => merge(...items.map((item: MatMenuItem) => item._focused))),
)
.subscribe(focusedItem => this._keyManager.updateActiveItem(focusedItem as MatMenuItem));
this._directDescendantItems.changes.subscribe((itemsList: QueryList<MatMenuItem>) => {
// Move focus to another item, if the active item is removed from the list.
// We need to debounce the callback, because multiple items might be removed
// in quick succession.
const manager = this._keyManager;
if (this._panelAnimationState === 'enter' && manager.activeItem?._hasFocus()) {
const items = itemsList.toArray();
const index = Math.max(0, Math.min(items.length - 1, manager.activeItemIndex || 0));
if (items[index] && !items[index].disabled) {
manager.setActiveItem(index);
} else {
manager.setNextItemActive();
}
}
});
}
ngOnDestroy() {
this._keyManager?.destroy();
this._directDescendantItems.destroy();
this.closed.complete();
this._firstItemFocusRef?.destroy();
}
/** Stream that emits whenever the hovered menu item changes. */
_hovered(): Observable<MatMenuItem> {
// Coerce the `changes` property because Angular types it as `Observable<any>`
const itemChanges = this._directDescendantItems.changes as Observable<QueryList<MatMenuItem>>;
return itemChanges.pipe(
startWith(this._directDescendantItems),
switchMap(items => merge(...items.map((item: MatMenuItem) => item._hovered))),
) as Observable<MatMenuItem>;
}
/*
* Registers a menu item with the menu.
* @docs-private
* @deprecated No longer being used. To be removed.
* @breaking-change 9.0.0
*/
addItem(_item: MatMenuItem) {}
/**
* Removes an item from the menu.
* @docs-private
* @deprecated No longer being used. To be removed.
* @breaking-change 9.0.0
*/
removeItem(_item: MatMenuItem) {}
/** Handle a keyboard event from the menu, delegating to the appropriate action. */ | {
"end_byte": 11406,
"start_byte": 3164,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.ts"
} |
components/src/material/menu/menu.ts_11409_18316 | _handleKeydown(event: KeyboardEvent) {
const keyCode = event.keyCode;
const manager = this._keyManager;
switch (keyCode) {
case ESCAPE:
if (!hasModifierKey(event)) {
event.preventDefault();
this.closed.emit('keydown');
}
break;
case LEFT_ARROW:
if (this.parentMenu && this.direction === 'ltr') {
this.closed.emit('keydown');
}
break;
case RIGHT_ARROW:
if (this.parentMenu && this.direction === 'rtl') {
this.closed.emit('keydown');
}
break;
default:
if (keyCode === UP_ARROW || keyCode === DOWN_ARROW) {
manager.setFocusOrigin('keyboard');
}
manager.onKeydown(event);
return;
}
// Don't allow the event to propagate if we've already handled it, or it may
// end up reaching other overlays that were opened earlier (see #22694).
event.stopPropagation();
}
/**
* Focus the first item in the menu.
* @param origin Action from which the focus originated. Used to set the correct styling.
*/
focusFirstItem(origin: FocusOrigin = 'program'): void {
// Wait for `afterNextRender` to ensure iOS VoiceOver screen reader focuses the first item (#24735).
this._firstItemFocusRef?.destroy();
this._firstItemFocusRef = afterNextRender(
() => {
let menuPanel: HTMLElement | null = null;
if (this._directDescendantItems.length) {
// Because the `mat-menuPanel` is at the DOM insertion point, not inside the overlay, we don't
// have a nice way of getting a hold of the menuPanel panel. We can't use a `ViewChild` either
// because the panel is inside an `ng-template`. We work around it by starting from one of
// the items and walking up the DOM.
menuPanel = this._directDescendantItems.first!._getHostElement().closest('[role="menu"]');
}
// If an item in the menuPanel is already focused, avoid overriding the focus.
if (!menuPanel || !menuPanel.contains(document.activeElement)) {
const manager = this._keyManager;
manager.setFocusOrigin(origin).setFirstItemActive();
// If there's no active item at this point, it means that all the items are disabled.
// Move focus to the menuPanel panel so keyboard events like Escape still work. Also this will
// give _some_ feedback to screen readers.
if (!manager.activeItem && menuPanel) {
menuPanel.focus();
}
}
},
{injector: this._injector},
);
}
/**
* Resets the active item in the menu. This is used when the menu is opened, allowing
* the user to start from the first option when pressing the down arrow.
*/
resetActiveItem() {
this._keyManager.setActiveItem(-1);
}
/**
* Sets the menu panel elevation.
* @param depth Number of parent menus that come before the menu.
*/
setElevation(depth: number): void {
// The base elevation depends on which version of the spec
// we're running so we have to resolve it at runtime.
if (this._baseElevation === null) {
const styles =
typeof getComputedStyle === 'function'
? getComputedStyle(this._elementRef.nativeElement)
: null;
const value = styles?.getPropertyValue('--mat-menu-base-elevation-level') || '8';
this._baseElevation = parseInt(value);
}
// The elevation starts at the base and increases by one for each level.
// Capped at 24 because that's the maximum elevation defined in the Material design spec.
const elevation = Math.min(this._baseElevation + depth, 24);
const newElevation = `${this._elevationPrefix}${elevation}`;
const customElevation = Object.keys(this._classList).find(className => {
return className.startsWith(this._elevationPrefix);
});
if (!customElevation || customElevation === this._previousElevation) {
const newClassList = {...this._classList};
if (this._previousElevation) {
newClassList[this._previousElevation] = false;
}
newClassList[newElevation] = true;
this._previousElevation = newElevation;
this._classList = newClassList;
}
}
/**
* Adds classes to the menu panel based on its position. Can be used by
* consumers to add specific styling based on the position.
* @param posX Position of the menu along the x axis.
* @param posY Position of the menu along the y axis.
* @docs-private
*/
setPositionClasses(posX: MenuPositionX = this.xPosition, posY: MenuPositionY = this.yPosition) {
this._classList = {
...this._classList,
['mat-menu-before']: posX === 'before',
['mat-menu-after']: posX === 'after',
['mat-menu-above']: posY === 'above',
['mat-menu-below']: posY === 'below',
};
this._changeDetectorRef.markForCheck();
}
/** Starts the enter animation. */
_startAnimation() {
// @breaking-change 8.0.0 Combine with _resetAnimation.
this._panelAnimationState = 'enter';
}
/** Resets the panel animation to its initial state. */
_resetAnimation() {
// @breaking-change 8.0.0 Combine with _startAnimation.
this._panelAnimationState = 'void';
}
/** Callback that is invoked when the panel animation completes. */
_onAnimationDone(event: AnimationEvent) {
this._animationDone.next(event);
this._isAnimating = false;
}
_onAnimationStart(event: AnimationEvent) {
this._isAnimating = true;
// Scroll the content element to the top as soon as the animation starts. This is necessary,
// because we move focus to the first item while it's still being animated, which can throw
// the browser off when it determines the scroll position. Alternatively we can move focus
// when the animation is done, however moving focus asynchronously will interrupt screen
// readers which are in the process of reading out the menu already. We take the `element`
// from the `event` since we can't use a `ViewChild` to access the pane.
if (event.toState === 'enter' && this._keyManager.activeItemIndex === 0) {
event.element.scrollTop = 0;
}
}
/**
* Sets up a stream that will keep track of any newly-added menu items and will update the list
* of direct descendants. We collect the descendants this way, because `_allItems` can include
* items that are part of child menus, and using a custom way of registering items is unreliable
* when it comes to maintaining the item order.
*/
private _updateDirectDescendants() {
this._allItems.changes
.pipe(startWith(this._allItems))
.subscribe((items: QueryList<MatMenuItem>) => {
this._directDescendantItems.reset(items.filter(item => item._parentMenu === this));
this._directDescendantItems.notifyOnChanges();
});
}
} | {
"end_byte": 18316,
"start_byte": 11409,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.ts"
} |
components/src/material/menu/README.md_0_95 | Please see the official documentation at https://material.angular.io/components/component/menu
| {
"end_byte": 95,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/README.md"
} |
components/src/material/menu/menu-panel.ts_0_1618 | /**
* @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 {EventEmitter, TemplateRef, InjectionToken} from '@angular/core';
import {MenuPositionX, MenuPositionY} from './menu-positions';
import {Direction} from '@angular/cdk/bidi';
import {FocusOrigin} from '@angular/cdk/a11y';
import {MatMenuContent} from './menu-content';
/**
* Injection token used to provide the parent menu to menu-specific components.
* @docs-private
*/
export const MAT_MENU_PANEL = new InjectionToken<MatMenuPanel>('MAT_MENU_PANEL');
/**
* Interface for a custom menu panel that can be used with `matMenuTriggerFor`.
* @docs-private
*/
export interface MatMenuPanel<T = any> {
xPosition: MenuPositionX;
yPosition: MenuPositionY;
overlapTrigger: boolean;
templateRef: TemplateRef<any>;
readonly close: EventEmitter<void | 'click' | 'keydown' | 'tab'>;
parentMenu?: MatMenuPanel | undefined;
direction?: Direction;
focusFirstItem: (origin?: FocusOrigin) => void;
resetActiveItem: () => void;
setPositionClasses?: (x: MenuPositionX, y: MenuPositionY) => void;
setElevation?(depth: number): void;
lazyContent?: MatMenuContent;
backdropClass?: string;
overlayPanelClass?: string | string[];
hasBackdrop?: boolean;
readonly panelId?: string;
/**
* @deprecated To be removed.
* @breaking-change 8.0.0
*/
addItem?: (item: T) => void;
/**
* @deprecated To be removed.
* @breaking-change 8.0.0
*/
removeItem?: (item: T) => void;
}
| {
"end_byte": 1618,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu-panel.ts"
} |
components/src/material/menu/menu-animations.ts_0_2123 | /**
* @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 {
trigger,
state,
style,
animate,
transition,
AnimationTriggerMetadata,
} from '@angular/animations';
/**
* Animations used by the mat-menu component.
* Animation duration and timing values are based on:
* https://material.io/guidelines/components/menus.html#menus-usage
* @docs-private
*/
export const matMenuAnimations: {
readonly transformMenu: AnimationTriggerMetadata;
readonly fadeInItems: AnimationTriggerMetadata;
} = {
/**
* This animation controls the menu panel's entry and exit from the page.
*
* When the menu panel is added to the DOM, it scales in and fades in its border.
*
* When the menu panel is removed from the DOM, it simply fades out after a brief
* delay to display the ripple.
*/
transformMenu: trigger('transformMenu', [
state(
'void',
style({
opacity: 0,
transform: 'scale(0.8)',
}),
),
transition(
'void => enter',
animate(
'120ms cubic-bezier(0, 0, 0.2, 1)',
style({
opacity: 1,
transform: 'scale(1)',
}),
),
),
transition('* => void', animate('100ms 25ms linear', style({opacity: 0}))),
]),
/**
* This animation fades in the background color and content of the menu panel
* after its containing element is scaled in.
*/
fadeInItems: trigger('fadeInItems', [
// TODO(crisbeto): this is inside the `transformMenu`
// now. Remove next time we do breaking changes.
state('showing', style({opacity: 1})),
transition('void => *', [
style({opacity: 0}),
animate('400ms 100ms cubic-bezier(0.55, 0, 0.55, 0.2)'),
]),
]),
};
/**
* @deprecated
* @breaking-change 8.0.0
* @docs-private
*/
export const fadeInItems = matMenuAnimations.fadeInItems;
/**
* @deprecated
* @breaking-change 8.0.0
* @docs-private
*/
export const transformMenu = matMenuAnimations.transformMenu;
| {
"end_byte": 2123,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu-animations.ts"
} |
components/src/material/menu/menu-item.ts_0_5362 | /**
* @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,
OnDestroy,
ViewEncapsulation,
Input,
AfterViewInit,
ChangeDetectorRef,
booleanAttribute,
inject,
} from '@angular/core';
import {FocusableOption, FocusMonitor, FocusOrigin} from '@angular/cdk/a11y';
import {Subject} from 'rxjs';
import {DOCUMENT} from '@angular/common';
import {MatMenuPanel, MAT_MENU_PANEL} from './menu-panel';
import {_StructuralStylesLoader, MatRipple} from '@angular/material/core';
import {_CdkPrivateStyleLoader} from '@angular/cdk/private';
/**
* Single item inside a `mat-menu`. Provides the menu item styling and accessibility treatment.
*/
@Component({
selector: '[mat-menu-item]',
exportAs: 'matMenuItem',
host: {
'[attr.role]': 'role',
'class': 'mat-mdc-menu-item mat-focus-indicator',
'[class.mat-mdc-menu-item-highlighted]': '_highlighted',
'[class.mat-mdc-menu-item-submenu-trigger]': '_triggersSubmenu',
'[attr.tabindex]': '_getTabIndex()',
'[attr.aria-disabled]': 'disabled',
'[attr.disabled]': 'disabled || null',
'(click)': '_checkDisabled($event)',
'(mouseenter)': '_handleMouseEnter()',
},
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
templateUrl: 'menu-item.html',
imports: [MatRipple],
})
export class MatMenuItem implements FocusableOption, AfterViewInit, OnDestroy {
private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private _document = inject(DOCUMENT);
private _focusMonitor = inject(FocusMonitor);
_parentMenu? = inject<MatMenuPanel<MatMenuItem>>(MAT_MENU_PANEL, {optional: true});
private _changeDetectorRef = inject(ChangeDetectorRef);
/** ARIA role for the menu item. */
@Input() role: 'menuitem' | 'menuitemradio' | 'menuitemcheckbox' = 'menuitem';
/** Whether the menu item is disabled. */
@Input({transform: booleanAttribute}) disabled: boolean = false;
/** Whether ripples are disabled on the menu item. */
@Input({transform: booleanAttribute}) disableRipple: boolean = false;
/** Stream that emits when the menu item is hovered. */
readonly _hovered: Subject<MatMenuItem> = new Subject<MatMenuItem>();
/** Stream that emits when the menu item is focused. */
readonly _focused = new Subject<MatMenuItem>();
/** Whether the menu item is highlighted. */
_highlighted: boolean = false;
/** Whether the menu item acts as a trigger for a sub-menu. */
_triggersSubmenu: boolean = false;
constructor(...args: unknown[]);
constructor() {
inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader);
this._parentMenu?.addItem?.(this);
}
/** Focuses the menu item. */
focus(origin?: FocusOrigin, options?: FocusOptions): void {
if (this._focusMonitor && origin) {
this._focusMonitor.focusVia(this._getHostElement(), origin, options);
} else {
this._getHostElement().focus(options);
}
this._focused.next(this);
}
ngAfterViewInit() {
if (this._focusMonitor) {
// Start monitoring the element, so it gets the appropriate focused classes. We want
// to show the focus style for menu items only when the focus was not caused by a
// mouse or touch interaction.
this._focusMonitor.monitor(this._elementRef, false);
}
}
ngOnDestroy() {
if (this._focusMonitor) {
this._focusMonitor.stopMonitoring(this._elementRef);
}
if (this._parentMenu && this._parentMenu.removeItem) {
this._parentMenu.removeItem(this);
}
this._hovered.complete();
this._focused.complete();
}
/** Used to set the `tabindex`. */
_getTabIndex(): string {
return this.disabled ? '-1' : '0';
}
/** Returns the host DOM element. */
_getHostElement(): HTMLElement {
return this._elementRef.nativeElement;
}
/** Prevents the default element actions if it is disabled. */
_checkDisabled(event: Event): void {
if (this.disabled) {
event.preventDefault();
event.stopPropagation();
}
}
/** Emits to the hover stream. */
_handleMouseEnter() {
this._hovered.next(this);
}
/** Gets the label to be used when determining whether the option should be focused. */
getLabel(): string {
const clone = this._elementRef.nativeElement.cloneNode(true) as HTMLElement;
const icons = clone.querySelectorAll('mat-icon, .material-icons');
// Strip away icons, so they don't show up in the text.
for (let i = 0; i < icons.length; i++) {
icons[i].remove();
}
return clone.textContent?.trim() || '';
}
_setHighlighted(isHighlighted: boolean) {
// We need to mark this for check for the case where the content is coming from a
// `matMenuContent` whose change detection tree is at the declaration position,
// not the insertion position. See #23175.
this._highlighted = isHighlighted;
this._changeDetectorRef.markForCheck();
}
_setTriggersSubmenu(triggersSubmenu: boolean) {
this._triggersSubmenu = triggersSubmenu;
this._changeDetectorRef.markForCheck();
}
_hasFocus(): boolean {
return this._document && this._document.activeElement === this._getHostElement();
}
}
| {
"end_byte": 5362,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu-item.ts"
} |
components/src/material/menu/menu-content.ts_0_3292 | /**
* @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 {DomPortalOutlet, TemplatePortal} from '@angular/cdk/portal';
import {DOCUMENT} from '@angular/common';
import {
ApplicationRef,
ChangeDetectorRef,
Directive,
InjectionToken,
Injector,
OnDestroy,
TemplateRef,
ViewContainerRef,
inject,
} from '@angular/core';
import {Subject} from 'rxjs';
/**
* Injection token that can be used to reference instances of `MatMenuContent`. It serves
* as alternative token to the actual `MatMenuContent` class which could cause unnecessary
* retention of the class and its directive metadata.
*/
export const MAT_MENU_CONTENT = new InjectionToken<MatMenuContent>('MatMenuContent');
/** Menu content that will be rendered lazily once the menu is opened. */
@Directive({
selector: 'ng-template[matMenuContent]',
providers: [{provide: MAT_MENU_CONTENT, useExisting: MatMenuContent}],
})
export class MatMenuContent implements OnDestroy {
private _template = inject<TemplateRef<any>>(TemplateRef);
private _appRef = inject(ApplicationRef);
private _injector = inject(Injector);
private _viewContainerRef = inject(ViewContainerRef);
private _document = inject(DOCUMENT);
private _changeDetectorRef = inject(ChangeDetectorRef);
private _portal: TemplatePortal<any>;
private _outlet: DomPortalOutlet;
/** Emits when the menu content has been attached. */
readonly _attached = new Subject<void>();
constructor(...args: unknown[]);
constructor() {}
/**
* Attaches the content with a particular context.
* @docs-private
*/
attach(context: any = {}) {
if (!this._portal) {
this._portal = new TemplatePortal(this._template, this._viewContainerRef);
}
this.detach();
if (!this._outlet) {
this._outlet = new DomPortalOutlet(
this._document.createElement('div'),
null,
this._appRef,
this._injector,
);
}
const element: HTMLElement = this._template.elementRef.nativeElement;
// Because we support opening the same menu from different triggers (which in turn have their
// own `OverlayRef` panel), we have to re-insert the host element every time, otherwise we
// risk it staying attached to a pane that's no longer in the DOM.
element.parentNode!.insertBefore(this._outlet.outletElement, element);
// When `MatMenuContent` is used in an `OnPush` component, the insertion of the menu
// content via `createEmbeddedView` does not cause the content to be seen as "dirty"
// by Angular. This causes the `@ContentChildren` for menu items within the menu to
// not be updated by Angular. By explicitly marking for check here, we tell Angular that
// it needs to check for new menu items and update the `@ContentChild` in `MatMenu`.
this._changeDetectorRef.markForCheck();
this._portal.attach(this._outlet, context);
this._attached.next();
}
/**
* Detaches the content.
* @docs-private
*/
detach() {
if (this._portal.isAttached) {
this._portal.detach();
}
}
ngOnDestroy() {
if (this._outlet) {
this._outlet.dispose();
}
}
}
| {
"end_byte": 3292,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu-content.ts"
} |
components/src/material/menu/menu.spec.ts_0_1304 | import {FocusMonitor} from '@angular/cdk/a11y';
import {Direction, Directionality} from '@angular/cdk/bidi';
import {
DOWN_ARROW,
END,
ENTER,
ESCAPE,
HOME,
LEFT_ARROW,
RIGHT_ARROW,
TAB,
} from '@angular/cdk/keycodes';
import {Overlay, OverlayContainer} from '@angular/cdk/overlay';
import {ScrollDispatcher, ViewportRuler} from '@angular/cdk/scrolling';
import {
ChangeDetectionStrategy,
Component,
ElementRef,
EventEmitter,
Input,
Output,
Provider,
QueryList,
TemplateRef,
Type,
ViewChild,
ViewChildren,
} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush, tick} from '@angular/core/testing';
import {MatRipple} from '@angular/material/core';
import {By} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {Subject} from 'rxjs';
import {
createKeyboardEvent,
createMouseEvent,
dispatchEvent,
dispatchFakeEvent,
dispatchKeyboardEvent,
dispatchMouseEvent,
patchElementFocus,
} from '../../cdk/testing/private';
import {MatMenu, MatMenuItem, MatMenuModule} from './index';
import {
MAT_MENU_DEFAULT_OPTIONS,
MAT_MENU_SCROLL_STRATEGY,
MatMenuPanel,
MatMenuTrigger,
MenuPositionX,
MenuPositionY,
} from './public-api';
const MENU_PANEL_TOP_PADDING = 8; | {
"end_byte": 1304,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/menu.spec.ts_1306_11005 | describe('MatMenu', () => {
let overlayContainerElement: HTMLElement;
let focusMonitor: FocusMonitor;
let viewportRuler: ViewportRuler;
function createComponent<T>(
component: Type<T>,
providers: Provider[] = [],
declarations: any[] = [],
): ComponentFixture<T> {
TestBed.configureTestingModule({
providers,
imports: [MatMenuModule, NoopAnimationsModule],
declarations: [component, ...declarations],
});
overlayContainerElement = TestBed.inject(OverlayContainer).getContainerElement();
focusMonitor = TestBed.inject(FocusMonitor);
viewportRuler = TestBed.inject(ViewportRuler);
const fixture = TestBed.createComponent<T>(component);
window.scroll(0, 0);
return fixture;
}
it('should aria-controls the menu panel', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
expect(fixture.componentInstance.triggerEl.nativeElement.getAttribute('aria-controls')).toBe(
fixture.componentInstance.menu.panelId,
);
}));
it('should set aria-haspopup based on whether a menu is assigned', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerElement = fixture.componentInstance.triggerEl.nativeElement;
expect(triggerElement.getAttribute('aria-haspopup')).toBe('menu');
fixture.componentInstance.trigger.menu = null;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(triggerElement.hasAttribute('aria-haspopup')).toBe(false);
}));
it('should open the menu as an idempotent operation', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
expect(overlayContainerElement.textContent).toBe('');
expect(() => {
fixture.componentInstance.trigger.openMenu();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.textContent).toContain('Item');
expect(overlayContainerElement.textContent).toContain('Disabled');
}).not.toThrowError();
}));
it('should close the menu when a click occurs outside the menu', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
const backdrop = <HTMLElement>overlayContainerElement.querySelector('.cdk-overlay-backdrop');
backdrop.click();
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.textContent).toBe('');
}));
it('should be able to remove the backdrop', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.menu.hasBackdrop = false;
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.querySelector('.cdk-overlay-backdrop')).toBeFalsy();
}));
it('should set the correct aria-haspopup value on the trigger element', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerElement = fixture.componentInstance.triggerEl.nativeElement;
expect(triggerElement.getAttribute('aria-haspopup')).toBe('menu');
}));
it('should be able to remove the backdrop on repeat openings', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
// Start off with a backdrop.
expect(overlayContainerElement.querySelector('.cdk-overlay-backdrop')).toBeTruthy();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
// Change `hasBackdrop` after the first open.
fixture.componentInstance.menu.hasBackdrop = false;
fixture.detectChanges();
// Reopen the menu.
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.querySelector('.cdk-overlay-backdrop')).toBeFalsy();
}));
it('should restore focus to the trigger when the menu was opened by keyboard', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
// A click without a mousedown before it is considered a keyboard open.
triggerEl.click();
fixture.detectChanges();
expect(overlayContainerElement.querySelector('.mat-mdc-menu-panel')).toBeTruthy();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
expect(document.activeElement).toBe(triggerEl);
}));
it('should not restore focus to the trigger if focus restoration is disabled', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
fixture.componentInstance.restoreFocus = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// A click without a mousedown before it is considered a keyboard open.
triggerEl.click();
fixture.detectChanges();
expect(overlayContainerElement.querySelector('.mat-mdc-menu-panel')).toBeTruthy();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
expect(document.activeElement).not.toBe(triggerEl);
}));
it('should be able to move focus in the closed event', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
const instance = fixture.componentInstance;
fixture.detectChanges();
const triggerEl = instance.triggerEl.nativeElement;
const button = document.createElement('button');
button.setAttribute('tabindex', '0');
document.body.appendChild(button);
triggerEl.click();
fixture.detectChanges();
const subscription = instance.trigger.menuClosed.subscribe(() => button.focus());
instance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
expect(document.activeElement).toBe(button);
button.remove();
subscription.unsubscribe();
}));
it('should restore focus to the trigger immediately once the menu is closed', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
// A click without a mousedown before it is considered a keyboard open.
triggerEl.click();
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.querySelector('.mat-mdc-menu-panel')).toBeTruthy();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
// Note: don't add a `tick` here since we're testing
// that focus is restored before the animation is done.
expect(document.activeElement).toBe(triggerEl);
tick(500);
}));
it('should move focus to another item if the active item is destroyed', fakeAsync(() => {
const fixture = createComponent(MenuWithRepeatedItems, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
triggerEl.click();
fixture.detectChanges();
tick(500);
const items = overlayContainerElement.querySelectorAll(
'.mat-mdc-menu-panel .mat-mdc-menu-item',
);
expect(document.activeElement).toBe(items[0]);
fixture.componentInstance.items.shift();
fixture.detectChanges();
tick(500);
expect(document.activeElement).toBe(items[1]);
}));
it('should be able to set a custom class on the backdrop', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.componentInstance.backdropClass = 'custom-backdrop';
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const backdrop = <HTMLElement>overlayContainerElement.querySelector('.cdk-overlay-backdrop');
expect(backdrop.classList).toContain('custom-backdrop');
}));
it('should be able to set a custom class on the overlay panel', fakeAsync(() => {
const optionsProvider = {
provide: MAT_MENU_DEFAULT_OPTIONS,
useValue: {overlayPanelClass: 'custom-panel-class'},
};
const fixture = createComponent(SimpleMenu, [optionsProvider], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const overlayPane = <HTMLElement>overlayContainerElement.querySelector('.cdk-overlay-pane');
expect(overlayPane.classList).toContain('custom-panel-class');
}));
it('should be able to set a custom classes on the overlay panel', fakeAsync(() => {
const optionsProvider = {
provide: MAT_MENU_DEFAULT_OPTIONS,
useValue: {overlayPanelClass: ['custom-panel-class-1', 'custom-panel-class-2']},
};
const fixture = createComponent(SimpleMenu, [optionsProvider], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const overlayPane = <HTMLElement>overlayContainerElement.querySelector('.cdk-overlay-pane');
expect(overlayPane.classList).toContain('custom-panel-class-1');
expect(overlayPane.classList).toContain('custom-panel-class-2');
})); | {
"end_byte": 11005,
"start_byte": 1306,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/menu.spec.ts_11009_20146 | it('should restore focus to the root trigger when the menu was opened by mouse', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchFakeEvent(triggerEl, 'mousedown');
triggerEl.click();
fixture.detectChanges();
expect(overlayContainerElement.querySelector('.mat-mdc-menu-panel')).toBeTruthy();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
expect(document.activeElement).toBe(triggerEl);
}));
it('should restore focus to the root trigger when the menu was opened by touch', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchFakeEvent(triggerEl, 'touchstart');
triggerEl.click();
fixture.detectChanges();
expect(overlayContainerElement.querySelector('.mat-mdc-menu-panel')).toBeTruthy();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
flush();
expect(document.activeElement).toBe(triggerEl);
}));
it('should scroll the panel to the top on open, when it is scrollable', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
// Add 50 items to make the menu scrollable
fixture.componentInstance.extraItems = new Array(50).fill('Hello there');
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchFakeEvent(triggerEl, 'mousedown');
triggerEl.click();
fixture.detectChanges();
// Flush due to the additional tick that is necessary for the FocusMonitor.
flush();
expect(overlayContainerElement.querySelector('.mat-mdc-menu-panel')!.scrollTop).toBe(0);
}));
it('should set the proper focus origin when restoring focus after opening by keyboard', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
patchElementFocus(triggerEl);
focusMonitor.monitor(triggerEl, false);
triggerEl.click(); // A click without a mousedown before it is considered a keyboard open.
fixture.detectChanges();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(triggerEl.classList).toContain('cdk-program-focused');
focusMonitor.stopMonitoring(triggerEl);
}));
it('should set the proper focus origin when restoring focus after opening by mouse', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchMouseEvent(triggerEl, 'mousedown');
triggerEl.click();
fixture.detectChanges();
patchElementFocus(triggerEl);
focusMonitor.monitor(triggerEl, false);
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(triggerEl.classList).toContain('cdk-mouse-focused');
focusMonitor.stopMonitoring(triggerEl);
}));
it('should set proper focus origin when right clicking on trigger, before opening by keyboard', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
patchElementFocus(triggerEl);
focusMonitor.monitor(triggerEl, false);
// Trigger a fake right click.
dispatchEvent(triggerEl, createMouseEvent('mousedown', 50, 100, undefined, undefined, 2));
// A click without a left button mousedown before it is considered a keyboard open.
triggerEl.click();
fixture.detectChanges();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(triggerEl.classList).toContain('cdk-program-focused');
focusMonitor.stopMonitoring(triggerEl);
}));
it('should set the proper focus origin when restoring focus after opening by touch', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchMouseEvent(triggerEl, 'touchstart');
triggerEl.click();
fixture.detectChanges();
patchElementFocus(triggerEl);
focusMonitor.monitor(triggerEl, false);
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
flush();
expect(triggerEl.classList).toContain('cdk-touch-focused');
focusMonitor.stopMonitoring(triggerEl);
}));
it('should close the menu when pressing ESCAPE', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
const panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel')!;
const event = createKeyboardEvent('keydown', ESCAPE);
spyOn(event, 'stopPropagation').and.callThrough();
dispatchEvent(panel, event);
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.textContent).toBe('');
expect(event.defaultPrevented).toBe(true);
expect(event.stopPropagation).toHaveBeenCalled();
}));
it('should not close the menu when pressing ESCAPE with a modifier', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
const panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel')!;
const event = createKeyboardEvent('keydown', ESCAPE, undefined, {alt: true});
dispatchEvent(panel, event);
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.textContent).toBeTruthy();
expect(event.defaultPrevented).toBe(false);
}));
it('should open a custom menu', () => {
const fixture = createComponent(CustomMenu, [], [CustomMenuPanel]);
fixture.detectChanges();
expect(overlayContainerElement.textContent).toBe('');
expect(() => {
fixture.componentInstance.trigger.openMenu();
fixture.componentInstance.trigger.openMenu();
expect(overlayContainerElement.textContent).toContain('Custom Menu header');
expect(overlayContainerElement.textContent).toContain('Custom Content');
}).not.toThrowError();
});
it('should set the panel direction based on the trigger direction', fakeAsync(() => {
const fixture = createComponent(
SimpleMenu,
[
{
provide: Directionality,
useFactory: () => ({value: 'rtl'}),
},
],
[FakeIcon],
);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const boundingBox = overlayContainerElement.querySelector(
'.cdk-overlay-connected-position-bounding-box',
)!;
expect(boundingBox.getAttribute('dir')).toEqual('rtl');
}));
it('should update the panel direction if the trigger direction changes', fakeAsync(() => {
const dirProvider = {value: 'rtl'};
const fixture = createComponent(
SimpleMenu,
[
{
provide: Directionality,
useFactory: () => dirProvider,
},
],
[FakeIcon],
);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
let boundingBox = overlayContainerElement.querySelector(
'.cdk-overlay-connected-position-bounding-box',
)!;
expect(boundingBox.getAttribute('dir')).toEqual('rtl');
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
dirProvider.value = 'ltr';
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
boundingBox = overlayContainerElement.querySelector(
'.cdk-overlay-connected-position-bounding-box',
)!;
expect(boundingBox.getAttribute('dir')).toEqual('ltr');
}));
it('should transfer any custom classes from the host to the overlay', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.componentInstance.panelClass = 'custom-one custom-two';
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const menuEl = fixture.debugElement.query(By.css('mat-menu'))!.nativeElement;
const panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel')!;
expect(menuEl.classList).not.toContain('custom-one');
expect(menuEl.classList).not.toContain('custom-two');
expect(panel.classList).toContain('custom-one');
expect(panel.classList).toContain('custom-two');
})); | {
"end_byte": 20146,
"start_byte": 11009,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/menu.spec.ts_20150_29918 | it('should not remove mat-elevation class from overlay when panelClass is changed', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.componentInstance.panelClass = 'custom-one';
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel')!;
expect(panel.classList).toContain('custom-one');
expect(panel.classList).toContain('mat-elevation-z2');
fixture.componentInstance.panelClass = 'custom-two';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(panel.classList).not.toContain('custom-one');
expect(panel.classList).toContain('custom-two');
expect(panel.classList).toContain('mat-mdc-elevation-specific');
expect(panel.classList)
.withContext('Expected mat-elevation-z2 not to be removed')
.toContain('mat-elevation-z2');
}));
it('should set the "menu" role on the overlay panel', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const menuPanel = overlayContainerElement.querySelector('.mat-mdc-menu-panel');
expect(menuPanel).withContext('Expected to find a menu panel.').toBeTruthy();
const role = menuPanel ? menuPanel.getAttribute('role') : '';
expect(role).withContext('Expected panel to have the "menu" role.').toBe('menu');
}));
it('should forward ARIA attributes to the menu panel', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
const instance = fixture.componentInstance;
fixture.detectChanges();
instance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const menuPanel = overlayContainerElement.querySelector('.mat-mdc-menu-panel')!;
expect(menuPanel.hasAttribute('aria-label')).toBe(false);
expect(menuPanel.hasAttribute('aria-labelledby')).toBe(false);
expect(menuPanel.hasAttribute('aria-describedby')).toBe(false);
// Note that setting all of these at the same time is invalid,
// but it's up to the consumer to handle it correctly.
instance.ariaLabel = 'Custom aria-label';
instance.ariaLabelledby = 'custom-labelled-by';
instance.ariaDescribedby = 'custom-described-by';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(menuPanel.getAttribute('aria-label')).toBe('Custom aria-label');
expect(menuPanel.getAttribute('aria-labelledby')).toBe('custom-labelled-by');
expect(menuPanel.getAttribute('aria-describedby')).toBe('custom-described-by');
// Change these to empty strings to make sure that we don't preserve empty attributes.
instance.ariaLabel = instance.ariaLabelledby = instance.ariaDescribedby = '';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(menuPanel.hasAttribute('aria-label')).toBe(false);
expect(menuPanel.hasAttribute('aria-labelledby')).toBe(false);
expect(menuPanel.hasAttribute('aria-describedby')).toBe(false);
}));
it('should set the "menuitem" role on the items by default', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const items = Array.from(overlayContainerElement.querySelectorAll('.mat-mdc-menu-item'));
expect(items.length).toBeGreaterThan(0);
expect(items.every(item => item.getAttribute('role') === 'menuitem')).toBe(true);
}));
it('should be able to set an alternate role on the menu items', fakeAsync(() => {
const fixture = createComponent(MenuWithCheckboxItems);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const items = Array.from(overlayContainerElement.querySelectorAll('.mat-mdc-menu-item'));
expect(items.length).toBeGreaterThan(0);
expect(items.every(item => item.getAttribute('role') === 'menuitemcheckbox')).toBe(true);
}));
it('should not change focus origin if origin not specified for menu items', fakeAsync(() => {
const fixture = createComponent(MenuWithCheckboxItems);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
let [firstMenuItemDebugEl, secondMenuItemDebugEl] = fixture.debugElement.queryAll(
By.css('.mat-mdc-menu-item'),
)!;
const firstMenuItemInstance = firstMenuItemDebugEl.componentInstance as MatMenuItem;
const secondMenuItemInstance = secondMenuItemDebugEl.componentInstance as MatMenuItem;
firstMenuItemDebugEl.nativeElement.blur();
firstMenuItemInstance.focus('mouse');
secondMenuItemDebugEl.nativeElement.blur();
secondMenuItemInstance.focus();
tick(500);
expect(secondMenuItemDebugEl.nativeElement.classList).toContain('cdk-focused');
expect(secondMenuItemDebugEl.nativeElement.classList).toContain('cdk-mouse-focused');
}));
it('should not throw an error on destroy', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
expect(fixture.destroy.bind(fixture)).not.toThrow();
});
it('should be able to extract the menu item text', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
expect(fixture.componentInstance.items.first.getLabel()).toBe('Item');
});
it('should filter out icon nodes when figuring out the label', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const items = fixture.componentInstance.items.toArray();
expect(items[2].getLabel()).toBe('Item with an icon');
}));
it('should get the label of an item if the text is not in a direct descendant node', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const items = fixture.componentInstance.items.toArray();
expect(items[3].getLabel()).toBe('Item with text inside span');
}));
it('should set the proper focus origin when opening by mouse', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
spyOn(fixture.componentInstance.items.first, 'focus').and.callThrough();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchMouseEvent(triggerEl, 'mousedown');
triggerEl.click();
fixture.detectChanges();
tick(500);
expect(fixture.componentInstance.items.first.focus).toHaveBeenCalledWith('mouse');
}));
it('should set the proper focus origin when opening by touch', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
spyOn(fixture.componentInstance.items.first, 'focus').and.callThrough();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchMouseEvent(triggerEl, 'touchstart');
triggerEl.click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.items.first.focus).toHaveBeenCalledWith('touch');
}));
it('should set the proper origin when calling focusFirstItem after the opening sequence has started', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
spyOn(fixture.componentInstance.items.first, 'focus').and.callThrough();
fixture.componentInstance.trigger.openMenu();
fixture.componentInstance.menu.focusFirstItem('mouse');
fixture.componentInstance.menu.focusFirstItem('touch');
fixture.detectChanges();
expect(fixture.componentInstance.items.first.focus).toHaveBeenCalledOnceWith('touch');
});
it('should close the menu when using the CloseScrollStrategy', fakeAsync(() => {
const scrolledSubject = new Subject();
const fixture = createComponent(
SimpleMenu,
[
{provide: ScrollDispatcher, useFactory: () => ({scrolled: () => scrolledSubject})},
{
provide: MAT_MENU_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: (overlay: Overlay) => () => overlay.scrollStrategies.close(),
},
],
[FakeIcon],
);
fixture.detectChanges();
const trigger = fixture.componentInstance.trigger;
trigger.openMenu();
fixture.detectChanges();
expect(trigger.menuOpen).toBe(true);
scrolledSubject.next();
tick(500);
expect(trigger.menuOpen).toBe(false);
}));
it('should switch to keyboard focus when using the keyboard after opening using the mouse', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.triggerEl.nativeElement.click();
fixture.detectChanges();
const panel = document.querySelector('.mat-mdc-menu-panel')! as HTMLElement;
const items: HTMLElement[] = Array.from(
panel.querySelectorAll('.mat-mdc-menu-panel [mat-menu-item]'),
);
items.forEach(item => patchElementFocus(item));
tick(500);
tick();
fixture.detectChanges();
expect(items.some(item => item.classList.contains('cdk-keyboard-focused'))).toBe(false);
dispatchKeyboardEvent(panel, 'keydown', DOWN_ARROW);
fixture.detectChanges();
// Flush due to the additional tick that is necessary for the FocusMonitor.
flush();
// We skip to the third item, because the second one is disabled.
expect(items[2].classList).toContain('cdk-focused');
expect(items[2].classList).toContain('cdk-keyboard-focused');
})); | {
"end_byte": 29918,
"start_byte": 20150,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/menu.spec.ts_29922_39136 | it('should set the keyboard focus origin when opened using the keyboard', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const trigger = fixture.componentInstance.triggerEl.nativeElement;
// Note that we dispatch both a `click` and a `keydown` to imitate the browser behavior.
dispatchKeyboardEvent(trigger, 'keydown', ENTER);
trigger.click();
fixture.detectChanges();
const items = Array.from<HTMLElement>(
document.querySelectorAll('.mat-mdc-menu-panel [mat-menu-item]'),
);
items.forEach(item => patchElementFocus(item));
tick(500);
tick();
fixture.detectChanges();
expect(items[0].classList).toContain('cdk-keyboard-focused');
}));
it('should toggle the aria-expanded attribute on the trigger', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
expect(triggerEl.getAttribute('aria-expanded')).toBe('false');
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
expect(triggerEl.getAttribute('aria-expanded')).toBe('true');
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
expect(triggerEl.getAttribute('aria-expanded')).toBe('false');
}));
it('should toggle aria-expanded on the trigger in an OnPush component', fakeAsync(() => {
const fixture = createComponent(SimpleMenuOnPush, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
expect(triggerEl.getAttribute('aria-expanded')).toBe('false');
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
expect(triggerEl.getAttribute('aria-expanded')).toBe('true');
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
expect(triggerEl.getAttribute('aria-expanded')).toBe('false');
}));
it('should throw if assigning a menu that contains the trigger', fakeAsync(() => {
expect(() => {
const fixture = createComponent(InvalidRecursiveMenu, [], [FakeIcon]);
fixture.detectChanges();
tick(500);
}).toThrowError(/menu cannot contain its own trigger/);
}));
it('should be able to swap out a menu after the first time it is opened', fakeAsync(() => {
const fixture = createComponent(DynamicPanelMenu);
fixture.detectChanges();
expect(overlayContainerElement.textContent).toBe('');
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
expect(overlayContainerElement.textContent).toContain('One');
expect(overlayContainerElement.textContent).not.toContain('Two');
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(overlayContainerElement.textContent).toBe('');
fixture.componentInstance.trigger.menu = fixture.componentInstance.secondMenu;
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
expect(overlayContainerElement.textContent).not.toContain('One');
expect(overlayContainerElement.textContent).toContain('Two');
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(overlayContainerElement.textContent).toBe('');
}));
it('should focus the first item when pressing home', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
// Reset the automatic focus when the menu is opened.
(document.activeElement as HTMLElement)?.blur();
const panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel')!;
const items = Array.from(panel.querySelectorAll('.mat-mdc-menu-item')) as HTMLElement[];
items.forEach(patchElementFocus);
// Focus the last item since focus starts from the first one.
items[items.length - 1].focus();
fixture.detectChanges();
spyOn(items[0], 'focus').and.callThrough();
const event = dispatchKeyboardEvent(panel, 'keydown', HOME);
fixture.detectChanges();
expect(items[0].focus).toHaveBeenCalled();
expect(event.defaultPrevented).toBe(true);
flush();
}));
it('should not focus the first item when pressing home with a modifier key', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
const panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel')!;
const items = Array.from(panel.querySelectorAll('.mat-mdc-menu-item')) as HTMLElement[];
items.forEach(patchElementFocus);
// Focus the last item since focus starts from the first one.
items[items.length - 1].focus();
fixture.detectChanges();
spyOn(items[0], 'focus').and.callThrough();
const event = createKeyboardEvent('keydown', HOME, undefined, {alt: true});
dispatchEvent(panel, event);
fixture.detectChanges();
expect(items[0].focus).not.toHaveBeenCalled();
expect(event.defaultPrevented).toBe(false);
flush();
}));
it('should focus the last item when pressing end', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
const panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel')!;
const items = Array.from(panel.querySelectorAll('.mat-mdc-menu-item')) as HTMLElement[];
items.forEach(patchElementFocus);
spyOn(items[items.length - 1], 'focus').and.callThrough();
const event = dispatchKeyboardEvent(panel, 'keydown', END);
fixture.detectChanges();
expect(items[items.length - 1].focus).toHaveBeenCalled();
expect(event.defaultPrevented).toBe(true);
flush();
}));
it('should not focus the last item when pressing end with a modifier key', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
const panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel')!;
const items = Array.from(panel.querySelectorAll('.mat-mdc-menu-item')) as HTMLElement[];
items.forEach(patchElementFocus);
spyOn(items[items.length - 1], 'focus').and.callThrough();
const event = createKeyboardEvent('keydown', END, undefined, {alt: true});
dispatchEvent(panel, event);
fixture.detectChanges();
expect(items[items.length - 1].focus).not.toHaveBeenCalled();
expect(event.defaultPrevented).toBe(false);
flush();
}));
it('should respect the DOM order, rather than insertion order, when moving focus using the arrow keys', fakeAsync(() => {
let fixture = createComponent(SimpleMenuWithRepeater);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
let menuPanel = document.querySelector('.mat-mdc-menu-panel')!;
let items = menuPanel.querySelectorAll('.mat-mdc-menu-panel [mat-menu-item]');
expect(document.activeElement)
.withContext('Expected first item to be focused on open')
.toBe(items[0]);
// Add a new item after the first one.
fixture.componentInstance.items.splice(1, 0, {label: 'Calzone', disabled: false});
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
items = menuPanel.querySelectorAll('.mat-mdc-menu-panel [mat-menu-item]');
dispatchKeyboardEvent(menuPanel, 'keydown', DOWN_ARROW);
fixture.detectChanges();
tick();
expect(document.activeElement).withContext('Expected second item to be focused').toBe(items[1]);
flush();
}));
it('should sync the focus order when an item is focused programmatically', fakeAsync(() => {
const fixture = createComponent(SimpleMenuWithRepeater);
// Add some more items to work with.
for (let i = 0; i < 5; i++) {
fixture.componentInstance.items.push({label: `Extra ${i}`, disabled: false});
}
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const menuPanel = document.querySelector('.mat-mdc-menu-panel')!;
const items = menuPanel.querySelectorAll('.mat-mdc-menu-panel [mat-menu-item]');
expect(document.activeElement)
.withContext('Expected first item to be focused on open')
.toBe(items[0]);
fixture.componentInstance.itemInstances.toArray()[3].focus();
fixture.detectChanges();
expect(document.activeElement).withContext('Expected fourth item to be focused').toBe(items[3]);
dispatchKeyboardEvent(menuPanel, 'keydown', DOWN_ARROW);
fixture.detectChanges();
tick();
expect(document.activeElement).withContext('Expected fifth item to be focused').toBe(items[4]);
flush();
})); | {
"end_byte": 39136,
"start_byte": 29922,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/menu.spec.ts_39140_47391 | it('should open submenus when the menu is inside an OnPush component', fakeAsync(() => {
const fixture = createComponent(LazyMenuWithOnPush);
fixture.detectChanges();
// Open the top-level menu
fixture.componentInstance.rootTrigger.nativeElement.click();
fixture.detectChanges();
flush();
// Dispatch a `mouseenter` on the menu item to open the submenu.
// This will only work if the top-level menu is aware the this menu item exists.
dispatchMouseEvent(fixture.componentInstance.menuItemWithSubmenu.nativeElement, 'mouseenter');
fixture.detectChanges();
flush();
expect(overlayContainerElement.querySelectorAll('.mat-mdc-menu-item').length)
.withContext('Expected two open menus')
.toBe(2);
}));
it('should focus the menu panel if all items are disabled', fakeAsync(() => {
const fixture = createComponent(SimpleMenuWithRepeater, [], [FakeIcon]);
fixture.componentInstance.items.forEach(item => (item.disabled = true));
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
expect(document.activeElement).toBe(
overlayContainerElement.querySelector('.mat-mdc-menu-panel'),
);
}));
it('should focus the menu panel if all items are disabled inside lazy content', fakeAsync(() => {
const fixture = createComponent(SimpleMenuWithRepeaterInLazyContent, [], [FakeIcon]);
fixture.componentInstance.items.forEach(item => (item.disabled = true));
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
expect(document.activeElement).toBe(
overlayContainerElement.querySelector('.mat-mdc-menu-panel'),
);
}));
it('should clear the static aria-label from the menu host', fakeAsync(() => {
const fixture = createComponent(StaticAriaLabelMenu);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('mat-menu').hasAttribute('aria-label')).toBe(false);
}));
it('should clear the static aria-labelledby from the menu host', fakeAsync(() => {
const fixture = createComponent(StaticAriaLabelledByMenu);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('mat-menu').hasAttribute('aria-labelledby')).toBe(
false,
);
}));
it('should clear the static aria-describedby from the menu host', fakeAsync(() => {
const fixture = createComponent(StaticAriaDescribedbyMenu);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('mat-menu').hasAttribute('aria-describedby')).toBe(
false,
);
}));
it('should be able to move focus inside the `open` event', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.menuOpened.subscribe(() => {
(document.querySelectorAll('.mat-mdc-menu-panel [mat-menu-item]')[3] as HTMLElement).focus();
});
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const items = document.querySelectorAll('.mat-mdc-menu-panel [mat-menu-item]');
expect(document.activeElement).withContext('Expected fourth item to be focused').toBe(items[3]);
}));
it('should default to the "below" and "after" positions', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel') as HTMLElement;
expect(panel.classList).toContain('mat-menu-below');
expect(panel.classList).toContain('mat-menu-after');
}));
it('should keep the panel in the viewport when more items are added while open', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
triggerEl.style.position = 'absolute';
triggerEl.style.left = '200px';
triggerEl.style.bottom = '300px';
triggerEl.click();
fixture.detectChanges();
const panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel')!;
const viewportHeight = viewportRuler.getViewportSize().height;
let panelRect = panel.getBoundingClientRect();
expect(Math.floor(panelRect.bottom)).toBeLessThan(viewportHeight);
fixture.componentInstance.extraItems = new Array(50).fill('Hello there');
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
panelRect = panel.getBoundingClientRect();
expect(Math.floor(panelRect.bottom)).toBe(viewportHeight);
});
describe('lazy rendering', () => {
it('should be able to render the menu content lazily', fakeAsync(() => {
const fixture = createComponent(SimpleLazyMenu);
fixture.detectChanges();
fixture.componentInstance.triggerEl.nativeElement.click();
fixture.detectChanges();
tick(500);
const panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel')!;
expect(panel).withContext('Expected panel to be defined').toBeTruthy();
expect(panel.textContent)
.withContext('Expected panel to have correct content')
.toContain('Another item');
expect(fixture.componentInstance.trigger.menuOpen)
.withContext('Expected menu to be open')
.toBe(true);
}));
it('should detach the lazy content when the menu is closed', fakeAsync(() => {
const fixture = createComponent(SimpleLazyMenu);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
expect(fixture.componentInstance.items.length).toBeGreaterThan(0);
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(fixture.componentInstance.items.length).toBe(0);
}));
it('should wait for the close animation to finish before considering the panel as closed', fakeAsync(() => {
const fixture = createComponent(SimpleLazyMenu);
fixture.detectChanges();
const trigger = fixture.componentInstance.trigger;
expect(trigger.menuOpen).withContext('Expected menu to start off closed').toBe(false);
trigger.openMenu();
fixture.detectChanges();
tick(500);
expect(trigger.menuOpen).withContext('Expected menu to be open').toBe(true);
trigger.closeMenu();
fixture.detectChanges();
expect(trigger.menuOpen)
.withContext('Expected menu to be considered open while the close animation is running')
.toBe(true);
tick(500);
fixture.detectChanges();
expect(trigger.menuOpen).withContext('Expected menu to be closed').toBe(false);
}));
it('should focus the first menu item when opening a lazy menu via keyboard', async () => {
const fixture = createComponent(SimpleLazyMenu);
fixture.autoDetectChanges();
// A click without a mousedown before it is considered a keyboard open.
fixture.componentInstance.triggerEl.nativeElement.click();
await fixture.whenStable();
const item = document.querySelector('.mat-mdc-menu-panel [mat-menu-item]')!;
expect(document.activeElement).withContext('Expected first item to be focused').toBe(item);
});
it('should be able to open the same menu with a different context', fakeAsync(() => {
const fixture = createComponent(LazyMenuWithContext);
fixture.detectChanges();
fixture.componentInstance.triggerOne.openMenu();
fixture.detectChanges();
tick(500);
let item = overlayContainerElement.querySelector('.mat-mdc-menu-panel [mat-menu-item]')!;
expect(item.textContent!.trim()).toBe('one');
fixture.componentInstance.triggerOne.closeMenu();
fixture.detectChanges();
tick(500);
fixture.componentInstance.triggerTwo.openMenu();
fixture.detectChanges();
tick(500);
item = overlayContainerElement.querySelector('.mat-mdc-menu-panel [mat-menu-item]')!;
expect(item.textContent!.trim()).toBe('two');
}));
}); | {
"end_byte": 47391,
"start_byte": 39140,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/menu.spec.ts_47395_51620 | describe('positions', () => {
let fixture: ComponentFixture<PositionedMenu>;
let trigger: HTMLElement;
beforeEach(fakeAsync(() => {
fixture = createComponent(PositionedMenu);
fixture.detectChanges();
trigger = fixture.componentInstance.triggerEl.nativeElement;
// Push trigger to the bottom edge of viewport,so it has space to open "above"
trigger.style.position = 'fixed';
trigger.style.top = '600px';
// Push trigger to the right, so it has space to open "before"
trigger.style.left = '100px';
}));
it('should append mat-menu-before if the x position is changed', fakeAsync(() => {
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel') as HTMLElement;
expect(panel.classList).toContain('mat-menu-before');
expect(panel.classList).not.toContain('mat-menu-after');
fixture.componentInstance.xPosition = 'after';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(panel.classList).toContain('mat-menu-after');
expect(panel.classList).not.toContain('mat-menu-before');
}));
it('should append mat-menu-above if the y position is changed', fakeAsync(() => {
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel') as HTMLElement;
expect(panel.classList).toContain('mat-menu-above');
expect(panel.classList).not.toContain('mat-menu-below');
fixture.componentInstance.yPosition = 'below';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(panel.classList).toContain('mat-menu-below');
expect(panel.classList).not.toContain('mat-menu-above');
}));
it('should update the position classes if the window is resized', fakeAsync(() => {
trigger.style.position = 'fixed';
trigger.style.top = '300px';
fixture.componentInstance.yPosition = 'above';
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel') as HTMLElement;
expect(panel.classList).toContain('mat-menu-above');
expect(panel.classList).not.toContain('mat-menu-below');
trigger.style.top = '0';
dispatchFakeEvent(window, 'resize');
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(panel.classList).not.toContain('mat-menu-above');
expect(panel.classList).toContain('mat-menu-below');
}));
it('should be able to update the position after the first open', fakeAsync(() => {
trigger.style.position = 'fixed';
trigger.style.top = '200px';
fixture.componentInstance.yPosition = 'above';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
let panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel') as HTMLElement;
expect(Math.floor(panel.getBoundingClientRect().bottom))
.withContext('Expected menu to open above')
.toBe(Math.floor(trigger.getBoundingClientRect().top));
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
fixture.componentInstance.yPosition = 'below';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
panel = overlayContainerElement.querySelector('.mat-mdc-menu-panel') as HTMLElement;
expect(Math.floor(panel.getBoundingClientRect().top))
.withContext('Expected menu to open below')
.toBe(Math.floor(trigger.getBoundingClientRect().bottom));
}));
it('should not throw if a menu reposition is requested while the menu is closed', () => {
expect(() => fixture.componentInstance.trigger.updatePosition()).not.toThrow();
});
}); | {
"end_byte": 51620,
"start_byte": 47395,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/menu.spec.ts_51624_57614 | describe('fallback positions', () => {
it('should fall back to "before" mode if "after" mode would not fit on screen', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const trigger = fixture.componentInstance.triggerEl.nativeElement;
// Push trigger to the right side of viewport, so it doesn't have space to open
// in its default "after" position on the right side.
trigger.style.position = 'fixed';
trigger.style.right = '0';
trigger.style.top = '200px';
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const overlayPane = getOverlayPane();
const triggerRect = trigger.getBoundingClientRect();
const overlayRect = overlayPane.getBoundingClientRect();
// In "before" position, the right sides of the overlay and the origin are aligned.
// To find the overlay left, subtract the menu width from the origin's right side.
const expectedLeft = triggerRect.right - overlayRect.width;
expect(Math.floor(overlayRect.left))
.withContext(
`Expected menu to open in "before" position if "after" position ` + `wouldn't fit.`,
)
.toBe(Math.floor(expectedLeft));
// The y-position of the overlay should be unaffected, as it can already fit vertically
// The y-position of the overlay should be unaffected, as it can already fit vertically
expect(Math.floor(overlayRect.top))
.withContext(`Expected menu top position to be unchanged if it can fit in the viewport.`)
.toBe(Math.floor(triggerRect.bottom));
}));
it('should fall back to "above" mode if "below" mode would not fit on screen', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const trigger = fixture.componentInstance.triggerEl.nativeElement;
// Push trigger to the bottom part of viewport, so it doesn't have space to open
// in its default "below" position below the trigger.
trigger.style.position = 'fixed';
trigger.style.bottom = '65px';
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const overlayPane = getOverlayPane();
const triggerRect = trigger.getBoundingClientRect();
const overlayRect = overlayPane.getBoundingClientRect();
expect(Math.floor(overlayRect.bottom))
.withContext(`Expected menu to open in "above" position if "below" position wouldn't fit.`)
.toBe(Math.floor(triggerRect.top));
// The x-position of the overlay should be unaffected, as it can already fit horizontally
// The x-position of the overlay should be unaffected, as it can already fit horizontally
expect(Math.floor(overlayRect.left))
.withContext(`Expected menu x position to be unchanged if it can fit in the viewport.`)
.toBe(Math.floor(triggerRect.left));
}));
it('should re-position menu on both axes if both defaults would not fit', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const trigger = fixture.componentInstance.triggerEl.nativeElement;
// push trigger to the bottom, right part of viewport, so it doesn't have space to open
// in its default "after below" position.
trigger.style.position = 'fixed';
trigger.style.right = '0';
trigger.style.bottom = '0';
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const overlayPane = getOverlayPane();
const triggerRect = trigger.getBoundingClientRect();
const overlayRect = overlayPane.getBoundingClientRect();
const expectedLeft = triggerRect.right - overlayRect.width;
expect(Math.floor(overlayRect.left))
.withContext(`Expected menu to open in "before" position if "after" position wouldn't fit.`)
.toBe(Math.floor(expectedLeft));
expect(Math.floor(overlayRect.bottom))
.withContext(`Expected menu to open in "above" position if "below" position wouldn't fit.`)
.toBe(Math.floor(triggerRect.top));
}));
it('should re-position a menu with custom position set', fakeAsync(() => {
const fixture = createComponent(PositionedMenu);
fixture.detectChanges();
const trigger = fixture.componentInstance.triggerEl.nativeElement;
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const overlayPane = getOverlayPane();
const triggerRect = trigger.getBoundingClientRect();
const overlayRect = overlayPane.getBoundingClientRect();
// As designated "before" position won't fit on screen, the menu should fall back
// to "after" mode, where the left sides of the overlay and trigger are aligned.
// As designated "before" position won't fit on screen, the menu should fall back
// to "after" mode, where the left sides of the overlay and trigger are aligned.
expect(Math.floor(overlayRect.left))
.withContext(`Expected menu to open in "after" position if "before" position wouldn't fit.`)
.toBe(Math.floor(triggerRect.left));
// As designated "above" position won't fit on screen, the menu should fall back
// to "below" mode, where the top edges of the overlay and trigger are aligned.
// As designated "above" position won't fit on screen, the menu should fall back
// to "below" mode, where the top edges of the overlay and trigger are aligned.
expect(Math.floor(overlayRect.top))
.withContext(`Expected menu to open in "below" position if "above" position wouldn't fit.`)
.toBe(Math.floor(triggerRect.bottom));
}));
function getOverlayPane(): HTMLElement {
return overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement;
}
}); | {
"end_byte": 57614,
"start_byte": 51624,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/menu.spec.ts_57618_65412 | describe('overlapping trigger', () => {
/**
* This test class is used to create components containing a menu.
* It provides helpers to reposition the trigger, open the menu,
* and access the trigger and overlay positions.
* Additionally it can take any inputs for the menu wrapper component.
*
* Basic usage:
* const subject = new OverlapSubject(MyComponent);
* subject.openMenu();
*/
class OverlapSubject<T extends TestableMenu> {
readonly fixture: ComponentFixture<T>;
readonly trigger: HTMLElement;
constructor(ctor: {new (): T}, inputs: {[key: string]: any} = {}) {
this.fixture = createComponent(ctor);
Object.keys(inputs).forEach(
key => ((this.fixture.componentInstance as any)[key] = inputs[key]),
);
this.fixture.detectChanges();
this.trigger = this.fixture.componentInstance.triggerEl.nativeElement;
}
openMenu() {
this.fixture.componentInstance.trigger.openMenu();
this.fixture.detectChanges();
tick(500);
}
get overlayRect() {
return this._getOverlayPane().getBoundingClientRect();
}
get triggerRect() {
return this.trigger.getBoundingClientRect();
}
get menuPanel() {
return overlayContainerElement.querySelector('.mat-mdc-menu-panel');
}
private _getOverlayPane() {
return overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement;
}
}
let subject: OverlapSubject<OverlapMenu>;
describe('explicitly overlapping', () => {
beforeEach(fakeAsync(() => {
subject = new OverlapSubject(OverlapMenu, {overlapTrigger: true});
}));
it('positions the overlay below the trigger', fakeAsync(() => {
subject.openMenu();
// Since the menu is overlaying the trigger, the overlay top should be the trigger top.
// Since the menu is overlaying the trigger, the overlay top should be the trigger top.
expect(Math.floor(subject.overlayRect.top))
.withContext(`Expected menu to open in default "below" position.`)
.toBe(Math.floor(subject.triggerRect.top));
}));
});
describe('not overlapping', () => {
beforeEach(fakeAsync(() => {
subject = new OverlapSubject(OverlapMenu, {overlapTrigger: false});
}));
it('positions the overlay below the trigger', fakeAsync(() => {
subject.openMenu();
// Since the menu is below the trigger, the overlay top should be the trigger bottom.
// Since the menu is below the trigger, the overlay top should be the trigger bottom.
expect(Math.floor(subject.overlayRect.top))
.withContext(`Expected menu to open directly below the trigger.`)
.toBe(Math.floor(subject.triggerRect.bottom));
}));
it('supports above position fall back', fakeAsync(() => {
// Push trigger to the bottom part of viewport, so it doesn't have space to open
// in its default "below" position below the trigger.
subject.trigger.style.position = 'fixed';
subject.trigger.style.bottom = '0';
subject.openMenu();
// Since the menu is above the trigger, the overlay bottom should be the trigger top.
// Since the menu is above the trigger, the overlay bottom should be the trigger top.
expect(Math.floor(subject.overlayRect.bottom))
.withContext(
`Expected menu to open in "above" position if "below" position ` + `wouldn't fit.`,
)
.toBe(Math.floor(subject.triggerRect.top));
}));
it('repositions the origin to be below, so the menu opens from the trigger', fakeAsync(() => {
subject.openMenu();
subject.fixture.detectChanges();
expect(subject.menuPanel!.classList).toContain('mat-menu-below');
expect(subject.menuPanel!.classList).not.toContain('mat-menu-above');
}));
});
});
describe('animations', () => {
it('should enable ripples on items by default', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const item = fixture.debugElement.query(By.css('.mat-mdc-menu-item'))!;
const ripple = item.query(By.css('.mat-ripple'))!.injector.get<MatRipple>(MatRipple);
expect(ripple.disabled).toBe(false);
}));
it('should disable ripples on disabled items', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const items = fixture.debugElement.queryAll(By.css('.mat-mdc-menu-item'));
const ripple = items[1].query(By.css('.mat-ripple'))!.injector.get<MatRipple>(MatRipple);
expect(ripple.disabled).toBe(true);
}));
it('should disable ripples if disableRipple is set', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
// The third menu item in the `SimpleMenu` component has ripples disabled.
const items = fixture.debugElement.queryAll(By.css('.mat-mdc-menu-item'));
const ripple = items[2].query(By.css('.mat-ripple'))!.injector.get<MatRipple>(MatRipple);
expect(ripple.disabled).toBe(true);
}));
});
describe('close event', () => {
let fixture: ComponentFixture<SimpleMenu>;
beforeEach(fakeAsync(() => {
fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
}));
it('should emit an event when a menu item is clicked', fakeAsync(() => {
const menuItem = overlayContainerElement.querySelector('[mat-menu-item]') as HTMLElement;
menuItem.click();
fixture.detectChanges();
tick(500);
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledWith('click');
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledTimes(1);
}));
it('should emit a close event when the backdrop is clicked', fakeAsync(() => {
const backdrop = overlayContainerElement.querySelector(
'.cdk-overlay-backdrop',
) as HTMLElement;
backdrop.click();
fixture.detectChanges();
tick(500);
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledWith(undefined);
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledTimes(1);
}));
it('should emit an event when pressing ESCAPE', fakeAsync(() => {
const menu = overlayContainerElement.querySelector('.mat-mdc-menu-panel') as HTMLElement;
dispatchKeyboardEvent(menu, 'keydown', ESCAPE);
fixture.detectChanges();
tick(500);
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledWith('keydown');
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledTimes(1);
}));
it('should complete the callback when the menu is destroyed', fakeAsync(() => {
const emitCallback = jasmine.createSpy('emit callback');
const completeCallback = jasmine.createSpy('complete callback');
fixture.componentInstance.menu.closed.subscribe(emitCallback, null, completeCallback);
fixture.destroy();
tick(500);
expect(emitCallback).toHaveBeenCalledWith(undefined);
expect(emitCallback).toHaveBeenCalledTimes(1);
expect(completeCallback).toHaveBeenCalled();
}));
}); | {
"end_byte": 65412,
"start_byte": 57618,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/menu.spec.ts_65416_75192 | describe('nested menu', () => {
let fixture: ComponentFixture<NestedMenu>;
let instance: NestedMenu;
let overlay: HTMLElement;
let compileTestComponent = (direction: Direction = 'ltr') => {
fixture = createComponent(NestedMenu, [
{
provide: Directionality,
useFactory: () => ({value: direction}),
},
]);
fixture.detectChanges();
instance = fixture.componentInstance;
overlay = overlayContainerElement;
};
it('should set the `triggersSubmenu` flags on the triggers', fakeAsync(() => {
compileTestComponent();
expect(instance.rootTrigger.triggersSubmenu()).toBe(false);
expect(instance.levelOneTrigger.triggersSubmenu()).toBe(true);
expect(instance.levelTwoTrigger.triggersSubmenu()).toBe(true);
}));
it('should set the `parentMenu` on the sub-menu instances', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
tick(500);
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
tick(500);
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
tick(500);
expect(instance.rootMenu.parentMenu).toBeFalsy();
expect(instance.levelOneMenu.parentMenu).toBe(instance.rootMenu);
expect(instance.levelTwoMenu.parentMenu).toBe(instance.levelOneMenu);
}));
it('should pass the layout direction the nested menus', fakeAsync(() => {
compileTestComponent('rtl');
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
tick(500);
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
tick(500);
expect(instance.rootMenu.direction).toBe('rtl');
expect(instance.levelOneMenu.direction).toBe('rtl');
expect(instance.levelTwoMenu.direction).toBe('rtl');
}));
it('should emit an event when the hover state of the menu items changes', fakeAsync(() => {
compileTestComponent();
instance.rootTrigger.openMenu();
fixture.detectChanges();
tick(500);
const spy = jasmine.createSpy('hover spy');
const subscription = instance.rootMenu._hovered().subscribe(spy);
const menuItems = overlay.querySelectorAll('[mat-menu-item]');
dispatchMouseEvent(menuItems[0], 'mouseenter');
fixture.detectChanges();
tick(500);
expect(spy).toHaveBeenCalledTimes(1);
dispatchMouseEvent(menuItems[1], 'mouseenter');
fixture.detectChanges();
tick(500);
expect(spy).toHaveBeenCalledTimes(2);
subscription.unsubscribe();
}));
it('should toggle a nested menu when its trigger is hovered', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one open menu')
.toBe(1);
const items = Array.from(overlay.querySelectorAll('.mat-mdc-menu-panel [mat-menu-item]'));
const levelOneTrigger = overlay.querySelector('#level-one-trigger')!;
dispatchMouseEvent(levelOneTrigger, 'mouseenter');
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(levelOneTrigger.classList)
.withContext('Expected the trigger to be highlighted')
.toContain('mat-mdc-menu-item-highlighted');
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected two open menus')
.toBe(2);
dispatchMouseEvent(items[items.indexOf(levelOneTrigger) + 1], 'mouseenter');
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one open menu')
.toBe(1);
expect(levelOneTrigger.classList).not.toContain(
'mat-mdc-menu-item-highlighted',
'Expected the trigger to not be highlighted',
);
}));
it('should close all the open sub-menus when the hover state is changed at the root', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
const items = Array.from(overlay.querySelectorAll('.mat-mdc-menu-panel [mat-menu-item]'));
const levelOneTrigger = overlay.querySelector('#level-one-trigger')!;
dispatchMouseEvent(levelOneTrigger, 'mouseenter');
fixture.detectChanges();
tick();
const levelTwoTrigger = overlay.querySelector('#level-two-trigger')! as HTMLElement;
dispatchMouseEvent(levelTwoTrigger, 'mouseenter');
fixture.detectChanges();
tick();
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected three open menus')
.toBe(3);
dispatchMouseEvent(items[items.indexOf(levelOneTrigger) + 1], 'mouseenter');
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one open menu')
.toBe(1);
}));
it('should close submenu when hovering over disabled sibling item', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
tick(500);
const items = fixture.debugElement.queryAll(By.directive(MatMenuItem));
dispatchFakeEvent(items[0].nativeElement, 'mouseenter');
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected two open menus')
.toBe(2);
items[1].componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Invoke the handler directly since the fake events are flaky on disabled elements.
items[1].componentInstance._handleMouseEnter();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one open menu')
.toBe(1);
}));
it('should not open submenu when hovering over disabled trigger', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one open menu')
.toBe(1);
const item = fixture.debugElement.query(By.directive(MatMenuItem))!;
item.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Invoke the handler directly since the fake events are flaky on disabled elements.
item.componentInstance._handleMouseEnter();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected to remain at one open menu')
.toBe(1);
}));
it('should open a nested menu when its trigger is clicked', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one open menu')
.toBe(1);
const levelOneTrigger = overlay.querySelector('#level-one-trigger')! as HTMLElement;
levelOneTrigger.click();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected two open menus')
.toBe(2);
levelOneTrigger.click();
fixture.detectChanges();
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected repeat clicks not to close the menu.')
.toBe(2);
}));
it('should open and close a nested menu with arrow keys in ltr', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one open menu')
.toBe(1);
const levelOneTrigger = overlay.querySelector('#level-one-trigger')! as HTMLElement;
dispatchKeyboardEvent(levelOneTrigger, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
const panels = overlay.querySelectorAll('.mat-mdc-menu-panel');
expect(panels.length).withContext('Expected two open menus').toBe(2);
dispatchKeyboardEvent(panels[1], 'keydown', LEFT_ARROW);
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length).toBe(1);
}));
it('should open and close a nested menu with the arrow keys in rtl', fakeAsync(() => {
compileTestComponent('rtl');
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one open menu')
.toBe(1);
const levelOneTrigger = overlay.querySelector('#level-one-trigger')! as HTMLElement;
dispatchKeyboardEvent(levelOneTrigger, 'keydown', LEFT_ARROW);
fixture.detectChanges();
const panels = overlay.querySelectorAll('.mat-mdc-menu-panel');
expect(panels.length).withContext('Expected two open menus').toBe(2);
dispatchKeyboardEvent(panels[1], 'keydown', RIGHT_ARROW);
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length).toBe(1);
})); | {
"end_byte": 75192,
"start_byte": 65416,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/menu.spec.ts_75198_84633 | it('should not do anything with the arrow keys for a top-level menu', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
tick(500);
const menu = overlay.querySelector('.mat-mdc-menu-panel')!;
dispatchKeyboardEvent(menu, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one menu to remain open')
.toBe(1);
dispatchKeyboardEvent(menu, 'keydown', LEFT_ARROW);
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one menu to remain open')
.toBe(1);
}));
it('should close all of the menus when the backdrop is clicked', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
tick(500);
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
tick(500);
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected three open menus')
.toBe(3);
expect(overlay.querySelectorAll('.cdk-overlay-backdrop').length)
.withContext('Expected one backdrop element')
.toBe(1);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel, .cdk-overlay-backdrop')[0].classList)
.withContext('Expected backdrop to be beneath all of the menus')
.toContain('cdk-overlay-backdrop');
(overlay.querySelector('.cdk-overlay-backdrop')! as HTMLElement).click();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected no open menus')
.toBe(0);
}));
it('should shift focus between the sub-menus', fakeAsync(() => {
compileTestComponent();
instance.rootTrigger.openMenu();
fixture.detectChanges();
tick(500);
expect(overlay.querySelector('.mat-mdc-menu-panel')!.contains(document.activeElement))
.withContext('Expected focus to be inside the root menu')
.toBe(true);
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel')[1].contains(document.activeElement))
.withContext('Expected focus to be inside the first nested menu')
.toBe(true);
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel')[2].contains(document.activeElement))
.withContext('Expected focus to be inside the second nested menu')
.toBe(true);
instance.levelTwoTrigger.closeMenu();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel')[1].contains(document.activeElement))
.withContext('Expected focus to be back inside the first nested menu')
.toBe(true);
instance.levelOneTrigger.closeMenu();
fixture.detectChanges();
tick(500);
expect(overlay.querySelector('.mat-mdc-menu-panel')!.contains(document.activeElement))
.withContext('Expected focus to be back inside the root menu')
.toBe(true);
}));
it('should restore focus to a nested trigger when navigating via the keyboard', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
const levelOneTrigger = overlay.querySelector('#level-one-trigger')! as HTMLElement;
dispatchKeyboardEvent(levelOneTrigger, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
const spy = spyOn(levelOneTrigger, 'focus').and.callThrough();
dispatchKeyboardEvent(
overlay.querySelectorAll('.mat-mdc-menu-panel')[1],
'keydown',
LEFT_ARROW,
);
fixture.detectChanges();
tick(500);
expect(spy).toHaveBeenCalled();
}));
it('should position the sub-menu to the right edge of the trigger in ltr', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.style.position = 'fixed';
instance.rootTriggerEl.nativeElement.style.left = '50px';
instance.rootTriggerEl.nativeElement.style.top = '200px';
instance.rootTrigger.openMenu();
fixture.detectChanges();
tick(500);
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
tick(500);
const triggerRect = overlay.querySelector('#level-one-trigger')!.getBoundingClientRect();
const panelRect = overlay.querySelectorAll('.mat-mdc-menu-panel')[1].getBoundingClientRect();
expect(Math.round(triggerRect.right)).toBe(Math.round(panelRect.left));
expect(Math.round(triggerRect.top)).toBe(Math.round(panelRect.top) + MENU_PANEL_TOP_PADDING);
}));
it('should fall back to aligning to the left edge of the trigger in ltr', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.style.position = 'fixed';
instance.rootTriggerEl.nativeElement.style.right = '10px';
instance.rootTriggerEl.nativeElement.style.top = '200px';
instance.rootTrigger.openMenu();
fixture.detectChanges();
tick(500);
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
tick(500);
const triggerRect = overlay.querySelector('#level-one-trigger')!.getBoundingClientRect();
const panelRect = overlay.querySelectorAll('.mat-mdc-menu-panel')[1].getBoundingClientRect();
expect(Math.round(triggerRect.left)).toBe(Math.round(panelRect.right));
expect(Math.round(triggerRect.top)).toBe(Math.round(panelRect.top) + MENU_PANEL_TOP_PADDING);
}));
it('should position the sub-menu to the left edge of the trigger in rtl', fakeAsync(() => {
compileTestComponent('rtl');
instance.rootTriggerEl.nativeElement.style.position = 'fixed';
instance.rootTriggerEl.nativeElement.style.left = '50%';
instance.rootTriggerEl.nativeElement.style.top = '200px';
instance.rootTrigger.openMenu();
fixture.detectChanges();
tick(500);
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
tick(500);
const triggerRect = overlay.querySelector('#level-one-trigger')!.getBoundingClientRect();
const panelRect = overlay.querySelectorAll('.mat-mdc-menu-panel')[1].getBoundingClientRect();
expect(Math.round(triggerRect.left)).toBe(Math.round(panelRect.right));
expect(Math.round(triggerRect.top)).toBe(Math.round(panelRect.top) + MENU_PANEL_TOP_PADDING);
}));
it('should fall back to aligning to the right edge of the trigger in rtl', fakeAsync(() => {
compileTestComponent('rtl');
instance.rootTriggerEl.nativeElement.style.position = 'fixed';
instance.rootTriggerEl.nativeElement.style.left = '10px';
instance.rootTriggerEl.nativeElement.style.top = '200px';
instance.rootTrigger.openMenu();
fixture.detectChanges();
tick(500);
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
tick(500);
const triggerRect = overlay.querySelector('#level-one-trigger')!.getBoundingClientRect();
const panelRect = overlay.querySelectorAll('.mat-mdc-menu-panel')[1].getBoundingClientRect();
expect(Math.round(triggerRect.right)).toBe(Math.round(panelRect.left));
expect(Math.round(triggerRect.top)).toBe(Math.round(panelRect.top) + MENU_PANEL_TOP_PADDING);
}));
it('should account for custom padding when offsetting the sub-menu', () => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.style.position = 'fixed';
instance.rootTriggerEl.nativeElement.style.left = '10px';
instance.rootTriggerEl.nativeElement.style.top = '200px';
instance.rootTrigger.openMenu();
fixture.detectChanges();
// Change the padding to something different from the default.
(overlay.querySelector('.mat-mdc-menu-content') as HTMLElement).style.padding = '15px 0';
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
const triggerRect = overlay.querySelector('#level-one-trigger')!.getBoundingClientRect();
const panelRect = overlay.querySelectorAll('.mat-mdc-menu-panel')[1].getBoundingClientRect();
expect(Math.round(triggerRect.top)).toBe(Math.round(panelRect.top) + 15);
});
it('should close all of the menus when an item is clicked', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
const menus = overlay.querySelectorAll('.mat-mdc-menu-panel');
expect(menus.length).withContext('Expected three open menus').toBe(3);
(menus[2].querySelector('.mat-mdc-menu-item')! as HTMLElement).click();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected no open menus')
.toBe(0);
})); | {
"end_byte": 84633,
"start_byte": 75198,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/menu.spec.ts_84639_93496 | it('should close all of the menus when the user tabs away', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
const menus = overlay.querySelectorAll('.mat-mdc-menu-panel');
expect(menus.length).withContext('Expected three open menus').toBe(3);
dispatchKeyboardEvent(menus[menus.length - 1], 'keydown', TAB);
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected no open menus')
.toBe(0);
}));
it('should set a class on the menu items that trigger a sub-menu', fakeAsync(() => {
compileTestComponent();
instance.rootTrigger.openMenu();
fixture.detectChanges();
tick(500);
const menuItems = overlay.querySelectorAll('[mat-menu-item]');
expect(menuItems[0].classList).toContain('mat-mdc-menu-item-submenu-trigger');
expect(menuItems[0].querySelector('.mat-mdc-menu-submenu-icon')).toBeTruthy();
expect(menuItems[1].classList).not.toContain('mat-mdc-menu-item-submenu-trigger');
expect(menuItems[1].querySelector('.mat-mdc-menu-submenu-icon')).toBeFalsy();
instance.levelOneTrigger.menu = null;
fixture.detectChanges();
expect(menuItems[0].classList).not.toContain('mat-mdc-menu-item-submenu-trigger');
expect(menuItems[0].querySelector('.mat-mdc-menu-submenu-icon')).toBeFalsy();
}));
it('should increase the sub-menu elevation based on its depth', fakeAsync(() => {
compileTestComponent();
instance.rootTrigger.openMenu();
fixture.detectChanges();
tick(500);
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
tick(500);
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
tick(500);
const menus = overlay.querySelectorAll('.mat-mdc-menu-panel');
expect(menus[0].classList).toContain('mat-mdc-elevation-specific');
expect(menus[0].classList)
.withContext('Expected root menu to have base elevation.')
.toContain('mat-elevation-z2');
expect(menus[1].classList).toContain('mat-mdc-elevation-specific');
expect(menus[1].classList)
.withContext('Expected first sub-menu to have base elevation + 1.')
.toContain('mat-elevation-z3');
expect(menus[2].classList).toContain('mat-mdc-elevation-specific');
expect(menus[2].classList)
.withContext('Expected second sub-menu to have base elevation + 2.')
.toContain('mat-elevation-z4');
}));
it('should update the elevation when the same menu is opened at a different depth', fakeAsync(() => {
compileTestComponent();
instance.rootTrigger.openMenu();
fixture.detectChanges();
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
let lastMenu = overlay.querySelectorAll('.mat-mdc-menu-panel')[2];
expect(lastMenu.classList).toContain('mat-mdc-elevation-specific');
expect(lastMenu.classList)
.withContext('Expected menu to have the base elevation plus two.')
.toContain('mat-elevation-z4');
(overlay.querySelector('.cdk-overlay-backdrop')! as HTMLElement).click();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected no open menus')
.toBe(0);
instance.alternateTrigger.openMenu();
fixture.detectChanges();
tick(500);
lastMenu = overlay.querySelector('.mat-mdc-menu-panel') as HTMLElement;
expect(lastMenu.classList).toContain('mat-mdc-elevation-specific');
expect(lastMenu.classList)
.not.withContext('Expected menu not to maintain old elevation.')
.toContain('mat-elevation-z4');
expect(lastMenu.classList)
.withContext('Expected menu to have the proper updated elevation.')
.toContain('mat-elevation-z2');
}));
it('should not change focus origin if origin not specified for trigger', fakeAsync(() => {
compileTestComponent();
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
tick(500);
instance.levelOneTrigger.focus('mouse');
fixture.detectChanges();
instance.levelTwoTrigger.focus();
fixture.detectChanges();
tick(500);
const levelTwoTrigger = overlay.querySelector('#level-two-trigger')! as HTMLElement;
expect(levelTwoTrigger.classList).toContain('cdk-focused');
expect(levelTwoTrigger.classList).toContain('cdk-mouse-focused');
}));
it('should not increase the elevation if the user specified a custom one', fakeAsync(() => {
const elevationFixture = createComponent(NestedMenuCustomElevation);
elevationFixture.detectChanges();
elevationFixture.componentInstance.rootTrigger.openMenu();
elevationFixture.detectChanges();
tick(500);
elevationFixture.componentInstance.levelOneTrigger.openMenu();
elevationFixture.detectChanges();
tick(500);
const menuClasses =
overlayContainerElement.querySelectorAll('.mat-mdc-menu-panel')[1].classList;
expect(menuClasses).toContain('mat-mdc-elevation-specific');
expect(menuClasses)
.withContext('Expected user elevation to be maintained')
.toContain('mat-elevation-z24');
expect(menuClasses).not.toContain('mat-elevation-z2', 'Expected no stacked elevation.');
}));
it('should close all of the menus when the root is closed programmatically', fakeAsync(() => {
compileTestComponent();
instance.rootTrigger.openMenu();
fixture.detectChanges();
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
const menus = overlay.querySelectorAll('.mat-mdc-menu-panel');
expect(menus.length).withContext('Expected three open menus').toBe(3);
instance.rootTrigger.closeMenu();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected no open menus')
.toBe(0);
}));
it('should toggle a nested menu when its trigger is added after init', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one open menu')
.toBe(1);
instance.showLazy = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const lazyTrigger = overlay.querySelector('#lazy-trigger')!;
dispatchMouseEvent(lazyTrigger, 'mouseenter');
fixture.detectChanges();
tick(500);
fixture.detectChanges();
flush();
expect(lazyTrigger.classList)
.withContext('Expected the trigger to be highlighted')
.toContain('mat-mdc-menu-item-highlighted');
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected two open menus')
.toBe(2);
}));
it('should prevent the default mousedown action if the menu item opens a sub-menu', fakeAsync(() => {
compileTestComponent();
instance.rootTrigger.openMenu();
fixture.detectChanges();
tick(500);
const event = createMouseEvent('mousedown');
Object.defineProperty(event, 'buttons', {get: () => 1});
event.preventDefault = jasmine.createSpy('preventDefault spy');
dispatchEvent(overlay.querySelector('[mat-menu-item]')!, event);
fixture.detectChanges();
tick(500);
expect(event.preventDefault).toHaveBeenCalled();
}));
it('should handle the items being rendered in a repeater', fakeAsync(() => {
const repeaterFixture = createComponent(NestedMenuRepeater);
overlay = overlayContainerElement;
expect(() => repeaterFixture.detectChanges()).not.toThrow();
repeaterFixture.componentInstance.rootTriggerEl.nativeElement.click();
repeaterFixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one open menu')
.toBe(1);
dispatchMouseEvent(overlay.querySelector('.level-one-trigger')!, 'mouseenter');
repeaterFixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected two open menus')
.toBe(2);
})); | {
"end_byte": 93496,
"start_byte": 84639,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/menu.spec.ts_93502_102488 | it('should be able to trigger the same nested menu from different triggers', fakeAsync(() => {
const repeaterFixture = createComponent(NestedMenuRepeater);
overlay = overlayContainerElement;
repeaterFixture.detectChanges();
repeaterFixture.componentInstance.rootTriggerEl.nativeElement.click();
repeaterFixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one open menu')
.toBe(1);
const triggers = overlay.querySelectorAll('.level-one-trigger');
dispatchMouseEvent(triggers[0], 'mouseenter');
repeaterFixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected two open menus')
.toBe(2);
dispatchMouseEvent(triggers[1], 'mouseenter');
repeaterFixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected two open menus')
.toBe(2);
}));
it('should close the initial menu if the user moves away while animating', fakeAsync(() => {
const repeaterFixture = createComponent(NestedMenuRepeater);
overlay = overlayContainerElement;
repeaterFixture.detectChanges();
repeaterFixture.componentInstance.rootTriggerEl.nativeElement.click();
repeaterFixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one open menu')
.toBe(1);
const triggers = overlay.querySelectorAll('.level-one-trigger');
dispatchMouseEvent(triggers[0], 'mouseenter');
repeaterFixture.detectChanges();
tick(100);
dispatchMouseEvent(triggers[1], 'mouseenter');
repeaterFixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected two open menus')
.toBe(2);
}));
it(
'should be able to open a submenu through an item that is not a direct descendant ' +
'of the panel',
fakeAsync(() => {
const nestedFixture = createComponent(SubmenuDeclaredInsideParentMenu);
overlay = overlayContainerElement;
nestedFixture.detectChanges();
nestedFixture.componentInstance.rootTriggerEl.nativeElement.click();
nestedFixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one open menu')
.toBe(1);
dispatchMouseEvent(overlay.querySelector('.level-one-trigger')!, 'mouseenter');
nestedFixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected two open menus')
.toBe(2);
}),
);
it(
'should not close when hovering over a menu item inside a sub-menu panel that is declared' +
'inside the root menu',
fakeAsync(() => {
const nestedFixture = createComponent(SubmenuDeclaredInsideParentMenu);
overlay = overlayContainerElement;
nestedFixture.detectChanges();
nestedFixture.componentInstance.rootTriggerEl.nativeElement.click();
nestedFixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected one open menu')
.toBe(1);
dispatchMouseEvent(overlay.querySelector('.level-one-trigger')!, 'mouseenter');
nestedFixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected two open menus')
.toBe(2);
dispatchMouseEvent(overlay.querySelector('.level-two-item')!, 'mouseenter');
nestedFixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected two open menus to remain')
.toBe(2);
}),
);
it('should not re-focus a child menu trigger when hovering another trigger', fakeAsync(() => {
compileTestComponent();
dispatchFakeEvent(instance.rootTriggerEl.nativeElement, 'mousedown');
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
const items = Array.from(overlay.querySelectorAll('.mat-mdc-menu-panel [mat-menu-item]'));
const levelOneTrigger = overlay.querySelector('#level-one-trigger')!;
dispatchMouseEvent(levelOneTrigger, 'mouseenter');
fixture.detectChanges();
tick();
expect(overlay.querySelectorAll('.mat-mdc-menu-panel').length)
.withContext('Expected two open menus')
.toBe(2);
dispatchMouseEvent(items[items.indexOf(levelOneTrigger) + 1], 'mouseenter');
fixture.detectChanges();
tick(500);
expect(document.activeElement).not.toBe(
levelOneTrigger,
'Expected focus not to be returned to the initial trigger.',
);
}));
});
it('should have a focus indicator', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const menuItemNativeElements = Array.from(
overlayContainerElement.querySelectorAll('.mat-mdc-menu-item'),
);
expect(
menuItemNativeElements.every(element => element.classList.contains('mat-focus-indicator')),
).toBe(true);
}));
});
describe('MatMenu default overrides', () => {
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [MatMenuModule, NoopAnimationsModule],
providers: [
{
provide: MAT_MENU_DEFAULT_OPTIONS,
useValue: {overlapTrigger: true, xPosition: 'before', yPosition: 'above'},
},
],
declarations: [SimpleMenu, FakeIcon],
});
}));
it('should allow for the default menu options to be overridden', fakeAsync(() => {
const fixture = TestBed.createComponent(SimpleMenu);
fixture.detectChanges();
const menu = fixture.componentInstance.menu;
expect(menu.overlapTrigger).toBe(true);
expect(menu.xPosition).toBe('before');
expect(menu.yPosition).toBe('above');
}));
});
const SIMPLE_MENU_TEMPLATE = `
<button
[matMenuTriggerFor]="menu"
[matMenuTriggerRestoreFocus]="restoreFocus"
#triggerEl>Toggle menu</button>
<mat-menu
#menu="matMenu"
[class]="panelClass"
(closed)="closeCallback($event)"
[backdropClass]="backdropClass"
[aria-label]="ariaLabel"
[aria-labelledby]="ariaLabelledby"
[aria-describedby]="ariaDescribedby">
<button mat-menu-item> Item </button>
<button mat-menu-item disabled> Disabled </button>
<button mat-menu-item disableRipple>
<mat-icon>unicorn</mat-icon>
Item with an icon
</button>
<button mat-menu-item>
<span>Item with text inside span</span>
</button>
@for (item of extraItems; track $index) {
<button mat-menu-item> {{item}} </button>
}
</mat-menu>
`;
@Component({
template: SIMPLE_MENU_TEMPLATE,
standalone: false,
})
class SimpleMenu {
@ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;
@ViewChild('triggerEl') triggerEl: ElementRef<HTMLElement>;
@ViewChild(MatMenu) menu: MatMenu;
@ViewChildren(MatMenuItem) items: QueryList<MatMenuItem>;
extraItems: string[] = [];
closeCallback = jasmine.createSpy('menu closed callback');
backdropClass: string;
panelClass: string;
restoreFocus = true;
ariaLabel: string;
ariaLabelledby: string;
ariaDescribedby: string;
}
@Component({
template: SIMPLE_MENU_TEMPLATE,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
class SimpleMenuOnPush extends SimpleMenu {}
@Component({
template: `
<button [matMenuTriggerFor]="menu" #triggerEl>Toggle menu</button>
<mat-menu [xPosition]="xPosition" [yPosition]="yPosition" #menu="matMenu">
<button mat-menu-item> Positioned Content </button>
</mat-menu>
`,
standalone: false,
})
class PositionedMenu {
@ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;
@ViewChild('triggerEl') triggerEl: ElementRef<HTMLElement>;
xPosition: MenuPositionX = 'before';
yPosition: MenuPositionY = 'above';
}
interface TestableMenu {
trigger: MatMenuTrigger;
triggerEl: ElementRef<HTMLElement>;
}
@Component({
template: `
<button [matMenuTriggerFor]="menu" #triggerEl>Toggle menu</button>
<mat-menu [overlapTrigger]="overlapTrigger" #menu="matMenu">
<button mat-menu-item> Not overlapped Content </button>
</mat-menu>
`,
standalone: false,
})
class OverlapMenu implements TestableMenu {
@Input() overlapTrigger: boolean;
@ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;
@ViewChild('triggerEl') triggerEl: ElementRef<HTMLElement>;
} | {
"end_byte": 102488,
"start_byte": 93502,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/menu.spec.ts_102490_109758 | @Component({
selector: 'custom-menu',
template: `
<ng-template>
Custom Menu header
<ng-content></ng-content>
</ng-template>
`,
exportAs: 'matCustomMenu',
standalone: false,
})
class CustomMenuPanel implements MatMenuPanel {
direction: Direction;
xPosition: MenuPositionX = 'after';
yPosition: MenuPositionY = 'below';
overlapTrigger = true;
parentMenu: MatMenuPanel;
@ViewChild(TemplateRef) templateRef: TemplateRef<any>;
@Output() readonly close = new EventEmitter<void | 'click' | 'keydown' | 'tab'>();
focusFirstItem = () => {};
resetActiveItem = () => {};
setPositionClasses = () => {};
}
@Component({
template: `
<button [matMenuTriggerFor]="menu">Toggle menu</button>
<custom-menu #menu="matCustomMenu">
<button mat-menu-item> Custom Content </button>
</custom-menu>
`,
standalone: false,
})
class CustomMenu {
@ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;
}
@Component({
template: `
<button
[matMenuTriggerFor]="root"
#rootTrigger="matMenuTrigger"
#rootTriggerEl>Toggle menu</button>
<button
[matMenuTriggerFor]="levelTwo"
#alternateTrigger="matMenuTrigger">Toggle alternate menu</button>
<mat-menu #root="matMenu" (closed)="rootCloseCallback($event)">
<button mat-menu-item
id="level-one-trigger"
[matMenuTriggerFor]="levelOne"
#levelOneTrigger="matMenuTrigger">One</button>
<button mat-menu-item>Two</button>
@if (showLazy) {
<button mat-menu-item
id="lazy-trigger"
[matMenuTriggerFor]="lazy"
#lazyTrigger="matMenuTrigger">Three</button>
}
</mat-menu>
<mat-menu #levelOne="matMenu" (closed)="levelOneCloseCallback($event)">
<button mat-menu-item>Four</button>
<button mat-menu-item
id="level-two-trigger"
[matMenuTriggerFor]="levelTwo"
#levelTwoTrigger="matMenuTrigger">Five</button>
<button mat-menu-item>Six</button>
</mat-menu>
<mat-menu #levelTwo="matMenu" (closed)="levelTwoCloseCallback($event)">
<button mat-menu-item>Seven</button>
<button mat-menu-item>Eight</button>
<button mat-menu-item>Nine</button>
</mat-menu>
<mat-menu #lazy="matMenu">
<button mat-menu-item>Ten</button>
<button mat-menu-item>Eleven</button>
<button mat-menu-item>Twelve</button>
</mat-menu>
`,
standalone: false,
})
class NestedMenu {
@ViewChild('root') rootMenu: MatMenu;
@ViewChild('rootTrigger') rootTrigger: MatMenuTrigger;
@ViewChild('rootTriggerEl') rootTriggerEl: ElementRef<HTMLElement>;
@ViewChild('alternateTrigger') alternateTrigger: MatMenuTrigger;
readonly rootCloseCallback = jasmine.createSpy('root menu closed callback');
@ViewChild('levelOne') levelOneMenu: MatMenu;
@ViewChild('levelOneTrigger') levelOneTrigger: MatMenuTrigger;
readonly levelOneCloseCallback = jasmine.createSpy('level one menu closed callback');
@ViewChild('levelTwo') levelTwoMenu: MatMenu;
@ViewChild('levelTwoTrigger') levelTwoTrigger: MatMenuTrigger;
readonly levelTwoCloseCallback = jasmine.createSpy('level one menu closed callback');
@ViewChild('lazy') lazyMenu: MatMenu;
@ViewChild('lazyTrigger') lazyTrigger: MatMenuTrigger;
showLazy = false;
}
@Component({
template: `
<button [matMenuTriggerFor]="root" #rootTrigger="matMenuTrigger">Toggle menu</button>
<mat-menu #root="matMenu">
<button mat-menu-item
[matMenuTriggerFor]="levelOne"
#levelOneTrigger="matMenuTrigger">One</button>
</mat-menu>
<mat-menu #levelOne="matMenu" class="mat-elevation-z24">
<button mat-menu-item>Two</button>
</mat-menu>
`,
standalone: false,
})
class NestedMenuCustomElevation {
@ViewChild('rootTrigger') rootTrigger: MatMenuTrigger;
@ViewChild('levelOneTrigger') levelOneTrigger: MatMenuTrigger;
}
@Component({
template: `
<button [matMenuTriggerFor]="root" #rootTriggerEl>Toggle menu</button>
<mat-menu #root="matMenu">
@for (item of items; track $index) {
<button
mat-menu-item
class="level-one-trigger"
[matMenuTriggerFor]="levelOne">{{item}}</button>
}
</mat-menu>
<mat-menu #levelOne="matMenu">
<button mat-menu-item>Four</button>
<button mat-menu-item>Five</button>
</mat-menu>
`,
standalone: false,
})
class NestedMenuRepeater {
@ViewChild('rootTriggerEl') rootTriggerEl: ElementRef<HTMLElement>;
@ViewChild('levelOneTrigger') levelOneTrigger: MatMenuTrigger;
items = ['one', 'two', 'three'];
}
@Component({
template: `
<button [matMenuTriggerFor]="root" #rootTriggerEl>Toggle menu</button>
<mat-menu #root="matMenu">
<button mat-menu-item class="level-one-trigger" [matMenuTriggerFor]="levelOne">One</button>
<mat-menu #levelOne="matMenu">
<button mat-menu-item class="level-two-item">Two</button>
</mat-menu>
</mat-menu>
`,
standalone: false,
})
class SubmenuDeclaredInsideParentMenu {
@ViewChild('rootTriggerEl') rootTriggerEl: ElementRef;
}
@Component({
selector: 'mat-icon',
template: '<ng-content></ng-content>',
standalone: false,
})
class FakeIcon {}
@Component({
template: `
<button [matMenuTriggerFor]="menu" #triggerEl>Toggle menu</button>
<mat-menu #menu="matMenu">
<ng-template matMenuContent>
<button mat-menu-item>Item</button>
<button mat-menu-item>Another item</button>
</ng-template>
</mat-menu>
`,
standalone: false,
})
class SimpleLazyMenu {
@ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;
@ViewChild('triggerEl') triggerEl: ElementRef<HTMLElement>;
@ViewChildren(MatMenuItem) items: QueryList<MatMenuItem>;
}
@Component({
template: `
<button
[matMenuTriggerFor]="menu"
[matMenuTriggerData]="{label: 'one'}"
#triggerOne="matMenuTrigger">One</button>
<button
[matMenuTriggerFor]="menu"
[matMenuTriggerData]="{label: 'two'}"
#triggerTwo="matMenuTrigger">Two</button>
<mat-menu #menu="matMenu">
<ng-template let-label="label" matMenuContent>
<button mat-menu-item>{{label}}</button>
</ng-template>
</mat-menu>
`,
standalone: false,
})
class LazyMenuWithContext {
@ViewChild('triggerOne') triggerOne: MatMenuTrigger;
@ViewChild('triggerTwo') triggerTwo: MatMenuTrigger;
}
@Component({
template: `
<button [matMenuTriggerFor]="one">Toggle menu</button>
<mat-menu #one="matMenu">
<button mat-menu-item>One</button>
</mat-menu>
<mat-menu #two="matMenu">
<button mat-menu-item>Two</button>
</mat-menu>
`,
standalone: false,
})
class DynamicPanelMenu {
@ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;
@ViewChild('one') firstMenu: MatMenu;
@ViewChild('two') secondMenu: MatMenu;
}
@Component({
template: `
<button [matMenuTriggerFor]="menu">Toggle menu</button>
<mat-menu #menu="matMenu">
<button mat-menu-item role="menuitemcheckbox" aria-checked="true">Checked</button>
<button mat-menu-item role="menuitemcheckbox" aria-checked="false">Not checked</button>
</mat-menu>
`,
standalone: false,
})
class MenuWithCheckboxItems {
@ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;
} | {
"end_byte": 109758,
"start_byte": 102490,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/menu.spec.ts_109760_112772 | @Component({
template: `
<button [matMenuTriggerFor]="menu">Toggle menu</button>
<mat-menu #menu="matMenu">
@for (item of items; track $index) {
<button [disabled]="item.disabled"mat-menu-item>{{item.label}}</button>
}
</mat-menu>
`,
standalone: false,
})
class SimpleMenuWithRepeater {
@ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;
@ViewChild(MatMenu) menu: MatMenu;
@ViewChildren(MatMenuItem) itemInstances: QueryList<MatMenuItem>;
items = [
{label: 'Pizza', disabled: false},
{label: 'Pasta', disabled: false},
];
}
@Component({
template: `
<button [matMenuTriggerFor]="menu">Toggle menu</button>
<mat-menu #menu="matMenu">
<ng-template matMenuContent>
@for (item of items; track $index) {
<button [disabled]="item.disabled" mat-menu-item>{{item.label}}</button>
}
</ng-template>
</mat-menu>
`,
standalone: false,
})
class SimpleMenuWithRepeaterInLazyContent {
@ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;
@ViewChild(MatMenu) menu: MatMenu;
items = [
{label: 'Pizza', disabled: false},
{label: 'Pasta', disabled: false},
];
}
@Component({
template: `
<button [matMenuTriggerFor]="menu" #triggerEl>Toggle menu</button>
<mat-menu #menu="matMenu">
<ng-template matMenuContent>
<button [matMenuTriggerFor]="menu2" mat-menu-item #menuItem>Item</button>
</ng-template>
</mat-menu>
<mat-menu #menu2="matMenu">
<ng-template matMenuContent>
<button mat-menu-item #subMenuItem>Sub item</button>
</ng-template>
</mat-menu>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
class LazyMenuWithOnPush {
@ViewChild('triggerEl', {read: ElementRef}) rootTrigger: ElementRef;
@ViewChild('menuItem', {read: ElementRef}) menuItemWithSubmenu: ElementRef;
}
@Component({
template: `
<mat-menu #menu="matMenu">
<button [matMenuTriggerFor]="menu"></button>
</mat-menu>
`,
standalone: false,
})
class InvalidRecursiveMenu {}
@Component({
template: '<mat-menu aria-label="label"></mat-menu>',
standalone: false,
})
class StaticAriaLabelMenu {}
@Component({
template: '<mat-menu aria-labelledby="some-element"></mat-menu>',
standalone: false,
})
class StaticAriaLabelledByMenu {}
@Component({
template: '<mat-menu aria-describedby="some-element"></mat-menu>',
standalone: false,
})
class StaticAriaDescribedbyMenu {}
@Component({
template: `
<button [matMenuTriggerFor]="menu" #triggerEl>Toggle menu</button>
<mat-menu #menu="matMenu">
@for (item of items; track item) {
<button mat-menu-item>{{item}}</button>
}
</mat-menu>
`,
standalone: false,
})
class MenuWithRepeatedItems {
@ViewChild(MatMenuTrigger, {static: false}) trigger: MatMenuTrigger;
@ViewChild('triggerEl', {static: false}) triggerEl: ElementRef<HTMLElement>;
@ViewChild(MatMenu, {static: false}) menu: MatMenu;
items = ['One', 'Two', 'Three'];
} | {
"end_byte": 112772,
"start_byte": 109760,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu.spec.ts"
} |
components/src/material/menu/_menu-theme.scss_0_2831 | @use 'sass:map';
@use '../core/tokens/m2/mat/menu' as tokens-mat-menu;
@use '../core/style/sass-utils';
@use '../core/tokens/token-utils';
@use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/typography/typography';
@mixin base($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, base));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-menu.$prefix,
tokens-mat-menu.get-unthemable-tokens()
);
}
}
}
@mixin color($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, color));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-menu.$prefix,
tokens-mat-menu.get-color-tokens($theme)
);
}
}
}
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-menu.$prefix,
tokens-mat-menu.get-typography-tokens($theme)
);
}
}
}
@mixin density($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, density));
} @else {
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
@return (
(
namespace: tokens-mat-menu.$prefix,
tokens: tokens-mat-menu.get-token-slots(),
),
);
}
@mixin overrides($tokens: ()) {
@include token-utils.batch-create-token-values($tokens, _define-overrides()...);
}
@mixin theme($theme) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-menu') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme));
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
@if ($tokens != ()) {
@include token-utils.create-token-values(
tokens-mat-menu.$prefix,
map.get($tokens, tokens-mat-menu.$prefix)
);
}
}
| {
"end_byte": 2831,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/_menu-theme.scss"
} |
components/src/material/menu/BUILD.bazel_0_1658 | load(
"//tools:defaults.bzl",
"extract_tokens",
"markdown_to_html",
"ng_module",
"ng_test_library",
"ng_web_test_suite",
"sass_binary",
"sass_library",
)
package(default_visibility = ["//visibility:public"])
ng_module(
name = "menu",
srcs = glob(
["**/*.ts"],
exclude = [
"**/*.spec.ts",
],
),
assets = [":menu_scss"] + glob(["**/*.html"]),
deps = [
"//src/cdk/overlay",
"//src/cdk/scrolling",
"//src/material/core",
"@npm//@angular/animations",
"@npm//@angular/common",
"@npm//@angular/core",
],
)
sass_library(
name = "menu_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = [
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "menu_scss",
src = "menu.scss",
deps = [
"//src/cdk:sass_lib",
"//src/material/core:core_scss_lib",
],
)
ng_test_library(
name = "menu_tests_lib",
srcs = glob(
["**/*.spec.ts"],
),
deps = [
":menu",
"//src/cdk/a11y",
"//src/cdk/bidi",
"//src/cdk/keycodes",
"//src/cdk/overlay",
"//src/cdk/scrolling",
"//src/cdk/testing/private",
"//src/material/core",
"@npm//@angular/platform-browser",
"@npm//rxjs",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":menu_tests_lib",
],
)
markdown_to_html(
name = "overview",
srcs = [":menu.md"],
)
extract_tokens(
name = "tokens",
srcs = [":menu_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1658,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/BUILD.bazel"
} |
components/src/material/menu/menu-item.html_0_476 | <ng-content select="mat-icon, [matMenuItemIcon]"></ng-content>
<span class="mat-mdc-menu-item-text"><ng-content></ng-content></span>
<div class="mat-mdc-menu-ripple" matRipple
[matRippleDisabled]="disableRipple || disabled"
[matRippleTrigger]="_getHostElement()">
</div>
@if (_triggersSubmenu) {
<svg
class="mat-mdc-menu-submenu-icon"
viewBox="0 0 5 10"
focusable="false"
aria-hidden="true"><polygon points="0,0 5,5 0,10"/></svg>
}
| {
"end_byte": 476,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu-item.html"
} |
components/src/material/menu/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public-api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/index.ts"
} |
components/src/material/menu/menu-positions.ts_0_300 | /**
* @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 type MenuPositionX = 'before' | 'after';
export type MenuPositionY = 'above' | 'below';
| {
"end_byte": 300,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu-positions.ts"
} |
components/src/material/menu/menu-trigger.ts_0_2522 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
FocusMonitor,
FocusOrigin,
isFakeMousedownFromScreenReader,
isFakeTouchstartFromScreenReader,
} from '@angular/cdk/a11y';
import {Direction, Directionality} from '@angular/cdk/bidi';
import {ENTER, LEFT_ARROW, RIGHT_ARROW, SPACE} from '@angular/cdk/keycodes';
import {
FlexibleConnectedPositionStrategy,
HorizontalConnectionPos,
Overlay,
OverlayConfig,
OverlayRef,
ScrollStrategy,
VerticalConnectionPos,
} from '@angular/cdk/overlay';
import {TemplatePortal} from '@angular/cdk/portal';
import {
AfterContentInit,
ChangeDetectorRef,
Directive,
ElementRef,
EventEmitter,
inject,
InjectionToken,
Input,
NgZone,
OnDestroy,
Output,
ViewContainerRef,
} from '@angular/core';
import {normalizePassiveListenerOptions} from '@angular/cdk/platform';
import {asapScheduler, merge, Observable, of as observableOf, Subscription} from 'rxjs';
import {delay, filter, take, takeUntil} from 'rxjs/operators';
import {MatMenu, MenuCloseReason} from './menu';
import {throwMatMenuRecursiveError} from './menu-errors';
import {MatMenuItem} from './menu-item';
import {MAT_MENU_PANEL, MatMenuPanel} from './menu-panel';
import {MenuPositionX, MenuPositionY} from './menu-positions';
/** Injection token that determines the scroll handling while the menu is open. */
export const MAT_MENU_SCROLL_STRATEGY = new InjectionToken<() => ScrollStrategy>(
'mat-menu-scroll-strategy',
{
providedIn: 'root',
factory: () => {
const overlay = inject(Overlay);
return () => overlay.scrollStrategies.reposition();
},
},
);
/** @docs-private */
export function MAT_MENU_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy {
return () => overlay.scrollStrategies.reposition();
}
/** @docs-private */
export const MAT_MENU_SCROLL_STRATEGY_FACTORY_PROVIDER = {
provide: MAT_MENU_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: MAT_MENU_SCROLL_STRATEGY_FACTORY,
};
/** Options for binding a passive event listener. */
const passiveEventListenerOptions = normalizePassiveListenerOptions({passive: true});
/**
* Default top padding of the menu panel.
* @deprecated No longer being used. Will be removed.
* @breaking-change 15.0.0
*/
export const MENU_PANEL_TOP_PADDING = 8;
/** Directive applied to an element that should trigger a `mat-menu`. */ | {
"end_byte": 2522,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu-trigger.ts"
} |
components/src/material/menu/menu-trigger.ts_2523_10496 | @Directive({
selector: `[mat-menu-trigger-for], [matMenuTriggerFor]`,
host: {
'class': 'mat-mdc-menu-trigger',
'[attr.aria-haspopup]': 'menu ? "menu" : null',
'[attr.aria-expanded]': 'menuOpen',
'[attr.aria-controls]': 'menuOpen ? menu.panelId : null',
'(click)': '_handleClick($event)',
'(mousedown)': '_handleMousedown($event)',
'(keydown)': '_handleKeydown($event)',
},
exportAs: 'matMenuTrigger',
})
export class MatMenuTrigger implements AfterContentInit, OnDestroy {
private _overlay = inject(Overlay);
private _element = inject<ElementRef<HTMLElement>>(ElementRef);
private _viewContainerRef = inject(ViewContainerRef);
private _menuItemInstance = inject(MatMenuItem, {optional: true, self: true})!;
private _dir = inject(Directionality, {optional: true});
private _focusMonitor = inject(FocusMonitor);
private _ngZone = inject(NgZone);
private _scrollStrategy = inject(MAT_MENU_SCROLL_STRATEGY);
private _changeDetectorRef = inject(ChangeDetectorRef);
private _portal: TemplatePortal;
private _overlayRef: OverlayRef | null = null;
private _menuOpen: boolean = false;
private _closingActionsSubscription = Subscription.EMPTY;
private _hoverSubscription = Subscription.EMPTY;
private _menuCloseSubscription = Subscription.EMPTY;
/**
* We're specifically looking for a `MatMenu` here since the generic `MatMenuPanel`
* interface lacks some functionality around nested menus and animations.
*/
private _parentMaterialMenu: MatMenu | undefined;
/**
* Cached value of the padding of the parent menu panel.
* Used to offset sub-menus to compensate for the padding.
*/
private _parentInnerPadding: number | undefined;
/**
* Handles touch start events on the trigger.
* Needs to be an arrow function so we can easily use addEventListener and removeEventListener.
*/
private _handleTouchStart = (event: TouchEvent) => {
if (!isFakeTouchstartFromScreenReader(event)) {
this._openedBy = 'touch';
}
};
// Tracking input type is necessary so it's possible to only auto-focus
// the first item of the list when the menu is opened via the keyboard
_openedBy: Exclude<FocusOrigin, 'program' | null> | undefined = undefined;
/**
* @deprecated
* @breaking-change 8.0.0
*/
@Input('mat-menu-trigger-for')
get _deprecatedMatMenuTriggerFor(): MatMenuPanel | null {
return this.menu;
}
set _deprecatedMatMenuTriggerFor(v: MatMenuPanel | null) {
this.menu = v;
}
/** References the menu instance that the trigger is associated with. */
@Input('matMenuTriggerFor')
get menu(): MatMenuPanel | null {
return this._menu;
}
set menu(menu: MatMenuPanel | null) {
if (menu === this._menu) {
return;
}
this._menu = menu;
this._menuCloseSubscription.unsubscribe();
if (menu) {
if (menu === this._parentMaterialMenu && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throwMatMenuRecursiveError();
}
this._menuCloseSubscription = menu.close.subscribe((reason: MenuCloseReason) => {
this._destroyMenu(reason);
// If a click closed the menu, we should close the entire chain of nested menus.
if ((reason === 'click' || reason === 'tab') && this._parentMaterialMenu) {
this._parentMaterialMenu.closed.emit(reason);
}
});
}
this._menuItemInstance?._setTriggersSubmenu(this.triggersSubmenu());
}
private _menu: MatMenuPanel | null;
/** Data to be passed along to any lazily-rendered content. */
@Input('matMenuTriggerData') menuData: any;
/**
* Whether focus should be restored when the menu is closed.
* Note that disabling this option can have accessibility implications
* and it's up to you to manage focus, if you decide to turn it off.
*/
@Input('matMenuTriggerRestoreFocus') restoreFocus: boolean = true;
/** Event emitted when the associated menu is opened. */
@Output() readonly menuOpened: EventEmitter<void> = new EventEmitter<void>();
/**
* Event emitted when the associated menu is opened.
* @deprecated Switch to `menuOpened` instead
* @breaking-change 8.0.0
*/
// tslint:disable-next-line:no-output-on-prefix
@Output() readonly onMenuOpen: EventEmitter<void> = this.menuOpened;
/** Event emitted when the associated menu is closed. */
@Output() readonly menuClosed: EventEmitter<void> = new EventEmitter<void>();
/**
* Event emitted when the associated menu is closed.
* @deprecated Switch to `menuClosed` instead
* @breaking-change 8.0.0
*/
// tslint:disable-next-line:no-output-on-prefix
@Output() readonly onMenuClose: EventEmitter<void> = this.menuClosed;
constructor(...args: unknown[]);
constructor() {
const parentMenu = inject<MatMenuPanel>(MAT_MENU_PANEL, {optional: true});
this._parentMaterialMenu = parentMenu instanceof MatMenu ? parentMenu : undefined;
this._element.nativeElement.addEventListener(
'touchstart',
this._handleTouchStart,
passiveEventListenerOptions,
);
}
ngAfterContentInit() {
this._handleHover();
}
ngOnDestroy() {
if (this._overlayRef) {
this._overlayRef.dispose();
this._overlayRef = null;
}
this._element.nativeElement.removeEventListener(
'touchstart',
this._handleTouchStart,
passiveEventListenerOptions,
);
this._menuCloseSubscription.unsubscribe();
this._closingActionsSubscription.unsubscribe();
this._hoverSubscription.unsubscribe();
}
/** Whether the menu is open. */
get menuOpen(): boolean {
return this._menuOpen;
}
/** The text direction of the containing app. */
get dir(): Direction {
return this._dir && this._dir.value === 'rtl' ? 'rtl' : 'ltr';
}
/** Whether the menu triggers a sub-menu or a top-level one. */
triggersSubmenu(): boolean {
return !!(this._menuItemInstance && this._parentMaterialMenu && this.menu);
}
/** Toggles the menu between the open and closed states. */
toggleMenu(): void {
return this._menuOpen ? this.closeMenu() : this.openMenu();
}
/** Opens the menu. */
openMenu(): void {
const menu = this.menu;
if (this._menuOpen || !menu) {
return;
}
const overlayRef = this._createOverlay(menu);
const overlayConfig = overlayRef.getConfig();
const positionStrategy = overlayConfig.positionStrategy as FlexibleConnectedPositionStrategy;
this._setPosition(menu, positionStrategy);
overlayConfig.hasBackdrop =
menu.hasBackdrop == null ? !this.triggersSubmenu() : menu.hasBackdrop;
overlayRef.attach(this._getPortal(menu));
if (menu.lazyContent) {
menu.lazyContent.attach(this.menuData);
}
this._closingActionsSubscription = this._menuClosingActions().subscribe(() => this.closeMenu());
this._initMenu(menu);
if (menu instanceof MatMenu) {
menu._startAnimation();
menu._directDescendantItems.changes.pipe(takeUntil(menu.close)).subscribe(() => {
// Re-adjust the position without locking when the amount of items
// changes so that the overlay is allowed to pick a new optimal position.
positionStrategy.withLockedPosition(false).reapplyLastPosition();
positionStrategy.withLockedPosition(true);
});
}
}
/** Closes the menu. */
closeMenu(): void {
this.menu?.close.emit();
}
/**
* Focuses the menu trigger.
* @param origin Source of the menu trigger's focus.
*/
focus(origin?: FocusOrigin, options?: FocusOptions) {
if (this._focusMonitor && origin) {
this._focusMonitor.focusVia(this._element, origin, options);
} else {
this._element.nativeElement.focus(options);
}
}
/**
* Updates the position of the menu to ensure that it fits all options within the viewport.
*/
updatePosition(): void {
this._overlayRef?.updatePosition();
}
/** Closes the menu and does the necessary cleanup. */ | {
"end_byte": 10496,
"start_byte": 2523,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu-trigger.ts"
} |
components/src/material/menu/menu-trigger.ts_10499_18988 | private _destroyMenu(reason: MenuCloseReason) {
if (!this._overlayRef || !this.menuOpen) {
return;
}
const menu = this.menu;
this._closingActionsSubscription.unsubscribe();
this._overlayRef.detach();
// Always restore focus if the user is navigating using the keyboard or the menu was opened
// programmatically. We don't restore for non-root triggers, because it can prevent focus
// from making it back to the root trigger when closing a long chain of menus by clicking
// on the backdrop.
if (this.restoreFocus && (reason === 'keydown' || !this._openedBy || !this.triggersSubmenu())) {
this.focus(this._openedBy);
}
this._openedBy = undefined;
if (menu instanceof MatMenu) {
menu._resetAnimation();
if (menu.lazyContent) {
// Wait for the exit animation to finish before detaching the content.
menu._animationDone
.pipe(
filter(event => event.toState === 'void'),
take(1),
// Interrupt if the content got re-attached.
takeUntil(menu.lazyContent._attached),
)
.subscribe({
next: () => menu.lazyContent!.detach(),
// No matter whether the content got re-attached, reset the menu.
complete: () => this._setIsMenuOpen(false),
});
} else {
this._setIsMenuOpen(false);
}
} else {
this._setIsMenuOpen(false);
menu?.lazyContent?.detach();
}
}
/**
* This method sets the menu state to open and focuses the first item if
* the menu was opened via the keyboard.
*/
private _initMenu(menu: MatMenuPanel): void {
menu.parentMenu = this.triggersSubmenu() ? this._parentMaterialMenu : undefined;
menu.direction = this.dir;
this._setMenuElevation(menu);
menu.focusFirstItem(this._openedBy || 'program');
this._setIsMenuOpen(true);
}
/** Updates the menu elevation based on the amount of parent menus that it has. */
private _setMenuElevation(menu: MatMenuPanel): void {
if (menu.setElevation) {
let depth = 0;
let parentMenu = menu.parentMenu;
while (parentMenu) {
depth++;
parentMenu = parentMenu.parentMenu;
}
menu.setElevation(depth);
}
}
// set state rather than toggle to support triggers sharing a menu
private _setIsMenuOpen(isOpen: boolean): void {
if (isOpen !== this._menuOpen) {
this._menuOpen = isOpen;
this._menuOpen ? this.menuOpened.emit() : this.menuClosed.emit();
if (this.triggersSubmenu()) {
this._menuItemInstance._setHighlighted(isOpen);
}
this._changeDetectorRef.markForCheck();
}
}
/**
* This method creates the overlay from the provided menu's template and saves its
* OverlayRef so that it can be attached to the DOM when openMenu is called.
*/
private _createOverlay(menu: MatMenuPanel): OverlayRef {
if (!this._overlayRef) {
const config = this._getOverlayConfig(menu);
this._subscribeToPositions(
menu,
config.positionStrategy as FlexibleConnectedPositionStrategy,
);
this._overlayRef = this._overlay.create(config);
// Consume the `keydownEvents` in order to prevent them from going to another overlay.
// Ideally we'd also have our keyboard event logic in here, however doing so will
// break anybody that may have implemented the `MatMenuPanel` themselves.
this._overlayRef.keydownEvents().subscribe();
}
return this._overlayRef;
}
/**
* This method builds the configuration object needed to create the overlay, the OverlayState.
* @returns OverlayConfig
*/
private _getOverlayConfig(menu: MatMenuPanel): OverlayConfig {
return new OverlayConfig({
positionStrategy: this._overlay
.position()
.flexibleConnectedTo(this._element)
.withLockedPosition()
.withGrowAfterOpen()
.withTransformOriginOn('.mat-menu-panel, .mat-mdc-menu-panel'),
backdropClass: menu.backdropClass || 'cdk-overlay-transparent-backdrop',
panelClass: menu.overlayPanelClass,
scrollStrategy: this._scrollStrategy(),
direction: this._dir || 'ltr',
});
}
/**
* Listens to changes in the position of the overlay and sets the correct classes
* on the menu based on the new position. This ensures the animation origin is always
* correct, even if a fallback position is used for the overlay.
*/
private _subscribeToPositions(menu: MatMenuPanel, position: FlexibleConnectedPositionStrategy) {
if (menu.setPositionClasses) {
position.positionChanges.subscribe(change => {
this._ngZone.run(() => {
const posX: MenuPositionX =
change.connectionPair.overlayX === 'start' ? 'after' : 'before';
const posY: MenuPositionY = change.connectionPair.overlayY === 'top' ? 'below' : 'above';
menu.setPositionClasses!(posX, posY);
});
});
}
}
/**
* Sets the appropriate positions on a position strategy
* so the overlay connects with the trigger correctly.
* @param positionStrategy Strategy whose position to update.
*/
private _setPosition(menu: MatMenuPanel, positionStrategy: FlexibleConnectedPositionStrategy) {
let [originX, originFallbackX]: HorizontalConnectionPos[] =
menu.xPosition === 'before' ? ['end', 'start'] : ['start', 'end'];
let [overlayY, overlayFallbackY]: VerticalConnectionPos[] =
menu.yPosition === 'above' ? ['bottom', 'top'] : ['top', 'bottom'];
let [originY, originFallbackY] = [overlayY, overlayFallbackY];
let [overlayX, overlayFallbackX] = [originX, originFallbackX];
let offsetY = 0;
if (this.triggersSubmenu()) {
// When the menu is a sub-menu, it should always align itself
// to the edges of the trigger, instead of overlapping it.
overlayFallbackX = originX = menu.xPosition === 'before' ? 'start' : 'end';
originFallbackX = overlayX = originX === 'end' ? 'start' : 'end';
if (this._parentMaterialMenu) {
if (this._parentInnerPadding == null) {
const firstItem = this._parentMaterialMenu.items.first;
this._parentInnerPadding = firstItem ? firstItem._getHostElement().offsetTop : 0;
}
offsetY = overlayY === 'bottom' ? this._parentInnerPadding : -this._parentInnerPadding;
}
} else if (!menu.overlapTrigger) {
originY = overlayY === 'top' ? 'bottom' : 'top';
originFallbackY = overlayFallbackY === 'top' ? 'bottom' : 'top';
}
positionStrategy.withPositions([
{originX, originY, overlayX, overlayY, offsetY},
{originX: originFallbackX, originY, overlayX: overlayFallbackX, overlayY, offsetY},
{
originX,
originY: originFallbackY,
overlayX,
overlayY: overlayFallbackY,
offsetY: -offsetY,
},
{
originX: originFallbackX,
originY: originFallbackY,
overlayX: overlayFallbackX,
overlayY: overlayFallbackY,
offsetY: -offsetY,
},
]);
}
/** Returns a stream that emits whenever an action that should close the menu occurs. */
private _menuClosingActions() {
const backdrop = this._overlayRef!.backdropClick();
const detachments = this._overlayRef!.detachments();
const parentClose = this._parentMaterialMenu ? this._parentMaterialMenu.closed : observableOf();
const hover = this._parentMaterialMenu
? this._parentMaterialMenu._hovered().pipe(
filter(active => active !== this._menuItemInstance),
filter(() => this._menuOpen),
)
: observableOf();
return merge(backdrop, parentClose as Observable<MenuCloseReason>, hover, detachments);
}
/** Handles mouse presses on the trigger. */
_handleMousedown(event: MouseEvent): void {
if (!isFakeMousedownFromScreenReader(event)) {
// Since right or middle button clicks won't trigger the `click` event,
// we shouldn't consider the menu as opened by mouse in those cases.
this._openedBy = event.button === 0 ? 'mouse' : undefined;
// Since clicking on the trigger won't close the menu if it opens a sub-menu,
// we should prevent focus from moving onto it via click to avoid the
// highlight from lingering on the menu item.
if (this.triggersSubmenu()) {
event.preventDefault();
}
}
}
/** Handles key presses on the trigger. */ | {
"end_byte": 18988,
"start_byte": 10499,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu-trigger.ts"
} |
components/src/material/menu/menu-trigger.ts_18991_21772 | _handleKeydown(event: KeyboardEvent): void {
const keyCode = event.keyCode;
// Pressing enter on the trigger will trigger the click handler later.
if (keyCode === ENTER || keyCode === SPACE) {
this._openedBy = 'keyboard';
}
if (
this.triggersSubmenu() &&
((keyCode === RIGHT_ARROW && this.dir === 'ltr') ||
(keyCode === LEFT_ARROW && this.dir === 'rtl'))
) {
this._openedBy = 'keyboard';
this.openMenu();
}
}
/** Handles click events on the trigger. */
_handleClick(event: MouseEvent): void {
if (this.triggersSubmenu()) {
// Stop event propagation to avoid closing the parent menu.
event.stopPropagation();
this.openMenu();
} else {
this.toggleMenu();
}
}
/** Handles the cases where the user hovers over the trigger. */
private _handleHover() {
// Subscribe to changes in the hovered item in order to toggle the panel.
if (!this.triggersSubmenu() || !this._parentMaterialMenu) {
return;
}
this._hoverSubscription = this._parentMaterialMenu
._hovered()
// Since we might have multiple competing triggers for the same menu (e.g. a sub-menu
// with different data and triggers), we have to delay it by a tick to ensure that
// it won't be closed immediately after it is opened.
.pipe(
filter(active => active === this._menuItemInstance && !active.disabled),
delay(0, asapScheduler),
)
.subscribe(() => {
this._openedBy = 'mouse';
// If the same menu is used between multiple triggers, it might still be animating
// while the new trigger tries to re-open it. Wait for the animation to finish
// before doing so. Also interrupt if the user moves to another item.
if (this.menu instanceof MatMenu && this.menu._isAnimating) {
// We need the `delay(0)` here in order to avoid
// 'changed after checked' errors in some cases. See #12194.
this.menu._animationDone
.pipe(take(1), delay(0, asapScheduler), takeUntil(this._parentMaterialMenu!._hovered()))
.subscribe(() => this.openMenu());
} else {
this.openMenu();
}
});
}
/** Gets the portal that should be attached to the overlay. */
private _getPortal(menu: MatMenuPanel): TemplatePortal {
// Note that we can avoid this check by keeping the portal on the menu panel.
// While it would be cleaner, we'd have to introduce another required method on
// `MatMenuPanel`, making it harder to consume.
if (!this._portal || this._portal.templateRef !== menu.templateRef) {
this._portal = new TemplatePortal(menu.templateRef, this._viewContainerRef);
}
return this._portal;
}
} | {
"end_byte": 21772,
"start_byte": 18991,
"url": "https://github.com/angular/components/blob/main/src/material/menu/menu-trigger.ts"
} |
components/src/material/menu/testing/menu-harness.ts_0_7181 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ComponentHarnessConstructor,
ContentContainerComponentHarness,
HarnessLoader,
HarnessPredicate,
TestElement,
TestKey,
} from '@angular/cdk/testing';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {MenuHarnessFilters, MenuItemHarnessFilters} from './menu-harness-filters';
/** Harness for interacting with a mat-menu in tests. */
export class MatMenuHarness extends ContentContainerComponentHarness<string> {
private _documentRootLocator = this.documentRootLocatorFactory();
/** The selector for the host element of a `MatMenu` instance. */
static hostSelector = '.mat-mdc-menu-trigger';
/**
* Gets a `HarnessPredicate` that can be used to search for a menu with specific attributes.
* @param options Options for filtering which menu instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatMenuHarness>(
this: ComponentHarnessConstructor<T>,
options: MenuHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options).addOption(
'triggerText',
options.triggerText,
(harness, text) => HarnessPredicate.stringMatches(harness.getTriggerText(), text),
);
}
/** Whether the menu is disabled. */
async isDisabled(): Promise<boolean> {
const disabled = (await this.host()).getAttribute('disabled');
return coerceBooleanProperty(await disabled);
}
/** Whether the menu is open. */
async isOpen(): Promise<boolean> {
return !!(await this._getMenuPanel());
}
/** Gets the text of the menu's trigger element. */
async getTriggerText(): Promise<string> {
return (await this.host()).text();
}
/** Focuses the menu. */
async focus(): Promise<void> {
return (await this.host()).focus();
}
/** Blurs the menu. */
async blur(): Promise<void> {
return (await this.host()).blur();
}
/** Whether the menu is focused. */
async isFocused(): Promise<boolean> {
return (await this.host()).isFocused();
}
/** Opens the menu. */
async open(): Promise<void> {
if (!(await this.isOpen())) {
return (await this.host()).click();
}
}
/** Closes the menu. */
async close(): Promise<void> {
const panel = await this._getMenuPanel();
if (panel) {
return panel.sendKeys(TestKey.ESCAPE);
}
}
/**
* Gets a list of `MatMenuItemHarness` representing the items in the menu.
* @param filters Optionally filters which menu items are included.
*/
async getItems(
filters?: Omit<MenuItemHarnessFilters, 'ancestor'>,
): Promise<MatMenuItemHarness[]> {
const panelId = await this._getPanelId();
if (panelId) {
return this._documentRootLocator.locatorForAll(
MatMenuItemHarness.with({
...(filters || {}),
ancestor: `#${panelId}`,
} as MenuItemHarnessFilters),
)();
}
return [];
}
/**
* Clicks an item in the menu, and optionally continues clicking items in subsequent sub-menus.
* @param itemFilter A filter used to represent which item in the menu should be clicked. The
* first matching menu item will be clicked.
* @param subItemFilters A list of filters representing the items to click in any subsequent
* sub-menus. The first item in the sub-menu matching the corresponding filter in
* `subItemFilters` will be clicked.
*/
async clickItem(
itemFilter: Omit<MenuItemHarnessFilters, 'ancestor'>,
...subItemFilters: Omit<MenuItemHarnessFilters, 'ancestor'>[]
): Promise<void> {
await this.open();
const items = await this.getItems(itemFilter);
if (!items.length) {
throw Error(`Could not find item matching ${JSON.stringify(itemFilter)}`);
}
if (!subItemFilters.length) {
return await items[0].click();
}
const menu = await items[0].getSubmenu();
if (!menu) {
throw Error(`Item matching ${JSON.stringify(itemFilter)} does not have a submenu`);
}
return menu.clickItem(...(subItemFilters as [Omit<MenuItemHarnessFilters, 'ancestor'>]));
}
protected override async getRootHarnessLoader(): Promise<HarnessLoader> {
const panelId = await this._getPanelId();
return this.documentRootLocatorFactory().harnessLoaderFor(`#${panelId}`);
}
/** Gets the menu panel associated with this menu. */
private async _getMenuPanel(): Promise<TestElement | null> {
const panelId = await this._getPanelId();
return panelId ? this._documentRootLocator.locatorForOptional(`#${panelId}`)() : null;
}
/** Gets the id of the menu panel associated with this menu. */
private async _getPanelId(): Promise<string | null> {
const panelId = await (await this.host()).getAttribute('aria-controls');
return panelId || null;
}
}
export class MatMenuItemHarness extends ContentContainerComponentHarness<string> {
/** The selector for the host element of a `MatMenuItem` instance. */
static hostSelector = '.mat-mdc-menu-item';
/**
* Gets a `HarnessPredicate` that can be used to search for a menu item with specific attributes.
* @param options Options for filtering which menu item instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatMenuItemHarness>(
this: ComponentHarnessConstructor<T>,
options: MenuItemHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options)
.addOption('text', options.text, (harness, text) =>
HarnessPredicate.stringMatches(harness.getText(), text),
)
.addOption(
'hasSubmenu',
options.hasSubmenu,
async (harness, hasSubmenu) => (await harness.hasSubmenu()) === hasSubmenu,
);
}
/** Whether the menu is disabled. */
async isDisabled(): Promise<boolean> {
const disabled = (await this.host()).getAttribute('disabled');
return coerceBooleanProperty(await disabled);
}
/** Gets the text of the menu item. */
async getText(): Promise<string> {
return (await this.host()).text();
}
/** Focuses the menu item. */
async focus(): Promise<void> {
return (await this.host()).focus();
}
/** Blurs the menu item. */
async blur(): Promise<void> {
return (await this.host()).blur();
}
/** Whether the menu item is focused. */
async isFocused(): Promise<boolean> {
return (await this.host()).isFocused();
}
/** Clicks the menu item. */
async click(): Promise<void> {
return (await this.host()).click();
}
/** Whether this item has a submenu. */
async hasSubmenu(): Promise<boolean> {
return (await this.host()).matchesSelector(MatMenuHarness.hostSelector);
}
/** Gets the submenu associated with this menu item, or null if none. */
async getSubmenu(): Promise<MatMenuHarness | null> {
if (await this.hasSubmenu()) {
return new MatMenuHarness(this.locatorFactory);
}
return null;
}
}
| {
"end_byte": 7181,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/testing/menu-harness.ts"
} |
components/src/material/menu/testing/menu-harness-filters.ts_0_857 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {BaseHarnessFilters} from '@angular/cdk/testing';
/** A set of criteria that can be used to filter a list of `MatMenuHarness` instances. */
export interface MenuHarnessFilters extends BaseHarnessFilters {
/** Only find instances whose trigger text matches the given value. */
triggerText?: string | RegExp;
}
/** A set of criteria that can be used to filter a list of `MatMenuItemHarness` instances. */
export interface MenuItemHarnessFilters extends BaseHarnessFilters {
/** Only find instances whose text matches the given value. */
text?: string | RegExp;
/** Only find instances that have a sub-menu. */
hasSubmenu?: boolean;
}
| {
"end_byte": 857,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/testing/menu-harness-filters.ts"
} |
components/src/material/menu/testing/menu-harness.spec.ts_0_7409 | import {Component} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {MatMenuModule} from '@angular/material/menu';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatMenuHarness} from './menu-harness';
describe('MatMenuHarness', () => {
describe('single-level menu', () => {
let fixture: ComponentFixture<MenuHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatMenuModule, NoopAnimationsModule, MenuHarnessTest],
});
fixture = TestBed.createComponent(MenuHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all menu harnesses', async () => {
const menues = await loader.getAllHarnesses(MatMenuHarness);
expect(menues.length).toBe(2);
});
it('should load menu with exact text', async () => {
const menus = await loader.getAllHarnesses(MatMenuHarness.with({triggerText: 'Settings'}));
expect(menus.length).toBe(1);
expect(await menus[0].getTriggerText()).toBe('Settings');
});
it('should load menu with regex label match', async () => {
const menus = await loader.getAllHarnesses(MatMenuHarness.with({triggerText: /settings/i}));
expect(menus.length).toBe(1);
expect(await menus[0].getTriggerText()).toBe('Settings');
});
it('should get disabled state', async () => {
const [enabledMenu, disabledMenu] = await loader.getAllHarnesses(MatMenuHarness);
expect(await enabledMenu.isDisabled()).toBe(false);
expect(await disabledMenu.isDisabled()).toBe(true);
});
it('should get menu text', async () => {
const [firstMenu, secondMenu] = await loader.getAllHarnesses(MatMenuHarness);
expect(await firstMenu.getTriggerText()).toBe('Settings');
expect(await secondMenu.getTriggerText()).toBe('Disabled menu');
});
it('should focus and blur a menu', async () => {
const menu = await loader.getHarness(MatMenuHarness.with({triggerText: 'Settings'}));
expect(await menu.isFocused()).toBe(false);
await menu.focus();
expect(await menu.isFocused()).toBe(true);
await menu.blur();
expect(await menu.isFocused()).toBe(false);
});
it('should open and close', async () => {
const menu = await loader.getHarness(MatMenuHarness.with({triggerText: 'Settings'}));
expect(await menu.isOpen()).toBe(false);
await menu.open();
expect(await menu.isOpen()).toBe(true);
await menu.open();
expect(await menu.isOpen()).toBe(true);
await menu.close();
expect(await menu.isOpen()).toBe(false);
await menu.close();
expect(await menu.isOpen()).toBe(false);
});
it('should get all items', async () => {
const menu = await loader.getHarness(MatMenuHarness.with({triggerText: 'Settings'}));
await menu.open();
expect((await menu.getItems()).length).toBe(2);
});
it('should get filtered items', async () => {
const menu = await loader.getHarness(MatMenuHarness.with({triggerText: 'Settings'}));
await menu.open();
const items = await menu.getItems({text: 'Account'});
expect(items.length).toBe(1);
expect(await items[0].getText()).toBe('Account');
});
});
describe('multi-level menu', () => {
let fixture: ComponentFixture<NestedMenuHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatMenuModule, NoopAnimationsModule, NestedMenuHarnessTest],
});
fixture = TestBed.createComponent(NestedMenuHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should get submenus', async () => {
const menu1 = await loader.getHarness(MatMenuHarness.with({triggerText: 'Menu 1'}));
await menu1.open();
let submenus = await menu1.getItems({hasSubmenu: true});
expect(submenus.length).toBe(2);
const menu2 = (await submenus[0].getSubmenu())!;
const menu3 = (await submenus[1].getSubmenu())!;
expect(await menu2.getTriggerText()).toBe('Menu 2');
expect(await menu3.getTriggerText()).toBe('Menu 3');
await menu2.open();
expect((await menu2.getItems({hasSubmenu: true})).length).toBe(0);
await menu3.open();
submenus = await menu3.getItems({hasSubmenu: true});
expect(submenus.length).toBe(1);
const menu4 = (await submenus[0].getSubmenu())!;
expect(await menu4.getTriggerText()).toBe('Menu 4');
await menu4.open();
expect((await menu4.getItems({hasSubmenu: true})).length).toBe(0);
});
it('should select item in top-level menu', async () => {
const menu1 = await loader.getHarness(MatMenuHarness.with({triggerText: 'Menu 1'}));
await menu1.clickItem({text: /Leaf/});
expect(fixture.componentInstance.lastClickedLeaf).toBe(1);
});
it('should throw when item is not found', async () => {
const menu1 = await loader.getHarness(MatMenuHarness.with({triggerText: 'Menu 1'}));
await expectAsync(menu1.clickItem({text: 'Fake Item'})).toBeRejectedWithError(
/Could not find item matching {"text":"Fake Item"}/,
);
});
it('should select item in nested menu', async () => {
const menu1 = await loader.getHarness(MatMenuHarness.with({triggerText: 'Menu 1'}));
await menu1.clickItem({text: 'Menu 3'}, {text: 'Menu 4'}, {text: /Leaf/});
expect(fixture.componentInstance.lastClickedLeaf).toBe(3);
});
it('should throw when intermediate item does not have submenu', async () => {
const menu1 = await loader.getHarness(MatMenuHarness.with({triggerText: 'Menu 1'}));
await expectAsync(menu1.clickItem({text: 'Leaf Item 1'}, {})).toBeRejectedWithError(
/Item matching {"text":"Leaf Item 1"} does not have a submenu/,
);
});
});
});
@Component({
template: `
<button type="button" id="settings" [matMenuTriggerFor]="settingsMenu">Settings</button>
<button type="button" disabled [matMenuTriggerFor]="settingsMenu">Disabled menu</button>
<mat-menu #settingsMenu>
<menu mat-menu-item>Profile</menu>
<menu mat-menu-item>Account</menu>
</mat-menu>
`,
standalone: true,
imports: [MatMenuModule],
})
class MenuHarnessTest {}
@Component({
template: `
<button [matMenuTriggerFor]="menu1">Menu 1</button>
<mat-menu #menu1>
<button mat-menu-item [matMenuTriggerFor]="menu2">Menu 2</button>
<button mat-menu-item (click)="lastClickedLeaf = 1">Leaf Item 1</button>
<button mat-menu-item [matMenuTriggerFor]="menu3">Menu 3</button>
</mat-menu>
<mat-menu #menu2>
<button mat-menu-item (click)="lastClickedLeaf = 2">Leaf Item 2</button>
</mat-menu>
<mat-menu #menu3>
<button mat-menu-item [matMenuTriggerFor]="menu4">Menu 4</button>
</mat-menu>
<mat-menu #menu4>
<button mat-menu-item (click)="lastClickedLeaf = 3">Leaf Item 3</button>
</mat-menu>
`,
standalone: true,
imports: [MatMenuModule],
})
class NestedMenuHarnessTest {
lastClickedLeaf = 0;
}
| {
"end_byte": 7409,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/testing/menu-harness.spec.ts"
} |
components/src/material/menu/testing/public-api.ts_0_276 | /**
* @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 './menu-harness';
export * from './menu-harness-filters';
| {
"end_byte": 276,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/testing/public-api.ts"
} |
components/src/material/menu/testing/BUILD.bazel_0_830 | load("//tools:defaults.bzl", "ng_test_library", "ng_web_test_suite", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "testing",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
deps = [
"//src/cdk/coercion",
"//src/cdk/testing",
],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
ng_test_library(
name = "unit_tests_lib",
srcs = glob(["**/*.spec.ts"]),
deps = [
":testing",
"//src/cdk/overlay",
"//src/cdk/testing",
"//src/cdk/testing/private",
"//src/cdk/testing/testbed",
"//src/material/menu",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":unit_tests_lib",
],
)
| {
"end_byte": 830,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/testing/BUILD.bazel"
} |
components/src/material/menu/testing/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public-api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/menu/testing/index.ts"
} |
components/src/material/grid-list/grid-tile.html_0_71 | <div class="mat-grid-tile-content">
<ng-content></ng-content>
</div>
| {
"end_byte": 71,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/grid-tile.html"
} |
components/src/material/grid-list/grid-list.ts_0_5720 | /**
* @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,
AfterContentChecked,
OnInit,
Input,
ContentChildren,
QueryList,
ElementRef,
ChangeDetectionStrategy,
inject,
} from '@angular/core';
import {MatGridTile} from './grid-tile';
import {TileCoordinator} from './tile-coordinator';
import {
TileStyler,
FitTileStyler,
RatioTileStyler,
FixedTileStyler,
TileStyleTarget,
} from './tile-styler';
import {Directionality} from '@angular/cdk/bidi';
import {coerceNumberProperty, NumberInput} from '@angular/cdk/coercion';
import {MAT_GRID_LIST, MatGridListBase} from './grid-list-base';
// TODO(kara): Conditional (responsive) column count / row size.
// TODO(kara): Re-layout on window resize / media change (debounced).
// TODO(kara): gridTileHeader and gridTileFooter.
const MAT_FIT_MODE = 'fit';
@Component({
selector: 'mat-grid-list',
exportAs: 'matGridList',
templateUrl: 'grid-list.html',
styleUrl: 'grid-list.css',
host: {
'class': 'mat-grid-list',
// Ensures that the "cols" input value is reflected in the DOM. This is
// needed for the grid-list harness.
'[attr.cols]': 'cols',
},
providers: [
{
provide: MAT_GRID_LIST,
useExisting: MatGridList,
},
],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
})
export class MatGridList implements MatGridListBase, OnInit, AfterContentChecked, TileStyleTarget {
private _element = inject<ElementRef<HTMLElement>>(ElementRef);
private _dir = inject(Directionality, {optional: true});
/** Number of columns being rendered. */
private _cols: number;
/** Used for determining the position of each tile in the grid. */
private _tileCoordinator: TileCoordinator;
/**
* Row height value passed in by user. This can be one of three types:
* - Number value (ex: "100px"): sets a fixed row height to that value
* - Ratio value (ex: "4:3"): sets the row height based on width:height ratio
* - "Fit" mode (ex: "fit"): sets the row height to total height divided by number of rows
*/
private _rowHeight: string;
/** The amount of space between tiles. This will be something like '5px' or '2em'. */
private _gutter: string = '1px';
/** Sets position and size styles for a tile */
private _tileStyler: TileStyler;
/** Query list of tiles that are being rendered. */
@ContentChildren(MatGridTile, {descendants: true}) _tiles: QueryList<MatGridTile>;
constructor(...args: unknown[]);
constructor() {}
/** Amount of columns in the grid list. */
@Input()
get cols(): number {
return this._cols;
}
set cols(value: NumberInput) {
this._cols = Math.max(1, Math.round(coerceNumberProperty(value)));
}
/** Size of the grid list's gutter in pixels. */
@Input()
get gutterSize(): string {
return this._gutter;
}
set gutterSize(value: string) {
this._gutter = `${value == null ? '' : value}`;
}
/** Set internal representation of row height from the user-provided value. */
@Input()
get rowHeight(): string | number {
return this._rowHeight;
}
set rowHeight(value: string | number) {
const newValue = `${value == null ? '' : value}`;
if (newValue !== this._rowHeight) {
this._rowHeight = newValue;
this._setTileStyler(this._rowHeight);
}
}
ngOnInit() {
this._checkCols();
this._checkRowHeight();
}
/**
* The layout calculation is fairly cheap if nothing changes, so there's little cost
* to run it frequently.
*/
ngAfterContentChecked() {
this._layoutTiles();
}
/** Throw a friendly error if cols property is missing */
private _checkCols() {
if (!this.cols && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error(
`mat-grid-list: must pass in number of columns. ` + `Example: <mat-grid-list cols="3">`,
);
}
}
/** Default to equal width:height if rowHeight property is missing */
private _checkRowHeight(): void {
if (!this._rowHeight) {
this._setTileStyler('1:1');
}
}
/** Creates correct Tile Styler subtype based on rowHeight passed in by user */
private _setTileStyler(rowHeight: string): void {
if (this._tileStyler) {
this._tileStyler.reset(this);
}
if (rowHeight === MAT_FIT_MODE) {
this._tileStyler = new FitTileStyler();
} else if (rowHeight && rowHeight.indexOf(':') > -1) {
this._tileStyler = new RatioTileStyler(rowHeight);
} else {
this._tileStyler = new FixedTileStyler(rowHeight);
}
}
/** Computes and applies the size and position for all children grid tiles. */
private _layoutTiles(): void {
if (!this._tileCoordinator) {
this._tileCoordinator = new TileCoordinator();
}
const tracker = this._tileCoordinator;
const tiles = this._tiles.filter(tile => !tile._gridList || tile._gridList === this);
const direction = this._dir ? this._dir.value : 'ltr';
this._tileCoordinator.update(this.cols, tiles);
this._tileStyler.init(this.gutterSize, tracker, this.cols, direction);
tiles.forEach((tile, index) => {
const pos = tracker.positions[index];
this._tileStyler.setStyle(tile, pos.row, pos.col);
});
this._setListStyle(this._tileStyler.getComputedHeight());
}
/** Sets style on the main grid-list element, given the style name and value. */
_setListStyle(style: [string, string | null] | null): void {
if (style) {
(this._element.nativeElement.style as any)[style[0]] = style[1];
}
}
}
| {
"end_byte": 5720,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/grid-list.ts"
} |
components/src/material/grid-list/grid-tile.ts_0_3339 | /**
* @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,
ElementRef,
Input,
ContentChildren,
QueryList,
AfterContentInit,
Directive,
ChangeDetectionStrategy,
inject,
} from '@angular/core';
import {MatLine, setLines} from '@angular/material/core';
import {coerceNumberProperty, NumberInput} from '@angular/cdk/coercion';
import {MAT_GRID_LIST, MatGridListBase} from './grid-list-base';
@Component({
selector: 'mat-grid-tile',
exportAs: 'matGridTile',
host: {
'class': 'mat-grid-tile',
// Ensures that the "rowspan" and "colspan" input value is reflected in
// the DOM. This is needed for the grid-tile harness.
'[attr.rowspan]': 'rowspan',
'[attr.colspan]': 'colspan',
},
templateUrl: 'grid-tile.html',
styleUrl: 'grid-list.css',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatGridTile {
private _element = inject<ElementRef<HTMLElement>>(ElementRef);
_gridList? = inject<MatGridListBase>(MAT_GRID_LIST, {optional: true});
_rowspan: number = 1;
_colspan: number = 1;
constructor(...args: unknown[]);
constructor() {}
/** Amount of rows that the grid tile takes up. */
@Input()
get rowspan(): number {
return this._rowspan;
}
set rowspan(value: NumberInput) {
this._rowspan = Math.round(coerceNumberProperty(value));
}
/** Amount of columns that the grid tile takes up. */
@Input()
get colspan(): number {
return this._colspan;
}
set colspan(value: NumberInput) {
this._colspan = Math.round(coerceNumberProperty(value));
}
/**
* Sets the style of the grid-tile element. Needs to be set manually to avoid
* "Changed after checked" errors that would occur with HostBinding.
*/
_setStyle(property: string, value: any): void {
(this._element.nativeElement.style as any)[property] = value;
}
}
@Component({
selector: 'mat-grid-tile-header, mat-grid-tile-footer',
templateUrl: 'grid-tile-text.html',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
})
export class MatGridTileText implements AfterContentInit {
private _element = inject<ElementRef<HTMLElement>>(ElementRef);
@ContentChildren(MatLine, {descendants: true}) _lines: QueryList<MatLine>;
constructor(...args: unknown[]);
constructor() {}
ngAfterContentInit() {
setLines(this._lines, this._element);
}
}
/**
* Directive whose purpose is to add the mat- CSS styling to this selector.
* @docs-private
*/
@Directive({
selector: '[mat-grid-avatar], [matGridAvatar]',
host: {'class': 'mat-grid-avatar'},
})
export class MatGridAvatarCssMatStyler {}
/**
* Directive whose purpose is to add the mat- CSS styling to this selector.
* @docs-private
*/
@Directive({
selector: 'mat-grid-tile-header',
host: {'class': 'mat-grid-tile-header'},
})
export class MatGridTileHeaderCssMatStyler {}
/**
* Directive whose purpose is to add the mat- CSS styling to this selector.
* @docs-private
*/
@Directive({
selector: 'mat-grid-tile-footer',
host: {'class': 'mat-grid-tile-footer'},
})
export class MatGridTileFooterCssMatStyler {}
| {
"end_byte": 3339,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/grid-tile.ts"
} |
components/src/material/grid-list/grid-list.scss_0_2246 | @use '../core/style/list-common';
@use '../core/style/layout-common';
@use '../core/tokens/m2/mat/grid-list' as tokens-mat-grid-list;
@use '../core/tokens/token-utils';
// height of tile header or footer if it has one line
$one-line-height: 48px;
// height of tile header or footer if it has two lines
$two-line-height: 68px;
// side padding for text in tile headers and footers
$text-padding: 16px;
.mat-grid-list {
display: block;
position: relative;
}
.mat-grid-tile {
display: block;
position: absolute;
overflow: hidden;
// Headers & footers
.mat-grid-tile-header,
.mat-grid-tile-footer {
display: flex;
align-items: center;
height: $one-line-height;
color: #fff;
background: rgba(0, 0, 0, 0.38);
overflow: hidden;
padding: 0 $text-padding;
// Positioning
position: absolute;
left: 0;
right: 0;
@include list-common.normalize-text();
&.mat-2-line {
height: $two-line-height;
}
}
.mat-grid-list-text {
@include list-common.wrapper-base();
}
.mat-grid-tile-header {
top: 0;
}
.mat-grid-tile-footer {
bottom: 0;
}
.mat-grid-avatar {
padding-right: $text-padding;
[dir='rtl'] & {
padding-right: 0;
padding-left: $text-padding;
}
&:empty {
display: none;
}
}
}
.mat-grid-tile-header {
@include token-utils.use-tokens(
tokens-mat-grid-list.$prefix, tokens-mat-grid-list.get-token-slots()) {
$secondary-token-name: token-utils.get-token-variable(tile-header-secondary-text-size);
@include token-utils.create-token-slot(font-size, tile-header-primary-text-size);
@include list-common.base(#{$secondary-token-name});
}
}
.mat-grid-tile-footer {
@include token-utils.use-tokens(
tokens-mat-grid-list.$prefix, tokens-mat-grid-list.get-token-slots()) {
$secondary-token-name: token-utils.get-token-variable(tile-footer-secondary-text-size);
@include token-utils.create-token-slot(font-size, tile-footer-primary-text-size);
@include list-common.base(#{$secondary-token-name});
}
}
.mat-grid-tile-content {
@include layout-common.fill;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
padding: 0;
margin: 0;
}
| {
"end_byte": 2246,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/grid-list.scss"
} |
components/src/material/grid-list/grid-list-base.ts_0_617 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {InjectionToken} from '@angular/core';
/**
* Injection token used to provide a grid list to a tile and to avoid circular imports.
* @docs-private
*/
export const MAT_GRID_LIST = new InjectionToken<MatGridListBase>('MAT_GRID_LIST');
/**
* Base interface for a `MatGridList`.
* @docs-private
*/
export interface MatGridListBase {
cols: number;
gutterSize: string;
rowHeight: number | string;
}
| {
"end_byte": 617,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/grid-list-base.ts"
} |
components/src/material/grid-list/public-api.ts_0_450 | /**
* @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 {TileCoordinator} from './tile-coordinator';
export * from './grid-list-module';
export * from './grid-list';
export * from './grid-tile';
// Privately exported for the grid-list harness.
export const ɵTileCoordinator = TileCoordinator;
| {
"end_byte": 450,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/public-api.ts"
} |
components/src/material/grid-list/grid-list.md_0_2528 | `mat-grid-list` is a two-dimensional list view that arranges cells into grid-based layout.
See Material Design spec [here](https://material.io/design/components/image-lists.html).
<!-- example(grid-list-overview) -->
### Setting the number of columns
An `mat-grid-list` must specify a `cols` attribute which sets the number of columns in the grid. The
number of rows will be automatically determined based on the number of columns and the number of
items.
### Setting the row height
The height of the rows in a grid list can be set via the `rowHeight` attribute. Row height for the
list can be calculated in three ways:
1. **Fixed height**: The height can be in `px`, `em`, or `rem`. If no units are specified, `px`
units are assumed (e.g. `100px`, `5em`, `250`).
2. **Ratio**: This ratio is column-width:row-height, and must be passed in with a colon, not a
decimal (e.g. `4:3`).
3. **Fit**: Setting `rowHeight` to `fit` This mode automatically divides the available height by
the number of rows. Please note the height of the grid-list or its container must be set.
If `rowHeight` is not specified, it defaults to a `1:1` ratio of width:height.
### Setting the gutter size
The gutter size can be set to any `px`, `em`, or `rem` value with the `gutterSize` property. If no
units are specified, `px` units are assumed. By default the gutter size is `1px`.
### Adding tiles that span multiple rows or columns
It is possible to set the rowspan and colspan of each `mat-grid-tile` individually, using the
`rowspan` and `colspan` properties. If not set, they both default to `1`. The `colspan` must not
exceed the number of `cols` in the `mat-grid-list`. There is no such restriction on the `rowspan`
however, more rows will simply be added for it the tile to fill.
### Tile headers and footers
A header and footer can be added to an `mat-grid-tile` using the `mat-grid-tile-header` and
`mat-grid-tile-footer` elements respectively.
### Accessibility
By default, the grid-list assumes that it will be used in a purely decorative fashion and thus sets
no roles, ARIA attributes, or keyboard shortcuts. This is equivalent to having a sequence of `<div>`
elements on the page. Any interactive content within the grid-list should be given an appropriate
accessibility treatment based on the specific workflow of your application.
If the grid-list is used to present a list of _non-interactive_ content items, then the grid-list
element should be given `role="list"` and each tile should be given `role="listitem"`.
| {
"end_byte": 2528,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/grid-list.md"
} |
components/src/material/grid-list/_grid-list-theme.scss_0_2552 | @use 'sass:map';
@use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/typography/typography';
@use '../core/tokens/m2/mat/grid-list' as tokens-mat-grid-list;
@use '../core/style/sass-utils';
@use '../core/tokens/token-utils';
@mixin base($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, base));
} @else {
}
}
// Include this empty mixin for consistency with the other components.
@mixin color($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, color));
} @else {
}
}
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-grid-list.$prefix,
tokens-mat-grid-list.get-typography-tokens($theme)
);
}
}
}
@mixin density($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, density));
} @else {
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
@return (
(
namespace: tokens-mat-grid-list.$prefix,
tokens: tokens-mat-grid-list.get-token-slots(),
),
);
}
@mixin overrides($tokens: ()) {
@include token-utils.batch-create-token-values($tokens, _define-overrides()...);
}
@mixin theme($theme) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-grid-list') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme));
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
@if ($tokens != ()) {
@include token-utils.create-token-values(
tokens-mat-grid-list.$prefix,
map.get($tokens, tokens-mat-grid-list.$prefix)
);
}
}
| {
"end_byte": 2552,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/_grid-list-theme.scss"
} |
components/src/material/grid-list/grid-list.html_0_40 | <div>
<ng-content></ng-content>
</div> | {
"end_byte": 40,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/grid-list.html"
} |
components/src/material/grid-list/grid-list.spec.ts_0_346 | import {Directionality} from '@angular/cdk/bidi';
import {Component, DebugElement, Type, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {MatGridTile, MatGridTileText} from './grid-tile';
import {MatGridList, MatGridListModule} from './index'; | {
"end_byte": 346,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/grid-list.spec.ts"
} |
components/src/material/grid-list/grid-list.spec.ts_348_8728 | describe('MatGridList', () => {
function createComponent<T>(componentType: Type<T>): ComponentFixture<T> {
TestBed.configureTestingModule({
imports: [MatGridListModule],
declarations: [componentType],
});
return TestBed.createComponent<T>(componentType);
}
it('should throw error if cols is not defined', () => {
const fixture = createComponent(GridListWithoutCols);
expect(() => fixture.detectChanges()).toThrowError(/must pass in number of columns/);
});
it('should throw error if rowHeight ratio is invalid', () => {
expect(() => {
const fixture = createComponent(GridListWithInvalidRowHeightRatio);
fixture.detectChanges();
}).toThrowError(/invalid ratio given for row-height/);
});
it('should throw error if tile colspan is wider than total cols', () => {
const fixture = createComponent(GridListWithTooWideColspan);
expect(() => fixture.detectChanges()).toThrowError(/tile with colspan 5 is wider than grid/);
});
it('should not throw when setting the `rowHeight` programmatically before init', () => {
const fixture = createComponent(GridListWithUnspecifiedRowHeight);
const gridList = fixture.debugElement.query(By.directive(MatGridList))!;
expect(() => {
// Set the row height twice so the tile styler is initialized.
gridList.componentInstance.rowHeight = 12.3;
gridList.componentInstance.rowHeight = 32.1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
}).not.toThrow();
});
it('should preserve value when zero is set as row height', () => {
const fixture = createComponent(GridListWithUnspecifiedRowHeight);
const gridList = fixture.debugElement.query(By.directive(MatGridList))!.componentInstance;
gridList.rowHeight = 0;
expect(gridList.rowHeight).toBe('0');
});
it('should set the columns to zero if a negative number is passed in', () => {
const fixture = createComponent(GridListWithDynamicCols);
fixture.detectChanges();
expect(fixture.componentInstance.gridList.cols).toBe(2);
expect(() => {
fixture.componentInstance.cols = -2;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
}).not.toThrow();
expect(fixture.componentInstance.gridList.cols).toBe(1);
});
it('should default to 1:1 row height if undefined ', () => {
const fixture = createComponent(GridListWithUnspecifiedRowHeight);
fixture.detectChanges();
const tile = fixture.debugElement.query(By.directive(MatGridTile))!;
const inlineStyles = tile.nativeElement.style;
// In ratio mode, heights are set using the padding-top property.
expect(inlineStyles.paddingTop).toBeTruthy();
expect(inlineStyles.height).toBeFalsy();
expect(getDimension(tile, 'height')).toBe(200);
});
it('should use a ratio row height if passed in', () => {
const fixture = createComponent(GirdListWithRowHeightRatio);
fixture.componentInstance.rowHeight = '4:1';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const tile = fixture.debugElement.query(By.directive(MatGridTile))!;
const inlineStyles = tile.nativeElement.style;
expect(inlineStyles.paddingTop).toBeTruthy();
expect(inlineStyles.height).toBeFalsy();
expect(getDimension(tile, 'height')).toBe(100);
fixture.componentInstance.rowHeight = '2:1';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(inlineStyles.paddingTop).toBeTruthy();
expect(inlineStyles.height).toBeFalsy();
expect(getDimension(tile, 'height')).toBe(200);
});
it('should divide row height evenly in "fit" mode', () => {
const fixture = createComponent(GridListWithFitRowHeightMode);
fixture.componentInstance.totalHeight = '300px';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const tile = fixture.debugElement.query(By.directive(MatGridTile))!;
// 149.5 * 2 = 299px + 1px gutter = 300px
expect(getDimension(tile, 'height')).toBe(149.5);
fixture.componentInstance.totalHeight = '200px';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// 99.5 * 2 = 199px + 1px gutter = 200px
expect(getDimension(tile, 'height')).toBe(99.5);
});
it('should use the fixed row height if passed in', () => {
const fixture = createComponent(GridListWithFixedRowHeightMode);
fixture.componentInstance.rowHeight = '100px';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const tile = fixture.debugElement.query(By.directive(MatGridTile))!;
expect(getDimension(tile, 'height')).toBe(100);
fixture.componentInstance.rowHeight = '200px';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(getDimension(tile, 'height')).toBe(200);
});
it('should default to pixels if row height units are missing', () => {
const fixture = createComponent(GridListWithUnitlessFixedRowHeight);
fixture.detectChanges();
const tile = fixture.debugElement.query(By.directive(MatGridTile))!;
expect(getDimension(tile, 'height')).toBe(100);
});
it('should default gutter size to 1px', () => {
const fixture = createComponent(GridListWithUnspecifiedGutterSize);
fixture.detectChanges();
const tiles = fixture.debugElement.queryAll(By.css('mat-grid-tile'));
// check horizontal gutter
expect(getDimension(tiles[0], 'width')).toBe(99.5);
expect(getComputedLeft(tiles[1])).toBe(100.5);
// check vertical gutter
expect(getDimension(tiles[0], 'height')).toBe(100);
expect(getDimension(tiles[2], 'top')).toBe(101);
});
it('should be able to set the gutter size to zero', () => {
const fixture = createComponent(GridListWithUnspecifiedGutterSize);
const gridList = fixture.debugElement.query(By.directive(MatGridList))!;
gridList.componentInstance.gutterSize = 0;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const tiles = fixture.debugElement.queryAll(By.css('mat-grid-tile'));
// check horizontal gutter
expect(getDimension(tiles[0], 'width')).toBe(100);
expect(getComputedLeft(tiles[1])).toBe(100);
// check vertical gutter
expect(getDimension(tiles[0], 'height')).toBe(100);
expect(getDimension(tiles[2], 'top')).toBe(100);
});
it('should lay out the tiles correctly for a nested grid list', () => {
const fixture = createComponent(NestedGridList);
fixture.detectChanges();
const innerTiles = fixture.debugElement.queryAll(
By.css('mat-grid-tile mat-grid-list mat-grid-tile'),
);
expect(getDimension(innerTiles[0], 'top')).toBe(0);
expect(getDimension(innerTiles[1], 'top')).toBe(101);
expect(getDimension(innerTiles[2], 'top')).toBe(202);
});
it('should set the gutter size if passed', () => {
const fixture = createComponent(GridListWithGutterSize);
fixture.detectChanges();
const tiles = fixture.debugElement.queryAll(By.css('mat-grid-tile'));
// check horizontal gutter
expect(getDimension(tiles[0], 'width')).toBe(99);
expect(getComputedLeft(tiles[1])).toBe(101);
// check vertical gutter
expect(getDimension(tiles[0], 'height')).toBe(100);
expect(getDimension(tiles[2], 'top')).toBe(102);
});
it('should use pixels if gutter units are missing', () => {
const fixture = createComponent(GridListWithUnitlessGutterSize);
fixture.detectChanges();
const tiles = fixture.debugElement.queryAll(By.css('mat-grid-tile'));
// check horizontal gutter
expect(getDimension(tiles[0], 'width')).toBe(99);
expect(getComputedLeft(tiles[1])).toBe(101);
// check vertical gutter
expect(getDimension(tiles[0], 'height')).toBe(100);
expect(getDimension(tiles[2], 'top')).toBe(102);
});
it('should allow alternate units for the gutter size', () => {
const fixture = createComponent(GridListWithUnspecifiedGutterSize);
const gridList = fixture.debugElement.query(By.directive(MatGridList))!;
gridList.componentInstance.gutterSize = '10%';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const tiles = fixture.debugElement.queryAll(By.css('mat-grid-tile'));
expect(getDimension(tiles[0], 'width')).toBe(90);
expect(getComputedLeft(tiles[1])).toBe(110);
}); | {
"end_byte": 8728,
"start_byte": 348,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/grid-list.spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.