_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
components/src/material/icon/icon.spec.ts_11735_19679
describe('Icons from URLs', () => { it('should register icon URLs by name', fakeAsync(() => { iconRegistry.addSvgIcon('fluffy', trustUrl('cat.svg')); iconRegistry.addSvgIcon('fido', trustUrl('dog.svg')); iconRegistry.addSvgIcon('felix', trustUrl('auth-cat.svg'), {withCredentials: true}); const fixture = TestBed.createComponent(IconFromSvgName); let svgElement: SVGElement; let testRequest: TestRequest; const testComponent = fixture.componentInstance; const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); testComponent.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('dog.svg').flush(FAKE_SVGS.dog); svgElement = verifyAndGetSingleSvgChild(iconElement); verifyPathChildElement(svgElement, 'woof'); // Change the icon, and the SVG element should be replaced. testComponent.iconName = 'fluffy'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('cat.svg').flush(FAKE_SVGS.cat); svgElement = verifyAndGetSingleSvgChild(iconElement); verifyPathChildElement(svgElement, 'meow'); // Using an icon from a previously loaded URL should not cause another HTTP request. testComponent.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectNone('dog.svg'); svgElement = verifyAndGetSingleSvgChild(iconElement); verifyPathChildElement(svgElement, 'woof'); // Change icon to one that needs credentials during fetch. testComponent.iconName = 'felix'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); testRequest = http.expectOne('auth-cat.svg'); expect(testRequest.request.withCredentials).toBeTrue(); testRequest.flush(FAKE_SVGS.cat); svgElement = verifyAndGetSingleSvgChild(iconElement); verifyPathChildElement(svgElement, 'meow'); // Assert that a registered icon can be looked-up by url. iconRegistry.getSvgIconFromUrl(trustUrl('cat.svg')).subscribe(element => { verifyPathChildElement(element, 'meow'); }); tick(); })); it('should be able to set the viewBox when registering a single SVG icon', fakeAsync(() => { iconRegistry.addSvgIcon('fluffy', trustUrl('cat.svg'), {viewBox: '0 0 27 27'}); iconRegistry.addSvgIcon('fido', trustUrl('dog.svg'), {viewBox: '0 0 43 43'}); const fixture = TestBed.createComponent(IconFromSvgName); let svgElement: SVGElement; const testComponent = fixture.componentInstance; const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); testComponent.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('dog.svg').flush(FAKE_SVGS.dog); svgElement = verifyAndGetSingleSvgChild(iconElement); expect(svgElement.getAttribute('viewBox')).toBe('0 0 43 43'); // Change the icon, and the SVG element should be replaced. testComponent.iconName = 'fluffy'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('cat.svg').flush(FAKE_SVGS.cat); svgElement = verifyAndGetSingleSvgChild(iconElement); expect(svgElement.getAttribute('viewBox')).toBe('0 0 27 27'); })); it('should throw an error when using an untrusted icon url', () => { iconRegistry.addSvgIcon('fluffy', 'farm-set-1.svg'); expect(() => { const fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'fluffy'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); }).toThrowError(/unsafe value used in a resource URL context/); }); it('should throw an error when using an untrusted icon set url', () => { iconRegistry.addSvgIconSetInNamespace('farm', 'farm-set-1.svg'); expect(() => { const fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'farm:pig'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); }).toThrowError(/unsafe value used in a resource URL context/); }); it('should delegate http error logging to the ErrorHandler', () => { const handleErrorSpy = spyOn(errorHandler, 'handleError'); iconRegistry.addSvgIconSetInNamespace('farm', trustUrl('farm-set-1.svg')); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; testComponent.iconName = 'farm:pig'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('farm-set-1.svg').error(new ErrorEvent('Network error')); fixture.detectChanges(); // Called twice once for the HTTP request failing and once for the icon // then not being able to be found. expect(handleErrorSpy).toHaveBeenCalledTimes(2); expect(handleErrorSpy.calls.argsFor(0)[0].message).toEqual( 'Loading icon set URL: farm-set-1.svg failed: Http failure response ' + 'for farm-set-1.svg: 0 ', ); expect(handleErrorSpy.calls.argsFor(1)[0].message).toEqual( `Error retrieving icon ${testComponent.iconName}! ` + 'Unable to find icon with the name "pig"', ); }); it('should delegate an error getting an SVG icon to the ErrorHandler', () => { const handleErrorSpy = spyOn(errorHandler, 'handleError'); iconRegistry.addSvgIconSetInNamespace('farm', trustUrl('farm-set-1.svg')); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; testComponent.iconName = 'farm:DNE'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('farm-set-1.svg').flush(FAKE_SVGS.farmSet1); fixture.detectChanges(); // The HTTP request succeeded but the icon was not found so we logged. expect(handleErrorSpy).toHaveBeenCalledTimes(1); expect(handleErrorSpy.calls.argsFor(0)[0].message).toEqual( `Error retrieving icon ${testComponent.iconName}! ` + 'Unable to find icon with the name "DNE"', ); }); it('should extract icon from SVG icon set', () => { iconRegistry.addSvgIconSetInNamespace('farm', trustUrl('farm-set-1.svg')); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); let svgElement: SVGElement; let svgChild: any; testComponent.iconName = 'farm:pig'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('farm-set-1.svg').flush(FAKE_SVGS.farmSet1); expect(matIconElement.childNodes.length).toBe(1); svgElement = verifyAndGetSingleSvgChild(matIconElement); expect(svgElement.childNodes.length).toBe(1); svgChild = svgElement.childNodes[0]; // The first <svg> child should be the <g id="pig"> element. expect(svgChild.tagName.toLowerCase()).toBe('g'); expect(svgChild.getAttribute('name')).toBe('pig'); verifyPathChildElement(svgChild, 'oink'); // Change the icon, and the SVG element should be replaced. testComponent.iconName = 'farm:cow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(matIconElement); svgChild = svgElement.childNodes[0]; // The first <svg> child should be the <g id="cow"> element. expect(svgChild.tagName.toLowerCase()).toBe('g'); expect(svgChild.getAttribute('name')).toBe('cow'); verifyPathChildElement(svgChild, 'moo'); });
{ "end_byte": 19679, "start_byte": 11735, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon.spec.ts" }
components/src/material/icon/icon.spec.ts_19685_28504
it('should handle unescape characters in icon names', () => { iconRegistry.addSvgIconSetInNamespace('farm', trustUrl('farm-set-4.svg')); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); let svgElement: SVGElement; let svgChild: any; testComponent.iconName = 'farm:pig with spaces'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('farm-set-4.svg').flush(FAKE_SVGS.farmSet4); expect(matIconElement.childNodes.length).toBe(1); svgElement = verifyAndGetSingleSvgChild(matIconElement); expect(svgElement.childNodes.length).toBe(1); svgChild = svgElement.childNodes[0]; // The first <svg> child should be the <g id="pig"> element. expect(svgChild.tagName.toLowerCase()).toBe('g'); expect(svgChild.getAttribute('name')).toBe('pig'); verifyPathChildElement(svgChild, 'oink'); }); it('should never parse the same icon set multiple times', () => { // Normally we avoid spying on private methods like this, but the parsing is a private // implementation detail that should not be exposed to the public API. This test, though, // is important enough to warrant the brittle-ness that results. spyOn(iconRegistry, '_svgElementFromString' as any).and.callThrough(); iconRegistry.addSvgIconSetInNamespace('farm', trustUrl('farm-set-1.svg')); // Requests for icons must be subscribed to in order for requests to be made. iconRegistry.getNamedSvgIcon('pig', 'farm').subscribe(() => {}); iconRegistry.getNamedSvgIcon('cow', 'farm').subscribe(() => {}); http.expectOne('farm-set-1.svg').flush(FAKE_SVGS.farmSet1); // _svgElementFromString is called once for each icon to create an empty SVG element // and once to parse the full icon set. expect((iconRegistry as any)._svgElementFromString).toHaveBeenCalledTimes(3); }); it('should allow multiple icon sets in a namespace', () => { iconRegistry.addSvgIconSetInNamespace('farm', trustUrl('farm-set-1.svg')); iconRegistry.addSvgIconSetInNamespace('farm', trustUrl('farm-set-2.svg')); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); let svgElement: SVGElement; let svgChild: any; testComponent.iconName = 'farm:pig'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('farm-set-1.svg').flush(FAKE_SVGS.farmSet1); http.expectOne('farm-set-2.svg').flush(FAKE_SVGS.farmSet2); svgElement = verifyAndGetSingleSvgChild(matIconElement); expect(svgElement.childNodes.length).toBe(1); svgChild = svgElement.childNodes[0]; // The <svg> child should be the <g id="pig"> element. expect(svgChild.tagName.toLowerCase()).toBe('g'); expect(svgChild.getAttribute('name')).toBe('pig'); expect(svgChild.getAttribute('id')).toBeFalsy(); expect(svgChild.childNodes.length).toBe(1); verifyPathChildElement(svgChild, 'oink'); // Change the icon name to one that appears in both icon sets. The icon from the set that // was registered last should be used (with id attribute of 'moo moo' instead of 'moo'), // and no additional HTTP request should be made. testComponent.iconName = 'farm:cow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(matIconElement); svgChild = svgElement.childNodes[0]; // The first <svg> child should be the <g id="cow"> element. expect(svgChild.tagName.toLowerCase()).toBe('g'); expect(svgChild.getAttribute('name')).toBe('cow'); expect(svgChild.childNodes.length).toBe(1); verifyPathChildElement(svgChild, 'moo moo'); }); it('should clear the id attribute from the svg node', () => { iconRegistry.addSvgIconSetInNamespace('farm', trustUrl('farm-set-1.svg')); const fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'farm:pig'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('farm-set-1.svg').flush(FAKE_SVGS.farmSet1); const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); const svgElement = verifyAndGetSingleSvgChild(matIconElement); expect(svgElement.hasAttribute('id')).toBe(false); }); it('should unwrap <symbol> nodes', () => { iconRegistry.addSvgIconSetInNamespace('farm', trustUrl('farm-set-3.svg')); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); testComponent.iconName = 'farm:duck'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('farm-set-3.svg').flush(FAKE_SVGS.farmSet3); const svgElement = verifyAndGetSingleSvgChild(matIconElement); const firstChild = svgElement.childNodes[0]; expect(svgElement.querySelector('symbol')).toBeFalsy(); expect(svgElement.childNodes.length).toBe(1); expect(firstChild.nodeName.toLowerCase()).toBe('path'); expect((firstChild as HTMLElement).getAttribute('name')).toBe('quack'); }); it('should copy over the attributes when unwrapping <symbol> nodes', () => { iconRegistry.addSvgIconSetInNamespace('farm', trustUrl('farm-set-5.svg')); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); testComponent.iconName = 'farm:duck'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('farm-set-5.svg').flush(FAKE_SVGS.farmSet5); const svgElement = verifyAndGetSingleSvgChild(matIconElement); expect(svgElement.getAttribute('viewBox')).toBe('0 0 13 37'); expect(svgElement.getAttribute('id')).toBeFalsy(); expect(svgElement.querySelector('symbol')).toBeFalsy(); }); it('should not wrap <svg> elements in icon sets in another svg tag', () => { iconRegistry.addSvgIconSet(trustUrl('arrow-set.svg')); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); let svgElement: SVGElement; testComponent.iconName = 'left-arrow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('arrow-set.svg').flush(FAKE_SVGS.arrows); // arrow-set.svg stores its icons as nested <svg> elements, so they should be used // directly and not wrapped in an outer <svg> tag like the <g> elements in other sets. svgElement = verifyAndGetSingleSvgChild(matIconElement); verifyPathChildElement(svgElement, 'left'); }); it('should return unmodified copies of icons from icon sets', () => { iconRegistry.addSvgIconSet(trustUrl('arrow-set.svg')); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); let svgElement: SVGElement; testComponent.iconName = 'left-arrow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('arrow-set.svg').flush(FAKE_SVGS.arrows); svgElement = verifyAndGetSingleSvgChild(matIconElement); verifyPathChildElement(svgElement, 'left'); // Modify the SVG element by setting a viewBox attribute. svgElement.setAttribute('viewBox', '0 0 100 100'); // Switch to a different icon. testComponent.iconName = 'right-arrow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(matIconElement); verifyPathChildElement(svgElement, 'right'); // Switch back to the first icon. The viewBox attribute should not be present. testComponent.iconName = 'left-arrow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(matIconElement); verifyPathChildElement(svgElement, 'left'); expect(svgElement.getAttribute('viewBox')).toBeFalsy(); });
{ "end_byte": 28504, "start_byte": 19685, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon.spec.ts" }
components/src/material/icon/icon.spec.ts_28510_32953
it('should not throw when toggling an icon that has a binding in IE11', () => { iconRegistry.addSvgIcon('fluffy', trustUrl('cat.svg')); const fixture = TestBed.createComponent(IconWithBindingAndNgIf); fixture.detectChanges(); http.expectOne('cat.svg').flush(FAKE_SVGS.cat); expect(() => { fixture.componentInstance.showIcon = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.showIcon = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); }).not.toThrow(); }); it('should be able to configure the viewBox for the icon set', () => { iconRegistry.addSvgIconSet(trustUrl('arrow-set.svg'), {viewBox: '0 0 43 43'}); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); let svgElement: SVGElement; testComponent.iconName = 'left-arrow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('arrow-set.svg').flush(FAKE_SVGS.arrows); svgElement = verifyAndGetSingleSvgChild(matIconElement); expect(svgElement.getAttribute('viewBox')).toBe('0 0 43 43'); }); it('should remove the SVG element from the DOM when the binding is cleared', () => { iconRegistry.addSvgIconSet(trustUrl('arrow-set.svg')); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const icon = fixture.debugElement.nativeElement.querySelector('mat-icon'); testComponent.iconName = 'left-arrow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('arrow-set.svg').flush(FAKE_SVGS.arrows); expect(icon.querySelector('svg')).toBeTruthy(); testComponent.iconName = undefined; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(icon.querySelector('svg')).toBeFalsy(); }); it('should keep non-SVG user content inside the icon element', fakeAsync(() => { iconRegistry.addSvgIcon('fido', trustUrl('dog.svg')); const fixture = TestBed.createComponent(SvgIconWithUserContent); const testComponent = fixture.componentInstance; const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); testComponent.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('dog.svg').flush(FAKE_SVGS.dog); const userDiv = iconElement.querySelector('div'); expect(userDiv).toBeTruthy(); expect(iconElement.textContent.trim()).toContain('Hello'); tick(); })); it('should cancel in-progress fetches if the icon changes', fakeAsync(() => { // Register an icon that will resolve immediately. iconRegistry.addSvgIconLiteral('fluffy', trustHtml(FAKE_SVGS.cat)); // Register a different icon that takes some time to resolve. iconRegistry.addSvgIcon('fido', trustUrl('dog.svg')); const fixture = TestBed.createComponent(IconFromSvgName); const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); // Assign the slow icon first. fixture.componentInstance.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); // Assign the quick icon while the slow one is still in-flight. fixture.componentInstance.iconName = 'fluffy'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); // Expect for the in-flight request to have been cancelled. expect(http.expectOne('dog.svg').cancelled).toBe(true); // Expect the last icon to have been assigned. verifyPathChildElement(verifyAndGetSingleSvgChild(iconElement), 'meow'); })); it('should cancel in-progress fetches if the component is destroyed', fakeAsync(() => { iconRegistry.addSvgIcon('fido', trustUrl('dog.svg')); const fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.destroy(); expect(http.expectOne('dog.svg').cancelled).toBe(true); })); });
{ "end_byte": 32953, "start_byte": 28510, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon.spec.ts" }
components/src/material/icon/icon.spec.ts_32957_41066
describe('Icons from HTML string', () => { it('should register icon HTML strings by name', fakeAsync(() => { iconRegistry.addSvgIconLiteral('fluffy', trustHtml(FAKE_SVGS.cat)); iconRegistry.addSvgIconLiteral('fido', trustHtml(FAKE_SVGS.dog)); const fixture = TestBed.createComponent(IconFromSvgName); let svgElement: SVGElement; const testComponent = fixture.componentInstance; const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); testComponent.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(iconElement); verifyPathChildElement(svgElement, 'woof'); testComponent.iconName = 'fluffy'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(iconElement); verifyPathChildElement(svgElement, 'meow'); // Assert that a registered icon can be looked-up by name. iconRegistry.getNamedSvgIcon('fluffy').subscribe(element => { verifyPathChildElement(element, 'meow'); }); tick(); })); it('should be able to configure the icon viewBox', fakeAsync(() => { iconRegistry.addSvgIconLiteral('fluffy', trustHtml(FAKE_SVGS.cat), {viewBox: '0 0 43 43'}); iconRegistry.addSvgIconLiteral('fido', trustHtml(FAKE_SVGS.dog), {viewBox: '0 0 27 27'}); const fixture = TestBed.createComponent(IconFromSvgName); let svgElement: SVGElement; const testComponent = fixture.componentInstance; const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); testComponent.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(iconElement); expect(svgElement.getAttribute('viewBox')).toBe('0 0 27 27'); testComponent.iconName = 'fluffy'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(iconElement); expect(svgElement.getAttribute('viewBox')).toBe('0 0 43 43'); })); it('should throw an error when using untrusted HTML', () => { // Stub out console.warn so we don't pollute our logs with Angular's warnings. // Jasmine will tear the spy down at the end of the test. spyOn(console, 'warn'); expect(() => { iconRegistry.addSvgIconLiteral('circle', '<svg><circle></svg>'); }).toThrowError(/was not trusted as safe HTML/); }); it('should extract an icon from SVG icon set', () => { iconRegistry.addSvgIconSetLiteralInNamespace('farm', trustHtml(FAKE_SVGS.farmSet1)); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); let svgElement: SVGElement; let svgChild: any; testComponent.iconName = 'farm:pig'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(matIconElement.childNodes.length).toBe(1); svgElement = verifyAndGetSingleSvgChild(matIconElement); expect(svgElement.childNodes.length).toBe(1); svgChild = svgElement.childNodes[0]; // The first <svg> child should be the <g id="pig"> element. expect(svgChild.tagName.toLowerCase()).toBe('g'); expect(svgChild.getAttribute('name')).toBe('pig'); verifyPathChildElement(svgChild, 'oink'); // Change the icon, and the SVG element should be replaced. testComponent.iconName = 'farm:cow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(matIconElement); svgChild = svgElement.childNodes[0]; // The first <svg> child should be the <g id="cow"> element. expect(svgChild.tagName.toLowerCase()).toBe('g'); expect(svgChild.getAttribute('name')).toBe('cow'); verifyPathChildElement(svgChild, 'moo'); }); it('should allow multiple icon sets in a namespace', () => { iconRegistry.addSvgIconSetLiteralInNamespace('farm', trustHtml(FAKE_SVGS.farmSet1)); iconRegistry.addSvgIconSetLiteralInNamespace('farm', trustHtml(FAKE_SVGS.farmSet2)); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); let svgElement: SVGElement; let svgChild: any; testComponent.iconName = 'farm:pig'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(matIconElement); expect(svgElement.childNodes.length).toBe(1); svgChild = svgElement.childNodes[0]; // The <svg> child should be the <g id="pig"> element. expect(svgChild.tagName.toLowerCase()).toBe('g'); expect(svgChild.getAttribute('name')).toBe('pig'); expect(svgChild.getAttribute('id')).toBeFalsy(); expect(svgChild.childNodes.length).toBe(1); verifyPathChildElement(svgChild, 'oink'); // Change the icon name to one that appears in both icon sets. The icon from the set that // was registered last should be used (with id attribute of 'moo moo' instead of 'moo'), // and no additional HTTP request should be made. testComponent.iconName = 'farm:cow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(matIconElement); svgChild = svgElement.childNodes[0]; // The first <svg> child should be the <g id="cow"> element. expect(svgChild.tagName.toLowerCase()).toBe('g'); expect(svgChild.getAttribute('name')).toBe('cow'); expect(svgChild.childNodes.length).toBe(1); verifyPathChildElement(svgChild, 'moo moo'); }); it('should return unmodified copies of icons from icon sets', () => { iconRegistry.addSvgIconSetLiteral(trustHtml(FAKE_SVGS.arrows)); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); let svgElement: SVGElement; testComponent.iconName = 'left-arrow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(matIconElement); verifyPathChildElement(svgElement, 'left'); // Modify the SVG element by setting a viewBox attribute. svgElement.setAttribute('viewBox', '0 0 100 100'); // Switch to a different icon. testComponent.iconName = 'right-arrow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(matIconElement); verifyPathChildElement(svgElement, 'right'); // Switch back to the first icon. The viewBox attribute should not be present. testComponent.iconName = 'left-arrow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(matIconElement); verifyPathChildElement(svgElement, 'left'); expect(svgElement.getAttribute('viewBox')).toBeFalsy(); }); it('should be able to configure the viewBox for the icon set', () => { iconRegistry.addSvgIconSetLiteral(trustHtml(FAKE_SVGS.arrows), {viewBox: '0 0 43 43'}); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); let svgElement: SVGElement; testComponent.iconName = 'left-arrow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(matIconElement); expect(svgElement.getAttribute('viewBox')).toBe('0 0 43 43'); });
{ "end_byte": 41066, "start_byte": 32957, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon.spec.ts" }
components/src/material/icon/icon.spec.ts_41072_47998
it('should prepend the current path to attributes with `url()` references', fakeAsync(() => { iconRegistry.addSvgIconLiteral( 'fido', trustHtml(` <svg> <filter id="blur"> <feGaussianBlur in="SourceGraphic" stdDeviation="5" /> </filter> <circle cx="170" cy="60" r="50" fill="green" filter="url('#blur')" /> </svg> `), ); const fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const circle = fixture.nativeElement.querySelector('mat-icon svg circle'); // We use a regex to match here, rather than the exact value, because different browsers // return different quotes through `getAttribute`, while some even omit the quotes altogether. expect(circle.getAttribute('filter')).toMatch(/^url\(['"]?\/\$fake-path#blur['"]?\)$/); tick(); })); it('should use latest path when prefixing the `url()` references', fakeAsync(() => { iconRegistry.addSvgIconLiteral( 'fido', trustHtml(` <svg> <filter id="blur"> <feGaussianBlur in="SourceGraphic" stdDeviation="5" /> </filter> <circle cx="170" cy="60" r="50" fill="green" filter="url('#blur')" /> </svg> `), ); let fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); let circle = fixture.nativeElement.querySelector('mat-icon svg circle'); expect(circle.getAttribute('filter')).toMatch(/^url\(['"]?\/\$fake-path#blur['"]?\)$/); tick(); fixture.destroy(); fakePath = '/$another-fake-path'; fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); circle = fixture.nativeElement.querySelector('mat-icon svg circle'); expect(circle.getAttribute('filter')).toMatch( /^url\(['"]?\/\$another-fake-path#blur['"]?\)$/, ); tick(); })); it('should update the `url()` references when the path changes', fakeAsync(() => { iconRegistry.addSvgIconLiteral( 'fido', trustHtml(` <svg> <filter id="blur"> <feGaussianBlur in="SourceGraphic" stdDeviation="5" /> </filter> <circle cx="170" cy="60" r="50" fill="green" filter="url('#blur')" /> </svg> `), ); const fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const circle = fixture.nativeElement.querySelector('mat-icon svg circle'); // We use a regex to match here, rather than the exact value, because different browsers // return different quotes through `getAttribute`, while some even omit the quotes altogether. expect(circle.getAttribute('filter')).toMatch(/^url\(['"]?\/\$fake-path#blur['"]?\)$/); tick(); fakePath = '/$different-path'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(circle.getAttribute('filter')).toMatch(/^url\(['"]?\/\$different-path#blur['"]?\)$/); })); }); describe('custom fonts', () => { it('should apply CSS classes for custom font and icon', () => { iconRegistry.registerFontClassAlias('f1', 'font1'); iconRegistry.registerFontClassAlias('f2'); const fixture = TestBed.createComponent(IconWithCustomFontCss); const testComponent = fixture.componentInstance; const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); testComponent.fontSet = 'f1'; testComponent.fontIcon = 'house'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(sortedClassNames(matIconElement)).toEqual([ 'font1', 'house', 'mat-icon', 'mat-icon-no-color', 'notranslate', ]); testComponent.fontSet = 'f2'; testComponent.fontIcon = 'igloo'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(sortedClassNames(matIconElement)).toEqual([ 'f2', 'igloo', 'mat-icon', 'mat-icon-no-color', 'notranslate', ]); testComponent.fontSet = 'f3'; testComponent.fontIcon = 'tent'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(sortedClassNames(matIconElement)).toEqual([ 'f3', 'mat-icon', 'mat-icon-no-color', 'notranslate', 'tent', ]); }); it('should handle values with extraneous spaces being passed in to `fontSet`', () => { const fixture = TestBed.createComponent(IconWithCustomFontCss); const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); expect(() => { fixture.componentInstance.fontSet = 'font set'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); }).not.toThrow(); expect(sortedClassNames(matIconElement)).toEqual([ 'font', 'mat-icon', 'mat-icon-no-color', 'notranslate', ]); expect(() => { fixture.componentInstance.fontSet = ' changed'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); }).not.toThrow(); expect(sortedClassNames(matIconElement)).toEqual([ 'changed', 'mat-icon', 'mat-icon-no-color', 'notranslate', ]); }); it('should handle values with extraneous spaces being passed in to `fontIcon`', () => { const fixture = TestBed.createComponent(IconWithCustomFontCss); const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); fixture.componentInstance.fontSet = 'f1'; fixture.changeDetectorRef.markForCheck(); expect(() => { fixture.componentInstance.fontIcon = 'font icon'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); }).not.toThrow(); expect(sortedClassNames(matIconElement)).toEqual([ 'f1', 'font', 'mat-icon', 'mat-icon-no-color', 'notranslate', ]); expect(() => { fixture.componentInstance.fontIcon = ' changed'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); }).not.toThrow(); expect(sortedClassNames(matIconElement)).toEqual([ 'changed', 'f1', 'mat-icon', 'mat-icon-no-color', 'notranslate', ]); }); });
{ "end_byte": 47998, "start_byte": 41072, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon.spec.ts" }
components/src/material/icon/icon.spec.ts_48002_55029
describe('Icons resolved through a resolver function', () => { it('should resolve icons through a resolver function', fakeAsync(() => { iconRegistry.addSvgIconResolver(name => { if (name === 'fluffy') { return trustUrl('cat.svg'); } else if (name === 'fido') { return trustUrl('dog.svg'); } else if (name === 'felix') { return {url: trustUrl('auth-cat.svg'), options: {withCredentials: true}}; } return null; }); const fixture = TestBed.createComponent(IconFromSvgName); let svgElement: SVGElement; let testRequest: TestRequest; const testComponent = fixture.componentInstance; const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); testComponent.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('dog.svg').flush(FAKE_SVGS.dog); svgElement = verifyAndGetSingleSvgChild(iconElement); verifyPathChildElement(svgElement, 'woof'); // Change the icon, and the SVG element should be replaced. testComponent.iconName = 'fluffy'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('cat.svg').flush(FAKE_SVGS.cat); svgElement = verifyAndGetSingleSvgChild(iconElement); verifyPathChildElement(svgElement, 'meow'); // Using an icon from a previously loaded URL should not cause another HTTP request. testComponent.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectNone('dog.svg'); svgElement = verifyAndGetSingleSvgChild(iconElement); verifyPathChildElement(svgElement, 'woof'); // Change icon to one that needs credentials during fetch. testComponent.iconName = 'felix'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); testRequest = http.expectOne('auth-cat.svg'); expect(testRequest.request.withCredentials).toBeTrue(); testRequest.flush(FAKE_SVGS.cat); svgElement = verifyAndGetSingleSvgChild(iconElement); verifyPathChildElement(svgElement, 'meow'); // Assert that a registered icon can be looked-up by url. iconRegistry.getSvgIconFromUrl(trustUrl('cat.svg')).subscribe(element => { verifyPathChildElement(element, 'meow'); }); tick(); })); it('should fall back to second resolver if the first one returned null', fakeAsync(() => { iconRegistry .addSvgIconResolver(() => null) .addSvgIconResolver(name => (name === 'fido' ? trustUrl('dog.svg') : null)); const fixture = TestBed.createComponent(IconFromSvgName); const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); fixture.componentInstance.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('dog.svg').flush(FAKE_SVGS.dog); verifyPathChildElement(verifyAndGetSingleSvgChild(iconElement), 'woof'); tick(); })); it('should be able to set the viewBox when resolving an icon with a function', fakeAsync(() => { iconRegistry.addSvgIconResolver(name => { if (name === 'fluffy') { return {url: trustUrl('cat.svg'), options: {viewBox: '0 0 27 27'}}; } else if (name === 'fido') { return {url: trustUrl('dog.svg'), options: {viewBox: '0 0 43 43'}}; } return null; }); const fixture = TestBed.createComponent(IconFromSvgName); let svgElement: SVGElement; const testComponent = fixture.componentInstance; const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); testComponent.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('dog.svg').flush(FAKE_SVGS.dog); svgElement = verifyAndGetSingleSvgChild(iconElement); expect(svgElement.getAttribute('viewBox')).toBe('0 0 43 43'); // Change the icon, and the SVG element should be replaced. testComponent.iconName = 'fluffy'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('cat.svg').flush(FAKE_SVGS.cat); svgElement = verifyAndGetSingleSvgChild(iconElement); expect(svgElement.getAttribute('viewBox')).toBe('0 0 27 27'); })); it('should throw an error when the resolver returns an untrusted URL', () => { iconRegistry.addSvgIconResolver(() => 'not-trusted.svg'); expect(() => { const fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'fluffy'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); }).toThrowError(/unsafe value used in a resource URL context/); }); }); it('should handle assigning an icon through the setter', fakeAsync(() => { iconRegistry.addSvgIconLiteral('fido', trustHtml(FAKE_SVGS.dog)); const fixture = TestBed.createComponent(BlankIcon); fixture.detectChanges(); let svgElement: SVGElement; const testComponent = fixture.componentInstance; const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); testComponent.icon.svgIcon = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); svgElement = verifyAndGetSingleSvgChild(iconElement); verifyPathChildElement(svgElement, 'woof'); tick(); })); /** Marks an SVG icon url as explicitly trusted. */ function trustUrl(iconUrl: string): SafeResourceUrl { return sanitizer.bypassSecurityTrustResourceUrl(iconUrl); } /** Marks an SVG icon string as explicitly trusted. */ function trustHtml(iconHtml: string): SafeHtml { return sanitizer.bypassSecurityTrustHtml(iconHtml); } }); describe('MatIcon without HttpClientModule', () => { let iconRegistry: MatIconRegistry; let sanitizer: DomSanitizer; @Component({ template: `<mat-icon [svgIcon]="iconName"></mat-icon>`, standalone: false, }) class IconFromSvgName { iconName: string | undefined = ''; } beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [MatIconModule], declarations: [IconFromSvgName], }); })); beforeEach(inject([MatIconRegistry, DomSanitizer], (mir: MatIconRegistry, ds: DomSanitizer) => { iconRegistry = mir; sanitizer = ds; })); it('should throw an error when trying to load a remote icon', () => { const expectedError = wrappedErrorMessage(getMatIconNoHttpProviderError()); expect(() => { iconRegistry.addSvgIcon('fido', sanitizer.bypassSecurityTrustResourceUrl('dog.svg')); const fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); }).toThrowError(expectedError); }); });
{ "end_byte": 55029, "start_byte": 48002, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon.spec.ts" }
components/src/material/icon/icon.spec.ts_55031_60331
describe('MatIcon with default options', () => { it('should be able to configure color globally', fakeAsync(() => { const fixture = createComponent(IconWithLigature, [ {provide: MAT_ICON_DEFAULT_OPTIONS, useValue: {color: 'accent'}}, ]); const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); fixture.detectChanges(); expect(iconElement.classList).not.toContain('mat-icon-no-color'); expect(iconElement.classList).toContain('mat-accent'); })); it('should use passed color rather then color provided', fakeAsync(() => { const fixture = createComponent(IconWithColor, [ {provide: MAT_ICON_DEFAULT_OPTIONS, useValue: {color: 'warn'}}, ]); const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); fixture.detectChanges(); expect(iconElement.classList).not.toContain('mat-warn'); expect(iconElement.classList).toContain('mat-primary'); })); it('should use default color if no color passed', fakeAsync(() => { const fixture = createComponent(IconWithColor, [ {provide: MAT_ICON_DEFAULT_OPTIONS, useValue: {color: 'accent'}}, ]); const component = fixture.componentInstance; const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); component.iconColor = ''; fixture.detectChanges(); expect(iconElement.classList).not.toContain('mat-icon-no-color'); expect(iconElement.classList).not.toContain('mat-primary'); expect(iconElement.classList).toContain('mat-accent'); })); it('should be able to configure font set globally', fakeAsync(() => { const fixture = createComponent(IconWithLigature, [ {provide: MAT_ICON_DEFAULT_OPTIONS, useValue: {fontSet: 'custom-font-set'}}, ]); const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); fixture.detectChanges(); expect(iconElement.classList).toContain('custom-font-set'); })); it('should use passed fontSet rather then default one', fakeAsync(() => { const fixture = createComponent(IconWithCustomFontCss, [ {provide: MAT_ICON_DEFAULT_OPTIONS, useValue: {fontSet: 'default-font-set'}}, ]); const component = fixture.componentInstance; const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); component.fontSet = 'custom-font-set'; fixture.detectChanges(); expect(iconElement.classList).not.toContain('default-font-set'); expect(iconElement.classList).toContain('custom-font-set'); })); it('should use passed empty fontSet rather then default one', fakeAsync(() => { const fixture = createComponent(IconWithCustomFontCss, [ {provide: MAT_ICON_DEFAULT_OPTIONS, useValue: {fontSet: 'default-font-set'}}, ]); const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); fixture.detectChanges(); expect(iconElement.classList).not.toContain('default-font-set'); })); }); @Component({ template: `<mat-icon>{{iconName}}</mat-icon>`, standalone: true, imports: [HttpClientTestingModule, MatIconModule], }) class IconWithLigature { iconName = ''; } @Component({ template: `<mat-icon [fontIcon]="iconName"></mat-icon>`, standalone: true, imports: [HttpClientTestingModule, MatIconModule], }) class IconWithLigatureByAttribute { iconName = ''; } @Component({ template: `<mat-icon [color]="iconColor">{{iconName}}</mat-icon>`, standalone: true, imports: [HttpClientTestingModule, MatIconModule], }) class IconWithColor { iconName = ''; iconColor = 'primary'; } @Component({ template: `<mat-icon [fontSet]="fontSet" [fontIcon]="fontIcon"></mat-icon>`, standalone: true, imports: [HttpClientTestingModule, MatIconModule], }) class IconWithCustomFontCss { fontSet = ''; fontIcon = ''; } @Component({ template: `<mat-icon [svgIcon]="iconName"></mat-icon>`, standalone: true, imports: [HttpClientTestingModule, MatIconModule], }) class IconFromSvgName { iconName: string | undefined = ''; } @Component({ template: '<mat-icon aria-hidden="false">face</mat-icon>', standalone: true, imports: [HttpClientTestingModule, MatIconModule], }) class IconWithAriaHiddenFalse {} @Component({ template: `@if (showIcon) {<mat-icon [svgIcon]="iconName">{{iconName}}</mat-icon>}`, standalone: true, imports: [HttpClientTestingModule, MatIconModule], }) class IconWithBindingAndNgIf { iconName = 'fluffy'; showIcon = true; } @Component({ template: `<mat-icon [inline]="inline">{{iconName}}</mat-icon>`, standalone: true, imports: [HttpClientTestingModule, MatIconModule], }) class InlineIcon { inline = false; } @Component({ template: `<mat-icon [svgIcon]="iconName"><div>Hello</div></mat-icon>`, standalone: true, imports: [HttpClientTestingModule, MatIconModule], }) class SvgIconWithUserContent { iconName: string | undefined = ''; } @Component({ template: '<mat-icon [svgIcon]="iconName">house</mat-icon>', standalone: true, imports: [HttpClientTestingModule, MatIconModule], }) class IconWithLigatureAndSvgBinding { iconName: string | undefined; } @Component({ template: `<mat-icon></mat-icon>`, standalone: true, imports: [HttpClientTestingModule, MatIconModule], }) class BlankIcon { @ViewChild(MatIcon) icon: MatIcon; }
{ "end_byte": 60331, "start_byte": 55031, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon.spec.ts" }
components/src/material/icon/fake-svgs.ts_0_1636
/** * @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 */ /** * Fake URLs and associated SVG documents used by tests. * The ID attribute is used to load the icons, the name attribute is only used for testing. * @docs-private */ export const FAKE_SVGS = { cat: '<svg><path id="meow" name="meow"></path></svg>', dog: '<svg><path id="woof" name="woof"></path></svg>', dogWithSpaces: '<svg><path id="woof says the dog" name="woof"></path></svg>', farmSet1: ` <svg> <defs> <g id="pig" name="pig"><path name="oink"></path></g> <g id="cow" name="cow"><path name="moo"></path></g> </defs> </svg> `, farmSet2: ` <svg> <defs> <g id="cow" name="cow"><path name="moo moo"></path></g> <g id="sheep" name="sheep"><path name="baa"></path></g> </defs> </svg> `, farmSet3: ` <svg> <symbol id="duck" name="duck"> <path id="quack" name="quack"></path> </symbol> </svg> `, farmSet4: ` <svg> <defs> <g id="pig with spaces" name="pig"><path name="oink"></path></g> </defs> </svg> `, farmSet5: ` <svg> <symbol id="duck" viewBox="0 0 13 37"> <path id="quack" name="quack"></path> </symbol> </svg> `, arrows: ` <svg> <defs> <svg id="left-arrow" name="left-arrow"><path name="left"></path></svg> <svg id="right-arrow" name="right-arrow"><path name="right"></path></svg> </defs> </svg> `, };
{ "end_byte": 1636, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/icon/fake-svgs.ts" }
components/src/material/icon/icon.md_0_7062
`mat-icon` makes it easier to use _vector-based_ icons in your app. This directive supports both icon fonts and SVG icons, but not bitmap-based formats (png, jpg, etc.). <!-- example(icon-overview) --> ### Registering icons `MatIconRegistry` is an injectable service that allows you to associate icon names with SVG URLs, HTML strings and to define aliases for CSS font classes. Its methods are discussed below and listed in the API summary. ### Font icons with ligatures Some fonts are designed to show icons by using [ligatures](https://en.wikipedia.org/wiki/Typographic_ligature), for example by rendering the text "home" as a home image. To use a ligature icon, put its text in the content of the `mat-icon` component. By default, `<mat-icon>` expects the [Material icons font](https://google.github.io/material-design-icons/#icon-font-for-the-web). (You will still need to include the HTML to load the font and its CSS, as described in the link). You can specify a different font, such as Material's latest icons, [Material Symbols](https://fonts.google.com/icons), by setting the `fontSet` input to either the CSS class to apply to use the desired font, or to an alias previously registered with `MatIconRegistry.registerFontClassAlias`. Alternatively you can set the default for all your application's icons using `MatIconRegistry.setDefaultFontSetClass`. ### Font icons with CSS Fonts can also display icons by defining a CSS class for each icon glyph, which typically uses a `:before` selector to cause the icon to appear. [Font Awesome](https://fontawesome.com/icons) uses this approach to display its icons. To use such a font, set the `fontSet` input to the font's CSS class (either the class itself or an alias registered with `MatIconRegistry.registerFontClassAlias`), and set the `fontIcon` input to the class for the specific icon to show. For both types of font icons, you can specify the default font class to use when `fontSet` is not explicitly set by calling `MatIconRegistry.setDefaultFontSetClass`. ### SVG icons `<mat-icon>` displays SVG icons by directly inlining the SVG content into the DOM as a child of itself. This approach offers an advantage over an `<img>` tag or a CSS `background-image` because it allows styling the SVG with CSS. For example, the default color of the SVG content is the CSS [currentColor](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#currentColor_keyword) value. This makes SVG icons by default have the same color as surrounding text, and allows you to change the color by setting the `color` style on the `mat-icon` element. In order to guard against XSS vulnerabilities, any SVG URLs and HTML strings passed to the `MatIconRegistry` must be marked as trusted by using Angular's `DomSanitizer` service. `MatIconRegistry` fetches all remote SVG icons via Angular's `HttpClient` service. If you haven't included [`HttpClientModule` from the `@angular/common/http` package](https://angular.dev/guide/http) in your `NgModule` imports, you will get an error at runtime. Note that `HttpClient` fetches SVG icons registered with a URL via `XmlHttpRequest`, subject to the [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy). This means that icon URLs must have the same origin as the containing page or that the application's server must be configured to allow cross-origin requests. #### Named icons To associate a name with an icon URL, use the `addSvgIcon`, `addSvgIconInNamespace`, `addSvgIconLiteral` or `addSvgIconLiteralInNamespace` methods of `MatIconRegistry`. After registering an icon, it can be displayed by setting the `svgIcon` input. For an icon in the default namespace, use the name directly. For a non-default namespace, use the format `[namespace]:[name]`. #### Icon sets Icon sets allow grouping multiple icons into a single SVG file. This is done by creating a single root `<svg>` tag that contains multiple nested `<svg>` tags in its `<defs>` section. Each of these nested tags is identified with an `id` attribute. This `id` is used as the name of the icon. Icon sets are registered using the `addSvgIconSet`, `addSvgIconSetInNamespace`, `addSvgIconSetLiteral` or `addSvgIconSetLiteralInNamespace` methods of `MatIconRegistry`. After an icon set is registered, each of its embedded icons can be accessed by their `id` attributes. To display an icon from an icon set, use the `svgIcon` input in the same way as for individually registered icons. Multiple icon sets can be registered in the same namespace. Requesting an icon whose id appears in more than one icon set, the icon from the most recently registered set will be used. ### Accessibility Similar to an `<img>` element, an icon alone does not convey any useful information for a screen-reader user. The user of `<mat-icon>` must provide additional information pertaining to how the icon is used. Based on the use-cases described below, `mat-icon` is marked as `aria-hidden="true"` by default, but this can be overridden by adding `aria-hidden="false"` to the element. In thinking about accessibility, it is useful to place icon use into one of three categories: 1. **Decorative**: the icon conveys no real semantic meaning and is purely cosmetic. 2. **Interactive**: a user will click or otherwise interact with the icon to perform some action. 3. **Indicator**: the icon is not interactive, but it conveys some information, such as a status. This includes using the icon in place of text inside of a larger message. #### Decorative icons When the icon is purely cosmetic and conveys no real semantic meaning, the `<mat-icon>` element is marked with `aria-hidden="true"`. #### Interactive icons Icons alone are not interactive elements for screen-reader users; when the user would interact with some icon on the page, a more appropriate element should "own" the interaction: * The `<mat-icon>` element should be a child of a `<button>` or `<a>` element. * The parent `<button>` or `<a>` should either have a meaningful label provided either through direct text content, `aria-label`, or `aria-labelledby`. #### Indicator icons When the presence of an icon communicates some information to the user whether as an indicator or by being inlined into a block of text, that information must also be made available to screen-readers. The most straightforward way to do this is to 1. Add a `<span>` as an adjacent sibling to the `<mat-icon>` element with text that conveys the same information as the icon. 2. Add the `cdk-visually-hidden` class to the `<span>`. This will make the message invisible on-screen but still available to screen-reader users. ### Bidirectionality By default icons in an RTL layout will look exactly the same as in LTR, however certain icons have to be [mirrored for RTL users](https://material.io/design/usability/bidirectionality.html). If you want to mirror an icon only in an RTL layout, you can use the `mat-icon-rtl-mirror` CSS class. ```html <mat-icon class="mat-icon-rtl-mirror" svgIcon="thumb-up"></mat-icon> ```
{ "end_byte": 7062, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon.md" }
components/src/material/icon/trusted-types.ts_0_2355
/** * @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 */ /** * @fileoverview * A module to facilitate use of a Trusted Types policy internally within * Angular Material. It lazily constructs the Trusted Types policy, providing * helper utilities for promoting strings to Trusted Types. When Trusted Types * are not available, strings are used as a fallback. * @security All use of this module is security-sensitive and should go through * security review. */ export declare interface TrustedHTML { __brand__: 'TrustedHTML'; } export declare interface TrustedTypePolicyFactory { createPolicy( policyName: string, policyOptions: { createHTML?: (input: string) => string; }, ): TrustedTypePolicy; } export declare interface TrustedTypePolicy { createHTML(input: string): TrustedHTML; } /** * The Trusted Types policy, or null if Trusted Types are not * enabled/supported, or undefined if the policy has not been created yet. */ let policy: TrustedTypePolicy | null | undefined; /** * Returns the Trusted Types policy, or null if Trusted Types are not * enabled/supported. The first call to this function will create the policy. */ function getPolicy(): TrustedTypePolicy | null { if (policy === undefined) { policy = null; if (typeof window !== 'undefined') { const ttWindow = window as unknown as {trustedTypes?: TrustedTypePolicyFactory}; if (ttWindow.trustedTypes !== undefined) { policy = ttWindow.trustedTypes.createPolicy('angular#components', { createHTML: (s: string) => s, }); } } } return policy; } /** * Unsafely promote a string to a TrustedHTML, falling back to strings when * Trusted Types are not available. * @security This is a security-sensitive function; any use of this function * must go through security review. In particular, it must be assured that the * provided string will never cause an XSS vulnerability if used in a context * that will be interpreted as HTML by a browser, e.g. when assigning to * element.innerHTML. */ export function trustedHTMLFromString(html: string): TrustedHTML { return getPolicy()?.createHTML(html) || (html as unknown as TrustedHTML); }
{ "end_byte": 2355, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/icon/trusted-types.ts" }
components/src/material/icon/BUILD.bazel_0_1432
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 = "icon", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), assets = [":icon.css"] + glob(["**/*.html"]), deps = [ "//src:dev_mode_types", "//src/material/core", "@npm//@angular/common", "@npm//@angular/core", "@npm//@angular/platform-browser", "@npm//rxjs", ], ) sass_library( name = "icon_scss_lib", srcs = glob(["**/_*.scss"]), deps = ["//src/material/core:core_scss_lib"], ) sass_binary( name = "icon_scss", src = "icon.scss", deps = ["//src/material/core:core_scss_lib"], ) ng_test_library( name = "unit_test_sources", srcs = glob( ["**/*.spec.ts"], ), deps = [ ":icon", "//src/cdk/testing", "//src/cdk/testing/private", "@npm//@angular/common", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_test_sources"], ) markdown_to_html( name = "overview", srcs = [":icon.md"], ) extract_tokens( name = "tokens", srcs = [":icon_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "end_byte": 1432, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/icon/BUILD.bazel" }
components/src/material/icon/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/icon/index.ts" }
components/src/material/icon/icon-registry.ts_0_3800
/** * @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 {DOCUMENT} from '@angular/common'; import {HttpClient, HttpErrorResponse} from '@angular/common/http'; import { ErrorHandler, Inject, Injectable, InjectionToken, OnDestroy, Optional, SecurityContext, SkipSelf, } from '@angular/core'; import {DomSanitizer, SafeHtml, SafeResourceUrl} from '@angular/platform-browser'; import {forkJoin, Observable, of as observableOf, throwError as observableThrow} from 'rxjs'; import {catchError, finalize, map, share, tap} from 'rxjs/operators'; import {TrustedHTML, trustedHTMLFromString} from './trusted-types'; /** * Returns an exception to be thrown in the case when attempting to * load an icon with a name that cannot be found. * @docs-private */ export function getMatIconNameNotFoundError(iconName: string): Error { return Error(`Unable to find icon with the name "${iconName}"`); } /** * Returns an exception to be thrown when the consumer attempts to use * `<mat-icon>` without including @angular/common/http. * @docs-private */ export function getMatIconNoHttpProviderError(): Error { return Error( 'Could not find HttpClient for use with Angular Material icons. ' + 'Please add provideHttpClient() to your providers.', ); } /** * Returns an exception to be thrown when a URL couldn't be sanitized. * @param url URL that was attempted to be sanitized. * @docs-private */ export function getMatIconFailedToSanitizeUrlError(url: SafeResourceUrl): Error { return Error( `The URL provided to MatIconRegistry was not trusted as a resource URL ` + `via Angular's DomSanitizer. Attempted URL was "${url}".`, ); } /** * Returns an exception to be thrown when a HTML string couldn't be sanitized. * @param literal HTML that was attempted to be sanitized. * @docs-private */ export function getMatIconFailedToSanitizeLiteralError(literal: SafeHtml): Error { return Error( `The literal provided to MatIconRegistry was not trusted as safe HTML by ` + `Angular's DomSanitizer. Attempted literal was "${literal}".`, ); } /** Options that can be used to configure how an icon or the icons in an icon set are presented. */ export interface IconOptions { /** View box to set on the icon. */ viewBox?: string; /** Whether or not to fetch the icon or icon set using HTTP credentials. */ withCredentials?: boolean; } /** * Function that will be invoked by the icon registry when trying to resolve the * URL from which to fetch an icon. The returned URL will be used to make a request for the icon. */ export type IconResolver = ( name: string, namespace: string, ) => SafeResourceUrl | SafeResourceUrlWithIconOptions | null; /** Object that specifies a URL from which to fetch an icon and the options to use for it. */ export interface SafeResourceUrlWithIconOptions { url: SafeResourceUrl; options: IconOptions; } /** * Configuration for an icon, including the URL and possibly the cached SVG element. * @docs-private */ class SvgIconConfig { svgElement: SVGElement | null; constructor( public url: SafeResourceUrl, public svgText: TrustedHTML | null, public options?: IconOptions, ) {} } /** Icon configuration whose content has already been loaded. */ type LoadedSvgIconConfig = SvgIconConfig & {svgText: TrustedHTML}; /** * Service to register and display icons used by the `<mat-icon>` component. * - Registers icon URLs by namespace and name. * - Registers icon set URLs by namespace. * - Registers aliases for CSS classes, for use with icon fonts. * - Loads icons from URLs and extracts individual icons from icon sets. */
{ "end_byte": 3800, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon-registry.ts" }
components/src/material/icon/icon-registry.ts_3801_11934
@Injectable({providedIn: 'root'}) export class MatIconRegistry implements OnDestroy { private _document: Document; /** * URLs and cached SVG elements for individual icons. Keys are of the format "[namespace]:[icon]". */ private _svgIconConfigs = new Map<string, SvgIconConfig>(); /** * SvgIconConfig objects and cached SVG elements for icon sets, keyed by namespace. * Multiple icon sets can be registered under the same namespace. */ private _iconSetConfigs = new Map<string, SvgIconConfig[]>(); /** Cache for icons loaded by direct URLs. */ private _cachedIconsByUrl = new Map<string, SVGElement>(); /** In-progress icon fetches. Used to coalesce multiple requests to the same URL. */ private _inProgressUrlFetches = new Map<string, Observable<TrustedHTML>>(); /** Map from font identifiers to their CSS class names. Used for icon fonts. */ private _fontCssClassesByAlias = new Map<string, string>(); /** Registered icon resolver functions. */ private _resolvers: IconResolver[] = []; /** * The CSS classes to apply when an `<mat-icon>` component has no icon name, url, or font * specified. The default 'material-icons' value assumes that the material icon font has been * loaded as described at https://google.github.io/material-design-icons/#icon-font-for-the-web */ private _defaultFontSetClass = ['material-icons', 'mat-ligature-font']; constructor( @Optional() private _httpClient: HttpClient, private _sanitizer: DomSanitizer, @Optional() @Inject(DOCUMENT) document: any, private readonly _errorHandler: ErrorHandler, ) { this._document = document; } /** * Registers an icon by URL in the default namespace. * @param iconName Name under which the icon should be registered. * @param url */ addSvgIcon(iconName: string, url: SafeResourceUrl, options?: IconOptions): this { return this.addSvgIconInNamespace('', iconName, url, options); } /** * Registers an icon using an HTML string in the default namespace. * @param iconName Name under which the icon should be registered. * @param literal SVG source of the icon. */ addSvgIconLiteral(iconName: string, literal: SafeHtml, options?: IconOptions): this { return this.addSvgIconLiteralInNamespace('', iconName, literal, options); } /** * Registers an icon by URL in the specified namespace. * @param namespace Namespace in which the icon should be registered. * @param iconName Name under which the icon should be registered. * @param url */ addSvgIconInNamespace( namespace: string, iconName: string, url: SafeResourceUrl, options?: IconOptions, ): this { return this._addSvgIconConfig(namespace, iconName, new SvgIconConfig(url, null, options)); } /** * Registers an icon resolver function with the registry. The function will be invoked with the * name and namespace of an icon when the registry tries to resolve the URL from which to fetch * the icon. The resolver is expected to return a `SafeResourceUrl` that points to the icon, * an object with the icon URL and icon options, or `null` if the icon is not supported. Resolvers * will be invoked in the order in which they have been registered. * @param resolver Resolver function to be registered. */ addSvgIconResolver(resolver: IconResolver): this { this._resolvers.push(resolver); return this; } /** * Registers an icon using an HTML string in the specified namespace. * @param namespace Namespace in which the icon should be registered. * @param iconName Name under which the icon should be registered. * @param literal SVG source of the icon. */ addSvgIconLiteralInNamespace( namespace: string, iconName: string, literal: SafeHtml, options?: IconOptions, ): this { const cleanLiteral = this._sanitizer.sanitize(SecurityContext.HTML, literal); // TODO: add an ngDevMode check if (!cleanLiteral) { throw getMatIconFailedToSanitizeLiteralError(literal); } // Security: The literal is passed in as SafeHtml, and is thus trusted. const trustedLiteral = trustedHTMLFromString(cleanLiteral); return this._addSvgIconConfig( namespace, iconName, new SvgIconConfig('', trustedLiteral, options), ); } /** * Registers an icon set by URL in the default namespace. * @param url */ addSvgIconSet(url: SafeResourceUrl, options?: IconOptions): this { return this.addSvgIconSetInNamespace('', url, options); } /** * Registers an icon set using an HTML string in the default namespace. * @param literal SVG source of the icon set. */ addSvgIconSetLiteral(literal: SafeHtml, options?: IconOptions): this { return this.addSvgIconSetLiteralInNamespace('', literal, options); } /** * Registers an icon set by URL in the specified namespace. * @param namespace Namespace in which to register the icon set. * @param url */ addSvgIconSetInNamespace(namespace: string, url: SafeResourceUrl, options?: IconOptions): this { return this._addSvgIconSetConfig(namespace, new SvgIconConfig(url, null, options)); } /** * Registers an icon set using an HTML string in the specified namespace. * @param namespace Namespace in which to register the icon set. * @param literal SVG source of the icon set. */ addSvgIconSetLiteralInNamespace( namespace: string, literal: SafeHtml, options?: IconOptions, ): this { const cleanLiteral = this._sanitizer.sanitize(SecurityContext.HTML, literal); if (!cleanLiteral) { throw getMatIconFailedToSanitizeLiteralError(literal); } // Security: The literal is passed in as SafeHtml, and is thus trusted. const trustedLiteral = trustedHTMLFromString(cleanLiteral); return this._addSvgIconSetConfig(namespace, new SvgIconConfig('', trustedLiteral, options)); } /** * Defines an alias for CSS class names to be used for icon fonts. Creating an matIcon * component with the alias as the fontSet input will cause the class name to be applied * to the `<mat-icon>` element. * * If the registered font is a ligature font, then don't forget to also include the special * class `mat-ligature-font` to allow the usage via attribute. So register like this: * * ```ts * iconRegistry.registerFontClassAlias('f1', 'font1 mat-ligature-font'); * ``` * * And use like this: * * ```html * <mat-icon fontSet="f1" fontIcon="home"></mat-icon> * ``` * * @param alias Alias for the font. * @param classNames Class names override to be used instead of the alias. */ registerFontClassAlias(alias: string, classNames: string = alias): this { this._fontCssClassesByAlias.set(alias, classNames); return this; } /** * Returns the CSS class name associated with the alias by a previous call to * registerFontClassAlias. If no CSS class has been associated, returns the alias unmodified. */ classNameForFontAlias(alias: string): string { return this._fontCssClassesByAlias.get(alias) || alias; } /** * Sets the CSS classes to be used for icon fonts when an `<mat-icon>` component does not * have a fontSet input value, and is not loading an icon by name or URL. */ setDefaultFontSetClass(...classNames: string[]): this { this._defaultFontSetClass = classNames; return this; } /** * Returns the CSS classes to be used for icon fonts when an `<mat-icon>` component does not * have a fontSet input value, and is not loading an icon by name or URL. */ getDefaultFontSetClass(): string[] { return this._defaultFontSetClass; } /** * Returns an Observable that produces the icon (as an `<svg>` DOM element) from the given URL. * The response from the URL may be cached so this will not always cause an HTTP request, but * the produced element will always be a new copy of the originally fetched icon. (That is, * it will not contain any modifications made to elements previously returned). * * @param safeUrl URL from which to fetch the SVG icon. */
{ "end_byte": 11934, "start_byte": 3801, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon-registry.ts" }
components/src/material/icon/icon-registry.ts_11937_19197
getSvgIconFromUrl(safeUrl: SafeResourceUrl): Observable<SVGElement> { const url = this._sanitizer.sanitize(SecurityContext.RESOURCE_URL, safeUrl); if (!url) { throw getMatIconFailedToSanitizeUrlError(safeUrl); } const cachedIcon = this._cachedIconsByUrl.get(url); if (cachedIcon) { return observableOf(cloneSvg(cachedIcon)); } return this._loadSvgIconFromConfig(new SvgIconConfig(safeUrl, null)).pipe( tap(svg => this._cachedIconsByUrl.set(url!, svg)), map(svg => cloneSvg(svg)), ); } /** * Returns an Observable that produces the icon (as an `<svg>` DOM element) with the given name * and namespace. The icon must have been previously registered with addIcon or addIconSet; * if not, the Observable will throw an error. * * @param name Name of the icon to be retrieved. * @param namespace Namespace in which to look for the icon. */ getNamedSvgIcon(name: string, namespace: string = ''): Observable<SVGElement> { const key = iconKey(namespace, name); let config = this._svgIconConfigs.get(key); // Return (copy of) cached icon if possible. if (config) { return this._getSvgFromConfig(config); } // Otherwise try to resolve the config from one of the resolver functions. config = this._getIconConfigFromResolvers(namespace, name); if (config) { this._svgIconConfigs.set(key, config); return this._getSvgFromConfig(config); } // See if we have any icon sets registered for the namespace. const iconSetConfigs = this._iconSetConfigs.get(namespace); if (iconSetConfigs) { return this._getSvgFromIconSetConfigs(name, iconSetConfigs); } return observableThrow(getMatIconNameNotFoundError(key)); } ngOnDestroy() { this._resolvers = []; this._svgIconConfigs.clear(); this._iconSetConfigs.clear(); this._cachedIconsByUrl.clear(); } /** * Returns the cached icon for a SvgIconConfig if available, or fetches it from its URL if not. */ private _getSvgFromConfig(config: SvgIconConfig): Observable<SVGElement> { if (config.svgText) { // We already have the SVG element for this icon, return a copy. return observableOf(cloneSvg(this._svgElementFromConfig(config as LoadedSvgIconConfig))); } else { // Fetch the icon from the config's URL, cache it, and return a copy. return this._loadSvgIconFromConfig(config).pipe(map(svg => cloneSvg(svg))); } } /** * Attempts to find an icon with the specified name in any of the SVG icon sets. * First searches the available cached icons for a nested element with a matching name, and * if found copies the element to a new `<svg>` element. If not found, fetches all icon sets * that have not been cached, and searches again after all fetches are completed. * The returned Observable produces the SVG element if possible, and throws * an error if no icon with the specified name can be found. */ private _getSvgFromIconSetConfigs( name: string, iconSetConfigs: SvgIconConfig[], ): Observable<SVGElement> { // For all the icon set SVG elements we've fetched, see if any contain an icon with the // requested name. const namedIcon = this._extractIconWithNameFromAnySet(name, iconSetConfigs); if (namedIcon) { // We could cache namedIcon in _svgIconConfigs, but since we have to make a copy every // time anyway, there's probably not much advantage compared to just always extracting // it from the icon set. return observableOf(namedIcon); } // Not found in any cached icon sets. If there are icon sets with URLs that we haven't // fetched, fetch them now and look for iconName in the results. const iconSetFetchRequests: Observable<TrustedHTML | null>[] = iconSetConfigs .filter(iconSetConfig => !iconSetConfig.svgText) .map(iconSetConfig => { return this._loadSvgIconSetFromConfig(iconSetConfig).pipe( catchError((err: HttpErrorResponse) => { const url = this._sanitizer.sanitize(SecurityContext.RESOURCE_URL, iconSetConfig.url); // Swallow errors fetching individual URLs so the // combined Observable won't necessarily fail. const errorMessage = `Loading icon set URL: ${url} failed: ${err.message}`; this._errorHandler.handleError(new Error(errorMessage)); return observableOf(null); }), ); }); // Fetch all the icon set URLs. When the requests complete, every IconSet should have a // cached SVG element (unless the request failed), and we can check again for the icon. return forkJoin(iconSetFetchRequests).pipe( map(() => { const foundIcon = this._extractIconWithNameFromAnySet(name, iconSetConfigs); // TODO: add an ngDevMode check if (!foundIcon) { throw getMatIconNameNotFoundError(name); } return foundIcon; }), ); } /** * Searches the cached SVG elements for the given icon sets for a nested icon element whose "id" * tag matches the specified name. If found, copies the nested element to a new SVG element and * returns it. Returns null if no matching element is found. */ private _extractIconWithNameFromAnySet( iconName: string, iconSetConfigs: SvgIconConfig[], ): SVGElement | null { // Iterate backwards, so icon sets added later have precedence. for (let i = iconSetConfigs.length - 1; i >= 0; i--) { const config = iconSetConfigs[i]; // Parsing the icon set's text into an SVG element can be expensive. We can avoid some of // the parsing by doing a quick check using `indexOf` to see if there's any chance for the // icon to be in the set. This won't be 100% accurate, but it should help us avoid at least // some of the parsing. if (config.svgText && config.svgText.toString().indexOf(iconName) > -1) { const svg = this._svgElementFromConfig(config as LoadedSvgIconConfig); const foundIcon = this._extractSvgIconFromSet(svg, iconName, config.options); if (foundIcon) { return foundIcon; } } } return null; } /** * Loads the content of the icon URL specified in the SvgIconConfig and creates an SVG element * from it. */ private _loadSvgIconFromConfig(config: SvgIconConfig): Observable<SVGElement> { return this._fetchIcon(config).pipe( tap(svgText => (config.svgText = svgText)), map(() => this._svgElementFromConfig(config as LoadedSvgIconConfig)), ); } /** * Loads the content of the icon set URL specified in the * SvgIconConfig and attaches it to the config. */ private _loadSvgIconSetFromConfig(config: SvgIconConfig): Observable<TrustedHTML | null> { if (config.svgText) { return observableOf(null); } return this._fetchIcon(config).pipe(tap(svgText => (config.svgText = svgText))); } /** * Searches the cached element of the given SvgIconConfig for a nested icon element whose "id" * tag matches the specified name. If found, copies the nested element to a new SVG element and * returns it. Returns null if no matching element is found. */
{ "end_byte": 19197, "start_byte": 11937, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon-registry.ts" }
components/src/material/icon/icon-registry.ts_19200_27475
private _extractSvgIconFromSet( iconSet: SVGElement, iconName: string, options?: IconOptions, ): SVGElement | null { // Use the `id="iconName"` syntax in order to escape special // characters in the ID (versus using the #iconName syntax). const iconSource = iconSet.querySelector(`[id="${iconName}"]`); if (!iconSource) { return null; } // Clone the element and remove the ID to prevent multiple elements from being added // to the page with the same ID. const iconElement = iconSource.cloneNode(true) as Element; iconElement.removeAttribute('id'); // If the icon node is itself an <svg> node, clone and return it directly. If not, set it as // the content of a new <svg> node. if (iconElement.nodeName.toLowerCase() === 'svg') { return this._setSvgAttributes(iconElement as SVGElement, options); } // If the node is a <symbol>, it won't be rendered so we have to convert it into <svg>. Note // that the same could be achieved by referring to it via <use href="#id">, however the <use> // tag is problematic on Firefox, because it needs to include the current page path. if (iconElement.nodeName.toLowerCase() === 'symbol') { return this._setSvgAttributes(this._toSvgElement(iconElement), options); } // createElement('SVG') doesn't work as expected; the DOM ends up with // the correct nodes, but the SVG content doesn't render. Instead we // have to create an empty SVG node using innerHTML and append its content. // Elements created using DOMParser.parseFromString have the same problem. // http://stackoverflow.com/questions/23003278/svg-innerhtml-in-firefox-can-not-display const svg = this._svgElementFromString(trustedHTMLFromString('<svg></svg>')); // Clone the node so we don't remove it from the parent icon set element. svg.appendChild(iconElement); return this._setSvgAttributes(svg, options); } /** * Creates a DOM element from the given SVG string. */ private _svgElementFromString(str: TrustedHTML): SVGElement { const div = this._document.createElement('DIV'); div.innerHTML = str as unknown as string; const svg = div.querySelector('svg') as SVGElement; // TODO: add an ngDevMode check if (!svg) { throw Error('<svg> tag not found'); } return svg; } /** * Converts an element into an SVG node by cloning all of its children. */ private _toSvgElement(element: Element): SVGElement { const svg = this._svgElementFromString(trustedHTMLFromString('<svg></svg>')); const attributes = element.attributes; // Copy over all the attributes from the `symbol` to the new SVG, except the id. for (let i = 0; i < attributes.length; i++) { const {name, value} = attributes[i]; if (name !== 'id') { svg.setAttribute(name, value); } } for (let i = 0; i < element.childNodes.length; i++) { if (element.childNodes[i].nodeType === this._document.ELEMENT_NODE) { svg.appendChild(element.childNodes[i].cloneNode(true)); } } return svg; } /** * Sets the default attributes for an SVG element to be used as an icon. */ private _setSvgAttributes(svg: SVGElement, options?: IconOptions): SVGElement { svg.setAttribute('fit', ''); svg.setAttribute('height', '100%'); svg.setAttribute('width', '100%'); svg.setAttribute('preserveAspectRatio', 'xMidYMid meet'); svg.setAttribute('focusable', 'false'); // Disable IE11 default behavior to make SVGs focusable. if (options && options.viewBox) { svg.setAttribute('viewBox', options.viewBox); } return svg; } /** * Returns an Observable which produces the string contents of the given icon. Results may be * cached, so future calls with the same URL may not cause another HTTP request. */ private _fetchIcon(iconConfig: SvgIconConfig): Observable<TrustedHTML> { const {url: safeUrl, options} = iconConfig; const withCredentials = options?.withCredentials ?? false; if (!this._httpClient) { throw getMatIconNoHttpProviderError(); } // TODO: add an ngDevMode check if (safeUrl == null) { throw Error(`Cannot fetch icon from URL "${safeUrl}".`); } const url = this._sanitizer.sanitize(SecurityContext.RESOURCE_URL, safeUrl); // TODO: add an ngDevMode check if (!url) { throw getMatIconFailedToSanitizeUrlError(safeUrl); } // Store in-progress fetches to avoid sending a duplicate request for a URL when there is // already a request in progress for that URL. It's necessary to call share() on the // Observable returned by http.get() so that multiple subscribers don't cause multiple XHRs. const inProgressFetch = this._inProgressUrlFetches.get(url); if (inProgressFetch) { return inProgressFetch; } const req = this._httpClient.get(url, {responseType: 'text', withCredentials}).pipe( map(svg => { // Security: This SVG is fetched from a SafeResourceUrl, and is thus // trusted HTML. return trustedHTMLFromString(svg); }), finalize(() => this._inProgressUrlFetches.delete(url)), share(), ); this._inProgressUrlFetches.set(url, req); return req; } /** * Registers an icon config by name in the specified namespace. * @param namespace Namespace in which to register the icon config. * @param iconName Name under which to register the config. * @param config Config to be registered. */ private _addSvgIconConfig(namespace: string, iconName: string, config: SvgIconConfig): this { this._svgIconConfigs.set(iconKey(namespace, iconName), config); return this; } /** * Registers an icon set config in the specified namespace. * @param namespace Namespace in which to register the icon config. * @param config Config to be registered. */ private _addSvgIconSetConfig(namespace: string, config: SvgIconConfig): this { const configNamespace = this._iconSetConfigs.get(namespace); if (configNamespace) { configNamespace.push(config); } else { this._iconSetConfigs.set(namespace, [config]); } return this; } /** Parses a config's text into an SVG element. */ private _svgElementFromConfig(config: LoadedSvgIconConfig): SVGElement { if (!config.svgElement) { const svg = this._svgElementFromString(config.svgText); this._setSvgAttributes(svg, config.options); config.svgElement = svg; } return config.svgElement; } /** Tries to create an icon config through the registered resolver functions. */ private _getIconConfigFromResolvers(namespace: string, name: string): SvgIconConfig | undefined { for (let i = 0; i < this._resolvers.length; i++) { const result = this._resolvers[i](name, namespace); if (result) { return isSafeUrlWithOptions(result) ? new SvgIconConfig(result.url, null, result.options) : new SvgIconConfig(result, null); } } return undefined; } } /** @docs-private */ export function ICON_REGISTRY_PROVIDER_FACTORY( parentRegistry: MatIconRegistry, httpClient: HttpClient, sanitizer: DomSanitizer, errorHandler: ErrorHandler, document?: any, ) { return parentRegistry || new MatIconRegistry(httpClient, sanitizer, document, errorHandler); } /** @docs-private */ export const ICON_REGISTRY_PROVIDER = { // If there is already an MatIconRegistry available, use that. Otherwise, provide a new one. provide: MatIconRegistry, deps: [ [new Optional(), new SkipSelf(), MatIconRegistry], [new Optional(), HttpClient], DomSanitizer, ErrorHandler, [new Optional(), DOCUMENT as InjectionToken<any>], ], useFactory: ICON_REGISTRY_PROVIDER_FACTORY, }; /** Clones an SVGElement while preserving type information. */ function cloneSvg(svg: SVGElement): SVGElement { return svg.cloneNode(true) as SVGElement; } /** Returns the cache key to use for an icon namespace and name. */ function iconKey(namespace: string, name: string) { return namespace + ':' + name; } function isSafeUrlWithOptions(value: any): value is SafeResourceUrlWithIconOptions { return !!(value.url && value.options); }
{ "end_byte": 27475, "start_byte": 19200, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon-registry.ts" }
components/src/material/icon/icon-module.ts_0_456
/** * @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 {MatIcon} from './icon'; @NgModule({ imports: [MatCommonModule, MatIcon], exports: [MatIcon, MatCommonModule], }) export class MatIconModule {}
{ "end_byte": 456, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon-module.ts" }
components/src/material/icon/icon.ts_0_5434
/** * @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 {DOCUMENT} from '@angular/common'; import { AfterViewChecked, booleanAttribute, ChangeDetectionStrategy, Component, ElementRef, ErrorHandler, inject, InjectionToken, Input, OnDestroy, OnInit, ViewEncapsulation, HostAttributeToken, } from '@angular/core'; import {ThemePalette} from '@angular/material/core'; import {Subscription} from 'rxjs'; import {take} from 'rxjs/operators'; import {MatIconRegistry} from './icon-registry'; /** Default options for `mat-icon`. */ export interface MatIconDefaultOptions { /** * Theme color of the icon. This API is supported in M2 themes only, it * has no effect in M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants. */ color?: ThemePalette; /** Font set that the icon is a part of. */ fontSet?: string; } /** Injection token to be used to override the default options for `mat-icon`. */ export const MAT_ICON_DEFAULT_OPTIONS = new InjectionToken<MatIconDefaultOptions>( 'MAT_ICON_DEFAULT_OPTIONS', ); /** * Injection token used to provide the current location to `MatIcon`. * Used to handle server-side rendering and to stub out during unit tests. * @docs-private */ export const MAT_ICON_LOCATION = new InjectionToken<MatIconLocation>('mat-icon-location', { providedIn: 'root', factory: MAT_ICON_LOCATION_FACTORY, }); /** * Stubbed out location for `MatIcon`. * @docs-private */ export interface MatIconLocation { getPathname: () => string; } /** @docs-private */ export function MAT_ICON_LOCATION_FACTORY(): MatIconLocation { const _document = inject(DOCUMENT); const _location = _document ? _document.location : null; return { // Note that this needs to be a function, rather than a property, because Angular // will only resolve it once, but we want the current path on each call. getPathname: () => (_location ? _location.pathname + _location.search : ''), }; } /** SVG attributes that accept a FuncIRI (e.g. `url(<something>)`). */ const funcIriAttributes = [ 'clip-path', 'color-profile', 'src', 'cursor', 'fill', 'filter', 'marker', 'marker-start', 'marker-mid', 'marker-end', 'mask', 'stroke', ]; /** Selector that can be used to find all elements that are using a `FuncIRI`. */ const funcIriAttributeSelector = funcIriAttributes.map(attr => `[${attr}]`).join(', '); /** Regex that can be used to extract the id out of a FuncIRI. */ const funcIriPattern = /^url\(['"]?#(.*?)['"]?\)$/; /** * Component to display an icon. It can be used in the following ways: * * - Specify the svgIcon input to load an SVG icon from a URL previously registered with the * addSvgIcon, addSvgIconInNamespace, addSvgIconSet, or addSvgIconSetInNamespace methods of * MatIconRegistry. If the svgIcon value contains a colon it is assumed to be in the format * "[namespace]:[name]", if not the value will be the name of an icon in the default namespace. * Examples: * `<mat-icon svgIcon="left-arrow"></mat-icon> * <mat-icon svgIcon="animals:cat"></mat-icon>` * * - Use a font ligature as an icon by putting the ligature text in the `fontIcon` attribute or the * content of the `<mat-icon>` component. If you register a custom font class, don't forget to also * include the special class `mat-ligature-font`. It is recommended to use the attribute alternative * to prevent the ligature text to be selectable and to appear in search engine results. * By default, the Material icons font is used as described at * http://google.github.io/material-design-icons/#icon-font-for-the-web. You can specify an * alternate font by setting the fontSet input to either the CSS class to apply to use the * desired font, or to an alias previously registered with MatIconRegistry.registerFontClassAlias. * Examples: * `<mat-icon fontIcon="home"></mat-icon> * <mat-icon>home</mat-icon> * <mat-icon fontSet="myfont" fontIcon="sun"></mat-icon> * <mat-icon fontSet="myfont">sun</mat-icon>` * * - Specify a font glyph to be included via CSS rules by setting the fontSet input to specify the * font, and the fontIcon input to specify the icon. Typically the fontIcon will specify a * CSS class which causes the glyph to be displayed via a :before selector, as in * https://fontawesome-v4.github.io/examples/ * Example: * `<mat-icon fontSet="fa" fontIcon="alarm"></mat-icon>` */ @Component({ template: '<ng-content></ng-content>', selector: 'mat-icon', exportAs: 'matIcon', styleUrl: 'icon.css', host: { 'role': 'img', 'class': 'mat-icon notranslate', '[class]': 'color ? "mat-" + color : ""', '[attr.data-mat-icon-type]': '_usingFontIcon() ? "font" : "svg"', '[attr.data-mat-icon-name]': '_svgName || fontIcon', '[attr.data-mat-icon-namespace]': '_svgNamespace || fontSet', '[attr.fontIcon]': '_usingFontIcon() ? fontIcon : null', '[class.mat-icon-inline]': 'inline', '[class.mat-icon-no-color]': 'color !== "primary" && color !== "accent" && color !== "warn"', }, encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) export
{ "end_byte": 5434, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon.ts" }
components/src/material/icon/icon.ts_5435_13695
class MatIcon implements OnInit, AfterViewChecked, OnDestroy { readonly _elementRef = inject<ElementRef<HTMLElement>>(ElementRef); private _iconRegistry = inject(MatIconRegistry); private _location = inject<MatIconLocation>(MAT_ICON_LOCATION); private readonly _errorHandler = inject(ErrorHandler); private _defaultColor: ThemePalette; /** * Theme color of the icon. This API is supported in M2 themes only, it * has no effect in M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants. */ @Input() get color() { return this._color || this._defaultColor; } set color(value: string | null | undefined) { this._color = value; } private _color: string | null | undefined; /** * Whether the icon should be inlined, automatically sizing the icon to match the font size of * the element the icon is contained in. */ @Input({transform: booleanAttribute}) inline: boolean = false; /** Name of the icon in the SVG icon set. */ @Input() get svgIcon(): string { return this._svgIcon; } set svgIcon(value: string) { if (value !== this._svgIcon) { if (value) { this._updateSvgIcon(value); } else if (this._svgIcon) { this._clearSvgElement(); } this._svgIcon = value; } } private _svgIcon: string; /** Font set that the icon is a part of. */ @Input() get fontSet(): string { return this._fontSet; } set fontSet(value: string) { const newValue = this._cleanupFontValue(value); if (newValue !== this._fontSet) { this._fontSet = newValue; this._updateFontIconClasses(); } } private _fontSet: string; /** Name of an icon within a font set. */ @Input() get fontIcon(): string { return this._fontIcon; } set fontIcon(value: string) { const newValue = this._cleanupFontValue(value); if (newValue !== this._fontIcon) { this._fontIcon = newValue; this._updateFontIconClasses(); } } private _fontIcon: string; private _previousFontSetClass: string[] = []; private _previousFontIconClass: string; _svgName: string | null; _svgNamespace: string | null; /** Keeps track of the current page path. */ private _previousPath?: string; /** Keeps track of the elements and attributes that we've prefixed with the current path. */ private _elementsWithExternalReferences?: Map<Element, {name: string; value: string}[]>; /** Subscription to the current in-progress SVG icon request. */ private _currentIconFetch = Subscription.EMPTY; constructor(...args: unknown[]); constructor() { const ariaHidden = inject(new HostAttributeToken('aria-hidden'), {optional: true}); const defaults = inject<MatIconDefaultOptions>(MAT_ICON_DEFAULT_OPTIONS, {optional: true}); if (defaults) { if (defaults.color) { this.color = this._defaultColor = defaults.color; } if (defaults.fontSet) { this.fontSet = defaults.fontSet; } } // If the user has not explicitly set aria-hidden, mark the icon as hidden, as this is // the right thing to do for the majority of icon use-cases. if (!ariaHidden) { this._elementRef.nativeElement.setAttribute('aria-hidden', 'true'); } } /** * Splits an svgIcon binding value into its icon set and icon name components. * Returns a 2-element array of [(icon set), (icon name)]. * The separator for the two fields is ':'. If there is no separator, an empty * string is returned for the icon set and the entire value is returned for * the icon name. If the argument is falsy, returns an array of two empty strings. * Throws an error if the name contains two or more ':' separators. * Examples: * `'social:cake' -> ['social', 'cake'] * 'penguin' -> ['', 'penguin'] * null -> ['', ''] * 'a:b:c' -> (throws Error)` */ private _splitIconName(iconName: string): [string, string] { if (!iconName) { return ['', '']; } const parts = iconName.split(':'); switch (parts.length) { case 1: return ['', parts[0]]; // Use default namespace. case 2: return <[string, string]>parts; default: throw Error(`Invalid icon name: "${iconName}"`); // TODO: add an ngDevMode check } } ngOnInit() { // Update font classes because ngOnChanges won't be called if none of the inputs are present, // e.g. <mat-icon>arrow</mat-icon> In this case we need to add a CSS class for the default font. this._updateFontIconClasses(); } ngAfterViewChecked() { const cachedElements = this._elementsWithExternalReferences; if (cachedElements && cachedElements.size) { const newPath = this._location.getPathname(); // We need to check whether the URL has changed on each change detection since // the browser doesn't have an API that will let us react on link clicks and // we can't depend on the Angular router. The references need to be updated, // because while most browsers don't care whether the URL is correct after // the first render, Safari will break if the user navigates to a different // page and the SVG isn't re-rendered. if (newPath !== this._previousPath) { this._previousPath = newPath; this._prependPathToReferences(newPath); } } } ngOnDestroy() { this._currentIconFetch.unsubscribe(); if (this._elementsWithExternalReferences) { this._elementsWithExternalReferences.clear(); } } _usingFontIcon(): boolean { return !this.svgIcon; } private _setSvgElement(svg: SVGElement) { this._clearSvgElement(); // Note: we do this fix here, rather than the icon registry, because the // references have to point to the URL at the time that the icon was created. const path = this._location.getPathname(); this._previousPath = path; this._cacheChildrenWithExternalReferences(svg); this._prependPathToReferences(path); this._elementRef.nativeElement.appendChild(svg); } private _clearSvgElement() { const layoutElement: HTMLElement = this._elementRef.nativeElement; let childCount = layoutElement.childNodes.length; if (this._elementsWithExternalReferences) { this._elementsWithExternalReferences.clear(); } // Remove existing non-element child nodes and SVGs, and add the new SVG element. Note that // we can't use innerHTML, because IE will throw if the element has a data binding. while (childCount--) { const child = layoutElement.childNodes[childCount]; // 1 corresponds to Node.ELEMENT_NODE. We remove all non-element nodes in order to get rid // of any loose text nodes, as well as any SVG elements in order to remove any old icons. if (child.nodeType !== 1 || child.nodeName.toLowerCase() === 'svg') { child.remove(); } } } private _updateFontIconClasses() { if (!this._usingFontIcon()) { return; } const elem: HTMLElement = this._elementRef.nativeElement; const fontSetClasses = ( this.fontSet ? this._iconRegistry.classNameForFontAlias(this.fontSet).split(/ +/) : this._iconRegistry.getDefaultFontSetClass() ).filter(className => className.length > 0); this._previousFontSetClass.forEach(className => elem.classList.remove(className)); fontSetClasses.forEach(className => elem.classList.add(className)); this._previousFontSetClass = fontSetClasses; if ( this.fontIcon !== this._previousFontIconClass && !fontSetClasses.includes('mat-ligature-font') ) { if (this._previousFontIconClass) { elem.classList.remove(this._previousFontIconClass); } if (this.fontIcon) { elem.classList.add(this.fontIcon); } this._previousFontIconClass = this.fontIcon; } } /** * Cleans up a value to be used as a fontIcon or fontSet. * Since the value ends up being assigned as a CSS class, we * have to trim the value and omit space-separated values. */ private _cleanupFontValue(value: string) { return typeof value === 'string' ? value.trim().split(' ')[0] : value; }
{ "end_byte": 13695, "start_byte": 5435, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon.ts" }
components/src/material/icon/icon.ts_13699_16120
/** * Prepends the current path to all elements that have an attribute pointing to a `FuncIRI` * reference. This is required because WebKit browsers require references to be prefixed with * the current path, if the page has a `base` tag. */ private _prependPathToReferences(path: string) { const elements = this._elementsWithExternalReferences; if (elements) { elements.forEach((attrs, element) => { attrs.forEach(attr => { element.setAttribute(attr.name, `url('${path}#${attr.value}')`); }); }); } } /** * Caches the children of an SVG element that have `url()` * references that we need to prefix with the current path. */ private _cacheChildrenWithExternalReferences(element: SVGElement) { const elementsWithFuncIri = element.querySelectorAll(funcIriAttributeSelector); const elements = (this._elementsWithExternalReferences = this._elementsWithExternalReferences || new Map()); for (let i = 0; i < elementsWithFuncIri.length; i++) { funcIriAttributes.forEach(attr => { const elementWithReference = elementsWithFuncIri[i]; const value = elementWithReference.getAttribute(attr); const match = value ? value.match(funcIriPattern) : null; if (match) { let attributes = elements.get(elementWithReference); if (!attributes) { attributes = []; elements.set(elementWithReference, attributes); } attributes!.push({name: attr, value: match[1]}); } }); } } /** Sets a new SVG icon with a particular name. */ private _updateSvgIcon(rawName: string | undefined) { this._svgNamespace = null; this._svgName = null; this._currentIconFetch.unsubscribe(); if (rawName) { const [namespace, iconName] = this._splitIconName(rawName); if (namespace) { this._svgNamespace = namespace; } if (iconName) { this._svgName = iconName; } this._currentIconFetch = this._iconRegistry .getNamedSvgIcon(iconName, namespace) .pipe(take(1)) .subscribe( svg => this._setSvgElement(svg), (err: Error) => { const errorMessage = `Error retrieving icon ${namespace}:${iconName}! ${err.message}`; this._errorHandler.handleError(new Error(errorMessage)); }, ); } } }
{ "end_byte": 16120, "start_byte": 13699, "url": "https://github.com/angular/components/blob/main/src/material/icon/icon.ts" }
components/src/material/icon/testing/fake-icon-registry.ts_0_2402
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Injectable, NgModule, OnDestroy} from '@angular/core'; import {MatIconRegistry} from '@angular/material/icon'; import {Observable, of as observableOf} from 'rxjs'; type PublicApi<T> = { [K in keyof T]: T[K] extends (...x: any[]) => T ? (...x: any[]) => PublicApi<T> : T[K]; }; /** * A null icon registry that must be imported to allow disabling of custom * icons. */ @Injectable() export class FakeMatIconRegistry implements PublicApi<MatIconRegistry>, OnDestroy { addSvgIcon(): this { return this; } addSvgIconLiteral(): this { return this; } addSvgIconInNamespace(): this { return this; } addSvgIconLiteralInNamespace(): this { return this; } addSvgIconSet(): this { return this; } addSvgIconSetLiteral(): this { return this; } addSvgIconSetInNamespace(): this { return this; } addSvgIconSetLiteralInNamespace(): this { return this; } registerFontClassAlias(): this { return this; } classNameForFontAlias(alias: string): string { return alias; } getDefaultFontSetClass() { return ['material-icons']; } getSvgIconFromUrl(): Observable<SVGElement> { return observableOf(this._generateEmptySvg()); } getNamedSvgIcon(): Observable<SVGElement> { return observableOf(this._generateEmptySvg()); } setDefaultFontSetClass(): this { return this; } addSvgIconResolver(): this { return this; } ngOnDestroy() {} private _generateEmptySvg(): SVGElement { const emptySvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); emptySvg.classList.add('fake-testing-svg'); // Emulate real icon characteristics from `MatIconRegistry` so size remains consistent in tests. emptySvg.setAttribute('fit', ''); emptySvg.setAttribute('height', '100%'); emptySvg.setAttribute('width', '100%'); emptySvg.setAttribute('preserveAspectRatio', 'xMidYMid meet'); emptySvg.setAttribute('focusable', 'false'); return emptySvg; } } /** Import this module in tests to install the null icon registry. */ @NgModule({ providers: [{provide: MatIconRegistry, useClass: FakeMatIconRegistry}], }) export class MatIconTestingModule {}
{ "end_byte": 2402, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/icon/testing/fake-icon-registry.ts" }
components/src/material/icon/testing/public-api.ts_0_314
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './icon-harness'; export * from './icon-harness-filters'; export * from './fake-icon-registry';
{ "end_byte": 314, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/icon/testing/public-api.ts" }
components/src/material/icon/testing/icon-harness-filters.ts_0_725
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {BaseHarnessFilters} from '@angular/cdk/testing'; /** Possible types of icons. */ export enum IconType { SVG, FONT, } /** A set of criteria that can be used to filter a list of `MatIconHarness` instances. */ export interface IconHarnessFilters extends BaseHarnessFilters { /** Filters based on the typef of the icon. */ type?: IconType; /** Filters based on the name of the icon. */ name?: string | RegExp; /** Filters based on the namespace of the icon. */ namespace?: string | null | RegExp; }
{ "end_byte": 725, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/icon/testing/icon-harness-filters.ts" }
components/src/material/icon/testing/icon-harness.ts_0_2905
/** * @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 {IconHarnessFilters, IconType} from './icon-harness-filters'; /** Harness for interacting with a standard mat-icon in tests. */ export class MatIconHarness extends ComponentHarness { /** The selector for the host element of a `MatIcon` instance. */ static hostSelector = '.mat-icon'; /** * Gets a `HarnessPredicate` that can be used to search for a `MatIconHarness` that meets * certain criteria. * @param options Options for filtering which icon instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with(options: IconHarnessFilters = {}): HarnessPredicate<MatIconHarness> { return new HarnessPredicate(MatIconHarness, options) .addOption('type', options.type, async (harness, type) => (await harness.getType()) === type) .addOption('name', options.name, (harness, text) => HarnessPredicate.stringMatches(harness.getName(), text), ) .addOption('namespace', options.namespace, (harness, text) => HarnessPredicate.stringMatches(harness.getNamespace(), text), ); } /** Gets the type of the icon. */ async getType(): Promise<IconType> { const type = await (await this.host()).getAttribute('data-mat-icon-type'); return type === 'svg' ? IconType.SVG : IconType.FONT; } /** Gets the name of the icon. */ async getName(): Promise<string | null> { const host = await this.host(); const nameFromDom = await host.getAttribute('data-mat-icon-name'); // If we managed to figure out the name from the attribute, use it. if (nameFromDom) { return nameFromDom; } // Some icons support defining the icon as a ligature. // As a fallback, try to extract it from the DOM text. if ((await this.getType()) === IconType.FONT) { // Other directives may add content to the icon (e.g. `MatBadge`), however only the direct // text nodes affect the name of the icon. Exclude all element descendants from the result. const text = await host.text({exclude: '*'}); // There are some internal cases where the icon name is wrapped in another node. // Fall back to extracting the entire text if we ended up excluding everything above. return text.length > 0 ? text : host.text(); } return null; } /** Gets the namespace of the icon. */ async getNamespace(): Promise<string | null> { return (await this.host()).getAttribute('data-mat-icon-namespace'); } /** Gets whether the icon is inline. */ async isInline(): Promise<boolean> { return (await this.host()).hasClass('mat-icon-inline'); } }
{ "end_byte": 2905, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/icon/testing/icon-harness.ts" }
components/src/material/icon/testing/icon-harness.spec.ts_0_4441
import {Component} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {HarnessLoader, parallel} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {MatIconModule, MatIconRegistry} from '@angular/material/icon'; import {DomSanitizer} from '@angular/platform-browser'; import {MatIconHarness} from './icon-harness'; import {IconType} from './icon-harness-filters'; describe('MatIconHarness', () => { let fixture: ComponentFixture<IconHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ imports: [MatIconModule, IconHarnessTest], }); const registry = TestBed.inject(MatIconRegistry); const sanitizer = TestBed.inject(DomSanitizer); registry.addSvgIconLiteralInNamespace( 'svgIcons', 'svgIcon', sanitizer.bypassSecurityTrustHtml('<svg></svg>'), ); fixture = TestBed.createComponent(IconHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); it('should load all icon harnesses', async () => { const icons = await loader.getAllHarnesses(MatIconHarness); expect(icons.length).toBe(6); }); it('should filter icon harnesses based on their type', async () => { const [svgIcons, fontIcons] = await parallel(() => [ loader.getAllHarnesses(MatIconHarness.with({type: IconType.SVG})), loader.getAllHarnesses(MatIconHarness.with({type: IconType.FONT})), ]); expect(svgIcons.length).toBe(1); expect(fontIcons.length).toBe(5); }); it('should filter icon harnesses based on their name', async () => { const [regexFilterResults, stringFilterResults] = await parallel(() => [ loader.getAllHarnesses(MatIconHarness.with({name: /^font/})), loader.getAllHarnesses(MatIconHarness.with({name: 'fontIcon'})), ]); expect(regexFilterResults.length).toBe(1); expect(stringFilterResults.length).toBe(1); }); it('should filter icon harnesses based on their namespace', async () => { const [regexFilterResults, stringFilterResults, nullFilterResults] = await parallel(() => [ loader.getAllHarnesses(MatIconHarness.with({namespace: /^font/})), loader.getAllHarnesses(MatIconHarness.with({namespace: 'svgIcons'})), loader.getAllHarnesses(MatIconHarness.with({namespace: null})), ]); expect(regexFilterResults.length).toBe(1); expect(stringFilterResults.length).toBe(1); expect(nullFilterResults.length).toBe(4); }); it('should get the type of each icon', async () => { const icons = await loader.getAllHarnesses(MatIconHarness); const types = await parallel(() => icons.map(icon => icon.getType())); expect(types).toEqual([ IconType.FONT, IconType.SVG, IconType.FONT, IconType.FONT, IconType.FONT, IconType.FONT, ]); }); it('should get the name of an icon', async () => { const icons = await loader.getAllHarnesses(MatIconHarness); const names = await parallel(() => icons.map(icon => icon.getName())); expect(names).toEqual([ 'fontIcon', 'svgIcon', 'ligature_icon', 'ligature_icon_by_attribute', 'ligature_icon_with_additional_content', 'ligature_icon_with_indirect_name', ]); }); it('should get the namespace of an icon', async () => { const icons = await loader.getAllHarnesses(MatIconHarness); const namespaces = await parallel(() => icons.map(icon => icon.getNamespace())); expect(namespaces).toEqual(['fontIcons', 'svgIcons', null, null, null, null]); }); it('should get whether an icon is inline', async () => { const icons = await loader.getAllHarnesses(MatIconHarness); const inlineStates = await parallel(() => icons.map(icon => icon.isInline())); expect(inlineStates).toEqual([false, false, true, false, false, false]); }); }); @Component({ template: ` <mat-icon fontSet="fontIcons" fontIcon="fontIcon"></mat-icon> <mat-icon svgIcon="svgIcons:svgIcon"></mat-icon> <mat-icon inline>ligature_icon</mat-icon> <mat-icon fontIcon="ligature_icon_by_attribute"></mat-icon> <mat-icon>ligature_icon_with_additional_content <span class="fake-badge">Hello</span></mat-icon> <mat-icon><span>ligature_icon_with_indirect_name</span></mat-icon> `, standalone: true, imports: [MatIconModule], }) class IconHarnessTest {}
{ "end_byte": 4441, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/icon/testing/icon-harness.spec.ts" }
components/src/material/icon/testing/BUILD.bazel_0_864
load("//tools:defaults.bzl", "ng_module", "ng_test_library", "ng_web_test_suite") package(default_visibility = ["//visibility:public"]) ng_module( name = "testing", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "//src/cdk/testing", "//src/material/icon", "@npm//@angular/common", "@npm//@angular/core", "@npm//rxjs", ], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), ) ng_test_library( name = "unit_tests_lib", srcs = glob(["**/*.spec.ts"]), deps = [ ":testing", "//src/cdk/platform", "//src/cdk/testing", "//src/cdk/testing/testbed", "//src/material/icon", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_tests_lib"], )
{ "end_byte": 864, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/icon/testing/BUILD.bazel" }
components/src/material/icon/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/icon/testing/index.ts" }
components/src/material/snack-bar/snack-bar.ts_0_1402
/** * @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 {LiveAnnouncer} from '@angular/cdk/a11y'; import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout'; import {ComponentType, Overlay, OverlayConfig, OverlayRef} from '@angular/cdk/overlay'; import { ComponentRef, EmbeddedViewRef, Injectable, InjectionToken, Injector, OnDestroy, TemplateRef, inject, } from '@angular/core'; import {SimpleSnackBar, TextOnlySnackBar} from './simple-snack-bar'; import {MatSnackBarContainer} from './snack-bar-container'; import {MAT_SNACK_BAR_DATA, MatSnackBarConfig} from './snack-bar-config'; import {MatSnackBarRef} from './snack-bar-ref'; import {ComponentPortal, TemplatePortal} from '@angular/cdk/portal'; import {takeUntil} from 'rxjs/operators'; /** @docs-private */ export function MAT_SNACK_BAR_DEFAULT_OPTIONS_FACTORY(): MatSnackBarConfig { return new MatSnackBarConfig(); } /** Injection token that can be used to specify default snack bar. */ export const MAT_SNACK_BAR_DEFAULT_OPTIONS = new InjectionToken<MatSnackBarConfig>( 'mat-snack-bar-default-options', { providedIn: 'root', factory: MAT_SNACK_BAR_DEFAULT_OPTIONS_FACTORY, }, ); /** * Service to dispatch Material Design snack bar messages. */
{ "end_byte": 1402, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar.ts" }
components/src/material/snack-bar/snack-bar.ts_1403_9374
@Injectable({providedIn: 'root'}) export class MatSnackBar implements OnDestroy { private _overlay = inject(Overlay); private _live = inject(LiveAnnouncer); private _injector = inject(Injector); private _breakpointObserver = inject(BreakpointObserver); private _parentSnackBar = inject(MatSnackBar, {optional: true, skipSelf: true}); private _defaultConfig = inject<MatSnackBarConfig>(MAT_SNACK_BAR_DEFAULT_OPTIONS); /** * Reference to the current snack bar in the view *at this level* (in the Angular injector tree). * If there is a parent snack-bar service, all operations should delegate to that parent * via `_openedSnackBarRef`. */ private _snackBarRefAtThisLevel: MatSnackBarRef<any> | null = null; /** The component that should be rendered as the snack bar's simple component. */ simpleSnackBarComponent = SimpleSnackBar; /** The container component that attaches the provided template or component. */ snackBarContainerComponent = MatSnackBarContainer; /** The CSS class to apply for handset mode. */ handsetCssClass = 'mat-mdc-snack-bar-handset'; /** Reference to the currently opened snackbar at *any* level. */ get _openedSnackBarRef(): MatSnackBarRef<any> | null { const parent = this._parentSnackBar; return parent ? parent._openedSnackBarRef : this._snackBarRefAtThisLevel; } set _openedSnackBarRef(value: MatSnackBarRef<any> | null) { if (this._parentSnackBar) { this._parentSnackBar._openedSnackBarRef = value; } else { this._snackBarRefAtThisLevel = value; } } constructor(...args: unknown[]); constructor() {} /** * Creates and dispatches a snack bar with a custom component for the content, removing any * currently opened snack bars. * * @param component Component to be instantiated. * @param config Extra configuration for the snack bar. */ openFromComponent<T, D = any>( component: ComponentType<T>, config?: MatSnackBarConfig<D>, ): MatSnackBarRef<T> { return this._attach(component, config) as MatSnackBarRef<T>; } /** * Creates and dispatches a snack bar with a custom template for the content, removing any * currently opened snack bars. * * @param template Template to be instantiated. * @param config Extra configuration for the snack bar. */ openFromTemplate( template: TemplateRef<any>, config?: MatSnackBarConfig, ): MatSnackBarRef<EmbeddedViewRef<any>> { return this._attach(template, config); } /** * Opens a snackbar with a message and an optional action. * @param message The message to show in the snackbar. * @param action The label for the snackbar action. * @param config Additional configuration options for the snackbar. */ open( message: string, action: string = '', config?: MatSnackBarConfig, ): MatSnackBarRef<TextOnlySnackBar> { const _config = {...this._defaultConfig, ...config}; // Since the user doesn't have access to the component, we can // override the data to pass in our own message and action. _config.data = {message, action}; // Since the snack bar has `role="alert"`, we don't // want to announce the same message twice. if (_config.announcementMessage === message) { _config.announcementMessage = undefined; } return this.openFromComponent(this.simpleSnackBarComponent, _config); } /** * Dismisses the currently-visible snack bar. */ dismiss(): void { if (this._openedSnackBarRef) { this._openedSnackBarRef.dismiss(); } } ngOnDestroy() { // Only dismiss the snack bar at the current level on destroy. if (this._snackBarRefAtThisLevel) { this._snackBarRefAtThisLevel.dismiss(); } } /** * Attaches the snack bar container component to the overlay. */ private _attachSnackBarContainer( overlayRef: OverlayRef, config: MatSnackBarConfig, ): MatSnackBarContainer { const userInjector = config && config.viewContainerRef && config.viewContainerRef.injector; const injector = Injector.create({ parent: userInjector || this._injector, providers: [{provide: MatSnackBarConfig, useValue: config}], }); const containerPortal = new ComponentPortal( this.snackBarContainerComponent, config.viewContainerRef, injector, ); const containerRef: ComponentRef<MatSnackBarContainer> = overlayRef.attach(containerPortal); containerRef.instance.snackBarConfig = config; return containerRef.instance; } /** * Places a new component or a template as the content of the snack bar container. */ private _attach<T>( content: ComponentType<T> | TemplateRef<T>, userConfig?: MatSnackBarConfig, ): MatSnackBarRef<T | EmbeddedViewRef<any>> { const config = {...new MatSnackBarConfig(), ...this._defaultConfig, ...userConfig}; const overlayRef = this._createOverlay(config); const container = this._attachSnackBarContainer(overlayRef, config); const snackBarRef = new MatSnackBarRef<T | EmbeddedViewRef<any>>(container, overlayRef); if (content instanceof TemplateRef) { const portal = new TemplatePortal(content, null!, { $implicit: config.data, snackBarRef, } as any); snackBarRef.instance = container.attachTemplatePortal(portal); } else { const injector = this._createInjector(config, snackBarRef); const portal = new ComponentPortal(content, undefined, injector); const contentRef = container.attachComponentPortal<T>(portal); // We can't pass this via the injector, because the injector is created earlier. snackBarRef.instance = contentRef.instance; } // Subscribe to the breakpoint observer and attach the mat-snack-bar-handset class as // appropriate. This class is applied to the overlay element because the overlay must expand to // fill the width of the screen for full width snackbars. this._breakpointObserver .observe(Breakpoints.HandsetPortrait) .pipe(takeUntil(overlayRef.detachments())) .subscribe(state => { overlayRef.overlayElement.classList.toggle(this.handsetCssClass, state.matches); }); if (config.announcementMessage) { // Wait until the snack bar contents have been announced then deliver this message. container._onAnnounce.subscribe(() => { this._live.announce(config.announcementMessage!, config.politeness); }); } this._animateSnackBar(snackBarRef, config); this._openedSnackBarRef = snackBarRef; return this._openedSnackBarRef; } /** Animates the old snack bar out and the new one in. */ private _animateSnackBar(snackBarRef: MatSnackBarRef<any>, config: MatSnackBarConfig) { // When the snackbar is dismissed, clear the reference to it. snackBarRef.afterDismissed().subscribe(() => { // Clear the snackbar ref if it hasn't already been replaced by a newer snackbar. if (this._openedSnackBarRef == snackBarRef) { this._openedSnackBarRef = null; } if (config.announcementMessage) { this._live.clear(); } }); if (this._openedSnackBarRef) { // If a snack bar is already in view, dismiss it and enter the // new snack bar after exit animation is complete. this._openedSnackBarRef.afterDismissed().subscribe(() => { snackBarRef.containerInstance.enter(); }); this._openedSnackBarRef.dismiss(); } else { // If no snack bar is in view, enter the new snack bar. snackBarRef.containerInstance.enter(); } // If a dismiss timeout is provided, set up dismiss based on after the snackbar is opened. if (config.duration && config.duration > 0) { snackBarRef.afterOpened().subscribe(() => snackBarRef._dismissAfter(config.duration!)); } } /** * Creates a new overlay and places it in the correct location. * @param config The user-specified snack bar config. */
{ "end_byte": 9374, "start_byte": 1403, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar.ts" }
components/src/material/snack-bar/snack-bar.ts_9377_11008
private _createOverlay(config: MatSnackBarConfig): OverlayRef { const overlayConfig = new OverlayConfig(); overlayConfig.direction = config.direction; let positionStrategy = this._overlay.position().global(); // Set horizontal position. const isRtl = config.direction === 'rtl'; const isLeft = config.horizontalPosition === 'left' || (config.horizontalPosition === 'start' && !isRtl) || (config.horizontalPosition === 'end' && isRtl); const isRight = !isLeft && config.horizontalPosition !== 'center'; if (isLeft) { positionStrategy.left('0'); } else if (isRight) { positionStrategy.right('0'); } else { positionStrategy.centerHorizontally(); } // Set horizontal position. if (config.verticalPosition === 'top') { positionStrategy.top('0'); } else { positionStrategy.bottom('0'); } overlayConfig.positionStrategy = positionStrategy; return this._overlay.create(overlayConfig); } /** * Creates an injector to be used inside of a snack bar component. * @param config Config that was used to create the snack bar. * @param snackBarRef Reference to the snack bar. */ private _createInjector<T>(config: MatSnackBarConfig, snackBarRef: MatSnackBarRef<T>): Injector { const userInjector = config && config.viewContainerRef && config.viewContainerRef.injector; return Injector.create({ parent: userInjector || this._injector, providers: [ {provide: MatSnackBarRef, useValue: snackBarRef}, {provide: MAT_SNACK_BAR_DATA, useValue: config.data}, ], }); } }
{ "end_byte": 11008, "start_byte": 9377, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar.ts" }
components/src/material/snack-bar/module.ts_0_1066
/** * @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 {OverlayModule} from '@angular/cdk/overlay'; import {PortalModule} from '@angular/cdk/portal'; import {NgModule} from '@angular/core'; import {MatButtonModule} from '@angular/material/button'; import {MatCommonModule} from '@angular/material/core'; import {SimpleSnackBar} from './simple-snack-bar'; import {MatSnackBarContainer} from './snack-bar-container'; import {MatSnackBarAction, MatSnackBarActions, MatSnackBarLabel} from './snack-bar-content'; import {MatSnackBar} from './snack-bar'; const DIRECTIVES = [MatSnackBarContainer, MatSnackBarLabel, MatSnackBarActions, MatSnackBarAction]; @NgModule({ imports: [ OverlayModule, PortalModule, MatButtonModule, MatCommonModule, SimpleSnackBar, ...DIRECTIVES, ], exports: [MatCommonModule, ...DIRECTIVES], providers: [MatSnackBar], }) export class MatSnackBarModule {}
{ "end_byte": 1066, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/module.ts" }
components/src/material/snack-bar/snack-bar.md_0_4236
`MatSnackBar` is a service for displaying snack-bar notifications. <!-- example(snack-bar-overview) --> ### Opening a snackbar A snackbar can contain either a string message or a given component. ```ts // Simple message. let snackBarRef = snackBar.open('Message archived'); // Simple message with an action. let snackBarRef = snackBar.open('Message archived', 'Undo'); // Load the given component into the snackbar. let snackBarRef = snackBar.openFromComponent(MessageArchivedComponent); ``` In either case, a `MatSnackBarRef` is returned. This can be used to dismiss the snackbar or to receive notification of when the snackbar is dismissed. For simple messages with an action, the `MatSnackBarRef` exposes an observable for when the action is triggered. If you want to close a custom snackbar that was opened via `openFromComponent`, from within the component itself, you can inject the `MatSnackBarRef`. ```ts snackBarRef.afterDismissed().subscribe(() => { console.log('The snackbar was dismissed'); }); snackBarRef.onAction().subscribe(() => { console.log('The snackbar action was triggered!'); }); snackBarRef.dismiss(); ``` ### Dismissal A snackbar can be dismissed manually by calling the `dismiss` method on the `MatSnackBarRef` returned from the call to `open`. Only one snackbar can ever be opened at one time. If a new snackbar is opened while a previous message is still showing, the older message will be automatically dismissed. A snackbar can also be given a duration via the optional configuration object: ```ts snackBar.open('Message archived', 'Undo', { duration: 3000 }); ``` ### Sharing data with a custom snackbar You can share data with the custom snackbar, that you opened via the `openFromComponent` method, by passing it through the `data` property. ```ts snackBar.openFromComponent(MessageArchivedComponent, { data: 'some data' }); ``` To access the data in your component, you have to use the `MAT_SNACK_BAR_DATA` injection token: ```ts import {Component, Inject} from '@angular/core'; import {MAT_SNACK_BAR_DATA} from '@angular/material/snack-bar'; @Component({ selector: 'your-snackbar', template: 'passed in {{ data }}', }) export class MessageArchivedComponent { constructor(@Inject(MAT_SNACK_BAR_DATA) public data: string) { } } ``` ### Annotating custom snackbar content When opening a custom snackbar via the `snackBar.openFromComponent` method, you can use the following directives to annotate the content and ensure that it is styled consistently compared to snackbars opened via `snackBar.open`. * `matSnackBarLabel` - Marks the text of the snackbar shown to users * `matSnackBarActions` - Marks the container element containing any action buttons * `matSnackBarAction` - Marks an individual action button If no annotations are used, all the content will be treated as text content. <!-- example(snack-bar-annotated-component) --> ### Setting the global configuration defaults If you want to override the default snack bar options, you can do so using the `MAT_SNACK_BAR_DEFAULT_OPTIONS` injection token. ```ts @NgModule({ providers: [ {provide: MAT_SNACK_BAR_DEFAULT_OPTIONS, useValue: {duration: 2500}} ] }) ``` ### Accessibility `MatSnackBar` announces messages via an `aria-live` region. While announcements use the `polite` setting by default, you can customize this by setting the `politeness` property of `MatSnackBarConfig`. `MatSnackBar` does not move focus to the snackbar element. Moving focus like this would disrupt users in the middle of a workflow. For any action offered in the snackbar, your application should provide an alternative way to perform the action. Alternative interactions are typically keyboard shortcuts or menu options. You should dismiss the snackbar once the user performs its corresponding action. A snackbar can contain a single action with an additional optional "dismiss" or "cancel" action. Avoid setting a `duration` for snackbars that have an action available, as screen reader users may want to navigate to the snackbar element to activate the action. If the user has manually moved their focus within the snackbar, you should return focus somewhere that makes sense in the context of the user's workflow.
{ "end_byte": 4236, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar.md" }
components/src/material/snack-bar/snack-bar-container.html_0_660
<div class="mdc-snackbar__surface mat-mdc-snackbar-surface"> <!-- This outer label wrapper will have the class `mdc-snackbar__label` applied if the attached template/component does not contain it. --> <div class="mat-mdc-snack-bar-label" #label> <!-- Initialy holds the snack bar content, will be empty after announcing to screen readers. --> <div aria-hidden="true"> <ng-template cdkPortalOutlet /> </div> <!-- Will receive the snack bar content from the non-live div, move will happen a short delay after opening --> <div [attr.aria-live]="_live" [attr.role]="_role" [attr.id]="_liveElementId"></div> </div> </div>
{ "end_byte": 660, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar-container.html" }
components/src/material/snack-bar/snack-bar-config.ts_0_2145
/** * @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 {ViewContainerRef, InjectionToken} from '@angular/core'; import {AriaLivePoliteness} from '@angular/cdk/a11y'; import {Direction} from '@angular/cdk/bidi'; /** Injection token that can be used to access the data that was passed in to a snack bar. */ export const MAT_SNACK_BAR_DATA = new InjectionToken<any>('MatSnackBarData'); /** Possible values for horizontalPosition on MatSnackBarConfig. */ export type MatSnackBarHorizontalPosition = 'start' | 'center' | 'end' | 'left' | 'right'; /** Possible values for verticalPosition on MatSnackBarConfig. */ export type MatSnackBarVerticalPosition = 'top' | 'bottom'; /** * Configuration used when opening a snack-bar. */ export class MatSnackBarConfig<D = any> { /** The politeness level for the MatAriaLiveAnnouncer announcement. */ politeness?: AriaLivePoliteness = 'assertive'; /** * Message to be announced by the LiveAnnouncer. When opening a snackbar without a custom * component or template, the announcement message will default to the specified message. */ announcementMessage?: string = ''; /** * The view container that serves as the parent for the snackbar for the purposes of dependency * injection. Note: this does not affect where the snackbar is inserted in the DOM. */ viewContainerRef?: ViewContainerRef; /** The length of time in milliseconds to wait before automatically dismissing the snack bar. */ duration?: number = 0; /** Extra CSS classes to be added to the snack bar container. */ panelClass?: string | string[]; /** Text layout direction for the snack bar. */ direction?: Direction; /** Data being injected into the child component. */ data?: D | null = null; /** The horizontal position to place the snack bar. */ horizontalPosition?: MatSnackBarHorizontalPosition = 'center'; /** The vertical position to place the snack bar. */ verticalPosition?: MatSnackBarVerticalPosition = 'bottom'; }
{ "end_byte": 2145, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar-config.ts" }
components/src/material/snack-bar/public-api.ts_0_480
/** * @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 './simple-snack-bar'; export * from './snack-bar-container'; export * from './snack-bar-content'; export * from './snack-bar'; export * from './module'; export * from './snack-bar-config'; export * from './snack-bar-ref'; export * from './snack-bar-animations';
{ "end_byte": 480, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/public-api.ts" }
components/src/material/snack-bar/_snack-bar-theme.scss_0_3412
@use 'sass:map'; @use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @use '../core/style/sass-utils'; @use '../core/typography/typography'; @use '../core/tokens/token-utils'; @use '../core/tokens/m2/mdc/snack-bar' as tokens-mdc-snack-bar; @use '../core/tokens/m2/mat/snack-bar' as tokens-mat-snack-bar; @mixin base($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, base)); } @else { // Add default values for tokens not related to color, typography, or density. @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-snack-bar.$prefix, tokens-mdc-snack-bar.get-unthemable-tokens() ); } } } @mixin color($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, color)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-snack-bar.$prefix, tokens-mdc-snack-bar.get-color-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-snack-bar.$prefix, tokens-mat-snack-bar.get-color-tokens($theme) ); } } } @mixin typography($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, typography)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-snack-bar.$prefix, tokens-mdc-snack-bar.get-typography-tokens($theme) ); } } } @mixin density($theme) { } /// Defines the tokens that will be available in the `overrides` mixin and for docs extraction. @function _define-overrides() { @return ( ( namespace: tokens-mdc-snack-bar.$prefix, tokens: tokens-mdc-snack-bar.get-token-slots(), ), ( namespace: tokens-mat-snack-bar.$prefix, tokens: tokens-mat-snack-bar.get-token-slots(), ), ); } /// Outputs the CSS variable values for the given tokens. /// @param {Map} $tokens The token values to emit. @mixin overrides($tokens: ()) { @include token-utils.batch-create-token-values($tokens, _define-overrides()...); } @mixin theme($theme) { @include theming.private-check-duplicate-theme-styles($theme, 'mat-snack-bar') { @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-mdc-snack-bar.$prefix, map.get($tokens, tokens-mdc-snack-bar.$prefix) ); @include token-utils.create-token-values( tokens-mat-snack-bar.$prefix, map.get($tokens, tokens-mat-snack-bar.$prefix) ); } }
{ "end_byte": 3412, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/_snack-bar-theme.scss" }
components/src/material/snack-bar/snack-bar-animations.ts_0_1068
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { animate, state, style, transition, trigger, AnimationTriggerMetadata, } from '@angular/animations'; /** * Animations used by the Material snack bar. * @docs-private */ export const matSnackBarAnimations: { readonly snackBarState: AnimationTriggerMetadata; } = { /** Animation that shows and hides a snack bar. */ snackBarState: trigger('state', [ state( 'void, hidden', style({ transform: 'scale(0.8)', opacity: 0, }), ), state( 'visible', style({ transform: 'scale(1)', opacity: 1, }), ), transition('* => visible', animate('150ms cubic-bezier(0, 0, 0.2, 1)')), transition( '* => void, * => hidden', animate( '75ms cubic-bezier(0.4, 0.0, 1, 1)', style({ opacity: 0, }), ), ), ]), };
{ "end_byte": 1068, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar-animations.ts" }
components/src/material/snack-bar/snack-bar-container.scss_0_3621
@use '@angular/cdk'; @use '../core/tokens/m2/mdc/snack-bar' as tokens-mdc-snack-bar; @use '../core/tokens/m2/mat/snack-bar' as tokens-mat-snack-bar; @use '../core/tokens/m2/mat/text-button' as tokens-mat-text-button; @use '../core/tokens/token-utils'; @use '../core/style/elevation'; $_side-padding: 8px; .mat-mdc-snack-bar-container { display: flex; align-items: center; justify-content: center; box-sizing: border-box; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); margin: 8px; .mat-mdc-snack-bar-handset & { width: 100vw; } } .mat-mdc-snackbar-surface { @include elevation.elevation(6); display: flex; align-items: center; justify-content: flex-start; box-sizing: border-box; padding-left: 0; padding-right: $_side-padding; [dir='rtl'] & { padding-right: 0; padding-left: $_side-padding; } .mat-mdc-snack-bar-container & { min-width: 344px; max-width: 672px; } // Ensures that the snack bar stretches to full width in handset mode. .mat-mdc-snack-bar-handset & { width: 100%; min-width: 0; } @include cdk.high-contrast { outline: solid 1px; } @include token-utils.use-tokens( tokens-mdc-snack-bar.$prefix, tokens-mdc-snack-bar.get-token-slots() ) { .mat-mdc-snack-bar-container & { @include token-utils.create-token-slot(color, supporting-text-color); @include token-utils.create-token-slot(border-radius, container-shape); @include token-utils.create-token-slot(background-color, container-color); } } } .mdc-snackbar__label { width: 100%; flex-grow: 1; box-sizing: border-box; margin: 0; padding: 14px $_side-padding 14px 16px; [dir='rtl'] & { padding-left: $_side-padding; padding-right: 16px; } @include token-utils.use-tokens( tokens-mdc-snack-bar.$prefix, tokens-mdc-snack-bar.get-token-slots() ) { .mat-mdc-snack-bar-container & { @include token-utils.create-token-slot(font-family, supporting-text-font); @include token-utils.create-token-slot(font-size, supporting-text-size); @include token-utils.create-token-slot(font-weight, supporting-text-weight); @include token-utils.create-token-slot(line-height, supporting-text-line-height); } } } .mat-mdc-snack-bar-actions { display: flex; flex-shrink: 0; align-items: center; box-sizing: border-box; } // These elements need to have full width using flex layout. .mat-mdc-snack-bar-handset, .mat-mdc-snack-bar-container, .mat-mdc-snack-bar-label { // Note that we need to include the full `flex` shorthand // declaration so the container doesn't collapse on IE11. flex: 1 1 auto; } // The `mat-mdc-button` and `:not(:disabled)` here are redundant, but we need them to increase // the specificity over the button styles that may bleed in from the rest of the app. .mat-mdc-snack-bar-container .mat-mdc-button.mat-mdc-snack-bar-action:not(:disabled) { // MDC's `action-label-text-color` should be able to do this, but the button theme has a // higher specificity so it ends up overriding it. Define our own variable that we can // use to control the color instead. @include token-utils.use-tokens( tokens-mat-snack-bar.$prefix, tokens-mat-snack-bar.get-token-slots() ) { @include token-utils.create-token-slot(color, button-color); } // Darken the ripples in the button so they're visible against the dark background. @include token-utils.create-token-values(tokens-mat-text-button.$prefix, ( state-layer-color: currentColor, ripple-color: currentColor, )); .mat-ripple-element { opacity: 0.1; } }
{ "end_byte": 3621, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar-container.scss" }
components/src/material/snack-bar/snack-bar.zone.spec.ts_0_2566
import { ChangeDetectionStrategy, Component, Directive, ViewChild, ViewContainerRef, provideZoneChangeDetection, signal, inject, } from '@angular/core'; import {ComponentFixture, TestBed, fakeAsync, flush, tick} from '@angular/core/testing'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {MatSnackBarModule} from './module'; import {MatSnackBar} from './snack-bar'; import {MatSnackBarConfig} from './snack-bar-config'; describe('MatSnackBar Zone.js integration', () => { let snackBar: MatSnackBar; let viewContainerFixture: ComponentFixture<ComponentWithChildViewContainer>; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [ MatSnackBarModule, NoopAnimationsModule, ComponentWithChildViewContainer, DirectiveWithViewContainer, ], providers: [provideZoneChangeDetection()], }); snackBar = TestBed.inject(MatSnackBar); viewContainerFixture = TestBed.createComponent(ComponentWithChildViewContainer); viewContainerFixture.detectChanges(); })); it('should clear the dismiss timeout when dismissed before timeout expiration', fakeAsync(() => { let config = new MatSnackBarConfig(); config.duration = 1000; snackBar.open('content', 'test', config); setTimeout(() => snackBar.dismiss(), 500); tick(600); flush(); expect(viewContainerFixture.isStable()).toBe(true); })); it('should clear the dismiss timeout when dismissed with action', fakeAsync(() => { let config = new MatSnackBarConfig(); config.duration = 1000; const snackBarRef = snackBar.open('content', 'test', config); setTimeout(() => snackBarRef.dismissWithAction(), 500); tick(600); viewContainerFixture.detectChanges(); tick(); expect(viewContainerFixture.isStable()).toBe(true); })); }); @Directive({ selector: 'dir-with-view-container', standalone: true, }) class DirectiveWithViewContainer { viewContainerRef = inject(ViewContainerRef); } @Component({ selector: 'arbitrary-component', template: `@if (childComponentExists()) {<dir-with-view-container></dir-with-view-container>}`, standalone: true, imports: [DirectiveWithViewContainer], changeDetection: ChangeDetectionStrategy.OnPush, }) class ComponentWithChildViewContainer { @ViewChild(DirectiveWithViewContainer) childWithViewContainer: DirectiveWithViewContainer; childComponentExists = signal(true); get childViewContainer() { return this.childWithViewContainer.viewContainerRef; } }
{ "end_byte": 2566, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar.zone.spec.ts" }
components/src/material/snack-bar/snack-bar.spec.ts_0_694
import {LiveAnnouncer} from '@angular/cdk/a11y'; import {OverlayContainer} from '@angular/cdk/overlay'; import {Platform} from '@angular/cdk/platform'; import { ChangeDetectionStrategy, Component, Directive, TemplateRef, ViewChild, ViewContainerRef, signal, inject, } from '@angular/core'; import {ComponentFixture, TestBed, fakeAsync, flush, tick} from '@angular/core/testing'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import { MAT_SNACK_BAR_DATA, MatSnackBar, MatSnackBarConfig, MatSnackBarContainer, MatSnackBarModule, MatSnackBarRef, SimpleSnackBar, } from './index'; import {MAT_SNACK_BAR_DEFAULT_OPTIONS} from './snack-bar';
{ "end_byte": 694, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar.spec.ts" }
components/src/material/snack-bar/snack-bar.spec.ts_696_9749
describe('MatSnackBar', () => { let snackBar: MatSnackBar; let liveAnnouncer: LiveAnnouncer; let overlayContainerElement: HTMLElement; let testViewContainerRef: ViewContainerRef; let viewContainerFixture: ComponentFixture<ComponentWithChildViewContainer>; let simpleMessage = 'Burritos are here!'; let simpleActionLabel = 'pickup'; const announceDelay = 150; const animationFrameDelay = 16; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [ MatSnackBarModule, NoopAnimationsModule, ComponentWithChildViewContainer, BurritosNotification, DirectiveWithViewContainer, ], }); snackBar = TestBed.inject(MatSnackBar); liveAnnouncer = TestBed.inject(LiveAnnouncer); overlayContainerElement = TestBed.inject(OverlayContainer).getContainerElement(); viewContainerFixture = TestBed.createComponent(ComponentWithChildViewContainer); viewContainerFixture.detectChanges(); testViewContainerRef = viewContainerFixture.componentInstance.childViewContainer; })); it('should open with content first in the inert region', () => { snackBar.open('Snack time!', 'Chew'); viewContainerFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; const inertElement = containerElement.querySelector('[aria-hidden]')!; expect(inertElement.getAttribute('aria-hidden')) .withContext('Expected the non-live region to be aria-hidden') .toBe('true'); expect(inertElement.textContent) .withContext('Expected non-live region to contain the snack bar content') .toContain('Snack time!'); const liveElement = containerElement.querySelector('[aria-live]')!; expect(liveElement.childNodes.length) .withContext('Expected live region to not contain any content') .toBe(0); }); it('should move content to the live region after 150ms', fakeAsync(() => { snackBar.open('Snack time!', 'Chew'); viewContainerFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; const liveElement = containerElement.querySelector('[aria-live]')!; tick(announceDelay); expect(liveElement.textContent) .withContext('Expected live region to contain the snack bar content') .toContain('Snack time!'); const inertElement = containerElement.querySelector('[aria-hidden]')!; expect(inertElement) .withContext('Expected non-live region to not contain any content') .toBeFalsy(); flush(); })); it('should preserve focus when moving content to the live region', fakeAsync(() => { snackBar.open('Snack time!', 'Chew'); viewContainerFixture.detectChanges(); tick(animationFrameDelay); const actionButton = overlayContainerElement.querySelector( '.mat-mdc-simple-snack-bar .mat-mdc-snack-bar-action', )! as HTMLElement; actionButton.focus(); expect(document.activeElement) .withContext('Expected the focus to move to the action button') .toBe(actionButton); flush(); expect(document.activeElement) .withContext('Expected the focus to remain on the action button') .toBe(actionButton); })); it( 'should have aria-live of `assertive` with an `assertive` politeness if no announcement ' + 'message is provided', () => { snackBar.openFromComponent(BurritosNotification, { announcementMessage: '', politeness: 'assertive', }); viewContainerFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; const liveElement = containerElement.querySelector('[aria-live]')!; expect(liveElement.getAttribute('aria-live')) .withContext('Expected snack bar container live region to have aria-live="assertive"') .toBe('assertive'); }, ); it( 'should have aria-live of `polite` with an `assertive` politeness if an announcement ' + 'message is provided', () => { snackBar.openFromComponent(BurritosNotification, { announcementMessage: 'Yay Burritos', politeness: 'assertive', }); viewContainerFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; const liveElement = containerElement.querySelector('[aria-live]')!; expect(liveElement.getAttribute('aria-live')) .withContext('Expected snack bar container live region to have aria-live="polite"') .toBe('polite'); }, ); it('should have aria-live of `polite` with a `polite` politeness', () => { snackBar.openFromComponent(BurritosNotification, {politeness: 'polite'}); viewContainerFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; const liveElement = containerElement.querySelector('[aria-live]')!; expect(liveElement.getAttribute('aria-live')) .withContext('Expected snack bar container live region to have aria-live="polite"') .toBe('polite'); }); it('should have aria-live of `off` if the politeness is turned off', () => { snackBar.openFromComponent(BurritosNotification, {politeness: 'off'}); viewContainerFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; const liveElement = containerElement.querySelector('[aria-live]')!; expect(liveElement.getAttribute('aria-live')) .withContext('Expected snack bar container live region to have aria-live="off"') .toBe('off'); }); it('should have role of `alert` with an `assertive` politeness (Firefox only)', () => { const platform = TestBed.inject(Platform); snackBar.openFromComponent(BurritosNotification, {politeness: 'assertive'}); viewContainerFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; const liveElement = containerElement.querySelector('[aria-live]')!; expect(liveElement.getAttribute('role')).toBe(platform.FIREFOX ? 'alert' : null); }); it('should have role of `status` with an `polite` politeness (Firefox only)', () => { const platform = TestBed.inject(Platform); snackBar.openFromComponent(BurritosNotification, {politeness: 'polite'}); viewContainerFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; const liveElement = containerElement.querySelector('[aria-live]')!; expect(liveElement.getAttribute('role')).toBe(platform.FIREFOX ? 'status' : null); }); it('should have exactly one MDC label element when opened through simple snack bar', () => { let config: MatSnackBarConfig = {viewContainerRef: testViewContainerRef}; snackBar.open(simpleMessage, simpleActionLabel, config); viewContainerFixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.mdc-snackbar__label').length).toBe(1); }); it('should open and close a snackbar without a ViewContainerRef', fakeAsync(() => { let snackBarRef = snackBar.open('Snack time!', 'Chew'); viewContainerFixture.detectChanges(); let messageElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; expect(messageElement.textContent) .withContext('Expected snack bar to show a message without a ViewContainerRef') .toContain('Snack time!'); snackBarRef.dismiss(); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.childNodes.length) .withContext('Expected snack bar to be dismissed without a ViewContainerRef') .toBe(0); })); it('should open a simple message with a button', () => { let config: MatSnackBarConfig = {viewContainerRef: testViewContainerRef}; let snackBarRef = snackBar.open(simpleMessage, simpleActionLabel, config); viewContainerFixture.detectChanges(); expect(snackBarRef.instance instanceof SimpleSnackBar) .withContext('Expected the snack bar content component to be SimpleSnackBar') .toBe(true); expect(snackBarRef.instance.snackBarRef) .withContext('Expected the snack bar reference to be placed in the component instance') .toBe(snackBarRef); let messageElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; expect(messageElement.textContent) .withContext(`Expected the snack bar message to be '${simpleMessage}'`) .toContain(simpleMessage); let buttonElement = overlayContainerElement.querySelector('button.mat-mdc-button')!; expect(buttonElement.tagName) .withContext('Expected snack bar action label to be a <button>') .toBe('BUTTON'); expect((buttonElement.textContent || '').trim()) .withContext(`Expected the snack bar action label to be '${simpleActionLabel}'`) .toBe(simpleActionLabel); });
{ "end_byte": 9749, "start_byte": 696, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar.spec.ts" }
components/src/material/snack-bar/snack-bar.spec.ts_9753_19202
it('should open a simple message with no button', () => { let config: MatSnackBarConfig = {viewContainerRef: testViewContainerRef}; let snackBarRef = snackBar.open(simpleMessage, undefined, config); viewContainerFixture.detectChanges(); expect(snackBarRef.instance instanceof SimpleSnackBar) .withContext('Expected the snack bar content component to be SimpleSnackBar') .toBe(true); expect(snackBarRef.instance.snackBarRef) .withContext('Expected the snack bar reference to be placed in the component instance') .toBe(snackBarRef); let messageElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; expect(messageElement.textContent) .withContext(`Expected the snack bar message to be '${simpleMessage}'`) .toContain(simpleMessage); expect(overlayContainerElement.querySelector('button.mat-mdc-button')) .withContext('Expected the query selection for action label to be null') .toBeNull(); }); it('should dismiss the snack bar and remove itself from the view', fakeAsync(() => { let config: MatSnackBarConfig = {viewContainerRef: testViewContainerRef}; let dismissCompleteSpy = jasmine.createSpy('dismiss complete spy'); let snackBarRef = snackBar.open(simpleMessage, undefined, config); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.childElementCount) .withContext('Expected overlay container element to have at least one child') .toBeGreaterThan(0); snackBarRef.afterDismissed().subscribe({complete: dismissCompleteSpy}); const messageElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; snackBarRef.dismiss(); viewContainerFixture.detectChanges(); expect(messageElement.hasAttribute('mat-exit')) .withContext('Expected the snackbar container to have the "exit" attribute upon dismiss') .toBe(true); flush(); expect(dismissCompleteSpy).toHaveBeenCalled(); expect(overlayContainerElement.childElementCount) .withContext('Expected the overlay container element to have no child elements') .toBe(0); })); it('should clear the announcement message if it is the same as main message', fakeAsync(() => { spyOn(liveAnnouncer, 'announce'); snackBar.open(simpleMessage, undefined, {announcementMessage: simpleMessage}); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.childElementCount) .withContext('Expected the overlay with the default announcement message to be added') .toBe(1); expect(liveAnnouncer.announce).not.toHaveBeenCalled(); })); it('should be able to specify a custom announcement message', fakeAsync(() => { spyOn(liveAnnouncer, 'announce'); snackBar.open(simpleMessage, '', { announcementMessage: 'Custom announcement', politeness: 'assertive', }); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.childElementCount) .withContext('Expected the overlay with a custom `announcementMessage` to be added') .toBe(1); expect(liveAnnouncer.announce).toHaveBeenCalledWith('Custom announcement', 'assertive'); })); it('should be able to get dismissed through the service', fakeAsync(() => { snackBar.open(simpleMessage); viewContainerFixture.detectChanges(); expect(overlayContainerElement.childElementCount).toBeGreaterThan(0); snackBar.dismiss(); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.childElementCount).toBe(0); })); it('should clean itself up when the view container gets destroyed', fakeAsync(() => { snackBar.open(simpleMessage, undefined, {viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); expect(overlayContainerElement.childElementCount).toBeGreaterThan(0); viewContainerFixture.componentInstance.childComponentExists.set(false); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.childElementCount) .withContext('Expected snack bar to be removed after the view container was destroyed') .toBe(0); })); it('should set the animation state to visible on entry', () => { const config: MatSnackBarConfig = {viewContainerRef: testViewContainerRef}; const snackBarRef = snackBar.open(simpleMessage, undefined, config); viewContainerFixture.detectChanges(); const container = snackBarRef.containerInstance as MatSnackBarContainer; expect(container._animationState) .withContext(`Expected the animation state would be 'visible'.`) .toBe('visible'); snackBarRef.dismiss(); viewContainerFixture.detectChanges(); expect(container._animationState) .withContext(`Expected the animation state would be 'hidden'.`) .toBe('hidden'); }); it('should set the animation state to complete on exit', () => { const config: MatSnackBarConfig = {viewContainerRef: testViewContainerRef}; const snackBarRef = snackBar.open(simpleMessage, undefined, config); snackBarRef.dismiss(); viewContainerFixture.detectChanges(); const container = snackBarRef.containerInstance as MatSnackBarContainer; expect(container._animationState) .withContext(`Expected the animation state would be 'hidden'.`) .toBe('hidden'); }); it(`should set the old snack bar animation state to complete and the new snack bar animation state to visible on entry of new snack bar`, fakeAsync(() => { const config: MatSnackBarConfig = {viewContainerRef: testViewContainerRef}; const snackBarRef = snackBar.open(simpleMessage, undefined, config); const dismissCompleteSpy = jasmine.createSpy('dismiss complete spy'); viewContainerFixture.detectChanges(); const containerElement = document.querySelector('mat-snack-bar-container')!; expect(containerElement.classList).toContain('ng-animating'); const container1 = snackBarRef.containerInstance as MatSnackBarContainer; expect(container1._animationState) .withContext(`Expected the animation state would be 'visible'.`) .toBe('visible'); const config2 = {viewContainerRef: testViewContainerRef}; const snackBarRef2 = snackBar.open(simpleMessage, undefined, config2); viewContainerFixture.detectChanges(); snackBarRef.afterDismissed().subscribe({complete: dismissCompleteSpy}); flush(); expect(dismissCompleteSpy).toHaveBeenCalled(); const container2 = snackBarRef2.containerInstance as MatSnackBarContainer; expect(container1._animationState) .withContext(`Expected the animation state would be 'hidden'.`) .toBe('hidden'); expect(container2._animationState) .withContext(`Expected the animation state would be 'visible'.`) .toBe('visible'); })); it('should open a new snackbar after dismissing a previous snackbar', fakeAsync(() => { let config: MatSnackBarConfig = {viewContainerRef: testViewContainerRef}; let snackBarRef = snackBar.open(simpleMessage, 'Dismiss', config); viewContainerFixture.detectChanges(); snackBarRef.dismiss(); viewContainerFixture.detectChanges(); // Wait for the snackbar dismiss animation to finish. flush(); snackBar.open('Second snackbar'); viewContainerFixture.detectChanges(); // Wait for the snackbar open animation to finish. flush(); expect(overlayContainerElement.textContent!.trim()).toBe('Second snackbar'); })); it('should remove past snackbars when opening new snackbars', fakeAsync(() => { snackBar.open('First snackbar'); viewContainerFixture.detectChanges(); snackBar.open('Second snackbar'); viewContainerFixture.detectChanges(); flush(); snackBar.open('Third snackbar'); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.textContent!.trim()).toBe('Third snackbar'); })); it('should remove snackbar if another is shown while its still animating open', fakeAsync(() => { snackBar.open('First snackbar'); viewContainerFixture.detectChanges(); snackBar.open('Second snackbar'); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.textContent!.trim()).toBe('Second snackbar'); })); it('should dismiss the snackbar when the action is called, notifying of both action and dismiss', fakeAsync(() => { const dismissNextSpy = jasmine.createSpy('dismiss next spy'); const dismissCompleteSpy = jasmine.createSpy('dismiss complete spy'); const actionNextSpy = jasmine.createSpy('action next spy'); const actionCompleteSpy = jasmine.createSpy('action complete spy'); const snackBarRef = snackBar.open('Some content', 'Dismiss'); viewContainerFixture.detectChanges(); snackBarRef.afterDismissed().subscribe({next: dismissNextSpy, complete: dismissCompleteSpy}); snackBarRef.onAction().subscribe({next: actionNextSpy, complete: actionCompleteSpy}); const actionButton = overlayContainerElement.querySelector( 'button.mat-mdc-button', ) as HTMLButtonElement; actionButton.click(); viewContainerFixture.detectChanges(); tick(); expect(dismissNextSpy).toHaveBeenCalled(); expect(dismissCompleteSpy).toHaveBeenCalled(); expect(actionNextSpy).toHaveBeenCalled(); expect(actionCompleteSpy).toHaveBeenCalled(); tick(500); }));
{ "end_byte": 19202, "start_byte": 9753, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar.spec.ts" }
components/src/material/snack-bar/snack-bar.spec.ts_19206_27951
it('should allow manually dismissing with an action', fakeAsync(() => { const dismissCompleteSpy = jasmine.createSpy('dismiss complete spy'); const actionCompleteSpy = jasmine.createSpy('action complete spy'); const snackBarRef = snackBar.open('Some content'); viewContainerFixture.detectChanges(); snackBarRef.afterDismissed().subscribe({complete: dismissCompleteSpy}); snackBarRef.onAction().subscribe({complete: actionCompleteSpy}); snackBarRef.dismissWithAction(); viewContainerFixture.detectChanges(); flush(); expect(dismissCompleteSpy).toHaveBeenCalled(); expect(actionCompleteSpy).toHaveBeenCalled(); })); it('should indicate in `afterClosed` whether it was dismissed by an action', fakeAsync(() => { const dismissSpy = jasmine.createSpy('dismiss spy'); const snackBarRef = snackBar.open('Some content'); viewContainerFixture.detectChanges(); snackBarRef.afterDismissed().subscribe(dismissSpy); snackBarRef.dismissWithAction(); viewContainerFixture.detectChanges(); flush(); expect(dismissSpy).toHaveBeenCalledWith(jasmine.objectContaining({dismissedByAction: true})); })); it('should complete the onAction stream when not closing via an action', fakeAsync(() => { const actionCompleteSpy = jasmine.createSpy('action complete spy'); const snackBarRef = snackBar.open('Some content'); viewContainerFixture.detectChanges(); snackBarRef.onAction().subscribe({complete: actionCompleteSpy}); snackBarRef.dismiss(); viewContainerFixture.detectChanges(); flush(); expect(actionCompleteSpy).toHaveBeenCalled(); })); it('should dismiss automatically after a specified timeout', fakeAsync(() => { const config = new MatSnackBarConfig(); config.duration = 250; const snackBarRef = snackBar.open('content', 'test', config); const afterDismissSpy = jasmine.createSpy('after dismiss spy'); snackBarRef.afterDismissed().subscribe(afterDismissSpy); viewContainerFixture.detectChanges(); tick(); expect(afterDismissSpy).not.toHaveBeenCalled(); tick(1000); viewContainerFixture.detectChanges(); tick(); expect(afterDismissSpy).toHaveBeenCalled(); })); it('should add extra classes to the container', () => { snackBar.open(simpleMessage, simpleActionLabel, {panelClass: ['one', 'two']}); viewContainerFixture.detectChanges(); let containerClasses = overlayContainerElement.querySelector('mat-snack-bar-container')!.classList; expect(containerClasses).toContain('one'); expect(containerClasses).toContain('two'); }); it('should set the layout direction', () => { snackBar.open(simpleMessage, simpleActionLabel, {direction: 'rtl'}); viewContainerFixture.detectChanges(); let pane = overlayContainerElement.querySelector('.cdk-global-overlay-wrapper')!; expect(pane.getAttribute('dir')) .withContext('Expected the pane to be in RTL mode.') .toBe('rtl'); }); it('should be able to override the default config', fakeAsync(() => { viewContainerFixture.destroy(); TestBed.resetTestingModule() .overrideProvider(MAT_SNACK_BAR_DEFAULT_OPTIONS, { deps: [], useFactory: () => ({panelClass: 'custom-class'}), }) .configureTestingModule({imports: [MatSnackBarModule, NoopAnimationsModule]}); snackBar = TestBed.inject(MatSnackBar); overlayContainerElement = TestBed.inject(OverlayContainer).getContainerElement(); snackBar.open(simpleMessage); flush(); expect(overlayContainerElement.querySelector('mat-snack-bar-container')!.classList) .withContext('Expected class applied through the defaults to be applied.') .toContain('custom-class'); })); it('should dismiss the open snack bar on destroy', fakeAsync(() => { snackBar.open(simpleMessage); viewContainerFixture.detectChanges(); expect(overlayContainerElement.childElementCount).toBeGreaterThan(0); snackBar.ngOnDestroy(); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.childElementCount).toBe(0); })); it('should cap the timeout to the maximum accepted delay in setTimeout', fakeAsync(() => { const config = new MatSnackBarConfig(); config.duration = Infinity; snackBar.open('content', 'test', config); viewContainerFixture.detectChanges(); spyOn(window, 'setTimeout').and.callThrough(); tick(100); expect(window.setTimeout).toHaveBeenCalledWith(jasmine.any(Function), Math.pow(2, 31) - 1); flush(); })); it('should only keep one snack bar in the DOM if multiple are opened at the same time', fakeAsync(() => { for (let i = 0; i < 10; i++) { snackBar.open('Snack time!', 'Chew'); viewContainerFixture.detectChanges(); } flush(); expect(overlayContainerElement.querySelectorAll('mat-snack-bar-container').length).toBe(1); })); describe('with custom component', () => { it('should open a custom component', () => { const snackBarRef = snackBar.openFromComponent(BurritosNotification); expect(snackBarRef.instance instanceof BurritosNotification) .withContext('Expected the snack bar content component to be BurritosNotification') .toBe(true); expect(overlayContainerElement.textContent!.trim()) .withContext('Expected component to have the proper text.') .toBe('Burritos are on the way.'); }); it('should inject the snack bar reference into the component', () => { const snackBarRef = snackBar.openFromComponent(BurritosNotification); expect(snackBarRef.instance.snackBarRef) .withContext('Expected component to have an injected snack bar reference.') .toBe(snackBarRef); }); it('should have exactly one MDC label element', () => { snackBar.openFromComponent(BurritosNotification); viewContainerFixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.mdc-snackbar__label').length).toBe(1); }); it('should be able to inject arbitrary user data', () => { const snackBarRef = snackBar.openFromComponent(BurritosNotification, { data: { burritoType: 'Chimichanga', }, }); expect(snackBarRef.instance.data) .withContext('Expected component to have a data object.') .toBeTruthy(); expect(snackBarRef.instance.data.burritoType) .withContext('Expected the injected data object to be the one the user provided.') .toBe('Chimichanga'); }); it('should allow manually dismissing with an action', fakeAsync(() => { const dismissCompleteSpy = jasmine.createSpy('dismiss complete spy'); const actionCompleteSpy = jasmine.createSpy('action complete spy'); const snackBarRef = snackBar.openFromComponent(BurritosNotification); viewContainerFixture.detectChanges(); snackBarRef.afterDismissed().subscribe({complete: dismissCompleteSpy}); snackBarRef.onAction().subscribe({complete: actionCompleteSpy}); snackBarRef.dismissWithAction(); viewContainerFixture.detectChanges(); flush(); expect(dismissCompleteSpy).toHaveBeenCalled(); expect(actionCompleteSpy).toHaveBeenCalled(); })); }); describe('with TemplateRef', () => { let templateFixture: ComponentFixture<ComponentWithTemplateRef>; beforeEach(() => { templateFixture = TestBed.createComponent(ComponentWithTemplateRef); templateFixture.detectChanges(); }); it('should be able to open a snack bar using a TemplateRef', () => { templateFixture.componentInstance.localValue = 'Pizza'; templateFixture.changeDetectorRef.markForCheck(); snackBar.openFromTemplate(templateFixture.componentInstance.templateRef); templateFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; expect(containerElement.textContent).toContain('Fries'); expect(containerElement.textContent).toContain('Pizza'); templateFixture.componentInstance.localValue = 'Pasta'; templateFixture.changeDetectorRef.markForCheck(); templateFixture.detectChanges(); expect(containerElement.textContent).toContain('Pasta'); }); it('should be able to pass in contextual data when opening with a TemplateRef', () => { snackBar.openFromTemplate(templateFixture.componentInstance.templateRef, { data: {value: 'Oranges'}, }); templateFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; expect(containerElement.textContent).toContain('Oranges'); }); }); });
{ "end_byte": 27951, "start_byte": 19206, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar.spec.ts" }
components/src/material/snack-bar/snack-bar.spec.ts_27953_30255
describe('MatSnackBar with parent MatSnackBar', () => { let parentSnackBar: MatSnackBar; let childSnackBar: MatSnackBar; let overlayContainerElement: HTMLElement; let fixture: ComponentFixture<ComponentThatProvidesMatSnackBar>; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [ MatSnackBarModule, NoopAnimationsModule, ComponentThatProvidesMatSnackBar, DirectiveWithViewContainer, ], }); parentSnackBar = TestBed.inject(MatSnackBar); overlayContainerElement = TestBed.inject(OverlayContainer).getContainerElement(); fixture = TestBed.createComponent(ComponentThatProvidesMatSnackBar); childSnackBar = fixture.componentInstance.snackBar; fixture.detectChanges(); })); it('should close snackBars opened by parent when opening from child', fakeAsync(() => { parentSnackBar.open('Pizza'); fixture.detectChanges(); tick(1000); expect(overlayContainerElement.textContent) .withContext('Expected a snackBar to be opened') .toContain('Pizza'); childSnackBar.open('Taco'); fixture.detectChanges(); tick(1000); expect(overlayContainerElement.textContent) .withContext('Expected parent snackbar msg to be dismissed by opening from child') .toContain('Taco'); })); it('should close snackBars opened by child when opening from parent', fakeAsync(() => { childSnackBar.open('Pizza'); fixture.detectChanges(); tick(1000); expect(overlayContainerElement.textContent) .withContext('Expected a snackBar to be opened') .toContain('Pizza'); parentSnackBar.open('Taco'); fixture.detectChanges(); tick(1000); expect(overlayContainerElement.textContent) .withContext('Expected child snackbar msg to be dismissed by opening from parent') .toContain('Taco'); })); it('should not dismiss parent snack bar if child is destroyed', fakeAsync(() => { parentSnackBar.open('Pizza'); fixture.detectChanges(); expect(overlayContainerElement.childElementCount).toBeGreaterThan(0); childSnackBar.ngOnDestroy(); fixture.detectChanges(); flush(); expect(overlayContainerElement.childElementCount).toBeGreaterThan(0); })); }); describe('MatSnackBar Positioning', () =>
{ "end_byte": 30255, "start_byte": 27953, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar.spec.ts" }
components/src/material/snack-bar/snack-bar.spec.ts_30256_38895
{ let snackBar: MatSnackBar; let overlayContainerEl: HTMLElement; let viewContainerFixture: ComponentFixture<ComponentWithChildViewContainer>; let simpleMessage = 'Burritos are here!'; let simpleActionLabel = 'pickup'; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [ MatSnackBarModule, NoopAnimationsModule, ComponentWithChildViewContainer, DirectiveWithViewContainer, ], }); snackBar = TestBed.inject(MatSnackBar); overlayContainerEl = TestBed.inject(OverlayContainer).getContainerElement(); viewContainerFixture = TestBed.createComponent(ComponentWithChildViewContainer); viewContainerFixture.detectChanges(); })); it('should default to bottom center', fakeAsync(() => { snackBar.open(simpleMessage, simpleActionLabel); viewContainerFixture.detectChanges(); flush(); const overlayPaneEl = overlayContainerEl.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPaneEl.style.marginBottom) .withContext('Expected margin-bottom to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginTop).withContext('Expected margin-top to be ""').toBe(''); expect(overlayPaneEl.style.marginRight).withContext('Expected margin-right to be ""').toBe(''); expect(overlayPaneEl.style.marginLeft).withContext('Expected margin-left to be ""').toBe(''); })); it('should be in the bottom left corner', fakeAsync(() => { snackBar.open(simpleMessage, simpleActionLabel, { verticalPosition: 'bottom', horizontalPosition: 'left', }); viewContainerFixture.detectChanges(); flush(); const overlayPaneEl = overlayContainerEl.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPaneEl.style.marginBottom) .withContext('Expected margin-bottom to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginTop).withContext('Expected margin-top to be ""').toBe(''); expect(overlayPaneEl.style.marginRight).withContext('Expected margin-right to be ""').toBe(''); expect(overlayPaneEl.style.marginLeft) .withContext('Expected margin-left to be "0px"') .toBe('0px'); })); it('should be in the bottom right corner', fakeAsync(() => { snackBar.open(simpleMessage, simpleActionLabel, { verticalPosition: 'bottom', horizontalPosition: 'right', }); viewContainerFixture.detectChanges(); flush(); const overlayPaneEl = overlayContainerEl.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPaneEl.style.marginBottom) .withContext('Expected margin-bottom to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginTop).withContext('Expected margin-top to be ""').toBe(''); expect(overlayPaneEl.style.marginRight) .withContext('Expected margin-right to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginLeft).withContext('Expected margin-left to be ""').toBe(''); })); it('should be in the bottom center', fakeAsync(() => { snackBar.open(simpleMessage, simpleActionLabel, { verticalPosition: 'bottom', horizontalPosition: 'center', }); viewContainerFixture.detectChanges(); flush(); const overlayPaneEl = overlayContainerEl.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPaneEl.style.marginBottom) .withContext('Expected margin-bottom to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginTop).withContext('Expected margin-top to be ""').toBe(''); expect(overlayPaneEl.style.marginRight).withContext('Expected margin-right to be ""').toBe(''); expect(overlayPaneEl.style.marginLeft).withContext('Expected margin-left to be ""').toBe(''); })); it('should be in the top left corner', fakeAsync(() => { snackBar.open(simpleMessage, simpleActionLabel, { verticalPosition: 'top', horizontalPosition: 'left', }); viewContainerFixture.detectChanges(); flush(); const overlayPaneEl = overlayContainerEl.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPaneEl.style.marginBottom) .withContext('Expected margin-bottom to be ""') .toBe(''); expect(overlayPaneEl.style.marginTop) .withContext('Expected margin-top to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginRight).withContext('Expected margin-right to be ""').toBe(''); expect(overlayPaneEl.style.marginLeft) .withContext('Expected margin-left to be "0px"') .toBe('0px'); })); it('should be in the top right corner', fakeAsync(() => { snackBar.open(simpleMessage, simpleActionLabel, { verticalPosition: 'top', horizontalPosition: 'right', }); viewContainerFixture.detectChanges(); flush(); const overlayPaneEl = overlayContainerEl.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPaneEl.style.marginBottom) .withContext('Expected margin-bottom to be ""') .toBe(''); expect(overlayPaneEl.style.marginTop) .withContext('Expected margin-top to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginRight) .withContext('Expected margin-right to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginLeft).withContext('Expected margin-left to be ""').toBe(''); })); it('should be in the top center', fakeAsync(() => { snackBar.open(simpleMessage, simpleActionLabel, { verticalPosition: 'top', horizontalPosition: 'center', }); viewContainerFixture.detectChanges(); flush(); const overlayPaneEl = overlayContainerEl.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPaneEl.style.marginBottom) .withContext('Expected margin-bottom to be ""') .toBe(''); expect(overlayPaneEl.style.marginTop) .withContext('Expected margin-top to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginRight).withContext('Expected margin-right to be ""').toBe(''); expect(overlayPaneEl.style.marginLeft).withContext('Expected margin-left to be ""').toBe(''); })); it('should handle start based on direction (rtl)', fakeAsync(() => { snackBar.open(simpleMessage, simpleActionLabel, { verticalPosition: 'top', horizontalPosition: 'start', direction: 'rtl', }); viewContainerFixture.detectChanges(); flush(); const overlayPaneEl = overlayContainerEl.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPaneEl.style.marginBottom) .withContext('Expected margin-bottom to be ""') .toBe(''); expect(overlayPaneEl.style.marginTop) .withContext('Expected margin-top to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginRight) .withContext('Expected margin-right to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginLeft).withContext('Expected margin-left to be ""').toBe(''); })); it('should handle start based on direction (ltr)', fakeAsync(() => { snackBar.open(simpleMessage, simpleActionLabel, { verticalPosition: 'top', horizontalPosition: 'start', direction: 'ltr', }); viewContainerFixture.detectChanges(); flush(); const overlayPaneEl = overlayContainerEl.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPaneEl.style.marginBottom) .withContext('Expected margin-bottom to be ""') .toBe(''); expect(overlayPaneEl.style.marginTop) .withContext('Expected margin-top to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginRight).withContext('Expected margin-right to be ""').toBe(''); expect(overlayPaneEl.style.marginLeft) .withContext('Expected margin-left to be "0px"') .toBe('0px'); })); it('should handle end based on direction (rtl)', fakeAsync(() => { snackBar.open(simpleMessage, simpleActionLabel, { verticalPosition: 'top', horizontalPosition: 'end', direction: 'rtl', }); viewContainerFixture.detectChanges(); flush(); const overlayPaneEl = overlayContainerEl.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPaneEl.style.marginBottom) .withContext('Expected margin-bottom to be ""') .toBe(''); expect(overlayPaneEl.style.marginTop) .withContext('Expected margin-top to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginRight).withContext('Expected margin-right to be ""').toBe(''); expect(overlayPaneEl.style.marginLeft) .withContext('Expected margin-left to be "0px"') .toBe('0px'); }));
{ "end_byte": 38895, "start_byte": 30256, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar.spec.ts" }
components/src/material/snack-bar/snack-bar.spec.ts_38899_41171
it('should handle end based on direction (ltr)', fakeAsync(() => { snackBar.open(simpleMessage, simpleActionLabel, { verticalPosition: 'top', horizontalPosition: 'end', direction: 'ltr', }); viewContainerFixture.detectChanges(); flush(); const overlayPaneEl = overlayContainerEl.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPaneEl.style.marginBottom) .withContext('Expected margin-bottom to be ""') .toBe(''); expect(overlayPaneEl.style.marginTop) .withContext('Expected margin-top to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginRight) .withContext('Expected margin-right to be "0px"') .toBe('0px'); expect(overlayPaneEl.style.marginLeft).withContext('Expected margin-left to be ""').toBe(''); })); }); @Directive({ selector: 'dir-with-view-container', standalone: true, }) class DirectiveWithViewContainer { viewContainerRef = inject(ViewContainerRef); } @Component({ selector: 'arbitrary-component', template: `@if (childComponentExists()) {<dir-with-view-container></dir-with-view-container>}`, standalone: true, imports: [DirectiveWithViewContainer], changeDetection: ChangeDetectionStrategy.OnPush, }) class ComponentWithChildViewContainer { @ViewChild(DirectiveWithViewContainer) childWithViewContainer: DirectiveWithViewContainer; childComponentExists = signal(true); get childViewContainer() { return this.childWithViewContainer.viewContainerRef; } } @Component({ selector: 'arbitrary-component-with-template-ref', template: ` <ng-template let-data> Fries {{localValue}} {{data?.value}} </ng-template> `, standalone: true, }) class ComponentWithTemplateRef { @ViewChild(TemplateRef) templateRef: TemplateRef<any>; localValue: string; } /** Simple component for testing ComponentPortal. */ @Component({ template: '<p>Burritos are on the way.</p>', standalone: true, }) class BurritosNotification { snackBarRef = inject<MatSnackBarRef<BurritosNotification>>(MatSnackBarRef); data = inject(MAT_SNACK_BAR_DATA); } @Component({ template: '', providers: [MatSnackBar], standalone: true, }) class ComponentThatProvidesMatSnackBar { snackBar = inject(MatSnackBar); }
{ "end_byte": 41171, "start_byte": 38899, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar.spec.ts" }
components/src/material/snack-bar/README.md_0_100
Please see the official documentation at https://material.angular.io/components/component/snack-bar
{ "end_byte": 100, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/README.md" }
components/src/material/snack-bar/simple-snack-bar.ts_0_1644
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ChangeDetectionStrategy, Component, ViewEncapsulation, inject} from '@angular/core'; import {MatButton} from '@angular/material/button'; import {MatSnackBarRef} from './snack-bar-ref'; import {MAT_SNACK_BAR_DATA} from './snack-bar-config'; import {MatSnackBarAction, MatSnackBarActions, MatSnackBarLabel} from './snack-bar-content'; /** * Interface for a simple snack bar component that has a message and a single action. */ export interface TextOnlySnackBar { data: {message: string; action: string}; snackBarRef: MatSnackBarRef<TextOnlySnackBar>; action: () => void; hasAction: boolean; } @Component({ selector: 'simple-snack-bar', templateUrl: 'simple-snack-bar.html', styleUrl: 'simple-snack-bar.css', exportAs: 'matSnackBar', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, imports: [MatButton, MatSnackBarLabel, MatSnackBarActions, MatSnackBarAction], host: { 'class': 'mat-mdc-simple-snack-bar', }, }) export class SimpleSnackBar implements TextOnlySnackBar { snackBarRef = inject<MatSnackBarRef<SimpleSnackBar>>(MatSnackBarRef); data = inject(MAT_SNACK_BAR_DATA); constructor(...args: unknown[]); constructor() {} /** Performs the action on the snack bar. */ action(): void { this.snackBarRef.dismissWithAction(); } /** If the action button should be shown. */ get hasAction(): boolean { return !!this.data.action; } }
{ "end_byte": 1644, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/simple-snack-bar.ts" }
components/src/material/snack-bar/BUILD.bazel_0_1800
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 = "snack-bar", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), assets = [ ":simple_snack_bar_scss", ":snack_bar_container_scss", ] + glob(["**/*.html"]), deps = [ "//src:dev_mode_types", "//src/cdk/overlay", "//src/cdk/portal", "//src/material/button", "//src/material/core", "@npm//@angular/core", ], ) sass_library( name = "snack_bar_scss_lib", srcs = glob(["**/_*.scss"]), deps = [ "//src/material/core:core_scss_lib", ], ) sass_binary( name = "simple_snack_bar_scss", src = "simple-snack-bar.scss", ) sass_binary( name = "snack_bar_container_scss", src = "snack-bar-container.scss", deps = [ "//src/cdk:sass_lib", "//src/material/core:core_scss_lib", ], ) ########### # Testing ########### ng_test_library( name = "unit_test_sources", srcs = glob( ["**/*.spec.ts"], exclude = ["**/*.e2e.spec.ts"], ), deps = [ ":snack-bar", "//src/cdk/a11y", "//src/cdk/overlay", "//src/cdk/platform", "@npm//@angular/common", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":unit_test_sources", ], ) markdown_to_html( name = "overview", srcs = [":snack-bar.md"], ) extract_tokens( name = "tokens", srcs = [":snack_bar_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "end_byte": 1800, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/BUILD.bazel" }
components/src/material/snack-bar/simple-snack-bar.scss_0_225
// The label and actions expect to be in a flex container. Since this component adds another // wrapping layer to the mdc-snackbar__surface, it should also include flex display. .mat-mdc-simple-snack-bar { display: flex; }
{ "end_byte": 225, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/simple-snack-bar.scss" }
components/src/material/snack-bar/snack-bar-content.ts_0_1008
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Directive} from '@angular/core'; /** Directive that should be applied to the text element to be rendered in the snack bar. */ @Directive({ selector: `[matSnackBarLabel]`, host: { 'class': 'mat-mdc-snack-bar-label mdc-snackbar__label', }, }) export class MatSnackBarLabel {} /** Directive that should be applied to the element containing the snack bar's action buttons. */ @Directive({ selector: `[matSnackBarActions]`, host: { 'class': 'mat-mdc-snack-bar-actions mdc-snackbar__actions', }, }) export class MatSnackBarActions {} /** Directive that should be applied to each of the snack bar's action buttons. */ @Directive({ selector: `[matSnackBarAction]`, host: { 'class': 'mat-mdc-snack-bar-action mdc-snackbar__action', }, }) export class MatSnackBarAction {}
{ "end_byte": 1008, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar-content.ts" }
components/src/material/snack-bar/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/snack-bar/index.ts" }
components/src/material/snack-bar/snack-bar-container.ts_0_1817
/** * @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, ChangeDetectorRef, Component, ComponentRef, ElementRef, EmbeddedViewRef, inject, NgZone, OnDestroy, ViewChild, ViewEncapsulation, } from '@angular/core'; import {DOCUMENT} from '@angular/common'; import {matSnackBarAnimations} from './snack-bar-animations'; import { BasePortalOutlet, CdkPortalOutlet, ComponentPortal, DomPortal, TemplatePortal, } from '@angular/cdk/portal'; import {Observable, Subject} from 'rxjs'; import {AriaLivePoliteness} from '@angular/cdk/a11y'; import {Platform} from '@angular/cdk/platform'; import {AnimationEvent} from '@angular/animations'; import {MatSnackBarConfig} from './snack-bar-config'; let uniqueId = 0; /** * Internal component that wraps user-provided snack bar content. * @docs-private */ @Component({ selector: 'mat-snack-bar-container', templateUrl: 'snack-bar-container.html', styleUrl: 'snack-bar-container.css', // In Ivy embedded views will be change detected from their declaration place, rather than // where they were stamped out. This means that we can't have the snack bar container be OnPush, // because it might cause snack bars that were opened from a template not to be out of date. // tslint:disable-next-line:validate-decorators changeDetection: ChangeDetectionStrategy.Default, encapsulation: ViewEncapsulation.None, animations: [matSnackBarAnimations.snackBarState], imports: [CdkPortalOutlet], host: { 'class': 'mdc-snackbar mat-mdc-snack-bar-container', '[@state]': '_animationState', '(@state.done)': 'onAnimationEnd($event)', }, }) export
{ "end_byte": 1817, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar-container.ts" }
components/src/material/snack-bar/snack-bar-container.ts_1818_9722
class MatSnackBarContainer extends BasePortalOutlet implements OnDestroy { private _ngZone = inject(NgZone); private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef); private _changeDetectorRef = inject(ChangeDetectorRef); private _platform = inject(Platform); snackBarConfig = inject(MatSnackBarConfig); private _document = inject(DOCUMENT); private _trackedModals = new Set<Element>(); /** The number of milliseconds to wait before announcing the snack bar's content. */ private readonly _announceDelay: number = 150; /** The timeout for announcing the snack bar's content. */ private _announceTimeoutId: number; /** Whether the component has been destroyed. */ private _destroyed = false; /** The portal outlet inside of this container into which the snack bar content will be loaded. */ @ViewChild(CdkPortalOutlet, {static: true}) _portalOutlet: CdkPortalOutlet; /** Subject for notifying that the snack bar has announced to screen readers. */ readonly _onAnnounce: Subject<void> = new Subject(); /** Subject for notifying that the snack bar has exited from view. */ readonly _onExit: Subject<void> = new Subject(); /** Subject for notifying that the snack bar has finished entering the view. */ readonly _onEnter: Subject<void> = new Subject(); /** The state of the snack bar animations. */ _animationState = 'void'; /** aria-live value for the live region. */ _live: AriaLivePoliteness; /** * Element that will have the `mdc-snackbar__label` class applied if the attached component * or template does not have it. This ensures that the appropriate structure, typography, and * color is applied to the attached view. */ @ViewChild('label', {static: true}) _label: ElementRef; /** * Role of the live region. This is only for Firefox as there is a known issue where Firefox + * JAWS does not read out aria-live message. */ _role?: 'status' | 'alert'; /** Unique ID of the aria-live element. */ readonly _liveElementId = `mat-snack-bar-container-live-${uniqueId++}`; constructor(...args: unknown[]); constructor() { super(); const config = this.snackBarConfig; // Use aria-live rather than a live role like 'alert' or 'status' // because NVDA and JAWS have show inconsistent behavior with live roles. if (config.politeness === 'assertive' && !config.announcementMessage) { this._live = 'assertive'; } else if (config.politeness === 'off') { this._live = 'off'; } else { this._live = 'polite'; } // Only set role for Firefox. Set role based on aria-live because setting role="alert" implies // aria-live="assertive" which may cause issues if aria-live is set to "polite" above. if (this._platform.FIREFOX) { if (this._live === 'polite') { this._role = 'status'; } if (this._live === 'assertive') { this._role = 'alert'; } } } /** Attach a component portal as content to this snack bar container. */ attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> { this._assertNotAttached(); const result = this._portalOutlet.attachComponentPortal(portal); this._afterPortalAttached(); return result; } /** Attach a template portal as content to this snack bar container. */ attachTemplatePortal<C>(portal: TemplatePortal<C>): EmbeddedViewRef<C> { this._assertNotAttached(); const result = this._portalOutlet.attachTemplatePortal(portal); this._afterPortalAttached(); return result; } /** * Attaches a DOM portal to the snack bar container. * @deprecated To be turned into a method. * @breaking-change 10.0.0 */ override attachDomPortal = (portal: DomPortal) => { this._assertNotAttached(); const result = this._portalOutlet.attachDomPortal(portal); this._afterPortalAttached(); return result; }; /** Handle end of animations, updating the state of the snackbar. */ onAnimationEnd(event: AnimationEvent) { const {fromState, toState} = event; if ((toState === 'void' && fromState !== 'void') || toState === 'hidden') { this._completeExit(); } if (toState === 'visible') { // Note: we shouldn't use `this` inside the zone callback, // because it can cause a memory leak. const onEnter = this._onEnter; this._ngZone.run(() => { onEnter.next(); onEnter.complete(); }); } } /** Begin animation of snack bar entrance into view. */ enter(): void { if (!this._destroyed) { this._animationState = 'visible'; // _animationState lives in host bindings and `detectChanges` does not refresh host bindings // so we have to call `markForCheck` to ensure the host view is refreshed eventually. this._changeDetectorRef.markForCheck(); this._changeDetectorRef.detectChanges(); this._screenReaderAnnounce(); } } /** Begin animation of the snack bar exiting from view. */ exit(): Observable<void> { // It's common for snack bars to be opened by random outside calls like HTTP requests or // errors. Run inside the NgZone to ensure that it functions correctly. this._ngZone.run(() => { // Note: this one transitions to `hidden`, rather than `void`, in order to handle the case // where multiple snack bars are opened in quick succession (e.g. two consecutive calls to // `MatSnackBar.open`). this._animationState = 'hidden'; this._changeDetectorRef.markForCheck(); // Mark this element with an 'exit' attribute to indicate that the snackbar has // been dismissed and will soon be removed from the DOM. This is used by the snackbar // test harness. this._elementRef.nativeElement.setAttribute('mat-exit', ''); // If the snack bar hasn't been announced by the time it exits it wouldn't have been open // long enough to visually read it either, so clear the timeout for announcing. clearTimeout(this._announceTimeoutId); }); return this._onExit; } /** Makes sure the exit callbacks have been invoked when the element is destroyed. */ ngOnDestroy() { this._destroyed = true; this._clearFromModals(); this._completeExit(); } /** * Removes the element in a microtask. Helps prevent errors where we end up * removing an element which is in the middle of an animation. */ private _completeExit() { queueMicrotask(() => { this._onExit.next(); this._onExit.complete(); }); } /** * Called after the portal contents have been attached. Can be * used to modify the DOM once it's guaranteed to be in place. */ private _afterPortalAttached() { const element: HTMLElement = this._elementRef.nativeElement; const panelClasses = this.snackBarConfig.panelClass; if (panelClasses) { if (Array.isArray(panelClasses)) { // Note that we can't use a spread here, because IE doesn't support multiple arguments. panelClasses.forEach(cssClass => element.classList.add(cssClass)); } else { element.classList.add(panelClasses); } } this._exposeToModals(); // Check to see if the attached component or template uses the MDC template structure, // specifically the MDC label. If not, the container should apply the MDC label class to this // component's label container, which will apply MDC's label styles to the attached view. const label = this._label.nativeElement; const labelClass = 'mdc-snackbar__label'; label.classList.toggle(labelClass, !label.querySelector(`.${labelClass}`)); } /** * Some browsers won't expose the accessibility node of the live element if there is an * `aria-modal` and the live element is outside of it. This method works around the issue by * pointing the `aria-owns` of all modals to the live element. */
{ "end_byte": 9722, "start_byte": 1818, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar-container.ts" }
components/src/material/snack-bar/snack-bar-container.ts_9725_12833
private _exposeToModals() { // TODO(http://github.com/angular/components/issues/26853): consider de-duplicating this with the // `LiveAnnouncer` and any other usages. // // Note that the selector here is limited to CDK overlays at the moment in order to reduce the // section of the DOM we need to look through. This should cover all the cases we support, but // the selector can be expanded if it turns out to be too narrow. const id = this._liveElementId; const modals = this._document.querySelectorAll( 'body > .cdk-overlay-container [aria-modal="true"]', ); for (let i = 0; i < modals.length; i++) { const modal = modals[i]; const ariaOwns = modal.getAttribute('aria-owns'); this._trackedModals.add(modal); if (!ariaOwns) { modal.setAttribute('aria-owns', id); } else if (ariaOwns.indexOf(id) === -1) { modal.setAttribute('aria-owns', ariaOwns + ' ' + id); } } } /** Clears the references to the live element from any modals it was added to. */ private _clearFromModals() { this._trackedModals.forEach(modal => { const ariaOwns = modal.getAttribute('aria-owns'); if (ariaOwns) { const newValue = ariaOwns.replace(this._liveElementId, '').trim(); if (newValue.length > 0) { modal.setAttribute('aria-owns', newValue); } else { modal.removeAttribute('aria-owns'); } } }); this._trackedModals.clear(); } /** Asserts that no content is already attached to the container. */ private _assertNotAttached() { if (this._portalOutlet.hasAttached() && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error('Attempting to attach snack bar content after content is already attached'); } } /** * Starts a timeout to move the snack bar content to the live region so screen readers will * announce it. */ private _screenReaderAnnounce() { if (!this._announceTimeoutId) { this._ngZone.runOutsideAngular(() => { this._announceTimeoutId = setTimeout(() => { const inertElement = this._elementRef.nativeElement.querySelector('[aria-hidden]'); const liveElement = this._elementRef.nativeElement.querySelector('[aria-live]'); if (inertElement && liveElement) { // If an element in the snack bar content is focused before being moved // track it and restore focus after moving to the live region. let focusedElement: HTMLElement | null = null; if ( this._platform.isBrowser && document.activeElement instanceof HTMLElement && inertElement.contains(document.activeElement) ) { focusedElement = document.activeElement; } inertElement.removeAttribute('aria-hidden'); liveElement.appendChild(inertElement); focusedElement?.focus(); this._onAnnounce.next(); this._onAnnounce.complete(); } }, this._announceDelay); }); } } }
{ "end_byte": 12833, "start_byte": 9725, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar-container.ts" }
components/src/material/snack-bar/snack-bar-ref.ts_0_4028
/** * @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 {OverlayRef} from '@angular/cdk/overlay'; import {Observable, Subject} from 'rxjs'; import {MatSnackBarContainer} from './snack-bar-container'; /** Event that is emitted when a snack bar is dismissed. */ export interface MatSnackBarDismiss { /** Whether the snack bar was dismissed using the action button. */ dismissedByAction: boolean; } /** Maximum amount of milliseconds that can be passed into setTimeout. */ const MAX_TIMEOUT = Math.pow(2, 31) - 1; /** * Reference to a snack bar dispatched from the snack bar service. */ export class MatSnackBarRef<T> { /** The instance of the component making up the content of the snack bar. */ instance: T; /** * The instance of the component making up the content of the snack bar. * @docs-private */ containerInstance: MatSnackBarContainer; /** Subject for notifying the user that the snack bar has been dismissed. */ private readonly _afterDismissed = new Subject<MatSnackBarDismiss>(); /** Subject for notifying the user that the snack bar has opened and appeared. */ private readonly _afterOpened = new Subject<void>(); /** Subject for notifying the user that the snack bar action was called. */ private readonly _onAction = new Subject<void>(); /** * Timeout ID for the duration setTimeout call. Used to clear the timeout if the snackbar is * dismissed before the duration passes. */ private _durationTimeoutId: number; /** Whether the snack bar was dismissed using the action button. */ private _dismissedByAction = false; constructor( containerInstance: MatSnackBarContainer, private _overlayRef: OverlayRef, ) { this.containerInstance = containerInstance; containerInstance._onExit.subscribe(() => this._finishDismiss()); } /** Dismisses the snack bar. */ dismiss(): void { if (!this._afterDismissed.closed) { this.containerInstance.exit(); } clearTimeout(this._durationTimeoutId); } /** Marks the snackbar action clicked. */ dismissWithAction(): void { if (!this._onAction.closed) { this._dismissedByAction = true; this._onAction.next(); this._onAction.complete(); this.dismiss(); } clearTimeout(this._durationTimeoutId); } /** * Marks the snackbar action clicked. * @deprecated Use `dismissWithAction` instead. * @breaking-change 8.0.0 */ closeWithAction(): void { this.dismissWithAction(); } /** Dismisses the snack bar after some duration */ _dismissAfter(duration: number): void { // Note that we need to cap the duration to the maximum value for setTimeout, because // it'll revert to 1 if somebody passes in something greater (e.g. `Infinity`). See #17234. this._durationTimeoutId = setTimeout(() => this.dismiss(), Math.min(duration, MAX_TIMEOUT)); } /** Marks the snackbar as opened */ _open(): void { if (!this._afterOpened.closed) { this._afterOpened.next(); this._afterOpened.complete(); } } /** Cleans up the DOM after closing. */ private _finishDismiss(): void { this._overlayRef.dispose(); if (!this._onAction.closed) { this._onAction.complete(); } this._afterDismissed.next({dismissedByAction: this._dismissedByAction}); this._afterDismissed.complete(); this._dismissedByAction = false; } /** Gets an observable that is notified when the snack bar is finished closing. */ afterDismissed(): Observable<MatSnackBarDismiss> { return this._afterDismissed; } /** Gets an observable that is notified when the snack bar has opened and appeared. */ afterOpened(): Observable<void> { return this.containerInstance._onEnter; } /** Gets an observable that is notified when the snack bar action is called. */ onAction(): Observable<void> { return this._onAction; } }
{ "end_byte": 4028, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/snack-bar-ref.ts" }
components/src/material/snack-bar/simple-snack-bar.html_0_203
<div matSnackBarLabel> {{data.message}} </div> @if (hasAction) { <div matSnackBarActions> <button mat-button matSnackBarAction (click)="action()"> {{data.action}} </button> </div> }
{ "end_byte": 203, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/simple-snack-bar.html" }
components/src/material/snack-bar/testing/snack-bar-harness.spec.ts_0_7641
import {Component, TemplateRef, ViewChild, inject} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {HarnessLoader} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import { MatSnackBar, MatSnackBarAction, MatSnackBarActions, MatSnackBarConfig, MatSnackBarLabel, } from '@angular/material/snack-bar'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {MatSnackBarHarness} from './snack-bar-harness'; describe('MatSnackBarHarness', () => { let fixture: ComponentFixture<SnackbarHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ imports: [NoopAnimationsModule], }); fixture = TestBed.createComponent(SnackbarHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.documentRootLoader(fixture); }); it('should load harness for simple snack-bar', async () => { const snackBarRef = fixture.componentInstance.openSimple('Hello!', ''); let snackBars = await loader.getAllHarnesses(MatSnackBarHarness); expect(snackBars.length).toBe(1); snackBarRef.dismiss(); snackBars = await loader.getAllHarnesses(MatSnackBarHarness); expect(snackBars.length).toBe(0); }); it('should load harness for custom snack-bar', async () => { const snackBarRef = fixture.componentInstance.openCustom(); let snackBars = await loader.getAllHarnesses(MatSnackBarHarness); expect(snackBars.length).toBe(1); snackBarRef.dismiss(); snackBars = await loader.getAllHarnesses(MatSnackBarHarness); expect(snackBars.length).toBe(0); }); it('should load snack-bar harness by selector', async () => { fixture.componentInstance.openSimple('Hello!', '', {panelClass: 'my-snack-bar'}); const snackBars = await loader.getAllHarnesses( MatSnackBarHarness.with({ selector: '.my-snack-bar', }), ); expect(snackBars.length).toBe(1); }); it('should be able to get role of snack-bar', async () => { // Get role is now deprecated, so it should always return null. fixture.componentInstance.openCustom(); let snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.getRole()).toBe(null); fixture.componentInstance.openCustom({politeness: 'polite'}); snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.getRole()).toBe(null); fixture.componentInstance.openCustom({politeness: 'off'}); snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.getRole()).toBe(null); }); it('should be able to get aria-live of snack-bar', async () => { fixture.componentInstance.openCustom(); let snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.getAriaLive()).toBe('assertive'); fixture.componentInstance.openCustom({politeness: 'polite'}); snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.getAriaLive()).toBe('polite'); fixture.componentInstance.openCustom({politeness: 'off'}); snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.getAriaLive()).toBe('off'); }); it('should be able to get message of simple snack-bar', async () => { fixture.componentInstance.openSimple('Subscribed to newsletter.'); let snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.getMessage()).toBe('Subscribed to newsletter.'); }); it('should be able to get action description of simple snack-bar', async () => { fixture.componentInstance.openSimple('Hello', 'Unsubscribe'); let snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.getActionDescription()).toBe('Unsubscribe'); }); it('should be able to check whether simple snack-bar has action', async () => { fixture.componentInstance.openSimple('With action', 'Unsubscribe'); let snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.hasAction()).toBe(true); fixture.componentInstance.openSimple('No action'); snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.hasAction()).toBe(false); }); it('should be able to dismiss simple snack-bar with action', async () => { const snackBarRef = fixture.componentInstance.openSimple('With action', 'Unsubscribe'); let snackBar = await loader.getHarness(MatSnackBarHarness); let actionCount = 0; snackBarRef.onAction().subscribe(() => actionCount++); expect(await snackBar.isDismissed()) .withContext('The snackbar should be present in the DOM before dismiss') .toBe(false); await snackBar.dismissWithAction(); expect(actionCount).toBe(1); expect(await snackBar.isDismissed()) .withContext('The snackbar should be absent from the DOM after dismiss') .toBe(true); fixture.componentInstance.openSimple('No action'); snackBar = await loader.getHarness(MatSnackBarHarness); await expectAsync(snackBar.dismissWithAction()).toBeRejectedWithError(/without an action/); }); it('should be able to get message of a snack-bar with custom content', async () => { fixture.componentInstance.openCustom(); let snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.getMessage()).toBe('My custom snack-bar.'); fixture.componentInstance.openCustomWithAction(); snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.getMessage()).toBe('My custom snack-bar with action.'); }); it('should fail to get action description of a snack-bar with no action', async () => { fixture.componentInstance.openCustom(); const snackBar = await loader.getHarness(MatSnackBarHarness); await expectAsync(snackBar.getActionDescription()).toBeRejectedWithError(/without an action/); }); it('should be able to get action description of a snack-bar with an action', async () => { fixture.componentInstance.openCustomWithAction(); const snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.getActionDescription()).toBe('Ok'); }); it('should be able to check whether a snack-bar with custom content has an action', async () => { fixture.componentInstance.openCustom(); let snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.hasAction()).toBe(false); fixture.componentInstance.openCustomWithAction(); snackBar = await loader.getHarness(MatSnackBarHarness); expect(await snackBar.hasAction()).toBe(true); }); }); @Component({ template: ` <ng-template #custom>My custom snack-bar.</ng-template> <ng-template #customWithAction> <span matSnackBarLabel>My custom snack-bar with action.</span> <div matSnackBarActions><button matSnackBarAction>Ok</button></div> </ng-template> `, standalone: true, imports: [MatSnackBarLabel, MatSnackBarActions, MatSnackBarAction], }) class SnackbarHarnessTest { snackBar = inject(MatSnackBar); @ViewChild('custom') customTmpl: TemplateRef<any>; @ViewChild('customWithAction') customWithActionTmpl: TemplateRef<any>; openSimple(message: string, action = '', config?: MatSnackBarConfig) { return this.snackBar.open(message, action, config); } openCustom(config?: MatSnackBarConfig) { return this.snackBar.openFromTemplate(this.customTmpl, config); } openCustomWithAction(config?: MatSnackBarConfig) { return this.snackBar.openFromTemplate(this.customWithActionTmpl, config); } }
{ "end_byte": 7641, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/testing/snack-bar-harness.spec.ts" }
components/src/material/snack-bar/testing/snack-bar-harness.ts_0_4402
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ContentContainerComponentHarness, HarnessPredicate, parallel} from '@angular/cdk/testing'; import {AriaLivePoliteness} from '@angular/cdk/a11y'; import {SnackBarHarnessFilters} from './snack-bar-harness-filters'; /** Harness for interacting with a mat-snack-bar in tests. */ export class MatSnackBarHarness extends ContentContainerComponentHarness<string> { // Developers can provide a custom component or template for the // snackbar. The canonical snack-bar parent is the "MatSnackBarContainer". /** The selector for the host element of a `MatSnackBar` instance. */ static hostSelector = '.mat-mdc-snack-bar-container:not([mat-exit])'; private _messageSelector = '.mdc-snackbar__label'; private _actionButtonSelector = '.mat-mdc-snack-bar-action'; private _snackBarLiveRegion = this.locatorFor('[aria-live]'); /** * Gets a `HarnessPredicate` that can be used to search for a `MatSnackBarHarness` that meets * certain criteria. * @param options Options for filtering which snack bar instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with(options: SnackBarHarnessFilters = {}): HarnessPredicate<MatSnackBarHarness> { return new HarnessPredicate(MatSnackBarHarness, options); } /** * Gets the role of the snack-bar. The role of a snack-bar is determined based * on the ARIA politeness specified in the snack-bar config. * @deprecated Use `getAriaLive` instead. * @breaking-change 13.0.0 */ async getRole(): Promise<'alert' | 'status' | null> { return (await this.host()).getAttribute('role') as Promise<'alert' | 'status' | null>; } /** * Gets the aria-live of the snack-bar's live region. The aria-live of a snack-bar is * determined based on the ARIA politeness specified in the snack-bar config. */ async getAriaLive(): Promise<AriaLivePoliteness> { return (await this._snackBarLiveRegion()).getAttribute( 'aria-live', ) as Promise<AriaLivePoliteness>; } /** * Whether the snack-bar has an action. Method cannot be used for snack-bar's with custom content. */ async hasAction(): Promise<boolean> { return (await this._getActionButton()) !== null; } /** * Gets the description of the snack-bar. Method cannot be used for snack-bar's without action or * with custom content. */ async getActionDescription(): Promise<string> { await this._assertHasAction(); return (await this._getActionButton())!.text(); } /** * Dismisses the snack-bar by clicking the action button. Method cannot be used for snack-bar's * without action or with custom content. */ async dismissWithAction(): Promise<void> { await this._assertHasAction(); await (await this._getActionButton())!.click(); } /** * Gets the message of the snack-bar. Method cannot be used for snack-bar's with custom content. */ async getMessage(): Promise<string> { return (await this.locatorFor(this._messageSelector)()).text(); } /** Gets whether the snack-bar has been dismissed. */ async isDismissed(): Promise<boolean> { // We consider the snackbar dismissed if it's not in the DOM. We can assert that the // element isn't in the DOM by seeing that its width and height are zero. const host = await this.host(); const [exit, dimensions] = await parallel(() => [ // The snackbar container is marked with the "exit" attribute after it has been dismissed // but before the animation has finished (after which it's removed from the DOM). host.getAttribute('mat-exit'), host.getDimensions(), ]); return exit != null || (!!dimensions && dimensions.height === 0 && dimensions.width === 0); } /** * Asserts that the current snack-bar has an action defined. Otherwise the * promise will reject. */ private async _assertHasAction(): Promise<void> { if (!(await this.hasAction())) { throw Error('Method cannot be used for a snack-bar without an action.'); } } /** Gets the simple snack bar action button. */ private async _getActionButton() { return this.locatorForOptional(this._actionButtonSelector)(); } }
{ "end_byte": 4402, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/testing/snack-bar-harness.ts" }
components/src/material/snack-bar/testing/public-api.ts_0_286
/** * @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 './snack-bar-harness'; export * from './snack-bar-harness-filters';
{ "end_byte": 286, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/testing/public-api.ts" }
components/src/material/snack-bar/testing/snack-bar-harness-filters.ts_0_426
/** * @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 `MatSnackBarHarness` instances. */ export interface SnackBarHarnessFilters extends BaseHarnessFilters {}
{ "end_byte": 426, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/testing/snack-bar-harness-filters.ts" }
components/src/material/snack-bar/testing/BUILD.bazel_0_831
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/a11y", "//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/snack-bar", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":unit_tests_lib", ], )
{ "end_byte": 831, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/snack-bar/testing/BUILD.bazel" }
components/src/material/snack-bar/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/snack-bar/testing/index.ts" }
components/src/material/paginator/paginator.spec.ts_0_667
import {dispatchMouseEvent} from '@angular/cdk/testing/private'; import {ChangeDetectorRef, Component, Provider, Type, ViewChild, inject} from '@angular/core'; import {ComponentFixture, TestBed, fakeAsync, tick} from '@angular/core/testing'; import {ThemePalette} from '@angular/material/core'; import {MatSelect} from '@angular/material/select'; import {By} from '@angular/platform-browser'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import { MatPaginator, MatPaginatorIntl, MatPaginatorModule, MatPaginatorSelectConfig, } from './index'; import {MAT_PAGINATOR_DEFAULT_OPTIONS, MatPaginatorDefaultOptions} from './paginator';
{ "end_byte": 667, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/paginator.spec.ts" }
components/src/material/paginator/paginator.spec.ts_669_10047
describe('MatPaginator', () => { function createComponent<T>(type: Type<T>, providers: Provider[] = []): ComponentFixture<T> { TestBed.configureTestingModule({ imports: [MatPaginatorModule, NoopAnimationsModule], providers: [MatPaginatorIntl, ...providers], declarations: [type], }); const fixture = TestBed.createComponent(type); fixture.detectChanges(); return fixture; } describe('with the default internationalization provider', () => { describe('showing the right range text', () => { it('should show second page of list of 100, each page contains 10 items', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const rangeElement = fixture.nativeElement.querySelector('.mat-mdc-paginator-range-label'); component.length = 100; component.pageSize = 10; component.pageIndex = 1; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(rangeElement.textContent!.trim()).toBe('11 – 20 of 100'); }); it('should show third page of list of 200, each page contains 20 items', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const rangeElement = fixture.nativeElement.querySelector('.mat-mdc-paginator-range-label'); component.length = 200; component.pageSize = 20; component.pageIndex = 2; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(rangeElement.textContent!.trim()).toBe('41 – 60 of 200'); }); it('should show first page of list of 0, each page contains 5 items', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const rangeElement = fixture.nativeElement.querySelector('.mat-mdc-paginator-range-label'); component.length = 0; component.pageSize = 5; component.pageIndex = 2; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(rangeElement.textContent!.trim()).toBe('0 of 0'); }); it('should show third page of list of 12, each page contains 5 items', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const rangeElement = fixture.nativeElement.querySelector('.mat-mdc-paginator-range-label'); component.length = 12; component.pageSize = 5; component.pageIndex = 2; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(rangeElement.textContent!.trim()).toBe('11 – 12 of 12'); }); it('should show third page of list of 10, each page contains 5 items', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const rangeElement = fixture.nativeElement.querySelector('.mat-mdc-paginator-range-label'); component.length = 10; component.pageSize = 5; component.pageIndex = 2; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(rangeElement.textContent!.trim()).toBe('11 – 15 of 10'); }); it('should show third page of list of -5, each page contains 5 items', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const rangeElement = fixture.nativeElement.querySelector('.mat-mdc-paginator-range-label'); component.length = -5; component.pageSize = 5; component.pageIndex = 2; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(rangeElement.textContent!.trim()).toBe('11 – 15 of 0'); }); }); it('should show right aria-labels for select and buttons', () => { const fixture = createComponent(MatPaginatorApp); expect(getPreviousButton(fixture).getAttribute('aria-label')).toBe('Previous page'); expect(getNextButton(fixture).getAttribute('aria-label')).toBe('Next page'); const select = fixture.nativeElement.querySelector('.mat-mdc-select'); const selectLabelIds = select.getAttribute('aria-labelledby')?.split(/\s/g) as string[]; const selectLabelTexts = selectLabelIds?.map(labelId => { return fixture.nativeElement.querySelector(`#${labelId}`)?.textContent?.trim(); }); expect(selectLabelTexts).toContain('Items per page:'); }); it('should re-render when the i18n labels change', () => { const fixture = createComponent(MatPaginatorApp); const label = fixture.nativeElement.querySelector('.mat-mdc-paginator-page-size-label'); const intl = TestBed.inject(MatPaginatorIntl); intl.itemsPerPageLabel = '1337 items per page'; intl.changes.next(); fixture.detectChanges(); expect(label.textContent!.trim()).toBe('1337 items per page'); }); }); describe('when navigating with the next and previous buttons', () => { it('should be able to go to the next page', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const paginator = component.paginator; expect(paginator.pageIndex).toBe(0); dispatchMouseEvent(getNextButton(fixture), 'click'); expect(paginator.pageIndex).toBe(1); expect(component.pageEvent).toHaveBeenCalledWith( jasmine.objectContaining({ previousPageIndex: 0, pageIndex: 1, }), ); }); it('should be able to go to the previous page', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const paginator = component.paginator; paginator.pageIndex = 1; fixture.detectChanges(); expect(paginator.pageIndex).toBe(1); dispatchMouseEvent(getPreviousButton(fixture), 'click'); expect(paginator.pageIndex).toBe(0); expect(component.pageEvent).toHaveBeenCalledWith( jasmine.objectContaining({ previousPageIndex: 1, pageIndex: 0, }), ); }); }); it('should be able to show the first/last buttons', () => { const fixture = createComponent(MatPaginatorApp); expect(getFirstButton(fixture)).withContext('Expected first button to not exist.').toBeNull(); expect(getLastButton(fixture)).withContext('Expected last button to not exist.').toBeNull(); fixture.componentInstance.showFirstLastButtons = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(getFirstButton(fixture)) .withContext('Expected first button to be rendered.') .toBeTruthy(); expect(getLastButton(fixture)).withContext('Expected last button to be rendered.').toBeTruthy(); }); it('should mark itself as initialized', fakeAsync(() => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const paginator = component.paginator; let isMarkedInitialized = false; paginator.initialized.subscribe(() => (isMarkedInitialized = true)); tick(); expect(isMarkedInitialized).toBeTruthy(); })); it('should not allow a negative pageSize', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const paginator = component.paginator; paginator.pageSize = -1337; fixture.changeDetectorRef.markForCheck(); expect(paginator.pageSize).toBeGreaterThanOrEqual(0); }); it('should not allow a negative pageIndex', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const paginator = component.paginator; paginator.pageIndex = -42; expect(paginator.pageIndex).toBeGreaterThanOrEqual(0); }); it('should be able to set the color of the form field', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const formField: HTMLElement = fixture.nativeElement.querySelector('.mat-mdc-form-field'); component.color = 'accent'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(formField.classList).not.toContain('mat-warn'); expect(formField.classList).toContain('mat-accent'); component.color = 'warn'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(formField.classList).toContain('mat-warn'); expect(formField.classList).not.toContain('mat-accent'); }); it('should be able to pass options to the underlying mat-select', () => { const fixture = createComponent(MatPaginatorApp); fixture.detectChanges(); const select: MatSelect = fixture.debugElement.query(By.directive(MatSelect)).componentInstance; expect(select.disableOptionCentering).toBe(false); expect(select.panelClass).toBeFalsy(); fixture.componentInstance.selectConfig = { disableOptionCentering: true, panelClass: 'custom-class', }; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(select.disableOptionCentering).toBe(true); expect(select.panelClass).toBe('custom-class'); }); descri
{ "end_byte": 10047, "start_byte": 669, "url": "https://github.com/angular/components/blob/main/src/material/paginator/paginator.spec.ts" }
components/src/material/paginator/paginator.spec.ts_10051_19409
when showing the first and last button', () => { let fixture: ComponentFixture<MatPaginatorApp>; let component: MatPaginatorApp; let paginator: MatPaginator; beforeEach(() => { fixture = createComponent(MatPaginatorApp); component = fixture.componentInstance; paginator = component.paginator; component.showFirstLastButtons = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); }); it('should show right aria-labels for first/last buttons', () => { expect(getFirstButton(fixture).getAttribute('aria-label')).toBe('First page'); expect(getLastButton(fixture).getAttribute('aria-label')).toBe('Last page'); }); it('should be able to go to the last page via the last page button', () => { expect(paginator.pageIndex).toBe(0); dispatchMouseEvent(getLastButton(fixture), 'click'); expect(paginator.pageIndex).toBe(9); expect(component.pageEvent).toHaveBeenCalledWith( jasmine.objectContaining({ previousPageIndex: 0, pageIndex: 9, }), ); }); it('should be able to go to the first page via the first page button', () => { paginator.pageIndex = 3; fixture.detectChanges(); expect(paginator.pageIndex).toBe(3); dispatchMouseEvent(getFirstButton(fixture), 'click'); expect(paginator.pageIndex).toBe(0); expect(component.pageEvent).toHaveBeenCalledWith( jasmine.objectContaining({ previousPageIndex: 3, pageIndex: 0, }), ); }); it('should disable navigating to the next page if at last page', () => { component.goToLastPage(); fixture.detectChanges(); expect(paginator.pageIndex).toBe(9); expect(paginator.hasNextPage()).toBe(false); component.pageEvent.calls.reset(); dispatchMouseEvent(getNextButton(fixture), 'click'); expect(component.pageEvent).not.toHaveBeenCalled(); expect(paginator.pageIndex).toBe(9); }); it('should disable navigating to the previous page if at first page', () => { expect(paginator.pageIndex).toBe(0); expect(paginator.hasPreviousPage()).toBe(false); component.pageEvent.calls.reset(); dispatchMouseEvent(getPreviousButton(fixture), 'click'); expect(component.pageEvent).not.toHaveBeenCalled(); expect(paginator.pageIndex).toBe(0); }); }); it('should mark for check when inputs are changed directly', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const paginator = component.paginator; const rangeElement = fixture.nativeElement.querySelector('.mat-mdc-paginator-range-label'); expect(rangeElement.innerText.trim()).toBe('1 – 10 of 100'); paginator.length = 99; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(rangeElement.innerText.trim()).toBe('1 – 10 of 99'); paginator.pageSize = 6; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(rangeElement.innerText.trim()).toBe('1 – 6 of 99'); paginator.pageIndex = 1; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(rangeElement.innerText.trim()).toBe('7 – 12 of 99'); // Having one option and the same page size should remove the select menu expect(fixture.nativeElement.querySelector('.mat-mdc-select')).not.toBeNull(); paginator.pageSize = 10; paginator.pageSizeOptions = [10]; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('.mat-mdc-select')).toBeNull(); }); it('should default the page size options to the page size if no options provided', () => { const fixture = createComponent(MatPaginatorWithoutOptionsApp); fixture.detectChanges(); expect(fixture.componentInstance.paginator._displayedPageSizeOptions).toEqual([10]); }); it('should default the page size to the first page size option if not provided', () => { const fixture = createComponent(MatPaginatorWithoutPageSizeApp); fixture.detectChanges(); expect(fixture.componentInstance.paginator.pageSize).toEqual(10); }); it('should show a sorted list of page size options including the current page size', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const paginator = component.paginator; expect(paginator._displayedPageSizeOptions).toEqual([5, 10, 25, 100]); component.pageSize = 30; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(paginator.pageSizeOptions).toEqual([5, 10, 25, 100]); expect(paginator._displayedPageSizeOptions).toEqual([5, 10, 25, 30, 100]); component.pageSizeOptions = [100, 25, 10, 5]; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(paginator._displayedPageSizeOptions).toEqual([5, 10, 25, 30, 100]); }); it('should be able to change the page size while keeping the first item present', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const paginator = component.paginator; // Start on the third page of a list of 100 with a page size of 10. component.pageIndex = 4; component.pageSize = 10; component.length = 100; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); // The first item of the page should be item with index 40 expect(paginator.pageIndex * paginator.pageSize).toBe(40); // The first item on the page is now 25. Change the page size to 25 so that we should now be // on the second page where the top item is index 25. component.pageEvent.calls.reset(); paginator._changePageSize(25); expect(component.pageEvent).toHaveBeenCalledWith( jasmine.objectContaining({ pageIndex: 1, pageSize: 25, }), ); // The first item on the page is still 25. Change the page size to 8 so that we should now be // on the fourth page where the top item is index 24. component.pageEvent.calls.reset(); paginator._changePageSize(8); expect(component.pageEvent).toHaveBeenCalledWith( jasmine.objectContaining({ pageIndex: 3, pageSize: 8, }), ); // The first item on the page is 24. Change the page size to 16 so that we should now be // on the first page where the top item is index 0. component.pageEvent.calls.reset(); paginator._changePageSize(25); expect(component.pageEvent).toHaveBeenCalledWith( jasmine.objectContaining({ pageIndex: 0, pageSize: 25, }), ); }); it('should keep track of the right number of pages', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const paginator = component.paginator; component.pageSize = 10; component.length = 100; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(paginator.getNumberOfPages()).toBe(10); component.pageSize = 10; component.length = 0; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(paginator.getNumberOfPages()).toBe(0); component.pageSize = 10; component.length = 10; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(paginator.getNumberOfPages()).toBe(1); }); it('should show a select only if there are multiple options', () => { const fixture = createComponent(MatPaginatorApp); const component = fixture.componentInstance; const paginator = component.paginator; expect(paginator._displayedPageSizeOptions).toEqual([5, 10, 25, 100]); expect(fixture.nativeElement.querySelector('.mat-mdc-select')).not.toBeNull(); // Remove options so that the paginator only uses the current page size (10) as an option. // Should no longer show the select component since there is only one option. component.pageSizeOptions = []; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('.mat-mdc-select')).toBeNull(); }); it('should handle the number inputs being passed in as strings', () => { const fixture = createComponent(MatPaginatorWithStringValues); fixture.detectChanges(); const withStringPaginator = fixture.componentInstance.paginator; expect(withStringPaginator.pageIndex).toEqual(0); expect(withStringPaginator.length).toEqual(100); expect(withStringPaginator.pageSize).toEqual(10); expect(withStringPaginator.pageSizeOptions).toEqual([5, 10, 25, 100]); }); it('should be able to hide the page size select', () => { const fixture = createComponent(MatPaginatorApp); const element = fixture.nativeElement; expect(element.querySelector('.mat-mdc-paginator-page-size')) .withContext('Expected select to be rendered.') .toBeTruthy(); fixture.componentInstance.hidePageSize = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(element.querySelector('.mat-mdc-paginator-page-size')) .withContext('Expected select to be removed.') .toBeNull(); }); it('should be
{ "end_byte": 19409, "start_byte": 10051, "url": "https://github.com/angular/components/blob/main/src/material/paginator/paginator.spec.ts" }
components/src/material/paginator/paginator.spec.ts_19413_24828
to disable all the controls in the paginator via the binding', () => { const fixture = createComponent(MatPaginatorApp); const select: MatSelect = fixture.debugElement.query( By.directive(MatSelect), )!.componentInstance; fixture.componentInstance.pageIndex = 1; fixture.componentInstance.showFirstLastButtons = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(select.disabled).toBe(false); expect(getPreviousButton(fixture).hasAttribute('disabled')).toBe(false); expect(getNextButton(fixture).hasAttribute('disabled')).toBe(false); expect(getFirstButton(fixture).hasAttribute('disabled')).toBe(false); expect(getLastButton(fixture).hasAttribute('disabled')).toBe(false); fixture.componentInstance.disabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(select.disabled).toBe(true); expect(getPreviousButton(fixture).hasAttribute('aria-disabled')).toBe(true); expect(getNextButton(fixture).hasAttribute('aria-disabled')).toBe(true); expect(getFirstButton(fixture).hasAttribute('aria-disabled')).toBe(true); expect(getLastButton(fixture).hasAttribute('aria-disabled')).toBe(true); }); it('should be able to configure the default options via a provider', () => { const fixture = createComponent(MatPaginatorWithoutInputsApp, [ { provide: MAT_PAGINATOR_DEFAULT_OPTIONS, useValue: { pageSize: 7, pageSizeOptions: [7, 14, 21], hidePageSize: true, showFirstLastButtons: true, } as MatPaginatorDefaultOptions, }, ]); const paginator = fixture.componentInstance.paginator; expect(paginator.pageSize).toBe(7); expect(paginator.pageSizeOptions).toEqual([7, 14, 21]); expect(paginator.hidePageSize).toBe(true); expect(paginator.showFirstLastButtons).toBe(true); }); it('should set `role="group"` on the host element', () => { const fixture = createComponent(MatPaginatorApp); const hostElement = fixture.nativeElement.querySelector('mat-paginator'); expect(hostElement.getAttribute('role')).toBe('group'); }); it('should handle the page size options input being passed in as readonly array', () => { const fixture = createComponent(MatPaginatorWithReadonlyOptions); fixture.detectChanges(); expect(fixture.componentInstance.paginator._displayedPageSizeOptions).toEqual([5, 10, 25, 100]); }); }); function getPreviousButton(fixture: ComponentFixture<any>) { return fixture.nativeElement.querySelector('.mat-mdc-paginator-navigation-previous'); } function getNextButton(fixture: ComponentFixture<any>) { return fixture.nativeElement.querySelector('.mat-mdc-paginator-navigation-next'); } function getFirstButton(fixture: ComponentFixture<any>) { return fixture.nativeElement.querySelector('.mat-mdc-paginator-navigation-first'); } function getLastButton(fixture: ComponentFixture<any>) { return fixture.nativeElement.querySelector('.mat-mdc-paginator-navigation-last'); } @Component({ template: ` <mat-paginator [pageIndex]="pageIndex" [pageSize]="pageSize" [pageSizeOptions]="pageSizeOptions" [hidePageSize]="hidePageSize" [selectConfig]="selectConfig" [showFirstLastButtons]="showFirstLastButtons" [length]="length" [color]="color" [disabled]="disabled" (page)="pageEvent($event)"> </mat-paginator> `, standalone: false, }) class MatPaginatorApp { pageIndex = 0; pageSize = 10; pageSizeOptions = [5, 10, 25, 100]; hidePageSize = false; showFirstLastButtons = false; length = 100; disabled: boolean; pageEvent = jasmine.createSpy('page event'); color: ThemePalette; selectConfig: MatPaginatorSelectConfig = {}; @ViewChild(MatPaginator) paginator: MatPaginator; private readonly _changeDetectorRef = inject(ChangeDetectorRef); goToLastPage() { this.pageIndex = Math.ceil(this.length / this.pageSize) - 1; this._changeDetectorRef.markForCheck(); } } @Component({ template: ` <mat-paginator></mat-paginator> `, standalone: false, }) class MatPaginatorWithoutInputsApp { @ViewChild(MatPaginator) paginator: MatPaginator; } @Component({ template: ` <mat-paginator [pageSizeOptions]="[10, 20, 30]"></mat-paginator> `, standalone: false, }) class MatPaginatorWithoutPageSizeApp { @ViewChild(MatPaginator) paginator: MatPaginator; } @Component({ template: ` <mat-paginator [pageSize]="10"></mat-paginator> `, standalone: false, }) class MatPaginatorWithoutOptionsApp { @ViewChild(MatPaginator) paginator: MatPaginator; } @Component({ template: ` <mat-paginator pageIndex="0" pageSize="10" [pageSizeOptions]="['5', '10', '25', '100']" length="100"> </mat-paginator> `, standalone: false, }) class MatPaginatorWithStringValues { @ViewChild(MatPaginator) paginator: MatPaginator; } @Component({ template: ` <mat-paginator [pageSizeOptions]="pageSizeOptions"> </mat-paginator> `, standalone: false, }) class MatPaginatorWithReadonlyOptions { @ViewChild(MatPaginator) paginator: MatPaginator; pageSizeOptions: readonly number[] = [5, 10, 25, 100]; }
{ "end_byte": 24828, "start_byte": 19413, "url": "https://github.com/angular/components/blob/main/src/material/paginator/paginator.spec.ts" }
components/src/material/paginator/module.ts_0_725
/** * @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 {MAT_PAGINATOR_INTL_PROVIDER} from './paginator-intl'; import {MatButtonModule} from '@angular/material/button'; import {MatSelectModule} from '@angular/material/select'; import {MatTooltipModule} from '@angular/material/tooltip'; import {MatPaginator} from './paginator'; @NgModule({ imports: [MatButtonModule, MatSelectModule, MatTooltipModule, MatPaginator], exports: [MatPaginator], providers: [MAT_PAGINATOR_INTL_PROVIDER], }) export class MatPaginatorModule {}
{ "end_byte": 725, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/module.ts" }
components/src/material/paginator/paginator.md_0_1558
`<mat-paginator>` provides navigation for paged information, typically used with a table. <!-- example(paginator-overview) --> ### Basic use Each paginator instance requires: * The number of items per page (default set to 50) * The total number of items being paged The current page index defaults to 0, but can be explicitly set via pageIndex. When the user interacts with the paginator, a `PageEvent` will be fired that can be used to update any associated data view. ### Page size options The paginator displays a dropdown of page sizes for the user to choose from. The options for this dropdown can be set via `pageSizeOptions` The current pageSize will always appear in the dropdown, even if it is not included in pageSizeOptions. If you want to customize some of the optional of the `mat-select` inside the `mat-paginator`, you can use the `selectConfig` input. ### Internationalization The labels for the paginator can be customized by providing your own instance of `MatPaginatorIntl`. This will allow you to change the following: 1. The label for the length of each page. 2. The range text displayed to the user. 3. The tooltip messages on the navigation buttons. ### Accessibility The paginator uses `role="group"` to semantically group its child controls. You must add an `aria-label` or `aria-labelledby` attribute to `<mat-paginator>` with a label that describes the content controlled by the pagination control. You can set the `aria-label` attributes for the button and select controls within the paginator in `MatPaginatorIntl`.
{ "end_byte": 1558, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/paginator.md" }
components/src/material/paginator/public-api.ts_0_293
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './module'; export * from './paginator'; export * from './paginator-intl';
{ "end_byte": 293, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/public-api.ts" }
components/src/material/paginator/_paginator-theme.scss_0_3143
@use 'sass:map'; @use 'sass:meta'; @use '../core/tokens/m2/mat/paginator' as tokens-mat-paginator; @use '../core/style/sass-utils'; @use '../core/typography/typography'; @use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @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 { } } @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-paginator.$prefix, tokens-mat-paginator.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-paginator.$prefix, tokens-mat-paginator.get-typography-tokens($theme) ); } } } @mixin density($theme) { $density-scale: inspection.get-theme-density($theme); $form-field-density: if( (meta.type-of($density-scale) == 'number' and $density-scale >= -4) or ($density-scale == maximum), -4, $density-scale ); @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, density)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mat-paginator.$prefix, tokens-mat-paginator.get-density-tokens($theme) ); } } } /// Defines the tokens that will be available in the `overrides` mixin and for docs extraction. @function _define-overrides() { @return ( ( namespace: tokens-mat-paginator.$prefix, tokens: tokens-mat-paginator.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-paginator') { @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-paginator.$prefix, map.get($tokens, tokens-mat-paginator.$prefix) ); } }
{ "end_byte": 3143, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/_paginator-theme.scss" }
components/src/material/paginator/paginator.ts_0_3269
/** * @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, ChangeDetectorRef, Component, EventEmitter, Inject, InjectionToken, Input, OnDestroy, OnInit, Optional, Output, ViewEncapsulation, booleanAttribute, numberAttribute, } from '@angular/core'; import {MatOption, ThemePalette} from '@angular/material/core'; import {MatSelect} from '@angular/material/select'; import {MatIconButton} from '@angular/material/button'; import {MatTooltip} from '@angular/material/tooltip'; import {MatFormField, MatFormFieldAppearance} from '@angular/material/form-field'; import {Observable, ReplaySubject, Subscription} from 'rxjs'; import {MatPaginatorIntl} from './paginator-intl'; /** The default page size if there is no page size and there are no provided page size options. */ const DEFAULT_PAGE_SIZE = 50; /** Object that can used to configure the underlying `MatSelect` inside a `MatPaginator`. */ export interface MatPaginatorSelectConfig { /** Whether to center the active option over the trigger. */ disableOptionCentering?: boolean; /** Classes to be passed to the select panel. */ panelClass?: string | string[] | Set<string> | {[key: string]: any}; } /** * Change event object that is emitted when the user selects a * different page size or navigates to another page. */ export class PageEvent { /** The current page index. */ pageIndex: number; /** * Index of the page that was selected previously. * @breaking-change 8.0.0 To be made into a required property. */ previousPageIndex?: number; /** The current page size. */ pageSize: number; /** The current total number of items being paged. */ length: number; } // Note that while `MatPaginatorDefaultOptions` and `MAT_PAGINATOR_DEFAULT_OPTIONS` are identical // between the MDC and non-MDC versions, we have to duplicate them, because the type of // `formFieldAppearance` is narrower in the MDC version. /** Object that can be used to configure the default options for the paginator module. */ export interface MatPaginatorDefaultOptions { /** Number of items to display on a page. By default set to 50. */ pageSize?: number; /** The set of provided page size options to display to the user. */ pageSizeOptions?: number[]; /** Whether to hide the page size selection UI from the user. */ hidePageSize?: boolean; /** Whether to show the first/last buttons UI to the user. */ showFirstLastButtons?: boolean; /** The default form-field appearance to apply to the page size options selector. */ formFieldAppearance?: MatFormFieldAppearance; } /** Injection token that can be used to provide the default options for the paginator module. */ export const MAT_PAGINATOR_DEFAULT_OPTIONS = new InjectionToken<MatPaginatorDefaultOptions>( 'MAT_PAGINATOR_DEFAULT_OPTIONS', ); let nextUniqueId = 0; /** * Component to provide navigation between paged information. Displays the size of the current * page, user-selectable options to change that size, what items are being shown, and * navigational button to go to the previous or next page. */
{ "end_byte": 3269, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/paginator.ts" }
components/src/material/paginator/paginator.ts_3270_11783
@Component({ selector: 'mat-paginator', exportAs: 'matPaginator', templateUrl: 'paginator.html', styleUrl: 'paginator.css', host: { 'class': 'mat-mdc-paginator', 'role': 'group', }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, imports: [MatFormField, MatSelect, MatOption, MatIconButton, MatTooltip], }) export class MatPaginator implements OnInit, OnDestroy { /** If set, styles the "page size" form field with the designated style. */ _formFieldAppearance?: MatFormFieldAppearance; /** ID for the DOM node containing the paginator's items per page label. */ readonly _pageSizeLabelId = `mat-paginator-page-size-label-${nextUniqueId++}`; private _intlChanges: Subscription; private _isInitialized = false; private _initializedStream = new ReplaySubject<void>(1); /** * Theme color of the underlying form controls. This API is supported in M2 * themes only,it has no effect in M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants. */ @Input() color: ThemePalette; /** The zero-based page index of the displayed list of items. Defaulted to 0. */ @Input({transform: numberAttribute}) get pageIndex(): number { return this._pageIndex; } set pageIndex(value: number) { this._pageIndex = Math.max(value || 0, 0); this._changeDetectorRef.markForCheck(); } private _pageIndex = 0; /** The length of the total number of items that are being paginated. Defaulted to 0. */ @Input({transform: numberAttribute}) get length(): number { return this._length; } set length(value: number) { this._length = value || 0; this._changeDetectorRef.markForCheck(); } private _length = 0; /** Number of items to display on a page. By default set to 50. */ @Input({transform: numberAttribute}) get pageSize(): number { return this._pageSize; } set pageSize(value: number) { this._pageSize = Math.max(value || 0, 0); this._updateDisplayedPageSizeOptions(); } private _pageSize: number; /** The set of provided page size options to display to the user. */ @Input() get pageSizeOptions(): number[] { return this._pageSizeOptions; } set pageSizeOptions(value: number[] | readonly number[]) { this._pageSizeOptions = (value || ([] as number[])).map(p => numberAttribute(p, 0)); this._updateDisplayedPageSizeOptions(); } private _pageSizeOptions: number[] = []; /** Whether to hide the page size selection UI from the user. */ @Input({transform: booleanAttribute}) hidePageSize: boolean = false; /** Whether to show the first/last buttons UI to the user. */ @Input({transform: booleanAttribute}) showFirstLastButtons: boolean = false; /** Used to configure the underlying `MatSelect` inside the paginator. */ @Input() selectConfig: MatPaginatorSelectConfig = {}; /** Whether the paginator is disabled. */ @Input({transform: booleanAttribute}) disabled: boolean = false; /** Event emitted when the paginator changes the page size or page index. */ @Output() readonly page: EventEmitter<PageEvent> = new EventEmitter<PageEvent>(); /** Displayed set of page size options. Will be sorted and include current page size. */ _displayedPageSizeOptions: number[]; /** Emits when the paginator is initialized. */ initialized: Observable<void> = this._initializedStream; constructor( public _intl: MatPaginatorIntl, private _changeDetectorRef: ChangeDetectorRef, @Optional() @Inject(MAT_PAGINATOR_DEFAULT_OPTIONS) defaults?: MatPaginatorDefaultOptions, ) { this._intlChanges = _intl.changes.subscribe(() => this._changeDetectorRef.markForCheck()); if (defaults) { const {pageSize, pageSizeOptions, hidePageSize, showFirstLastButtons} = defaults; if (pageSize != null) { this._pageSize = pageSize; } if (pageSizeOptions != null) { this._pageSizeOptions = pageSizeOptions; } if (hidePageSize != null) { this.hidePageSize = hidePageSize; } if (showFirstLastButtons != null) { this.showFirstLastButtons = showFirstLastButtons; } } this._formFieldAppearance = defaults?.formFieldAppearance || 'outline'; } ngOnInit() { this._isInitialized = true; this._updateDisplayedPageSizeOptions(); this._initializedStream.next(); } ngOnDestroy() { this._initializedStream.complete(); this._intlChanges.unsubscribe(); } /** Advances to the next page if it exists. */ nextPage(): void { if (!this.hasNextPage()) { return; } const previousPageIndex = this.pageIndex; this.pageIndex = this.pageIndex + 1; this._emitPageEvent(previousPageIndex); } /** Move back to the previous page if it exists. */ previousPage(): void { if (!this.hasPreviousPage()) { return; } const previousPageIndex = this.pageIndex; this.pageIndex = this.pageIndex - 1; this._emitPageEvent(previousPageIndex); } /** Move to the first page if not already there. */ firstPage(): void { // hasPreviousPage being false implies at the start if (!this.hasPreviousPage()) { return; } const previousPageIndex = this.pageIndex; this.pageIndex = 0; this._emitPageEvent(previousPageIndex); } /** Move to the last page if not already there. */ lastPage(): void { // hasNextPage being false implies at the end if (!this.hasNextPage()) { return; } const previousPageIndex = this.pageIndex; this.pageIndex = this.getNumberOfPages() - 1; this._emitPageEvent(previousPageIndex); } /** Whether there is a previous page. */ hasPreviousPage(): boolean { return this.pageIndex >= 1 && this.pageSize != 0; } /** Whether there is a next page. */ hasNextPage(): boolean { const maxPageIndex = this.getNumberOfPages() - 1; return this.pageIndex < maxPageIndex && this.pageSize != 0; } /** Calculate the number of pages */ getNumberOfPages(): number { if (!this.pageSize) { return 0; } return Math.ceil(this.length / this.pageSize); } /** * Changes the page size so that the first item displayed on the page will still be * displayed using the new page size. * * For example, if the page size is 10 and on the second page (items indexed 10-19) then * switching so that the page size is 5 will set the third page as the current page so * that the 10th item will still be displayed. */ _changePageSize(pageSize: number) { // Current page needs to be updated to reflect the new page size. Navigate to the page // containing the previous page's first item. const startIndex = this.pageIndex * this.pageSize; const previousPageIndex = this.pageIndex; this.pageIndex = Math.floor(startIndex / pageSize) || 0; this.pageSize = pageSize; this._emitPageEvent(previousPageIndex); } /** Checks whether the buttons for going forwards should be disabled. */ _nextButtonsDisabled() { return this.disabled || !this.hasNextPage(); } /** Checks whether the buttons for going backwards should be disabled. */ _previousButtonsDisabled() { return this.disabled || !this.hasPreviousPage(); } /** * Updates the list of page size options to display to the user. Includes making sure that * the page size is an option and that the list is sorted. */ private _updateDisplayedPageSizeOptions() { if (!this._isInitialized) { return; } // If no page size is provided, use the first page size option or the default page size. if (!this.pageSize) { this._pageSize = this.pageSizeOptions.length != 0 ? this.pageSizeOptions[0] : DEFAULT_PAGE_SIZE; } this._displayedPageSizeOptions = this.pageSizeOptions.slice(); if (this._displayedPageSizeOptions.indexOf(this.pageSize) === -1) { this._displayedPageSizeOptions.push(this.pageSize); } // Sort the numbers using a number-specific sort function. this._displayedPageSizeOptions.sort((a, b) => a - b); this._changeDetectorRef.markForCheck(); } /** Emits an event notifying that a change of the paginator's properties has been triggered. */ private _emitPageEvent(previousPageIndex: number) { this.page.emit({ previousPageIndex, pageIndex: this.pageIndex, pageSize: this.pageSize, length: this.length, }); } }
{ "end_byte": 11783, "start_byte": 3270, "url": "https://github.com/angular/components/blob/main/src/material/paginator/paginator.ts" }
components/src/material/paginator/paginator.scss_0_4509
@use '@angular/cdk'; @use '../core/tokens/m2/mat/paginator' as tokens-mat-paginator; @use '../core/tokens/token-utils'; @use '../core/style/vendor-prefixes'; $padding: 0 8px; $page-size-margin-right: 8px; $items-per-page-label-margin: 0 4px; $selector-margin: 0 4px; $selector-trigger-width: 84px; $touch-target-height: 48px; $range-label-margin: 0 32px 0 24px; $button-icon-size: 28px; .mat-mdc-paginator { display: block; @include token-utils.use-tokens( tokens-mat-paginator.$prefix, tokens-mat-paginator.get-token-slots() ) { @include vendor-prefixes.smooth-font(); @include token-utils.create-token-slot(color, container-text-color); @include token-utils.create-token-slot(background-color, container-background-color); @include token-utils.create-token-slot(font-family, container-text-font); @include token-utils.create-token-slot(line-height, container-text-line-height); @include token-utils.create-token-slot(font-size, container-text-size); @include token-utils.create-token-slot(font-weight, container-text-weight); @include token-utils.create-token-slot(letter-spacing, container-text-tracking); // Apply custom form-field density for paginator. @include token-utils.create-token-slot( --mat-form-field-container-height, form-field-container-height ); @include token-utils.create-token-slot( --mat-form-field-container-vertical-padding, form-field-container-vertical-padding ); .mat-mdc-select-value { @include token-utils.create-token-slot(font-size, select-trigger-text-size); } } // This element reserves space for hints and error messages. // Hide it since we know that we won't need it. .mat-mdc-form-field-subscript-wrapper { display: none; } .mat-mdc-select { // The smaller font size inherited from the paginator throws off the centering of the select // inside the form field. This `line-height` helps to center it relative to the other text. line-height: 1.5; } } // Note: this wrapper element is only used to get the flexbox vertical centering to work // with the `min-height` on IE11. It can be removed if we drop support for IE. .mat-mdc-paginator-outer-container { display: flex; } .mat-mdc-paginator-container { display: flex; align-items: center; justify-content: flex-end; padding: $padding; flex-wrap: wrap; width: 100%; @include token-utils.use-tokens( tokens-mat-paginator.$prefix, tokens-mat-paginator.get-token-slots() ) { @include token-utils.create-token-slot(min-height, container-size); } } .mat-mdc-paginator-page-size { display: flex; align-items: baseline; margin-right: $page-size-margin-right; [dir='rtl'] & { margin-right: 0; margin-left: $page-size-margin-right; } } .mat-mdc-paginator-page-size-label { margin: $items-per-page-label-margin; } .mat-mdc-paginator-page-size-select { margin: $selector-margin; width: $selector-trigger-width; } .mat-mdc-paginator-range-label { margin: $range-label-margin; } .mat-mdc-paginator-range-actions { display: flex; align-items: center; } .mat-mdc-paginator-icon { display: inline-block; width: $button-icon-size; @include token-utils.use-tokens( tokens-mat-paginator.$prefix, tokens-mat-paginator.get-token-slots() ) { @include token-utils.create-token-slot(fill, enabled-icon-color); .mat-mdc-icon-button[aria-disabled] & { @include token-utils.create-token-slot(fill, disabled-icon-color); } } [dir='rtl'] & { transform: rotate(180deg); } } @include cdk.high-contrast { // The disabled button icon has to be set explicitly since the selector is too specific. .mat-mdc-icon-button[disabled] .mat-mdc-paginator-icon, .mat-mdc-paginator-icon { fill: currentColor; // On Chromium browsers the `currentColor` blends in with the // background for SVGs so we have to fall back to `CanvasText`. fill: CanvasText; } .mat-mdc-paginator-range-actions .mat-mdc-icon-button { outline: solid 1px; } } .mat-mdc-paginator-touch-target { @include token-utils.use-tokens( tokens-mat-paginator.$prefix, tokens-mat-paginator.get-token-slots() ) { @include token-utils.create-token-slot(display, touch-target-display); } position: absolute; top: 50%; left: 50%; width: $selector-trigger-width; height: $touch-target-height; background-color: transparent; transform: translate(-50%, -50%); cursor: pointer; }
{ "end_byte": 4509, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/paginator.scss" }
components/src/material/paginator/paginator.html_0_4569
<div class="mat-mdc-paginator-outer-container"> <div class="mat-mdc-paginator-container"> @if (!hidePageSize) { <div class="mat-mdc-paginator-page-size"> <div class="mat-mdc-paginator-page-size-label" [attr.id]="_pageSizeLabelId"> {{_intl.itemsPerPageLabel}} </div> @if (_displayedPageSizeOptions.length > 1) { <mat-form-field [appearance]="_formFieldAppearance!" [color]="color" class="mat-mdc-paginator-page-size-select"> <mat-select #selectRef [value]="pageSize" [disabled]="disabled" [aria-labelledby]="_pageSizeLabelId" [panelClass]="selectConfig.panelClass || ''" [disableOptionCentering]="selectConfig.disableOptionCentering" (selectionChange)="_changePageSize($event.value)" hideSingleSelectionIndicator> @for (pageSizeOption of _displayedPageSizeOptions; track pageSizeOption) { <mat-option [value]="pageSizeOption"> {{pageSizeOption}} </mat-option> } </mat-select> <div class="mat-mdc-paginator-touch-target" (click)="selectRef.open()"></div> </mat-form-field> } @if (_displayedPageSizeOptions.length <= 1) { <div class="mat-mdc-paginator-page-size-value">{{pageSize}}</div> } </div> } <div class="mat-mdc-paginator-range-actions"> <div class="mat-mdc-paginator-range-label" aria-live="polite"> {{_intl.getRangeLabel(pageIndex, pageSize, length)}} </div> @if (showFirstLastButtons) { <button mat-icon-button type="button" class="mat-mdc-paginator-navigation-first" (click)="firstPage()" [attr.aria-label]="_intl.firstPageLabel" [matTooltip]="_intl.firstPageLabel" [matTooltipDisabled]="_previousButtonsDisabled()" [matTooltipPosition]="'above'" [disabled]="_previousButtonsDisabled()" disabledInteractive> <svg class="mat-mdc-paginator-icon" viewBox="0 0 24 24" focusable="false" aria-hidden="true"> <path d="M18.41 16.59L13.82 12l4.59-4.59L17 6l-6 6 6 6zM6 6h2v12H6z"/> </svg> </button> } <button mat-icon-button type="button" class="mat-mdc-paginator-navigation-previous" (click)="previousPage()" [attr.aria-label]="_intl.previousPageLabel" [matTooltip]="_intl.previousPageLabel" [matTooltipDisabled]="_previousButtonsDisabled()" [matTooltipPosition]="'above'" [disabled]="_previousButtonsDisabled()" disabledInteractive> <svg class="mat-mdc-paginator-icon" viewBox="0 0 24 24" focusable="false" aria-hidden="true"> <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/> </svg> </button> <button mat-icon-button type="button" class="mat-mdc-paginator-navigation-next" (click)="nextPage()" [attr.aria-label]="_intl.nextPageLabel" [matTooltip]="_intl.nextPageLabel" [matTooltipDisabled]="_nextButtonsDisabled()" [matTooltipPosition]="'above'" [disabled]="_nextButtonsDisabled()" disabledInteractive> <svg class="mat-mdc-paginator-icon" viewBox="0 0 24 24" focusable="false" aria-hidden="true"> <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/> </svg> </button> @if (showFirstLastButtons) { <button mat-icon-button type="button" class="mat-mdc-paginator-navigation-last" (click)="lastPage()" [attr.aria-label]="_intl.lastPageLabel" [matTooltip]="_intl.lastPageLabel" [matTooltipDisabled]="_nextButtonsDisabled()" [matTooltipPosition]="'above'" [disabled]="_nextButtonsDisabled()" disabledInteractive> <svg class="mat-mdc-paginator-icon" viewBox="0 0 24 24" focusable="false" aria-hidden="true"> <path d="M5.59 7.41L10.18 12l-4.59 4.59L7 18l6-6-6-6zM16 6h2v12h-2z"/> </svg> </button> } </div> </div> </div>
{ "end_byte": 4569, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/paginator.html" }
components/src/material/paginator/BUILD.bazel_0_1660
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 = "paginator", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), assets = [":paginator.css"] + glob(["**/*.html"]), deps = [ "//src/material/button", "//src/material/core", "//src/material/select", "//src/material/tooltip", "@npm//@angular/core", "@npm//@angular/forms", # TODO(jelbourn): transitive dep via generated code "@npm//rxjs", ], ) sass_library( name = "paginator_scss_lib", srcs = glob(["**/_*.scss"]), deps = [ "//src/material/core:core_scss_lib", ], ) sass_binary( name = "paginator_scss", src = "paginator.scss", deps = [ "//src/cdk:sass_lib", "//src/material:sass_lib", ], ) ng_test_library( name = "paginator_tests_lib", srcs = glob( ["**/*.spec.ts"], exclude = ["**/*.e2e.spec.ts"], ), deps = [ ":paginator", "//src/cdk/testing/private", "//src/material/core", "//src/material/select", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":paginator_tests_lib", ], ) markdown_to_html( name = "overview", srcs = [":paginator.md"], ) extract_tokens( name = "tokens", srcs = [":paginator_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "end_byte": 1660, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/BUILD.bazel" }
components/src/material/paginator/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/paginator/index.ts" }
components/src/material/paginator/paginator-intl.ts_0_2365
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Injectable, Optional, SkipSelf} from '@angular/core'; import {Subject} from 'rxjs'; /** * To modify the labels and text displayed, create a new instance of MatPaginatorIntl and * include it in a custom provider */ @Injectable({providedIn: 'root'}) export class MatPaginatorIntl { /** * Stream to emit from when labels are changed. Use this to notify components when the labels have * changed after initialization. */ readonly changes: Subject<void> = new Subject<void>(); /** A label for the page size selector. */ itemsPerPageLabel: string = 'Items per page:'; /** A label for the button that increments the current page. */ nextPageLabel: string = 'Next page'; /** A label for the button that decrements the current page. */ previousPageLabel: string = 'Previous page'; /** A label for the button that moves to the first page. */ firstPageLabel: string = 'First page'; /** A label for the button that moves to the last page. */ lastPageLabel: string = 'Last page'; /** A label for the range of items within the current page and the length of the whole list. */ getRangeLabel: (page: number, pageSize: number, length: number) => string = ( page: number, pageSize: number, length: number, ) => { if (length == 0 || pageSize == 0) { return `0 of ${length}`; } length = Math.max(length, 0); const startIndex = page * pageSize; // If the start index exceeds the list length, do not try and fix the end index to the end. const endIndex = startIndex < length ? Math.min(startIndex + pageSize, length) : startIndex + pageSize; return `${startIndex + 1} – ${endIndex} of ${length}`; }; } /** @docs-private */ export function MAT_PAGINATOR_INTL_PROVIDER_FACTORY(parentIntl: MatPaginatorIntl) { return parentIntl || new MatPaginatorIntl(); } /** @docs-private */ export const MAT_PAGINATOR_INTL_PROVIDER = { // If there is already an MatPaginatorIntl available, use that. Otherwise, provide a new one. provide: MatPaginatorIntl, deps: [[new Optional(), new SkipSelf(), MatPaginatorIntl]], useFactory: MAT_PAGINATOR_INTL_PROVIDER_FACTORY, };
{ "end_byte": 2365, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/paginator-intl.ts" }
components/src/material/paginator/testing/public-api.ts_0_286
/** * @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 './paginator-harness'; export * from './paginator-harness-filters';
{ "end_byte": 286, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/testing/public-api.ts" }
components/src/material/paginator/testing/paginator-harness.ts_0_4487
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { ComponentHarness, ComponentHarnessConstructor, HarnessPredicate, } from '@angular/cdk/testing'; import {MatSelectHarness} from '@angular/material/select/testing'; import {coerceNumberProperty} from '@angular/cdk/coercion'; import {PaginatorHarnessFilters} from './paginator-harness-filters'; /** Harness for interacting with a mat-paginator in tests. */ export class MatPaginatorHarness extends ComponentHarness { /** Selector used to find paginator instances. */ static hostSelector = '.mat-mdc-paginator'; private _nextButton = this.locatorFor('.mat-mdc-paginator-navigation-next'); private _previousButton = this.locatorFor('.mat-mdc-paginator-navigation-previous'); private _firstPageButton = this.locatorForOptional('.mat-mdc-paginator-navigation-first'); private _lastPageButton = this.locatorForOptional('.mat-mdc-paginator-navigation-last'); _select = this.locatorForOptional( MatSelectHarness.with({ ancestor: '.mat-mdc-paginator-page-size', }), ); private _pageSizeFallback = this.locatorFor('.mat-mdc-paginator-page-size-value'); _rangeLabel = this.locatorFor('.mat-mdc-paginator-range-label'); /** * Gets a `HarnessPredicate` that can be used to search for a paginator with specific attributes. * @param options Options for filtering which paginator instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with<T extends MatPaginatorHarness>( this: ComponentHarnessConstructor<T>, options: PaginatorHarnessFilters = {}, ): HarnessPredicate<T> { return new HarnessPredicate(this, options); } /** Goes to the next page in the paginator. */ async goToNextPage(): Promise<void> { return (await this._nextButton()).click(); } /** Returns whether or not the next page button is disabled. */ async isNextPageDisabled(): Promise<boolean> { const disabledValue = await (await this._nextButton()).getAttribute('aria-disabled'); return disabledValue == 'true'; } /* Returns whether or not the previous page button is disabled. */ async isPreviousPageDisabled(): Promise<boolean> { const disabledValue = await (await this._previousButton()).getAttribute('aria-disabled'); return disabledValue == 'true'; } /** Goes to the previous page in the paginator. */ async goToPreviousPage(): Promise<void> { return (await this._previousButton()).click(); } /** Goes to the first page in the paginator. */ async goToFirstPage(): Promise<void> { const button = await this._firstPageButton(); // The first page button isn't enabled by default so we need to check for it. if (!button) { throw Error( 'Could not find first page button inside paginator. ' + 'Make sure that `showFirstLastButtons` is enabled.', ); } return button.click(); } /** Goes to the last page in the paginator. */ async goToLastPage(): Promise<void> { const button = await this._lastPageButton(); // The last page button isn't enabled by default so we need to check for it. if (!button) { throw Error( 'Could not find last page button inside paginator. ' + 'Make sure that `showFirstLastButtons` is enabled.', ); } return button.click(); } /** * Sets the page size of the paginator. * @param size Page size that should be select. */ async setPageSize(size: number): Promise<void> { const select = await this._select(); // The select is only available if the `pageSizeOptions` are // set to an array with more than one item. if (!select) { throw Error( 'Cannot find page size selector in paginator. ' + 'Make sure that the `pageSizeOptions` have been configured.', ); } return select.clickOptions({text: `${size}`}); } /** Gets the page size of the paginator. */ async getPageSize(): Promise<number> { const select = await this._select(); const value = select ? select.getValueText() : (await this._pageSizeFallback()).text(); return coerceNumberProperty(await value); } /** Gets the text of the range label of the paginator. */ async getRangeLabel(): Promise<string> { return (await this._rangeLabel()).text(); } }
{ "end_byte": 4487, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/testing/paginator-harness.ts" }
components/src/material/paginator/testing/paginator-harness.spec.ts_0_5100
import {Component, signal} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {HarnessLoader} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {MatPaginatorModule, PageEvent} from '@angular/material/paginator'; import {MatPaginatorHarness} from './paginator-harness'; describe('MatPaginatorHarness', () => { let fixture: ComponentFixture<PaginatorHarnessTest>; let loader: HarnessLoader; let instance: PaginatorHarnessTest; beforeEach(() => { TestBed.configureTestingModule({ imports: [MatPaginatorModule, NoopAnimationsModule, PaginatorHarnessTest], }); fixture = TestBed.createComponent(PaginatorHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); instance = fixture.componentInstance; }); it('should load all paginator harnesses', async () => { const paginators = await loader.getAllHarnesses(MatPaginatorHarness); expect(paginators.length).toBe(1); }); it('should be able to go to the next page', async () => { const paginator = await loader.getHarness(MatPaginatorHarness); expect(instance.pageIndex()).toBe(0); await paginator.goToNextPage(); expect(instance.pageIndex()).toBe(1); }); it('should be able to go to the previous page', async () => { const paginator = await loader.getHarness(MatPaginatorHarness); instance.pageIndex.set(5); fixture.detectChanges(); await paginator.goToPreviousPage(); expect(instance.pageIndex()).toBe(4); }); it('should be able to go to the first page', async () => { const paginator = await loader.getHarness(MatPaginatorHarness); instance.pageIndex.set(5); fixture.detectChanges(); await paginator.goToFirstPage(); expect(instance.pageIndex()).toBe(0); }); it('should be able to go to the last page', async () => { const paginator = await loader.getHarness(MatPaginatorHarness); expect(instance.pageIndex()).toBe(0); await paginator.goToLastPage(); expect(instance.pageIndex()).toBe(49); }); it('should be able to set the page size', async () => { const paginator = await loader.getHarness(MatPaginatorHarness); expect(instance.pageSize).toBe(10); await paginator.setPageSize(25); expect(instance.pageSize).toBe(25); }); it('should be able to get the page size', async () => { const paginator = await loader.getHarness(MatPaginatorHarness); expect(await paginator.getPageSize()).toBe(10); }); it('should be able to get the range label', async () => { const paginator = await loader.getHarness(MatPaginatorHarness); expect(await paginator.getRangeLabel()).toBe('1 – 10 of 500'); }); it('should throw an error if the first page button is not available', async () => { const paginator = await loader.getHarness(MatPaginatorHarness); instance.showFirstLastButtons.set(false); fixture.detectChanges(); await expectAsync(paginator.goToFirstPage()).toBeRejectedWithError( /Could not find first page button inside paginator/, ); }); it('should return whether or not the previous page is disabled', async () => { const paginator = await loader.getHarness(MatPaginatorHarness); expect(await paginator.isPreviousPageDisabled()).toBe(true); }); it('should return whether or not the next page is disabled', async () => { const paginator = await loader.getHarness(MatPaginatorHarness); await paginator.goToLastPage(); expect(await paginator.isNextPageDisabled()).toBe(true); }); it('should throw an error if the last page button is not available', async () => { const paginator = await loader.getHarness(MatPaginatorHarness); instance.showFirstLastButtons.set(false); fixture.detectChanges(); await expectAsync(paginator.goToLastPage()).toBeRejectedWithError( /Could not find last page button inside paginator/, ); }); it('should throw an error if the page size selector is not available', async () => { const paginator = await loader.getHarness(MatPaginatorHarness); instance.pageSizeOptions.set([]); fixture.detectChanges(); await expectAsync(paginator.setPageSize(10)).toBeRejectedWithError( /Cannot find page size selector in paginator/, ); }); }); @Component({ template: ` <mat-paginator (page)="handlePageEvent($event)" [length]="length" [pageSize]="pageSize" [showFirstLastButtons]="showFirstLastButtons()" [pageSizeOptions]="pageSizeOptions()" [pageIndex]="pageIndex()"> </mat-paginator> `, standalone: true, imports: [MatPaginatorModule], }) class PaginatorHarnessTest { length = 500; pageSize = 10; pageIndex = signal(0); pageSizeOptions = signal([5, 10, 25]); showFirstLastButtons = signal(true); handlePageEvent(event: PageEvent) { this.length = event.length; this.pageSize = event.pageSize; this.pageIndex.set(event.pageIndex); } }
{ "end_byte": 5100, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/testing/paginator-harness.spec.ts" }
components/src/material/paginator/testing/BUILD.bazel_0_847
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/select/testing", ], ) ng_test_library( name = "unit_tests_lib", srcs = glob(["**/*.spec.ts"]), deps = [ ":testing", "//src/cdk/testing", "//src/cdk/testing/private", "//src/cdk/testing/testbed", "//src/material/paginator", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":unit_tests_lib", ], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "end_byte": 847, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/testing/BUILD.bazel" }
components/src/material/paginator/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/paginator/testing/index.ts" }
components/src/material/paginator/testing/paginator-harness-filters.ts_0_428
/** * @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 `MatPaginatorHarness` instances. */ export interface PaginatorHarnessFilters extends BaseHarnessFilters {}
{ "end_byte": 428, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/paginator/testing/paginator-harness-filters.ts" }
components/src/material/schematics/BUILD.bazel_0_3587
load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin") load("//tools:defaults.bzl", "jasmine_node_test", "pkg_npm", "ts_library") package(default_visibility = ["//visibility:public"]) copy_to_bin( name = "collection_assets", srcs = [ "collection.json", "migration.json", ], ) copy_to_bin( name = "ng_generate_assets", srcs = glob([ "ng-generate/*/files/**/*", ]), ) copy_to_bin( name = "schema_assets", srcs = glob([ "**/schema.json", ]), ) ts_library( name = "schematics", srcs = glob( ["**/*.ts"], exclude = [ "**/*.spec.ts", "paths.ts", "ng-generate/*/files/**/*.ts", ], ), # Schematics can not yet run in ESM module. For now we continue to use CommonJS. # TODO(ESM): remove this once the Angular CLI supports ESM schematics. devmode_module = "commonjs", prodmode_module = "commonjs", tsconfig = ":tsconfig.json", deps = [ "//src/cdk/schematics", "@npm//@angular-devkit/core", "@npm//@angular-devkit/schematics", "@npm//@schematics/angular", # TODO(devversion): Only include jasmine for test sources (See: tsconfig types). "@npm//@types/jasmine", "@npm//@types/node", "@npm//rxjs", "@npm//tslint", "@npm//typescript", ], ) ts_library( name = "paths", testonly = True, srcs = ["paths.ts"], data = [ ":collection_assets", ], # Schematics can not yet run in ESM module. For now we continue to use CommonJS. # TODO(ESM): remove this once the Angular CLI supports ESM schematics. devmode_module = "commonjs", prodmode_module = "commonjs", tsconfig = ":tsconfig.json", deps = [ "@npm//@bazel/runfiles", ], ) # This package is intended to be combined into the main @angular/material package as a dep. pkg_npm( name = "npm_package", srcs = ["package.json"], nested_packages = [ "//src/material/schematics/ng-generate/theme-color:npm_package", ], deps = [ ":collection_assets", ":ng_generate_assets", ":schema_assets", ":schematics", "//src/material/schematics/ng-update:ng_update_index", ], ) ### Testing rules jasmine_node_test( name = "unit_tests", srcs = [":unit_test_sources"], data = [ ":collection_assets", ":ng_generate_assets", ":schema_assets", ":schematics_test_cases", ], ) ts_library( name = "unit_test_sources", testonly = True, srcs = glob( ["**/*.spec.ts"], exclude = [ "**/*.e2e.spec.ts", "ng-generate/*/files/**/*.spec.ts", ], ), # Schematics can not yet run in ESM module. For now we continue to use CommonJS. # TODO(ESM): remove this once the Angular CLI supports ESM schematics. devmode_module = "commonjs", prodmode_module = "commonjs", tsconfig = ":tsconfig.json", deps = [ ":paths", ":schematics", "//src/cdk/schematics", "//src/cdk/schematics/testing", "@npm//@angular-devkit/core", "@npm//@angular-devkit/schematics", "@npm//@schematics/angular", "@npm//@types/fs-extra", "@npm//@types/jasmine", "@npm//@types/node", "@npm//fs-extra", ], ) filegroup( name = "schematics_test_cases", testonly = True, srcs = glob([ "ng-update/test-cases/**/*_input.ts", "ng-update/test-cases/**/*_expected_output.ts", ]), )
{ "end_byte": 3587, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/BUILD.bazel" }
components/src/material/schematics/paths.ts_0_614
/** * @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 {runfiles} from '@bazel/runfiles'; /** Path to the schematic collection for non-migration schematics. */ export const COLLECTION_PATH = runfiles.resolveWorkspaceRelative( 'src/material/schematics/collection.json', ); /** Path to the schematic collection that includes the migrations. */ export const MIGRATION_PATH = runfiles.resolveWorkspaceRelative( 'src/material/schematics/migration.json', );
{ "end_byte": 614, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/paths.ts" }
components/src/material/schematics/migration-utilities/index.spec.ts_0_720
import {writeUpdates} from './index'; describe('migration-utilities', () => { describe('writeUpdates', () => { it('should call update functions in the correct order', () => { const fn1 = jasmine.createSpy().and.returnValue('1'); const fn2 = jasmine.createSpy().and.returnValue('2'); const fn3 = jasmine.createSpy().and.returnValue('3'); const result = writeUpdates('0', [ {offset: 1, updateFn: fn3}, {offset: 2, updateFn: fn2}, {offset: 3, updateFn: fn1}, ]); expect(fn1).toHaveBeenCalledOnceWith('0'); expect(fn2).toHaveBeenCalledOnceWith('1'); expect(fn3).toHaveBeenCalledOnceWith('2'); expect(result).toBe('3'); }); }); });
{ "end_byte": 720, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/migration-utilities/index.spec.ts" }
components/src/material/schematics/migration-utilities/BUILD.bazel_0_759
load("//tools:defaults.bzl", "jasmine_node_test", "spec_bundle", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "migration-utilities", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "@npm//typescript", ], ) ts_library( name = "unit_tests_lib", testonly = True, srcs = glob(["**/*.spec.ts"] + ["rules/components/test-setup-helper.ts"]), deps = [ ":migration-utilities", "@npm//@types/jasmine", "@npm//typescript", ], ) spec_bundle( name = "unit_tests_bundle", platform = "cjs-legacy", deps = [":unit_tests_lib"], ) jasmine_node_test( name = "unit_tests", deps = [":unit_tests_bundle"], )
{ "end_byte": 759, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/migration-utilities/BUILD.bazel" }
components/src/material/schematics/migration-utilities/index.ts_0_321
/** * @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 {updateModuleSpecifier} from './typescript/import-operations'; export {Update, writeUpdates} from './update';
{ "end_byte": 321, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/migration-utilities/index.ts" }
components/src/material/schematics/migration-utilities/update.ts_0_757
/** * @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 */ /** Stores the data needed to make a single update to a file. */ export interface Update { /** The start index of the location of the update. */ offset: number; /** A function to be used to update the file content. */ updateFn: (text: string) => string; } /** Applies the updates to the given file content in reverse offset order. */ export function writeUpdates(content: string, updates: Update[]): string { updates.sort((a, b) => b.offset - a.offset); updates.forEach(update => (content = update.updateFn(content))); return content; }
{ "end_byte": 757, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/migration-utilities/update.ts" }
components/src/material/schematics/migration-utilities/typescript/import-operations.ts_0_1827
/** * @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 {Update} from '../update'; import * as ts from 'typescript'; /** Returns an Update that renames the module specifier of the given import declaration node. */ export function updateModuleSpecifier( node: ts.ImportDeclaration, opts: { moduleSpecifier: string; }, ): Update { const moduleSpecifier = node.moduleSpecifier as ts.StringLiteral; return { offset: moduleSpecifier.pos, updateFn: (text: string) => { const index = text.indexOf(moduleSpecifier.text, moduleSpecifier.pos); return replaceAt(text, index, { old: moduleSpecifier.text, new: opts.moduleSpecifier, }); }, }; } /** Returns an Update that renames an export of the given named import node. */ export function updateNamedImport( node: ts.NamedImports, opts: { oldExport: string; newExport: string; }, ): Update | undefined { for (let i = 0; i < node.elements.length; i++) { const n = node.elements[i]; const name = n.propertyName ? n.propertyName : n.name; if (name.text === opts.oldExport) { return { offset: name.pos, updateFn: (text: string) => { const index = text.indexOf(opts.oldExport, name.pos); return replaceAt(text, index, { old: opts.oldExport, new: opts.newExport, }); }, }; } } return; } /** Replaces the first instance of substring.old after the given index. */ function replaceAt(str: string, index: number, substring: {old: string; new: string}): string { return str.slice(0, index) + substring.new + str.slice(index + substring.old.length); }
{ "end_byte": 1827, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/migration-utilities/typescript/import-operations.ts" }
components/src/material/schematics/migration-utilities/typescript/import-operations.spec.ts_0_4359
import * as ts from 'typescript'; import {updateModuleSpecifier, updateNamedImport} from './import-operations'; describe('import operations', () => { describe('updateModuleSpecifier', () => { function runUpdateModuleSpecifierTest( description: string, opts: {old: string; new: string}, ): void { const node = createNode(opts.old, ts.SyntaxKind.ImportDeclaration) as ts.ImportDeclaration; const update = updateModuleSpecifier(node!, {moduleSpecifier: 'new-module-name'}); const newImport = update?.updateFn(opts.old); expect(newImport).withContext(description).toBe(opts.new); } it('updates the module specifier of import declarations', () => { runUpdateModuleSpecifierTest('default export', { old: `import defaultExport from 'old-module-name';`, new: `import defaultExport from 'new-module-name';`, }); runUpdateModuleSpecifierTest('namespace import', { old: `import * as name from 'old-module-name';`, new: `import * as name from 'new-module-name';`, }); runUpdateModuleSpecifierTest('named import', { old: `import { export1 } from 'old-module-name';`, new: `import { export1 } from 'new-module-name';`, }); runUpdateModuleSpecifierTest('aliased named import', { old: `import { export1 as alias1 } from 'old-module-name';`, new: `import { export1 as alias1 } from 'new-module-name';`, }); runUpdateModuleSpecifierTest('multiple named import', { old: `import { export1, export2 } from 'old-module-name';`, new: `import { export1, export2 } from 'new-module-name';`, }); runUpdateModuleSpecifierTest('multiple named import w/ alias', { old: `import { export1, export2 as alias2 } from 'old-module-name';`, new: `import { export1, export2 as alias2 } from 'new-module-name';`, }); }); }); describe('updateNamedExport', () => { function runUpdateNamedExportTest( description: string, opts: { oldFile: string; newFile: string; oldExport: string; newExport: string; }, ): void { const node = createNode(opts.oldFile, ts.SyntaxKind.NamedImports) as ts.NamedImports; const newImport = updateNamedImport(node, { oldExport: opts.oldExport, newExport: opts.newExport, })?.updateFn(opts.oldFile); expect(newImport).withContext(description).toBe(opts.newFile); } it('updates the named exports of import declarations', () => { runUpdateNamedExportTest('named binding', { oldExport: 'oldExport', newExport: 'newExport', oldFile: `import { oldExport } from 'module-name';`, newFile: `import { newExport } from 'module-name';`, }); runUpdateNamedExportTest('aliased named binding', { oldExport: 'oldExport', newExport: 'newExport', oldFile: `import { oldExport as alias } from 'module-name';`, newFile: `import { newExport as alias } from 'module-name';`, }); runUpdateNamedExportTest('multiple named bindings', { oldExport: 'oldExport1', newExport: 'newExport1', oldFile: `import { oldExport1, export2 } from 'module-name';`, newFile: `import { newExport1, export2 } from 'module-name';`, }); runUpdateNamedExportTest('multiple named bindings w/ alias', { oldExport: 'oldExport2', newExport: 'newExport2', oldFile: `import { export1, oldExport2 as alias2 } from 'module-name';`, newFile: `import { export1, newExport2 as alias2 } from 'module-name';`, }); }); }); }); function createSourceFile(text: string): ts.SourceFile { return ts.createSourceFile('file.ts', text, ts.ScriptTarget.Latest); } function visitNodes(node: ts.SourceFile | ts.Node, visitFn: (node: ts.Node) => void): void { node.forEachChild(child => { visitFn(child); visitNodes(child, visitFn); }); } function getNodeByKind(file: ts.SourceFile, kind: ts.SyntaxKind): ts.Node | null { let node: ts.Node | null = null; visitNodes(file, (_node: ts.Node) => { if (_node.kind === kind) { node = _node; } }); return node; } function createNode(text: string, kind: ts.SyntaxKind): ts.Node | null { return getNodeByKind(createSourceFile(text), kind); }
{ "end_byte": 4359, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/migration-utilities/typescript/import-operations.spec.ts" }
components/src/material/schematics/ng-update/upgrade-data.ts_0_799
/** * @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 {UpgradeData} from '@angular/cdk/schematics'; import { attributeSelectors, classNames, constructorChecks, cssSelectors, cssTokens, elementSelectors, inputNames, methodCallChecks, outputNames, propertyNames, symbolRemoval, } from './data'; /** Upgrade data that will be used for the Angular Material ng-update schematic. */ export const materialUpgradeData: UpgradeData = { attributeSelectors, classNames, constructorChecks, cssSelectors, cssTokens, elementSelectors, inputNames, methodCallChecks, outputNames, propertyNames, symbolRemoval, };
{ "end_byte": 799, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/upgrade-data.ts" }
components/src/material/schematics/ng-update/BUILD.bazel_0_2597
load("//tools:defaults.bzl", "esbuild", "jasmine_node_test", "spec_bundle", "ts_library") ## THIS ONE IS ESM # By default everything is ESM # ESBUild needs ESM for bundling. Cannot reliably use CJS as input. ts_library( name = "ng_update_lib", srcs = glob( ["**/*.ts"], exclude = [ "test-cases/**/*.ts", ], ), # Schematics can not yet run in ESM module. For now we continue to use CommonJS. # TODO(ESM): remove this once the Angular CLI supports ESM schematics. devmode_module = "commonjs", deps = [ "//src/cdk/schematics", "@npm//@angular-devkit/core", "@npm//@angular-devkit/schematics", "@npm//@schematics/angular", "@npm//@types/node", "@npm//postcss", "@npm//postcss-scss", "@npm//typescript", ], ) esbuild( name = "ng_update_index", entry_point = ":index.ts", external = [ "@angular/cdk/schematics", "@schematics/angular", "@angular-devkit/schematics", "@angular-devkit/core", "typescript", ], # TODO: Switch to ESM when Angular CLI supports it. format = "cjs", output = "index_bundled.js", platform = "node", target = "es2015", visibility = ["//src/material/schematics:__pkg__"], deps = [":ng_update_lib"], ) ################# ## Specs ################# filegroup( name = "schematics_test_cases", testonly = True, srcs = glob([ "test-cases/**/*_input.ts", "test-cases/**/*_expected_output.ts", ]), ) # This one is now ESM, the default in the repository # Needs to be ESM because we import frm `ng_update_lib` (which is also ESM) ts_library( name = "test_lib", testonly = True, srcs = glob(["**/*.spec.ts"]), deps = [ ":ng_update_lib", "//src/cdk/schematics", "//src/cdk/schematics/testing", "//src/material/schematics:paths", "@npm//@angular-devkit/core", "@npm//@angular-devkit/schematics", "@npm//@bazel/runfiles", "@npm//@types/jasmine", "@npm//@types/node", ], ) spec_bundle( name = "spec_bundle", external = [ "*/paths.js", "@angular-devkit/core/node", ], platform = "cjs-legacy", target = "es2020", deps = [":test_lib"], ) jasmine_node_test( name = "test", data = [ ":ng_update_index", ":schematics_test_cases", "//src/cdk/schematics", "//src/material/schematics:collection_assets", ], shard_count = 4, deps = [ ":spec_bundle", ], )
{ "end_byte": 2597, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/BUILD.bazel" }
components/src/material/schematics/ng-update/index.ts_0_1380
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Rule, SchematicContext} from '@angular-devkit/schematics'; import { createMigrationSchematicRule, NullableDevkitMigration, TargetVersion, } from '@angular/cdk/schematics'; import {materialUpgradeData} from './upgrade-data'; import {MatCoreMigration} from './migrations/mat-core-removal'; const materialMigrations: NullableDevkitMigration[] = [MatCoreMigration]; /** Entry point for the migration schematics with target of Angular Material v19 */ export function updateToV19(): Rule { return createMigrationSchematicRule( TargetVersion.V19, materialMigrations, materialUpgradeData, onMigrationComplete, ); } /** Function that will be called when the migration completed. */ function onMigrationComplete( context: SchematicContext, targetVersion: TargetVersion, hasFailures: boolean, ) { context.logger.info(''); context.logger.info(` ✓ Updated Angular Material to ${targetVersion}`); context.logger.info(''); if (hasFailures) { context.logger.warn( ' ⚠ Some issues were detected but could not be fixed automatically. Please check the ' + 'output above and fix these issues manually.', ); } }
{ "end_byte": 1380, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/index.ts" }
components/src/material/schematics/ng-update/test-cases/index.spec.ts_0_780
import {getAllVersionNames} from '@angular/cdk/schematics'; import {defineJasmineTestCases, findBazelVersionTestCases} from '@angular/cdk/schematics/testing'; import {MIGRATION_PATH} from '../../paths'; describe('Material upgrade test cases', () => { const versionNames = getAllVersionNames().map(versionName => versionName.toLowerCase()); const testCasesMap = findBazelVersionTestCases( 'angular_material/src/material/schematics/ng-update/test-cases', ); // Setup the test cases for each target version. The test cases will be automatically // detected through Bazel's runfiles manifest. versionNames.forEach(version => describe(`${version} update`, () => { defineJasmineTestCases(version, MIGRATION_PATH, testCasesMap.get(version)); }), ); });
{ "end_byte": 780, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/test-cases/index.spec.ts" }
components/src/material/schematics/ng-update/test-cases/v19-mat-core-removal.spec.ts_0_2792
import {UnitTestTree} from '@angular-devkit/schematics/testing'; import {createTestCaseSetup} from '@angular/cdk/schematics/testing'; import {join} from 'path'; import {MIGRATION_PATH} from '../../paths'; const PROJECT_ROOT_DIR = '/projects/cdk-testing'; const THEME_FILE_PATH = join(PROJECT_ROOT_DIR, 'src/theme.scss'); describe('v15 legacy components migration', () => { let tree: UnitTestTree; /** Writes multiple lines to a file. */ let writeLines: (path: string, lines: string[]) => void; /** Reads multiple lines from a file. */ let readLines: (path: string) => string[]; /** Runs the v15 migration on the test application. */ let runMigration: () => Promise<{logOutput: string}>; beforeEach(async () => { const testSetup = await createTestCaseSetup('migration-v19', MIGRATION_PATH, []); tree = testSetup.appTree; runMigration = testSetup.runFixers; readLines = (path: string) => tree.readContent(path).split('\n'); writeLines = (path: string, lines: string[]) => testSetup.writeFile(path, lines.join('\n')); }); describe('style migrations', () => { async function runSassMigrationTest(ctx: string, opts: {old: string[]; new: string[]}) { writeLines(THEME_FILE_PATH, opts.old); await runMigration(); expect(readLines(THEME_FILE_PATH)).withContext(ctx).toEqual(opts.new); } it('should remove uses of the core mixin', async () => { await runSassMigrationTest('', { old: [`@use '@angular/material' as mat;`, `@include mat.core();`], new: [ `@use '@angular/material' as mat;`, `@include mat.elevation-classes();`, `@include mat.app-background();`, ], }); await runSassMigrationTest('w/ unique namespace', { old: [`@use '@angular/material' as material;`, `@include material.core();`], new: [ `@use '@angular/material' as material;`, `@include material.elevation-classes();`, `@include material.app-background();`, ], }); await runSassMigrationTest('w/ no namespace', { old: [`@use '@angular/material';`, `@include material.core();`], new: [ `@use '@angular/material';`, `@include material.elevation-classes();`, `@include material.app-background();`, ], }); await runSassMigrationTest('w/ unique whitespace', { old: [ ` @use '@angular/material' as material ; `, ` @include material.core( ) ; `, ], new: [ ` @use '@angular/material' as material ; `, ` @include material.elevation-classes();`, ` @include material.app-background(); `, ], }); }); }); });
{ "end_byte": 2792, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/test-cases/v19-mat-core-removal.spec.ts" }
components/src/material/schematics/ng-update/migrations/mat-core-removal.ts_0_2807
/** * @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 * as postcss from 'postcss'; import * as scss from 'postcss-scss'; import { DevkitContext, Migration, ResolvedResource, UpgradeData, WorkspacePath, } from '@angular/cdk/schematics'; export class MatCoreMigration extends Migration<UpgradeData, DevkitContext> { override enabled = true; private _namespace: string | undefined; override init() { // TODO: Check if mat-app-background is used in the application. } override visitStylesheet(stylesheet: ResolvedResource): void { const processor = new postcss.Processor([ { postcssPlugin: 'mat-core-removal-v19-plugin', AtRule: { use: node => this._getNamespace(node), include: node => this._handleAtInclude(node, stylesheet.filePath), }, }, ]); processor.process(stylesheet.content, {syntax: scss}).sync(); } /** Handles updating the at-include rules of uses of the core mixin. */ private _handleAtInclude(node: postcss.AtRule, filePath: WorkspacePath): void { if (!this._namespace || !node.source?.start || !node.source.end) { return; } if (this._isMatCoreMixin(node)) { const end = node.source.end.offset; const start = node.source.start.offset; const prefix = '\n' + (node.raws.before?.split('\n').pop() || ''); const snippet = prefix + node.source.input.css.slice(start, end); const elevation = prefix + `@include ${this._namespace}.elevation-classes();`; const background = prefix + `@include ${this._namespace}.app-background();`; this._replaceAt(filePath, node.source.start.offset - prefix.length, { old: snippet, new: elevation + background, }); } } /** Returns true if the given at-rule is a use of the core mixin. */ private _isMatCoreMixin(node: postcss.AtRule): boolean { if (node.params.startsWith(`${this._namespace}.core`)) { return true; } return false; } /** Sets the namespace if the given at-rule if it is importing from @angular/material. */ private _getNamespace(node: postcss.AtRule): void { if (!this._namespace && node.params.startsWith('@angular/material', 1)) { this._namespace = node.params.split(/\s+/)[2] || 'material'; } } /** Updates the source file with the given replacements. */ private _replaceAt( filePath: WorkspacePath, offset: number, str: {old: string; new: string}, ): void { const index = this.fileSystem.read(filePath)!.indexOf(str.old, offset); this.fileSystem.edit(filePath).remove(index, str.old.length).insertRight(index, str.new); } }
{ "end_byte": 2807, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/migrations/mat-core-removal.ts" }
components/src/material/schematics/ng-update/typescript/module-specifiers.ts_0_1383
/** * @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 {getExportDeclaration, getImportDeclaration} from '@angular/cdk/schematics'; import * as ts from 'typescript'; /** Name of the Angular Material module specifier. */ export const materialModuleSpecifier = '@angular/material'; /** Name of the Angular CDK module specifier. */ export const cdkModuleSpecifier = '@angular/cdk'; /** Whether the specified node is part of an Angular Material or CDK import declaration. */ export function isMaterialImportDeclaration(node: ts.Node) { return isMaterialDeclaration(getImportDeclaration(node)); } /** Whether the specified node is part of an Angular Material or CDK import declaration. */ export function isMaterialExportDeclaration(node: ts.Node) { return isMaterialDeclaration(getExportDeclaration(node)); } /** Whether the declaration is part of Angular Material. */ function isMaterialDeclaration(declaration: ts.ImportDeclaration | ts.ExportDeclaration) { if (!declaration.moduleSpecifier) { return false; } const moduleSpecifier = declaration.moduleSpecifier.getText(); return ( moduleSpecifier.indexOf(materialModuleSpecifier) !== -1 || moduleSpecifier.indexOf(cdkModuleSpecifier) !== -1 ); }
{ "end_byte": 1383, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/typescript/module-specifiers.ts" }
components/src/material/schematics/ng-update/data/symbol-removal.ts_0_362
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {SymbolRemovalUpgradeData, VersionChanges} from '@angular/cdk/schematics'; export const symbolRemoval: VersionChanges<SymbolRemovalUpgradeData> = {};
{ "end_byte": 362, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/data/symbol-removal.ts" }