_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
components/src/material/schematics/ng-update/data/output-names.ts_0_354
/** * @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 {OutputNameUpgradeData, VersionChanges} from '@angular/cdk/schematics'; export const outputNames: VersionChanges<OutputNameUpgradeData> = {};
{ "end_byte": 354, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/data/output-names.ts" }
components/src/material/schematics/ng-update/data/property-names.ts_0_360
/** * @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 {PropertyNameUpgradeData, VersionChanges} from '@angular/cdk/schematics'; export const propertyNames: VersionChanges<PropertyNameUpgradeData> = {};
{ "end_byte": 360, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/data/property-names.ts" }
components/src/material/schematics/ng-update/data/attribute-selectors.ts_0_375
/** * @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 {AttributeSelectorUpgradeData, VersionChanges} from '@angular/cdk/schematics'; export const attributeSelectors: VersionChanges<AttributeSelectorUpgradeData> = {};
{ "end_byte": 375, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/data/attribute-selectors.ts" }
components/src/material/schematics/ng-update/data/class-names.ts_0_351
/** * @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 {ClassNameUpgradeData, VersionChanges} from '@angular/cdk/schematics'; export const classNames: VersionChanges<ClassNameUpgradeData> = {};
{ "end_byte": 351, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/data/class-names.ts" }
components/src/material/schematics/ng-update/data/method-call-checks.ts_0_359
/** * @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 {MethodCallUpgradeData, VersionChanges} from '@angular/cdk/schematics'; export const methodCallChecks: VersionChanges<MethodCallUpgradeData> = {};
{ "end_byte": 359, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/data/method-call-checks.ts" }
components/src/material/schematics/ng-update/data/css-tokens.ts_0_847
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {VersionChanges} from '@angular/cdk/schematics'; export interface MaterialCssTokenData { /** The CSS selector to replace. */ replace: string; /** The new CSS selector. */ replaceWith: string; /** * Controls which file types in which this replacement is made. If omitted, it is made in all * files. */ replaceIn?: { /** Replace this name in stylesheet files. */ stylesheet?: boolean; /** Replace this name in HTML files. */ html?: boolean; /** Replace this name in TypeScript strings. */ tsStringLiterals?: boolean; }; } export const cssTokens: VersionChanges<MaterialCssTokenData> = {};
{ "end_byte": 847, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/data/css-tokens.ts" }
components/src/material/schematics/ng-update/data/element-selectors.ts_0_369
/** * @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 {ElementSelectorUpgradeData, VersionChanges} from '@angular/cdk/schematics'; export const elementSelectors: VersionChanges<ElementSelectorUpgradeData> = {};
{ "end_byte": 369, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/data/element-selectors.ts" }
components/src/material/schematics/ng-update/data/constructor-checks.ts_0_608
/** * @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 {ConstructorChecksUpgradeData, VersionChanges} from '@angular/cdk/schematics'; /** * List of class names for which the constructor signature has been changed. The new constructor * signature types don't need to be stored here because the signature will be determined * automatically through type checking. */ export const constructorChecks: VersionChanges<ConstructorChecksUpgradeData> = {};
{ "end_byte": 608, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/data/constructor-checks.ts" }
components/src/material/schematics/ng-update/data/css-selectors.ts_0_856
/** * @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 {VersionChanges} from '@angular/cdk/schematics'; export interface MaterialCssSelectorData { /** The CSS selector to replace. */ replace: string; /** The new CSS selector. */ replaceWith: string; /** * Controls which file types in which this replacement is made. If omitted, it is made in all * files. */ replaceIn?: { /** Replace this name in stylesheet files. */ stylesheet?: boolean; /** Replace this name in HTML files. */ html?: boolean; /** Replace this name in TypeScript strings. */ tsStringLiterals?: boolean; }; } export const cssSelectors: VersionChanges<MaterialCssSelectorData> = {};
{ "end_byte": 856, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/data/css-selectors.ts" }
components/src/material/schematics/ng-update/data/index.ts_0_581
/** * @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 './attribute-selectors'; export * from './class-names'; export * from './constructor-checks'; export * from './css-selectors'; export * from './css-tokens'; export * from './element-selectors'; export * from './input-names'; export * from './method-call-checks'; export * from './output-names'; export * from './property-names'; export * from './symbol-removal';
{ "end_byte": 581, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/data/index.ts" }
components/src/material/schematics/ng-update/data/input-names.ts_0_351
/** * @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 {InputNameUpgradeData, VersionChanges} from '@angular/cdk/schematics'; export const inputNames: VersionChanges<InputNameUpgradeData> = {};
{ "end_byte": 351, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-update/data/input-names.ts" }
components/src/material/schematics/ng-generate/tree/schema.ts_0_336
/** * @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 {Schema as ComponentSchema} from '@schematics/angular/component/schema'; export interface Schema extends ComponentSchema {}
{ "end_byte": 336, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/tree/schema.ts" }
components/src/material/schematics/ng-generate/tree/index.spec.ts_0_6365
import {SchematicTestRunner} from '@angular-devkit/schematics/testing'; import {createTestApp, getFileContent} from '@angular/cdk/schematics/testing'; import {COLLECTION_PATH} from '../../paths'; import {Schema} from './schema'; describe('Material tree schematic', () => { let runner: SchematicTestRunner; const baseOptions: Schema = { name: 'foo', project: 'material', }; beforeEach(() => { runner = new SchematicTestRunner('schematics', COLLECTION_PATH); }); it('should create tree component files and add them to module', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('tree', baseOptions, app); const files = tree.files; expect(files).toContain('/projects/material/src/app/foo/foo.component.css'); expect(files).toContain('/projects/material/src/app/foo/foo.component.html'); expect(files).toContain('/projects/material/src/app/foo/foo.component.spec.ts'); expect(files).toContain('/projects/material/src/app/foo/foo.component.ts'); const moduleContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(moduleContent).toMatch(/import.*Foo.*from '.\/foo\/foo.component'/); expect(moduleContent).toMatch(/declarations:\s*\[[^\]]+?,\r?\n\s+FooComponent\r?\n/m); }); it('should add tree imports to module', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('tree', baseOptions, app); const moduleContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(moduleContent).toContain('MatTreeModule'); expect(moduleContent).toContain('MatIconModule'); expect(moduleContent).toContain('MatButtonModule'); }); it('should throw if no name has been specified', async () => { const appTree = await createTestApp(runner); await expectAsync( runner.runSchematic('tree', {project: 'material'}, appTree), ).toBeRejectedWithError(/required property 'name'/); }); describe('standalone option', () => { it('should generate a standalone component', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('tree', {...baseOptions, standalone: true}, app); const module = getFileContent(tree, '/projects/material/src/app/app.module.ts'); const component = getFileContent(tree, '/projects/material/src/app/foo/foo.component.ts'); const requiredModules = ['MatTreeModule', 'MatButtonModule', 'MatIconModule']; requiredModules.forEach(name => { expect(module).withContext('Module should not import dependencies').not.toContain(name); expect(component).withContext('Component should import dependencies').toContain(name); }); expect(module).not.toContain('FooComponent'); expect(component).toContain('standalone: true'); expect(component).toContain('imports: ['); }); it('should infer the standalone option from the project structure', async () => { const app = await createTestApp(runner, {standalone: true}); const tree = await runner.runSchematic('tree', baseOptions, app); const componentContent = getFileContent( tree, '/projects/material/src/app/foo/foo.component.ts', ); expect(tree.exists('/projects/material/src/app/app.module.ts')).toBe(false); expect(componentContent).toContain('standalone: true'); expect(componentContent).toContain('imports: ['); }); }); describe('style option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'tree', {style: 'scss', ...baseOptions}, await createTestApp(runner), ); expect(tree.files).toContain('/projects/material/src/app/foo/foo.component.scss'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'tree', baseOptions, await createTestApp(runner, {style: 'less'}), ); expect(tree.files).toContain('/projects/material/src/app/foo/foo.component.less'); }); }); describe('inlineStyle option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'tree', {inlineStyle: true, ...baseOptions}, await createTestApp(runner), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.css'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'tree', baseOptions, await createTestApp(runner, {inlineStyle: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.css'); }); }); describe('inlineTemplate option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'tree', {inlineTemplate: true, ...baseOptions}, await createTestApp(runner), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.html'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'tree', baseOptions, await createTestApp(runner, {inlineTemplate: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.html'); }); }); describe('skipTests option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'tree', {skipTests: true, ...baseOptions}, await createTestApp(runner), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.spec.ts'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'tree', baseOptions, await createTestApp(runner, {skipTests: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.spec.ts'); }); }); });
{ "end_byte": 6365, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/tree/index.spec.ts" }
components/src/material/schematics/ng-generate/tree/index.ts_0_1587
/** * @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 {chain, noop, Rule, Tree} from '@angular-devkit/schematics'; import { addModuleImportToModule, buildComponent, findModuleFromOptions, isStandaloneSchematic, } from '@angular/cdk/schematics'; import {Schema} from './schema'; /** * Scaffolds a new tree component. * Internally it bootstraps the base component schematic */ export default function (options: Schema): Rule { return chain([ buildComponent( {...options}, { template: './__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template', stylesheet: './__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template', }, ), options.skipImport ? noop() : addTreeModulesToModule(options), ]); } /** * Adds the required modules to the relative module. */ function addTreeModulesToModule(options: Schema) { return async (host: Tree) => { const isStandalone = await isStandaloneSchematic(host, options); if (!isStandalone) { const modulePath = (await findModuleFromOptions(host, options))!; addModuleImportToModule(host, modulePath, 'MatTreeModule', '@angular/material/tree'); addModuleImportToModule(host, modulePath, 'MatIconModule', '@angular/material/icon'); addModuleImportToModule(host, modulePath, 'MatButtonModule', '@angular/material/button'); } }; }
{ "end_byte": 1587, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/tree/index.ts" }
components/src/material/schematics/ng-generate/tree/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template_0_54
.type-icon { color: #757575; margin-right: 5px; }
{ "end_byte": 54, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/tree/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template" }
components/src/material/schematics/ng-generate/tree/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template_0_909
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl"> <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle matTreeNodePadding> <button mat-icon-button disabled></button> <mat-icon class="type-icon" [attr.aria-label]="node.type + 'icon'"> {{ node.type === 'file' ? 'description' : 'folder' }} </mat-icon> {{node.name}} </mat-tree-node> <mat-tree-node *matTreeNodeDef="let node; when: hasChild" matTreeNodePadding> <button mat-icon-button matTreeNodeToggle [attr.aria-label]="'Toggle ' + node.name"> <mat-icon class="mat-icon-rtl-mirror"> {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}} </mat-icon> </button> <mat-icon class="type-icon" [attr.aria-label]="node.type + 'icon'"> {{ node.type ==='file' ? 'description' : 'folder' }} </mat-icon> {{node.name}} </mat-tree-node> </mat-tree>
{ "end_byte": 909, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/tree/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template" }
components/src/material/schematics/ng-generate/tree/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.spec.ts.template_0_1101
import { <% if(!standalone) { %>waitForAsync, <% } %>ComponentFixture, TestBed } from '@angular/core/testing';<% if(!standalone) { %> import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatTreeModule } from '@angular/material/tree';<% } %> import { <%= classify(name) %>Component } from './<%= dasherize(name) %>.component'; describe('<%= classify(name) %>Component', () => { let component: <%= classify(name) %>Component; let fixture: ComponentFixture<<%= classify(name) %>Component>;<% if(!standalone) { %> beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [<%= classify(name) %>Component], imports: [ MatButtonModule, MatIconModule, MatTreeModule, ] }).compileComponents(); }));<% } %> beforeEach(() => { fixture = TestBed.createComponent(<%= classify(name) %>Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should compile', () => { expect(component).toBeTruthy(); }); });
{ "end_byte": 1101, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/tree/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.spec.ts.template" }
components/src/material/schematics/ng-generate/tree/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.ts.template_0_3263
import { Component<% if (!!viewEncapsulation) { %>, ViewEncapsulation<% }%><% if (changeDetection !== 'Default') { %>, ChangeDetectionStrategy<% }%> } from '@angular/core'; import { <% if(standalone) { %>MatTreeModule, <% } %>MatTreeFlatDataSource, MatTreeFlattener } from '@angular/material/tree'; import { FlatTreeControl } from '@angular/cdk/tree';<% if(standalone) { %> import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon';<% } %> import { files } from './example-data'; /** File node data with possible child nodes. */ export interface FileNode { name: string; type: string; children?: FileNode[]; } /** * Flattened tree node that has been created from a FileNode through the flattener. Flattened * nodes include level index and whether they can be expanded or not. */ export interface FlatTreeNode { name: string; type: string; level: number; expandable: boolean; } @Component({ selector: '<%= selector %>',<% if (inlineTemplate) { %> template: ` <%= indentTextContent(resolvedFiles.template, 4) %> `,<% } else { %> templateUrl: './<%= dasherize(name) %>.component.html',<% } if (inlineStyle) { %> styles: ` <%= indentTextContent(resolvedFiles.stylesheet, 4) %> `<% } else { %> styleUrl: './<%= dasherize(name) %>.component.<%= style %>'<% } %><% if(!!viewEncapsulation) { %>, encapsulation: ViewEncapsulation.<%= viewEncapsulation %><% } if (changeDetection !== 'Default') { %>, changeDetection: ChangeDetectionStrategy.<%= changeDetection %><% } %><% if(standalone) { %>, standalone: true, imports: [MatTreeModule, MatButtonModule, MatIconModule]<% } %> }) export class <%= classify(name) %>Component { /** The TreeControl controls the expand/collapse state of tree nodes. */ treeControl: FlatTreeControl<FlatTreeNode>; /** The TreeFlattener is used to generate the flat list of items from hierarchical data. */ treeFlattener: MatTreeFlattener<FileNode, FlatTreeNode>; /** The MatTreeFlatDataSource connects the control and flattener to provide data. */ dataSource: MatTreeFlatDataSource<FileNode, FlatTreeNode>; constructor() { this.treeFlattener = new MatTreeFlattener( this.transformer, this.getLevel, this.isExpandable, this.getChildren); this.treeControl = new FlatTreeControl(this.getLevel, this.isExpandable); this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener); this.dataSource.data = files; } /** Transform the data to something the tree can read. */ transformer(node: FileNode, level: number): FlatTreeNode { return { name: node.name, type: node.type, level, expandable: !!node.children }; } /** Get the level of the node */ getLevel(node: FlatTreeNode): number { return node.level; } /** Get whether the node is expanded or not. */ isExpandable(node: FlatTreeNode): boolean { return node.expandable; } /** Get whether the node has children or not. */ hasChild(index: number, node: FlatTreeNode): boolean { return node.expandable; } /** Get the children for the node. */ getChildren(node: FileNode): FileNode[] | null | undefined { return node.children; } }
{ "end_byte": 3263, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/tree/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.ts.template" }
components/src/material/schematics/ng-generate/tree/files/__path__/__name@dasherize@if-flat__/example-data.ts.template_0_968
/** Example file/folder data. */ export const files = [ { name: 'components', type: 'folder', children: [ { name: 'src', type: 'folder', children: [ { name: 'cdk', type: 'folder', children: [ { name: 'package.json', type: 'file' }, { name: 'BUILD.bazel', type: 'file' }, ] }, { name: 'material', type: 'folder' } ] } ] }, { name: 'angular', type: 'folder', children: [ { name: 'packages', type: 'folder', children: [ { name: '.travis.yml', type: 'file' }, { name: 'firebase.json', type: 'file' } ] }, { name: 'package.json', type: 'file' } ] }, { name: 'angularjs', type: 'folder', children: [ { name: 'gulpfile.js', type: 'file' }, { name: 'README.md', type: 'file' } ] } ];
{ "end_byte": 968, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/tree/files/__path__/__name@dasherize@if-flat__/example-data.ts.template" }
components/src/material/schematics/ng-generate/address-form/schema.ts_0_336
/** * @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 {Schema as ComponentSchema} from '@schematics/angular/component/schema'; export interface Schema extends ComponentSchema {}
{ "end_byte": 336, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/address-form/schema.ts" }
components/src/material/schematics/ng-generate/address-form/index.spec.ts_0_6972
import {SchematicTestRunner} from '@angular-devkit/schematics/testing'; import {createTestApp, getFileContent} from '@angular/cdk/schematics/testing'; import {COLLECTION_PATH} from '../../paths'; import {Schema} from './schema'; describe('Material address-form schematic', () => { let runner: SchematicTestRunner; const baseOptions: Schema = { name: 'foo', project: 'material', }; beforeEach(() => { runner = new SchematicTestRunner('schematics', COLLECTION_PATH); }); it('should create address-form files and add them to module', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('address-form', baseOptions, app); const files = tree.files; expect(files).toContain('/projects/material/src/app/foo/foo.component.css'); expect(files).toContain('/projects/material/src/app/foo/foo.component.html'); expect(files).toContain('/projects/material/src/app/foo/foo.component.spec.ts'); expect(files).toContain('/projects/material/src/app/foo/foo.component.ts'); const moduleContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(moduleContent).toMatch(/import.*Foo.*from '.\/foo\/foo.component'/); expect(moduleContent).toMatch(/declarations:\s*\[[^\]]+?,\r?\n\s+FooComponent\r?\n/m); }); it('should add address-form imports to module', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('address-form', baseOptions, app); const moduleContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(moduleContent).toContain('MatInputModule'); expect(moduleContent).toContain('MatButtonModule'); expect(moduleContent).toContain('MatSelectModule'); expect(moduleContent).toContain('MatRadioModule'); expect(moduleContent).toContain('ReactiveFormsModule'); }); it('should throw if no name has been specified', async () => { const appTree = await createTestApp(runner); await expectAsync( runner.runSchematic('address-form', {project: 'material'}, appTree), ).toBeRejectedWithError(/required property 'name'/); }); describe('standalone option', () => { it('should generate a standalone component', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic( 'address-form', {...baseOptions, standalone: true}, app, ); const module = getFileContent(tree, '/projects/material/src/app/app.module.ts'); const content = getFileContent(tree, '/projects/material/src/app/foo/foo.component.ts'); const requiredModules = [ 'MatInputModule', 'MatButtonModule', 'MatSelectModule', 'MatRadioModule', 'ReactiveFormsModule', ]; requiredModules.forEach(name => { expect(module).withContext('Module should not import dependencies').not.toContain(name); expect(content).withContext('Component should import dependencies').toContain(name); }); expect(module).not.toContain('FooComponent'); expect(content).toContain('standalone: true'); expect(content).toContain('imports: ['); }); it('should infer the standalone option from the project structure', async () => { const app = await createTestApp(runner, {standalone: true}); const tree = await runner.runSchematic('address-form', baseOptions, app); const component = getFileContent(tree, '/projects/material/src/app/foo/foo.component.ts'); expect(tree.exists('/projects/material/src/app/app.module.ts')).toBe(false); expect(component).toContain('standalone: true'); expect(component).toContain('imports: ['); }); }); describe('style option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'address-form', {style: 'scss', ...baseOptions}, await createTestApp(runner), ); expect(tree.files).toContain('/projects/material/src/app/foo/foo.component.scss'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'address-form', baseOptions, await createTestApp(runner, {style: 'less'}), ); expect(tree.files).toContain('/projects/material/src/app/foo/foo.component.less'); }); }); describe('inlineStyle option', () => { it('should respect the option value', async () => { const app = await createTestApp(runner); const tree = await runner.runSchematic( 'address-form', {inlineStyle: true, ...baseOptions}, app, ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.css'); expect(tree.readContent('/projects/material/src/app/foo/foo.component.ts')).toContain( 'styles: `', ); }); it('should fall back to the @schematics/angular:component option value', async () => { const app = await createTestApp(runner, {inlineStyle: true}); const tree = await runner.runSchematic('address-form', baseOptions, app); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.css'); }); }); describe('inlineTemplate option', () => { it('should respect the option value', async () => { const app = await createTestApp(runner); const tree = await runner.runSchematic( 'address-form', {inlineTemplate: true, ...baseOptions}, app, ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.html'); expect(tree.readContent('/projects/material/src/app/foo/foo.component.ts')).toContain( 'template: `', ); }); it('should fall back to the @schematics/angular:component option value', async () => { const app = await createTestApp(runner, {inlineTemplate: true}); const tree = await runner.runSchematic('address-form', baseOptions, app); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.html'); }); }); describe('skipTests option', () => { it('should respect the option value', async () => { const app = await createTestApp(runner); const tree = await runner.runSchematic( 'address-form', {skipTests: true, ...baseOptions}, app, ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.spec.ts'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'address-form', baseOptions, await createTestApp(runner, {skipTests: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.spec.ts'); }); }); });
{ "end_byte": 6972, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/address-form/index.spec.ts" }
components/src/material/schematics/ng-generate/address-form/index.ts_0_1870
/** * @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 {chain, noop, Rule, Tree} from '@angular-devkit/schematics'; import { addModuleImportToModule, buildComponent, findModuleFromOptions, isStandaloneSchematic, } from '@angular/cdk/schematics'; import {Schema} from './schema'; /** * Scaffolds a new table component. * Internally it bootstraps the base component schematic */ export default function (options: Schema): Rule { return chain([ buildComponent( {...options}, { template: './__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template', stylesheet: './__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template', }, ), options.skipImport ? noop() : addFormModulesToModule(options), ]); } /** * Adds the required modules to the relative module. */ function addFormModulesToModule(options: Schema) { return async (host: Tree) => { const isStandalone = await isStandaloneSchematic(host, options); if (!isStandalone) { const modulePath = (await findModuleFromOptions(host, options))!; addModuleImportToModule(host, modulePath, 'MatInputModule', '@angular/material/input'); addModuleImportToModule(host, modulePath, 'MatButtonModule', '@angular/material/button'); addModuleImportToModule(host, modulePath, 'MatSelectModule', '@angular/material/select'); addModuleImportToModule(host, modulePath, 'MatRadioModule', '@angular/material/radio'); addModuleImportToModule(host, modulePath, 'MatCardModule', '@angular/material/card'); addModuleImportToModule(host, modulePath, 'ReactiveFormsModule', '@angular/forms'); } }; }
{ "end_byte": 1870, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/address-form/index.ts" }
components/src/material/schematics/ng-generate/address-form/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template_0_283
.full-width { width: 100%; } .shipping-card { min-width: 120px; margin: 20px auto; } .mat-radio-button { display: block; margin: 5px 0; } .row { display: flex; flex-direction: row; } .col { flex: 1; margin-right: 20px; } .col:last-child { margin-right: 0; }
{ "end_byte": 283, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/address-form/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template" }
components/src/material/schematics/ng-generate/address-form/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template_0_3919
<form [formGroup]="addressForm" novalidate (ngSubmit)="onSubmit()"> <mat-card class="shipping-card"> <mat-card-header> <mat-card-title>Shipping Information</mat-card-title> </mat-card-header> <mat-card-content> <div class="row"> <div class="col"> <mat-form-field class="full-width"> <input matInput placeholder="Company" formControlName="company"> </mat-form-field> </div> </div> <div class="row"> <div class="col"> <mat-form-field class="full-width"> <input matInput placeholder="First name" formControlName="firstName"> @if (addressForm.controls['firstName'].hasError('required')) { <mat-error>First name is <strong>required</strong></mat-error> } </mat-form-field> </div> <div class="col"> <mat-form-field class="full-width"> <input matInput placeholder="Last name" formControlName="lastName"> @if (addressForm.controls['lastName'].hasError('required')) { <mat-error>Last name is <strong>required</strong></mat-error> } </mat-form-field> </div> </div> <div class="row"> <div class="col"> <mat-form-field class="full-width"> <textarea matInput placeholder="Address" formControlName="address"></textarea> @if (addressForm.controls['address'].hasError('required')) { <mat-error>Address is <strong>required</strong></mat-error> } </mat-form-field> </div> </div> <div class="row"> <div class="col"> @if (hasUnitNumber) { <mat-form-field class="full-width"> <textarea matInput placeholder="Address 2" formControlName="address2"></textarea> </mat-form-field> } @else { <button mat-button type="button" (click)="hasUnitNumber = !hasUnitNumber"> + Add C/O, Apt, Suite, Unit </button> } </div> </div> <div class="row"> <div class="col"> <mat-form-field class="full-width"> <input matInput placeholder="City" formControlName="city"> @if (addressForm.controls['city'].hasError('required')) { <mat-error>City is <strong>required</strong></mat-error> } </mat-form-field> </div> <div class="col"> <mat-form-field class="full-width"> <mat-select placeholder="State" formControlName="state"> @for (state of states; track state) { <mat-option [value]="state.abbreviation">{{ state.name }}</mat-option> } </mat-select> @if (addressForm.controls['state'].hasError('required')) { <mat-error>State is <strong>required</strong></mat-error> } </mat-form-field> </div> </div> <div class="row"> <div class="col"> <mat-form-field class="full-width"> <input matInput #postalCode maxlength="5" placeholder="Postal Code" type="number" formControlName="postalCode"> <mat-hint align="end">{{postalCode.value.length}} / 5</mat-hint> </mat-form-field> </div> </div> <div class="row"> <div class="col"> <mat-radio-group formControlName="shipping"> <mat-radio-button value="free">Free Shipping</mat-radio-button> <mat-radio-button value="priority">Priority Shipping</mat-radio-button> <mat-radio-button value="nextday">Next Day Shipping</mat-radio-button> </mat-radio-group> </div> </div> </mat-card-content> <mat-card-actions> <button mat-raised-button color="primary" type="submit">Submit</button> </mat-card-actions> </mat-card> </form>
{ "end_byte": 3919, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/address-form/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template" }
components/src/material/schematics/ng-generate/address-form/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.spec.ts.template_0_1482
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations';<% if(!standalone) { %> import { ReactiveFormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatInputModule } from '@angular/material/input'; import { MatRadioModule } from '@angular/material/radio'; import { MatSelectModule } from '@angular/material/select';<% } %> import { <%= classify(name) %>Component } from './<%= dasherize(name) %>.component'; describe('<%= classify(name) %>Component', () => { let component: <%= classify(name) %>Component; let fixture: ComponentFixture<<%= classify(name) %>Component>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({<% if(standalone) { %> imports: [NoopAnimationsModule]<% } else { %> declarations: [<%= classify(name) %>Component], imports: [ NoopAnimationsModule, ReactiveFormsModule, MatButtonModule, MatCardModule, MatInputModule, MatRadioModule, MatSelectModule, ]<% } %> }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(<%= classify(name) %>Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should compile', () => { expect(component).toBeTruthy(); }); });
{ "end_byte": 1482, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/address-form/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.spec.ts.template" }
components/src/material/schematics/ng-generate/address-form/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.ts.template_0_4777
import { Component, inject<% if(!!viewEncapsulation) { %>, ViewEncapsulation<% }%><% if(changeDetection !== 'Default') { %>, ChangeDetectionStrategy<% }%> } from '@angular/core'; <% if(standalone) { %> import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms'; import { MatInputModule } from '@angular/material/input'; import { MatButtonModule } from '@angular/material/button'; import { MatSelectModule } from '@angular/material/select'; import { MatRadioModule } from '@angular/material/radio'; import { MatCardModule } from '@angular/material/card'; <% } else { %> import { FormBuilder, Validators } from '@angular/forms'; <% } %> @Component({ selector: '<%= selector %>',<% if(inlineTemplate) { %> template: ` <%= indentTextContent(resolvedFiles.template, 4) %> `,<% } else { %> templateUrl: './<%= dasherize(name) %>.component.html',<% } if(inlineStyle) { %> styles: ` <%= indentTextContent(resolvedFiles.stylesheet, 4) %> `<% } else { %> styleUrl: './<%= dasherize(name) %>.component.<%= style %>'<% } %><% if(!!viewEncapsulation) { %>, encapsulation: ViewEncapsulation.<%= viewEncapsulation %><% } if (changeDetection !== 'Default') { %>, changeDetection: ChangeDetectionStrategy.<%= changeDetection %><% } %><% if(standalone) { %>, standalone: true, imports: [ MatInputModule, MatButtonModule, MatSelectModule, MatRadioModule, MatCardModule, ReactiveFormsModule ]<% } %> }) export class <%= classify(name) %>Component { private fb = inject(FormBuilder); addressForm = this.fb.group({ company: null, firstName: [null, Validators.required], lastName: [null, Validators.required], address: [null, Validators.required], address2: null, city: [null, Validators.required], state: [null, Validators.required], postalCode: [null, Validators.compose([ Validators.required, Validators.minLength(5), Validators.maxLength(5)]) ], shipping: ['free', Validators.required] }); hasUnitNumber = false; states = [ {name: 'Alabama', abbreviation: 'AL'}, {name: 'Alaska', abbreviation: 'AK'}, {name: 'American Samoa', abbreviation: 'AS'}, {name: 'Arizona', abbreviation: 'AZ'}, {name: 'Arkansas', abbreviation: 'AR'}, {name: 'California', abbreviation: 'CA'}, {name: 'Colorado', abbreviation: 'CO'}, {name: 'Connecticut', abbreviation: 'CT'}, {name: 'Delaware', abbreviation: 'DE'}, {name: 'District Of Columbia', abbreviation: 'DC'}, {name: 'Federated States Of Micronesia', abbreviation: 'FM'}, {name: 'Florida', abbreviation: 'FL'}, {name: 'Georgia', abbreviation: 'GA'}, {name: 'Guam', abbreviation: 'GU'}, {name: 'Hawaii', abbreviation: 'HI'}, {name: 'Idaho', abbreviation: 'ID'}, {name: 'Illinois', abbreviation: 'IL'}, {name: 'Indiana', abbreviation: 'IN'}, {name: 'Iowa', abbreviation: 'IA'}, {name: 'Kansas', abbreviation: 'KS'}, {name: 'Kentucky', abbreviation: 'KY'}, {name: 'Louisiana', abbreviation: 'LA'}, {name: 'Maine', abbreviation: 'ME'}, {name: 'Marshall Islands', abbreviation: 'MH'}, {name: 'Maryland', abbreviation: 'MD'}, {name: 'Massachusetts', abbreviation: 'MA'}, {name: 'Michigan', abbreviation: 'MI'}, {name: 'Minnesota', abbreviation: 'MN'}, {name: 'Mississippi', abbreviation: 'MS'}, {name: 'Missouri', abbreviation: 'MO'}, {name: 'Montana', abbreviation: 'MT'}, {name: 'Nebraska', abbreviation: 'NE'}, {name: 'Nevada', abbreviation: 'NV'}, {name: 'New Hampshire', abbreviation: 'NH'}, {name: 'New Jersey', abbreviation: 'NJ'}, {name: 'New Mexico', abbreviation: 'NM'}, {name: 'New York', abbreviation: 'NY'}, {name: 'North Carolina', abbreviation: 'NC'}, {name: 'North Dakota', abbreviation: 'ND'}, {name: 'Northern Mariana Islands', abbreviation: 'MP'}, {name: 'Ohio', abbreviation: 'OH'}, {name: 'Oklahoma', abbreviation: 'OK'}, {name: 'Oregon', abbreviation: 'OR'}, {name: 'Palau', abbreviation: 'PW'}, {name: 'Pennsylvania', abbreviation: 'PA'}, {name: 'Puerto Rico', abbreviation: 'PR'}, {name: 'Rhode Island', abbreviation: 'RI'}, {name: 'South Carolina', abbreviation: 'SC'}, {name: 'South Dakota', abbreviation: 'SD'}, {name: 'Tennessee', abbreviation: 'TN'}, {name: 'Texas', abbreviation: 'TX'}, {name: 'Utah', abbreviation: 'UT'}, {name: 'Vermont', abbreviation: 'VT'}, {name: 'Virgin Islands', abbreviation: 'VI'}, {name: 'Virginia', abbreviation: 'VA'}, {name: 'Washington', abbreviation: 'WA'}, {name: 'West Virginia', abbreviation: 'WV'}, {name: 'Wisconsin', abbreviation: 'WI'}, {name: 'Wyoming', abbreviation: 'WY'} ]; onSubmit(): void { alert('Thanks!'); } }
{ "end_byte": 4777, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/address-form/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.ts.template" }
components/src/material/schematics/ng-generate/navigation/schema.ts_0_336
/** * @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 {Schema as ComponentSchema} from '@schematics/angular/component/schema'; export interface Schema extends ComponentSchema {}
{ "end_byte": 336, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/navigation/schema.ts" }
components/src/material/schematics/ng-generate/navigation/index.spec.ts_0_8438
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing'; import {createTestApp, getFileContent} from '@angular/cdk/schematics/testing'; import {COLLECTION_PATH} from '../../paths'; import {Schema} from './schema'; describe('material-navigation-schematic', () => { let runner: SchematicTestRunner; const baseOptions: Schema = { name: 'foo', project: 'material', }; beforeEach(() => { runner = new SchematicTestRunner('schematics', COLLECTION_PATH); }); function expectNavigationSchematicModuleImports(tree: UnitTestTree) { const moduleContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(moduleContent).toMatch(/MatToolbarModule,\s+/); expect(moduleContent).toMatch(/MatButtonModule,\s+/); expect(moduleContent).toMatch(/MatSidenavModule,\s+/); expect(moduleContent).toMatch(/MatIconModule,\s+/); expect(moduleContent).toMatch(/MatListModule\s+],/); expect(moduleContent).toContain(`import { MatButtonModule } from '@angular/material/button';`); expect(moduleContent).toContain(`import { MatIconModule } from '@angular/material/icon';`); expect(moduleContent).toContain(`import { MatListModule } from '@angular/material/list';`); expect(moduleContent).toContain( `import { MatToolbarModule } from '@angular/material/toolbar';`, ); expect(moduleContent).toContain( `import { MatSidenavModule } from '@angular/material/sidenav';`, ); } it('should create navigation files and add them to module', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('navigation', baseOptions, app); const files = tree.files; expect(files).toContain('/projects/material/src/app/foo/foo.component.css'); expect(files).toContain('/projects/material/src/app/foo/foo.component.html'); expect(files).toContain('/projects/material/src/app/foo/foo.component.spec.ts'); expect(files).toContain('/projects/material/src/app/foo/foo.component.ts'); const moduleContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(moduleContent).toMatch(/import.*Foo.*from '.\/foo\/foo.component'/); expect(moduleContent).toMatch(/declarations:\s*\[[^\]]+?,\r?\n\s+FooComponent\r?\n/m); }); it('should add navigation imports to module', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('navigation', baseOptions, app); expectNavigationSchematicModuleImports(tree); }); it('should support `nav` as schematic alias', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('nav', baseOptions, app); expectNavigationSchematicModuleImports(tree); }); it('should throw if no name has been specified', async () => { const appTree = await createTestApp(runner); await expectAsync( runner.runSchematic('navigation', {project: 'material'}, appTree), ).toBeRejectedWithError(/required property 'name'/); }); describe('standalone option', () => { it('should generate a standalone component', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('navigation', {...baseOptions, standalone: true}, app); const module = getFileContent(tree, '/projects/material/src/app/app.module.ts'); const component = getFileContent(tree, '/projects/material/src/app/foo/foo.component.ts'); const requiredModules = [ 'MatToolbarModule', 'MatButtonModule', 'MatSidenavModule', 'MatListModule', 'MatIconModule', ]; requiredModules.forEach(name => { expect(module).withContext('Module should not import dependencies').not.toContain(name); expect(component).withContext('Component should import dependencies').toContain(name); }); expect(module).not.toContain('FooComponent'); expect(component).toContain('standalone: true'); expect(component).toContain('imports: ['); }); it('should infer the standalone option from the project structure', async () => { const app = await createTestApp(runner, {standalone: true}); const tree = await runner.runSchematic('navigation', baseOptions, app); const componentContent = getFileContent( tree, '/projects/material/src/app/foo/foo.component.ts', ); expect(tree.exists('/projects/material/src/app/app.module.ts')).toBe(false); expect(componentContent).toContain('standalone: true'); expect(componentContent).toContain('imports: ['); }); }); describe('style option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'navigation', {style: 'scss', ...baseOptions}, await createTestApp(runner), ); expect(tree.files).toContain('/projects/material/src/app/foo/foo.component.scss'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'navigation', baseOptions, await createTestApp(runner, {style: 'less'}), ); expect(tree.files).toContain('/projects/material/src/app/foo/foo.component.less'); }); }); describe('inlineStyle option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'navigation', {inlineStyle: true, ...baseOptions}, await createTestApp(runner), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.css'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'navigation', baseOptions, await createTestApp(runner, {inlineStyle: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.css'); }); }); describe('inlineTemplate option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'navigation', {inlineTemplate: true, ...baseOptions}, await createTestApp(runner), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.html'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'navigation', baseOptions, await createTestApp(runner, {inlineTemplate: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.html'); }); }); describe('skipTests option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'navigation', {skipTests: true, ...baseOptions}, await createTestApp(runner), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.spec.ts'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'navigation', baseOptions, await createTestApp(runner, {skipTests: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.spec.ts'); }); }); describe('router option', () => { it('should respect the option value if routing true', async () => { const tree = await runner.runSchematic( 'navigation', {routing: true, ...baseOptions}, await createTestApp(runner), ); const template = tree.readContent('/projects/material/src/app/foo/foo.component.html'); expect(template).toContain('<a mat-list-item routerLink="/">Link 1</a>'); }); it('should respect the option value if routing false', async () => { const tree = await runner.runSchematic( 'navigation', {routing: false, ...baseOptions}, await createTestApp(runner), ); const template = tree.readContent('/projects/material/src/app/foo/foo.component.html'); expect(template).toContain('<a mat-list-item href="#">Link 1</a>'); }); }); });
{ "end_byte": 8438, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/navigation/index.spec.ts" }
components/src/material/schematics/ng-generate/navigation/index.ts_0_1787
/** * @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 {chain, noop, Rule, Tree} from '@angular-devkit/schematics'; import { addModuleImportToModule, buildComponent, findModuleFromOptions, isStandaloneSchematic, } from '@angular/cdk/schematics'; import {Schema} from './schema'; /** * Scaffolds a new navigation component. * Internally it bootstraps the base component schematic */ export default function (options: Schema): Rule { return chain([ buildComponent( {...options}, { template: './__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template', stylesheet: './__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template', }, ), options.skipImport ? noop() : addNavModulesToModule(options), ]); } /** * Adds the required modules to the relative module. */ function addNavModulesToModule(options: Schema) { return async (host: Tree) => { const isStandalone = await isStandaloneSchematic(host, options); if (!isStandalone) { const modulePath = (await findModuleFromOptions(host, options))!; addModuleImportToModule(host, modulePath, 'MatToolbarModule', '@angular/material/toolbar'); addModuleImportToModule(host, modulePath, 'MatButtonModule', '@angular/material/button'); addModuleImportToModule(host, modulePath, 'MatSidenavModule', '@angular/material/sidenav'); addModuleImportToModule(host, modulePath, 'MatIconModule', '@angular/material/icon'); addModuleImportToModule(host, modulePath, 'MatListModule', '@angular/material/list'); } }; }
{ "end_byte": 1787, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/navigation/index.ts" }
components/src/material/schematics/ng-generate/navigation/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template_0_193
.sidenav-container { height: 100%; } .sidenav { width: 200px; } .sidenav .mat-toolbar { background: inherit; } .mat-toolbar.mat-primary { position: sticky; top: 0; z-index: 1; }
{ "end_byte": 193, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/navigation/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template" }
components/src/material/schematics/ng-generate/navigation/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template_0_1071
<mat-sidenav-container class="sidenav-container"> <mat-sidenav #drawer class="sidenav" fixedInViewport [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'" [mode]="(isHandset$ | async) ? 'over' : 'side'" [opened]="(isHandset$ | async) === false"> <mat-toolbar>Menu</mat-toolbar> <mat-nav-list> <a mat-list-item <%= routing ? 'routerLink="/"' : 'href="#"' %>>Link 1</a> <a mat-list-item <%= routing ? 'routerLink="/"' : 'href="#"' %>>Link 2</a> <a mat-list-item <%= routing ? 'routerLink="/"' : 'href="#"' %>>Link 3</a> </mat-nav-list> </mat-sidenav> <mat-sidenav-content> <mat-toolbar color="primary"> @if (isHandset$ | async) { <button type="button" aria-label="Toggle sidenav" mat-icon-button (click)="drawer.toggle()"> <mat-icon aria-label="Side nav toggle icon">menu</mat-icon> </button> } <span><%= project %></span> </mat-toolbar> <!-- Add Content Here --> </mat-sidenav-content> </mat-sidenav-container>
{ "end_byte": 1071, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/navigation/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template" }
components/src/material/schematics/ng-generate/navigation/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.spec.ts.template_0_1405
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations';<% if(!standalone) { %> import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatListModule } from '@angular/material/list'; import { MatSidenavModule } from '@angular/material/sidenav'; import { MatToolbarModule } from '@angular/material/toolbar';<% } %> import { <%= classify(name) %>Component } from './<%= dasherize(name) %>.component'; describe('<%= classify(name) %>Component', () => { let component: <%= classify(name) %>Component; let fixture: ComponentFixture<<%= classify(name) %>Component>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({<% if(standalone) { %> imports: [NoopAnimationsModule]<% } else { %> declarations: [<%= classify(name) %>Component], imports: [ NoopAnimationsModule, MatButtonModule, MatIconModule, MatListModule, MatSidenavModule, MatToolbarModule, ]<% } %> }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(<%= classify(name) %>Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should compile', () => { expect(component).toBeTruthy(); }); });
{ "end_byte": 1405, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/navigation/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.spec.ts.template" }
components/src/material/schematics/ng-generate/navigation/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.ts.template_0_1776
import { Component, inject<% if(!!viewEncapsulation) { %>, ViewEncapsulation<% }%><% if(changeDetection !== 'Default') { %>, ChangeDetectionStrategy<% }%> } from '@angular/core'; import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';<% if(standalone) { %> import { AsyncPipe } from '@angular/common'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatButtonModule } from '@angular/material/button'; import { MatSidenavModule } from '@angular/material/sidenav'; import { MatListModule } from '@angular/material/list'; import { MatIconModule } from '@angular/material/icon';<% } %> import { Observable } from 'rxjs'; import { map, shareReplay } from 'rxjs/operators'; @Component({ selector: '<%= selector %>',<% if(inlineTemplate) { %> template: ` <%= indentTextContent(resolvedFiles.template, 4) %> `,<% } else { %> templateUrl: './<%= dasherize(name) %>.component.html',<% } if(inlineStyle) { %> styles: ` <%= indentTextContent(resolvedFiles.stylesheet, 4) %> `<% } else { %> styleUrl: './<%= dasherize(name) %>.component.<%= style %>'<% } %><% if(!!viewEncapsulation) { %>, encapsulation: ViewEncapsulation.<%= viewEncapsulation %><% } if (changeDetection !== 'Default') { %>, changeDetection: ChangeDetectionStrategy.<%= changeDetection %><% } %><% if(standalone) { %>, standalone: true, imports: [ MatToolbarModule, MatButtonModule, MatSidenavModule, MatListModule, MatIconModule, AsyncPipe, ]<% } %> }) export class <%= classify(name) %>Component { private breakpointObserver = inject(BreakpointObserver); isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset) .pipe( map(result => result.matches), shareReplay() ); }
{ "end_byte": 1776, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/navigation/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.ts.template" }
components/src/material/schematics/ng-generate/dashboard/schema.ts_0_336
/** * @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 {Schema as ComponentSchema} from '@schematics/angular/component/schema'; export interface Schema extends ComponentSchema {}
{ "end_byte": 336, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/dashboard/schema.ts" }
components/src/material/schematics/ng-generate/dashboard/index.spec.ts_0_7145
import {SchematicTestRunner} from '@angular-devkit/schematics/testing'; import {createTestApp, getFileContent} from '@angular/cdk/schematics/testing'; import {COLLECTION_PATH} from '../../paths'; import {Schema} from './schema'; describe('material-dashboard-schematic', () => { let runner: SchematicTestRunner; const baseOptions: Schema = { name: 'foo', project: 'material', }; beforeEach(() => { runner = new SchematicTestRunner('schematics', COLLECTION_PATH); }); it('should create dashboard files and add them to module', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('dashboard', baseOptions, app); const files = tree.files; expect(files).toContain('/projects/material/src/app/foo/foo.component.css'); expect(files).toContain('/projects/material/src/app/foo/foo.component.html'); expect(files).toContain('/projects/material/src/app/foo/foo.component.spec.ts'); expect(files).toContain('/projects/material/src/app/foo/foo.component.ts'); const moduleContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(moduleContent).toMatch(/import.*Foo.*from '.\/foo\/foo.component'/); expect(moduleContent).toMatch(/declarations:\s*\[[^\]]+?,\r?\n\s+FooComponent\r?\n/m); }); it('should add dashboard imports to module', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('dashboard', baseOptions, app); const moduleContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(moduleContent).toContain('MatGridListModule'); expect(moduleContent).toContain('MatCardModule'); expect(moduleContent).toContain('MatMenuModule'); expect(moduleContent).toContain('MatIconModule'); expect(moduleContent).toContain('MatButtonModule'); expect(moduleContent).toContain( `import { MatGridListModule } from '@angular/material/grid-list';`, ); expect(moduleContent).toContain(`import { MatCardModule } from '@angular/material/card';`); expect(moduleContent).toContain(`import { MatMenuModule } from '@angular/material/menu';`); expect(moduleContent).toContain(`import { MatIconModule } from '@angular/material/icon';`); expect(moduleContent).toContain(`import { MatButtonModule } from '@angular/material/button';`); }); it('should throw if no name has been specified', async () => { const appTree = await createTestApp(runner); await expectAsync( runner.runSchematic('dashboard', {project: 'material'}, appTree), ).toBeRejectedWithError(/required property 'name'/); }); describe('standalone option', () => { it('should generate a standalone component', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('dashboard', {...baseOptions, standalone: true}, app); const module = getFileContent(tree, '/projects/material/src/app/app.module.ts'); const component = getFileContent(tree, '/projects/material/src/app/foo/foo.component.ts'); const requiredModules = [ 'MatButtonModule', 'MatCardModule', 'MatGridListModule', 'MatIconModule', 'MatMenuModule', ]; requiredModules.forEach(name => { expect(module).withContext('Module should not import dependencies').not.toContain(name); expect(component).withContext('Component should import dependencies').toContain(name); }); expect(module).not.toContain('FooComponent'); expect(component).toContain('standalone: true'); expect(component).toContain('imports: ['); }); it('should infer the standalone option from the project structure', async () => { const app = await createTestApp(runner, {standalone: true}); const tree = await runner.runSchematic('dashboard', baseOptions, app); const componentContent = getFileContent( tree, '/projects/material/src/app/foo/foo.component.ts', ); expect(tree.exists('/projects/material/src/app/app.module.ts')).toBe(false); expect(componentContent).toContain('standalone: true'); expect(componentContent).toContain('imports: ['); }); }); describe('style option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'dashboard', {style: 'scss', ...baseOptions}, await createTestApp(runner), ); expect(tree.files).toContain('/projects/material/src/app/foo/foo.component.scss'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'dashboard', baseOptions, await createTestApp(runner, {style: 'less'}), ); expect(tree.files).toContain('/projects/material/src/app/foo/foo.component.less'); }); }); describe('inlineStyle option', () => { it('should respect the option value', async () => { const app = await createTestApp(runner); const tree = await runner.runSchematic('dashboard', {inlineStyle: true, ...baseOptions}, app); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.css'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'dashboard', baseOptions, await createTestApp(runner, {inlineStyle: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.css'); }); }); describe('inlineTemplate option', () => { it('should respect the option value', async () => { const app = await createTestApp(runner); const tree = await runner.runSchematic( 'dashboard', {inlineTemplate: true, ...baseOptions}, app, ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.html'); }); it('should fall back to the @schematics/angular:component option value', async () => { const app = await createTestApp(runner, {inlineTemplate: true}); const tree = await runner.runSchematic('dashboard', baseOptions, app); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.html'); }); }); describe('skipTests option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'dashboard', {skipTests: true, ...baseOptions}, await createTestApp(runner), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.spec.ts'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'dashboard', baseOptions, await createTestApp(runner, {skipTests: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.spec.ts'); }); }); });
{ "end_byte": 7145, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/dashboard/index.spec.ts" }
components/src/material/schematics/ng-generate/dashboard/index.ts_0_1783
/** * @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 {chain, noop, Rule, Tree} from '@angular-devkit/schematics'; import { addModuleImportToModule, buildComponent, findModuleFromOptions, isStandaloneSchematic, } from '@angular/cdk/schematics'; import {Schema} from './schema'; /** * Scaffolds a new dashboard component. * Internally it bootstraps the base component schematic */ export default function (options: Schema): Rule { return chain([ buildComponent( {...options}, { template: './__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template', stylesheet: './__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template', }, ), options.skipImport ? noop() : addNavModulesToModule(options), ]); } /** * Adds the required modules to the relative module. */ function addNavModulesToModule(options: Schema) { return async (host: Tree) => { const isStandalone = await isStandaloneSchematic(host, options); if (!isStandalone) { const modulePath = (await findModuleFromOptions(host, options))!; addModuleImportToModule(host, modulePath, 'MatGridListModule', '@angular/material/grid-list'); addModuleImportToModule(host, modulePath, 'MatCardModule', '@angular/material/card'); addModuleImportToModule(host, modulePath, 'MatMenuModule', '@angular/material/menu'); addModuleImportToModule(host, modulePath, 'MatIconModule', '@angular/material/icon'); addModuleImportToModule(host, modulePath, 'MatButtonModule', '@angular/material/button'); } }; }
{ "end_byte": 1783, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/dashboard/index.ts" }
components/src/material/schematics/ng-generate/dashboard/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template_0_255
.grid-container { margin: 20px; } .dashboard-card { position: absolute; top: 15px; left: 15px; right: 15px; bottom: 15px; } .more-button { position: absolute; top: 5px; right: 10px; } .dashboard-card-content { text-align: center; }
{ "end_byte": 255, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/dashboard/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template" }
components/src/material/schematics/ng-generate/dashboard/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template_0_992
<div class="grid-container"> <h1 class="mat-h1">Dashboard</h1> <mat-grid-list cols="2" rowHeight="350px"> @for (card of cards | async; track card) { <mat-grid-tile [colspan]="card.cols" [rowspan]="card.rows"> <mat-card class="dashboard-card"> <mat-card-header> <mat-card-title> {{card.title}} <button mat-icon-button class="more-button" [matMenuTriggerFor]="menu" aria-label="Toggle menu"> <mat-icon>more_vert</mat-icon> </button> <mat-menu #menu="matMenu" xPosition="before"> <button mat-menu-item>Expand</button> <button mat-menu-item>Remove</button> </mat-menu> </mat-card-title> </mat-card-header> <mat-card-content class="dashboard-card-content"> <div>Card Content Here</div> </mat-card-content> </mat-card> </mat-grid-tile> } </mat-grid-list> </div>
{ "end_byte": 992, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/dashboard/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template" }
components/src/material/schematics/ng-generate/dashboard/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.spec.ts.template_0_1400
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations';<% if(!standalone) { %> import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatGridListModule } from '@angular/material/grid-list'; import { MatIconModule } from '@angular/material/icon'; import { MatMenuModule } from '@angular/material/menu';<% } %> import { <%= classify(name) %>Component } from './<%= dasherize(name) %>.component'; describe('<%= classify(name) %>Component', () => { let component: <%= classify(name) %>Component; let fixture: ComponentFixture<<%= classify(name) %>Component>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({<% if(standalone) { %> imports: [NoopAnimationsModule]<% } else { %> declarations: [<%= classify(name) %>Component], imports: [ NoopAnimationsModule, MatButtonModule, MatCardModule, MatGridListModule, MatIconModule, MatMenuModule, ]<% } %> }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(<%= classify(name) %>Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should compile', () => { expect(component).toBeTruthy(); }); });
{ "end_byte": 1400, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/dashboard/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.spec.ts.template" }
components/src/material/schematics/ng-generate/dashboard/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.ts.template_0_2208
import { Component, inject<% if(!!viewEncapsulation) { %>, ViewEncapsulation<% }%><% if(changeDetection !== 'Default') { %>, ChangeDetectionStrategy<% }%> } from '@angular/core'; import { Breakpoints, BreakpointObserver } from '@angular/cdk/layout'; import { map } from 'rxjs/operators';<% if(standalone) { %> import { AsyncPipe } from '@angular/common'; import { MatGridListModule } from '@angular/material/grid-list'; import { MatMenuModule } from '@angular/material/menu'; import { MatIconModule } from '@angular/material/icon'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card';<% } %> @Component({ selector: '<%= selector %>',<% if(inlineTemplate) { %> template: ` <%= indentTextContent(resolvedFiles.template, 4) %> `,<% } else { %> templateUrl: './<%= dasherize(name) %>.component.html',<% } if(inlineStyle) { %> styles: ` <%= indentTextContent(resolvedFiles.stylesheet, 4) %> `<% } else { %> styleUrl: './<%= dasherize(name) %>.component.<%= style %>'<% } %><% if(!!viewEncapsulation) { %>, encapsulation: ViewEncapsulation.<%= viewEncapsulation %><% } if (changeDetection !== 'Default') { %>, changeDetection: ChangeDetectionStrategy.<%= changeDetection %><% } %><% if(standalone) { %>, standalone: true, imports: [ AsyncPipe, MatGridListModule, MatMenuModule, MatIconModule, MatButtonModule, MatCardModule ]<% } %> }) export class <%= classify(name) %>Component { private breakpointObserver = inject(BreakpointObserver); /** Based on the screen size, switch from standard to one column per row */ cards = this.breakpointObserver.observe(Breakpoints.Handset).pipe( map(({ matches }) => { if (matches) { return [ { title: 'Card 1', cols: 1, rows: 1 }, { title: 'Card 2', cols: 1, rows: 1 }, { title: 'Card 3', cols: 1, rows: 1 }, { title: 'Card 4', cols: 1, rows: 1 } ]; } return [ { title: 'Card 1', cols: 2, rows: 1 }, { title: 'Card 2', cols: 1, rows: 1 }, { title: 'Card 3', cols: 1, rows: 2 }, { title: 'Card 4', cols: 1, rows: 1 } ]; }) ); }
{ "end_byte": 2208, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/dashboard/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.ts.template" }
components/src/material/schematics/ng-generate/table/schema.ts_0_336
/** * @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 {Schema as ComponentSchema} from '@schematics/angular/component/schema'; export interface Schema extends ComponentSchema {}
{ "end_byte": 336, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/table/schema.ts" }
components/src/material/schematics/ng-generate/table/index.spec.ts_0_7189
import {SchematicTestRunner} from '@angular-devkit/schematics/testing'; import {createTestApp, getFileContent} from '@angular/cdk/schematics/testing'; import {COLLECTION_PATH} from '../../paths'; import {Schema} from './schema'; describe('material-table-schematic', () => { let runner: SchematicTestRunner; const baseOptions: Schema = { name: 'foo', project: 'material', }; beforeEach(() => { runner = new SchematicTestRunner('schematics', COLLECTION_PATH); }); it('should create table files and add them to module', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('table', baseOptions, app); const files = tree.files; expect(files).toContain('/projects/material/src/app/foo/foo.component.css'); expect(files).toContain('/projects/material/src/app/foo/foo.component.html'); expect(files).toContain('/projects/material/src/app/foo/foo.component.spec.ts'); expect(files).toContain('/projects/material/src/app/foo/foo.component.ts'); expect(files).toContain('/projects/material/src/app/foo/foo-datasource.ts'); const moduleContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(moduleContent).toMatch(/import.*Foo.*from '.\/foo\/foo.component'/); expect(moduleContent).toMatch(/declarations:\s*\[[^\]]+?,\r?\n\s+FooComponent\r?\n/m); const datasourceContent = getFileContent( tree, '/projects/material/src/app/foo/foo-datasource.ts', ); expect(datasourceContent).toContain('FooItem'); expect(datasourceContent).toContain('FooDataSource'); const componentContent = getFileContent( tree, '/projects/material/src/app/foo/foo.component.ts', ); expect(componentContent).toContain('FooDataSource'); }); it('should add table imports to module', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('table', baseOptions, app); const moduleContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(moduleContent).toContain('MatTableModule'); expect(moduleContent).toContain('MatPaginatorModule'); expect(moduleContent).toContain('MatSortModule'); expect(moduleContent).toContain(`import { MatTableModule } from '@angular/material/table';`); expect(moduleContent).toContain(`import { MatSortModule } from '@angular/material/sort';`); expect(moduleContent).toContain( `import { MatPaginatorModule } from '@angular/material/paginator';`, ); }); it('should throw if no name has been specified', async () => { const appTree = await createTestApp(runner); await expectAsync( runner.runSchematic('table', {project: 'material'}, appTree), ).toBeRejectedWithError(/required property 'name'/); }); describe('standalone option', () => { it('should generate a standalone component', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('table', {...baseOptions, standalone: true}, app); const module = getFileContent(tree, '/projects/material/src/app/app.module.ts'); const component = getFileContent(tree, '/projects/material/src/app/foo/foo.component.ts'); const requiredModules = ['MatTableModule', 'MatPaginatorModule', 'MatSortModule']; requiredModules.forEach(name => { expect(module).withContext('Module should not import dependencies').not.toContain(name); expect(component).withContext('Component should import dependencies').toContain(name); }); expect(module).not.toContain('FooComponent'); expect(component).toContain('standalone: true'); expect(component).toContain('imports: ['); }); it('should infer the standalone option from the project structure', async () => { const app = await createTestApp(runner, {standalone: true}); const tree = await runner.runSchematic('table', baseOptions, app); const componentContent = getFileContent( tree, '/projects/material/src/app/foo/foo.component.ts', ); expect(tree.exists('/projects/material/src/app/app.module.ts')).toBe(false); expect(componentContent).toContain('standalone: true'); expect(componentContent).toContain('imports: ['); }); }); describe('style option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'table', {style: 'scss', ...baseOptions}, await createTestApp(runner), ); expect(tree.files).toContain('/projects/material/src/app/foo/foo.component.scss'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'table', baseOptions, await createTestApp(runner, {style: 'less'}), ); expect(tree.files).toContain('/projects/material/src/app/foo/foo.component.less'); }); }); describe('inlineStyle option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'table', {inlineStyle: true, ...baseOptions}, await createTestApp(runner), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.css'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'table', baseOptions, await createTestApp(runner, {inlineStyle: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.css'); }); }); describe('inlineTemplate option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'table', {inlineTemplate: true, ...baseOptions}, await createTestApp(runner), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.html'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'table', baseOptions, await createTestApp(runner, {inlineTemplate: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.html'); }); }); describe('skipTests option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'table', {skipTests: true, ...baseOptions}, await createTestApp(runner), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.spec.ts'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'table', baseOptions, await createTestApp(runner, {skipTests: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.spec.ts'); }); }); });
{ "end_byte": 7189, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/table/index.spec.ts" }
components/src/material/schematics/ng-generate/table/index.ts_0_1639
/** * @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 {chain, noop, Rule, Tree} from '@angular-devkit/schematics'; import { addModuleImportToModule, buildComponent, findModuleFromOptions, isStandaloneSchematic, } from '@angular/cdk/schematics'; import {Schema} from './schema'; /** * Scaffolds a new table component. * Internally it bootstraps the base component schematic */ export default function (options: Schema): Rule { return chain([ buildComponent( {...options}, { template: './__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template', stylesheet: './__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template', }, ), options.skipImport ? noop() : addTableModulesToModule(options), ]); } /** * Adds the required modules to the relative module. */ function addTableModulesToModule(options: Schema) { return async (host: Tree) => { const isStandalone = await isStandaloneSchematic(host, options); if (!isStandalone) { const modulePath = (await findModuleFromOptions(host, options))!; addModuleImportToModule(host, modulePath, 'MatTableModule', '@angular/material/table'); addModuleImportToModule( host, modulePath, 'MatPaginatorModule', '@angular/material/paginator', ); addModuleImportToModule(host, modulePath, 'MatSortModule', '@angular/material/sort'); } }; }
{ "end_byte": 1639, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/table/index.ts" }
components/src/material/schematics/ng-generate/table/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template_0_37
.full-width-table { width: 100%; }
{ "end_byte": 37, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/table/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__style__.template" }
components/src/material/schematics/ng-generate/table/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template_0_882
<div class="mat-elevation-z2"> <table mat-table class="full-width-table" matSort aria-label="Elements"> <!-- Id Column --> <ng-container matColumnDef="id"> <th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th> <td mat-cell *matCellDef="let row">{{row.id}}</td> </ng-container> <!-- Name Column --> <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th> <td mat-cell *matCellDef="let row">{{row.name}}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> <mat-paginator #paginator [length]="dataSource.data.length" [pageIndex]="0" [pageSize]="10" [pageSizeOptions]="[5, 10, 20]" aria-label="Select page"> </mat-paginator> </div>
{ "end_byte": 882, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/table/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html.template" }
components/src/material/schematics/ng-generate/table/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.spec.ts.template_0_1241
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations';<% if(!standalone) { %> import { MatPaginatorModule } from '@angular/material/paginator'; import { MatSortModule } from '@angular/material/sort'; import { MatTableModule } from '@angular/material/table';<% } %> import { <%= classify(name) %>Component } from './<%= dasherize(name) %>.component'; describe('<%= classify(name) %>Component', () => { let component: <%= classify(name) %>Component; let fixture: ComponentFixture<<%= classify(name) %>Component>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({<% if(standalone) { %> imports: [NoopAnimationsModule]<% } else { %> declarations: [<%= classify(name) %>Component], imports: [ NoopAnimationsModule, MatPaginatorModule, MatSortModule, MatTableModule, ]<% } %> }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(<%= classify(name) %>Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should compile', () => { expect(component).toBeTruthy(); }); });
{ "end_byte": 1241, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/table/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.spec.ts.template" }
components/src/material/schematics/ng-generate/table/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.ts.template_0_1915
import { AfterViewInit, Component, ViewChild<% if(!!viewEncapsulation) { %>, ViewEncapsulation<% }%><% if(changeDetection !== 'Default') { %>, ChangeDetectionStrategy<% }%> } from '@angular/core'; import { <% if(standalone) { %>MatTableModule, <% } %>MatTable } from '@angular/material/table'; import { <% if(standalone) { %>MatPaginatorModule, <% } %>MatPaginator } from '@angular/material/paginator'; import { <% if(standalone) { %>MatSortModule, <% } %>MatSort } from '@angular/material/sort'; import { <%= classify(name) %>DataSource, <%= classify(name) %>Item } from './<%= dasherize(name) %>-datasource'; @Component({ selector: '<%= selector %>',<% if(inlineTemplate) { %> template: ` <%= indentTextContent(resolvedFiles.template, 4) %> `,<% } else { %> templateUrl: './<%= dasherize(name) %>.component.html',<% } if(inlineStyle) { %> styles: ` <%= indentTextContent(resolvedFiles.stylesheet, 4) %> `<% } else { %> styleUrl: './<%= dasherize(name) %>.component.<%= style %>'<% } %><% if(!!viewEncapsulation) { %>, encapsulation: ViewEncapsulation.<%= viewEncapsulation %><% } if (changeDetection !== 'Default') { %>, changeDetection: ChangeDetectionStrategy.<%= changeDetection %><% } %><% if(standalone) { %>, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule]<% } %> }) export class <%= classify(name) %>Component implements AfterViewInit { @ViewChild(MatPaginator) paginator!: MatPaginator; @ViewChild(MatSort) sort!: MatSort; @ViewChild(MatTable) table!: MatTable<<%= classify(name) %>Item>; dataSource = new <%= classify(name) %>DataSource(); /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */ displayedColumns = ['id', 'name']; ngAfterViewInit(): void { this.dataSource.sort = this.sort; this.dataSource.paginator = this.paginator; this.table.dataSource = this.dataSource; } }
{ "end_byte": 1915, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/table/files/__path__/__name@dasherize@if-flat__/__name@dasherize__.component.ts.template" }
components/src/material/schematics/ng-generate/table/files/__path__/__name@dasherize@if-flat__/__name@dasherize__-datasource.ts.template_0_3775
import { DataSource } from '@angular/cdk/collections'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { map } from 'rxjs/operators'; import { Observable, of as observableOf, merge } from 'rxjs'; // TODO: Replace this with your own data model type export interface <%= classify(name) %>Item { name: string; id: number; } // TODO: replace this with real data from your application const EXAMPLE_DATA: <%= classify(name) %>Item[] = [ {id: 1, name: 'Hydrogen'}, {id: 2, name: 'Helium'}, {id: 3, name: 'Lithium'}, {id: 4, name: 'Beryllium'}, {id: 5, name: 'Boron'}, {id: 6, name: 'Carbon'}, {id: 7, name: 'Nitrogen'}, {id: 8, name: 'Oxygen'}, {id: 9, name: 'Fluorine'}, {id: 10, name: 'Neon'}, {id: 11, name: 'Sodium'}, {id: 12, name: 'Magnesium'}, {id: 13, name: 'Aluminum'}, {id: 14, name: 'Silicon'}, {id: 15, name: 'Phosphorus'}, {id: 16, name: 'Sulfur'}, {id: 17, name: 'Chlorine'}, {id: 18, name: 'Argon'}, {id: 19, name: 'Potassium'}, {id: 20, name: 'Calcium'}, ]; /** * Data source for the <%= classify(name) %> view. This class should * encapsulate all logic for fetching and manipulating the displayed data * (including sorting, pagination, and filtering). */ export class <%= classify(name) %>DataSource extends DataSource<<%= classify(name) %>Item> { data: <%= classify(name) %>Item[] = EXAMPLE_DATA; paginator: MatPaginator | undefined; sort: MatSort | undefined; constructor() { super(); } /** * Connect this data source to the table. The table will only update when * the returned stream emits new items. * @returns A stream of the items to be rendered. */ connect(): Observable<<%= classify(name) %>Item[]> { if (this.paginator && this.sort) { // Combine everything that affects the rendered data into one update // stream for the data-table to consume. return merge(observableOf(this.data), this.paginator.page, this.sort.sortChange) .pipe(map(() => { return this.getPagedData(this.getSortedData([...this.data ])); })); } else { throw Error('Please set the paginator and sort on the data source before connecting.'); } } /** * Called when the table is being destroyed. Use this function, to clean up * any open connections or free any held resources that were set up during connect. */ disconnect(): void {} /** * Paginate the data (client-side). If you're using server-side pagination, * this would be replaced by requesting the appropriate data from the server. */ private getPagedData(data: <%= classify(name) %>Item[]): <%= classify(name) %>Item[] { if (this.paginator) { const startIndex = this.paginator.pageIndex * this.paginator.pageSize; return data.splice(startIndex, this.paginator.pageSize); } else { return data; } } /** * Sort the data (client-side). If you're using server-side sorting, * this would be replaced by requesting the appropriate data from the server. */ private getSortedData(data: <%= classify(name) %>Item[]): <%= classify(name) %>Item[] { if (!this.sort || !this.sort.active || this.sort.direction === '') { return data; } return data.sort((a, b) => { const isAsc = this.sort?.direction === 'asc'; switch (this.sort?.active) { case 'name': return compare(a.name, b.name, isAsc); case 'id': return compare(+a.id, +b.id, isAsc); default: return 0; } }); } } /** Simple sort comparator for example ID/Name columns (for client-side sorting). */ function compare(a: string | number, b: string | number, isAsc: boolean): number { return (a < b ? -1 : 1) * (isAsc ? 1 : -1); }
{ "end_byte": 3775, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/table/files/__path__/__name@dasherize@if-flat__/__name@dasherize__-datasource.ts.template" }
components/src/material/schematics/ng-generate/theme-color/index.spec.ts_0_7750
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing'; import {createTestApp} from '@angular/cdk/schematics/testing'; import {runfiles} from '@bazel/runfiles'; import {compileString} from 'sass'; import * as path from 'path'; import {createLocalAngularPackageImporter} from '../../../../../tools/sass/local-sass-importer'; import {generateSCSSTheme} from './index'; import {Schema} from './schema'; // Note: For Windows compatibility, we need to resolve the directory paths through runfiles // which are guaranteed to reside in the source tree. const testDir = runfiles.resolvePackageRelative('../theme-color'); const packagesDir = path.join(runfiles.resolveWorkspaceRelative('src/cdk/_index.scss'), '../..'); const localPackageSassImporter = createLocalAngularPackageImporter(packagesDir); describe('material-theme-color-schematic', () => { let runner: SchematicTestRunner; let testM3ThemePalette: Map<string, Map<number, string>>; /** Transpiles given Sass content into CSS. */ function transpileTheme(content: string): string { return compileString( ` ${content} html { @include mat.theme(( color: ( primary: $primary-palette, tertiary: $tertiary-palette, theme-type: light, ), )); @if mixin-exists(high-contrast-overrides) { & { @include high-contrast-overrides(light); } } &.dark-theme { @include mat.theme(( color: ( primary: $primary-palette, tertiary: $tertiary-palette, theme-type: dark, ), )); @if mixin-exists(high-contrast-overrides) { & { @include high-contrast-overrides(dark); } } } } `, { loadPaths: [testDir], importers: [localPackageSassImporter], }, ).css.toString(); } async function runM3ThemeSchematic( runner: SchematicTestRunner, options: Schema, ): Promise<UnitTestTree> { const app = await createTestApp(runner, {standalone: true}); return runner.runSchematic('theme-color', options, app); } beforeEach(() => { testM3ThemePalette = getPaletteMap(); runner = new SchematicTestRunner( '@angular/material', runfiles.resolveWorkspaceRelative('src/material/schematics/collection.json'), ); }); it('should throw error if given an incorrect color', async () => { try { await runM3ThemeSchematic(runner, { primaryColor: '#fffff', }); } catch (e) { expect((e as Error).message).toBe( 'Cannot parse the specified color #fffff. Please verify it is a hex color (ex. #ffffff or ffffff).', ); } }); it('should generate m3 theme file', async () => { const tree = await runM3ThemeSchematic(runner, { primaryColor: '#984061', }); expect(tree.exists('_theme-colors.scss')).toBe(true); }); it('should generate m3 theme file at specified path', async () => { const tree = await runM3ThemeSchematic(runner, { primaryColor: '#984061', directory: 'projects/', }); expect(tree.exists('projects/_theme-colors.scss')).toBe(true); }); it('should generate m3 theme file with correct indentation and formatting', async () => { const tree = await runM3ThemeSchematic(runner, { primaryColor: '#984061', }); expect(tree.readText('_theme-colors.scss')).toEqual(getTestTheme()); }); it('should generate themes when provided a primary color', async () => { const tree = await runM3ThemeSchematic(runner, { primaryColor: '#984061', }); const generatedSCSS = tree.readText('_theme-colors.scss'); const testSCSS = generateSCSSTheme( testM3ThemePalette, 'Color palettes are generated from primary: #984061', ); expect(generatedSCSS).toBe(testSCSS); expect(transpileTheme(generatedSCSS)).toBe(transpileTheme(testSCSS)); }); it('should generate themes when provided primary and secondary colors', async () => { const tree = await runM3ThemeSchematic(runner, { primaryColor: '#984061', secondaryColor: '#984061', }); const generatedSCSS = tree.readText('_theme-colors.scss'); // Change test theme palette so that secondary is the same source color as // primary to match schematic inputs let testPalette = testM3ThemePalette; testPalette.set('secondary', testM3ThemePalette.get('primary')!); const testSCSS = generateSCSSTheme( testPalette, 'Color palettes are generated from primary: #984061, secondary: #984061', ); expect(generatedSCSS).toBe(testSCSS); expect(transpileTheme(generatedSCSS)).toBe(transpileTheme(testSCSS)); }); it('should generate themes when provided primary, secondary, and tertiary colors', async () => { const tree = await runM3ThemeSchematic(runner, { primaryColor: '#984061', secondaryColor: '#984061', tertiaryColor: '#984061', }); const generatedSCSS = tree.readText('_theme-colors.scss'); // Change test theme palette so that secondary and tertiary are the same // source color as primary to match schematic inputs let testPalette = testM3ThemePalette; testPalette.set('secondary', testM3ThemePalette.get('primary')!); testPalette.set('tertiary', testM3ThemePalette.get('primary')!); const testSCSS = generateSCSSTheme( testPalette, 'Color palettes are generated from primary: #984061, secondary: #984061, tertiary: #984061', ); expect(generatedSCSS).toBe(testSCSS); expect(transpileTheme(generatedSCSS)).toBe(transpileTheme(testSCSS)); }); it('should generate themes when provided a primary, secondary, tertiary, and neutral colors', async () => { const tree = await runM3ThemeSchematic(runner, { primaryColor: '#984061', secondaryColor: '#984061', tertiaryColor: '#984061', neutralColor: '#984061', }); const generatedSCSS = tree.readText('_theme-colors.scss'); // Change test theme palette so that secondary, tertiary, and neutral are // the same source color as primary to match schematic inputs let testPalette = testM3ThemePalette; testPalette.set('secondary', testM3ThemePalette.get('primary')!); testPalette.set('tertiary', testM3ThemePalette.get('primary')!); // Neutral's tonal palette has additional tones as opposed to the other color palettes. let neutralPalette = new Map(testM3ThemePalette.get('primary')!); neutralPalette.set(4, '#26000f'); neutralPalette.set(6, '#2f0015'); neutralPalette.set(12, '#460022'); neutralPalette.set(17, '#55082c'); neutralPalette.set(22, '#631637'); neutralPalette.set(24, '#691a3c'); neutralPalette.set(87, '#ffcdda'); neutralPalette.set(92, '#ffe1e8'); neutralPalette.set(94, '#ffe8ed'); neutralPalette.set(96, '#fff0f2'); testPalette.set('neutral', neutralPalette); const testSCSS = generateSCSSTheme( testPalette, 'Color palettes are generated from primary: #984061, secondary: #984061, tertiary: #984061, neutral: #984061', ); expect(generatedSCSS).toBe(testSCSS); expect(transpileTheme(generatedSCSS)).toBe(transpileTheme(testSCSS)); }); it('should be able to generate high contrast overrides mixin', async () => { const tree = await runM3ThemeSchematic(runner, { primaryColor: '#984061', includeHighContrast: true, }); const generatedSCSS = tree.readText('_theme-colors.scss'); expect(generatedSCSS).toContain(`@mixin high-contrast-overrides`); });
{ "end_byte": 7750, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/theme-color/index.spec.ts" }
components/src/material/schematics/ng-generate/theme-color/index.spec.ts_7754_12160
it('should be able to generate high contrast themes overrides when provided a primary color', async () => { const tree = await runM3ThemeSchematic(runner, { primaryColor: '#984061', includeHighContrast: true, }); const generatedCSS = transpileTheme(tree.readText('_theme-colors.scss')); // Check a system variable from each color palette for their high contrast light theme value expect(generatedCSS).toContain(`--mat-sys-primary: #580b2f`); expect(generatedCSS).toContain(`--mat-sys-secondary: #45212d`); expect(generatedCSS).toContain(`--mat-sys-tertiary: #4d1f00`); expect(generatedCSS).toContain(`--mat-sys-error: #600004`); expect(generatedCSS).toContain(`--mat-sys-surface: #fff8f8`); expect(generatedCSS).toContain(`--mat-sys-outline: #37282c`); // Check a system variable from each color palette for their high contrast dark theme value expect(generatedCSS).toContain(`--mat-sys-primary: #ffebef`); expect(generatedCSS).toContain(`--mat-sys-secondary: #ffebef`); expect(generatedCSS).toContain(`--mat-sys-tertiary: #ffece4`); expect(generatedCSS).toContain(`--mat-sys-error: #ffece9`); expect(generatedCSS).toContain(`--mat-sys-surface: #191113`); expect(generatedCSS).toContain(`--mat-sys-outline: #ffebef`); }); it('should be able to generate high contrast themes overrides when provided a primary and secondary color', async () => { const tree = await runM3ThemeSchematic(runner, { primaryColor: '#984061', secondaryColor: '#984061', includeHighContrast: true, }); const generatedCSS = transpileTheme(tree.readText('_theme-colors.scss')); // Check a system variable from each color palette for their high contrast light theme value expect(generatedCSS).toContain(`--mat-sys-primary: #580b2f`); expect(generatedCSS).toContain(`--mat-sys-secondary: #580b2f`); // Check a system variable from each color palette for their high contrast dark theme value expect(generatedCSS).toContain(`--mat-sys-primary: #ffebef`); expect(generatedCSS).toContain(`--mat-sys-secondary: #ffebef`); }); it('should be able to generate high contrast themes overrides when provided primary, secondary, and tertiary color', async () => { const tree = await runM3ThemeSchematic(runner, { primaryColor: '#984061', secondaryColor: '#984061', tertiaryColor: '#984061', includeHighContrast: true, }); const generatedCSS = transpileTheme(tree.readText('_theme-colors.scss')); // Check a system variable from each color palette for their high contrast light theme value expect(generatedCSS).toContain(`--mat-sys-primary: #580b2f`); expect(generatedCSS).toContain(`--mat-sys-secondary: #580b2f`); expect(generatedCSS).toContain(`--mat-sys-tertiary: #580b2f`); // Check a system variable from each color palette for their high contrast dark theme value expect(generatedCSS).toContain(`--mat-sys-primary: #ffebef`); expect(generatedCSS).toContain(`--mat-sys-secondary: #ffebef`); expect(generatedCSS).toContain(`--mat-sys-tertiary: #ffebef`); }); it('should be able to generate high contrast themes overrides when provided primary, secondary, tertiary, and neutral color', async () => { const tree = await runM3ThemeSchematic(runner, { primaryColor: '#984061', secondaryColor: '#984061', tertiaryColor: '#984061', neutralColor: '#dfdfdf', // Different color since #984061 does not change the tonal palette includeHighContrast: true, }); const generatedCSS = transpileTheme(tree.readText('_theme-colors.scss')); // Check a system variable from each color palette for their high contrast light theme value expect(generatedCSS).toContain(`--mat-sys-primary: #580b2f`); expect(generatedCSS).toContain(`--mat-sys-secondary: #580b2f`); expect(generatedCSS).toContain(`--mat-sys-tertiary: #580b2f`); expect(generatedCSS).toContain(`--mat-sys-surface-bright: #f9f9f9`); // Check a system variable from each color palette for their high contrast dark theme value expect(generatedCSS).toContain(`--mat-sys-primary: #ffebef`); expect(generatedCSS).toContain(`--mat-sys-secondary: #ffebef`); expect(generatedCSS).toContain(`--mat-sys-tertiary: #ffebef`); expect(generatedCSS).toContain(`--mat-sys-surface-bright: #4f5051`); }); });
{ "end_byte": 12160, "start_byte": 7754, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/theme-color/index.spec.ts" }
components/src/material/schematics/ng-generate/theme-color/index.spec.ts_12162_14718
function getTestTheme() { return `// This file was generated by running 'ng generate @angular/material:theme-color'. // Proceed with caution if making changes to this file. @use 'sass:map'; @use '@angular/material' as mat; // Note: Color palettes are generated from primary: #984061 $_palettes: ( primary: ( 0: #000000, 10: #3e001d, 20: #5e1133, 25: #6c1d3e, 30: #7b2949, 35: #893455, 40: #984061, 50: #b6587a, 60: #d57194, 70: #f48bae, 80: #ffb0c8, 90: #ffd9e2, 95: #ffecf0, 98: #fff8f8, 99: #fffbff, 100: #ffffff, ), secondary: ( 0: #000000, 10: #31101d, 20: #4a2531, 25: #56303c, 30: #633b48, 35: #704653, 40: #7e525f, 50: #996a78, 60: #b58392, 70: #d29dac, 80: #efb8c7, 90: #ffd9e2, 95: #ffecf0, 98: #fff8f8, 99: #fffbff, 100: #ffffff, ), tertiary: ( 0: #000000, 10: #331200, 20: #532200, 25: #642a00, 30: #763300, 35: #883d03, 40: #974810, 50: #b66028, 60: #d6783e, 70: #f69256, 80: #ffb68e, 90: #ffdbc9, 95: #ffede5, 98: #fff8f6, 99: #fffbff, 100: #ffffff, ), neutral: ( 0: #000000, 10: #22191c, 20: #372e30, 25: #43393b, 30: #4f4446, 35: #5b5052, 40: #675b5e, 50: #807477, 60: #9b8d90, 70: #b6a8aa, 80: #d2c3c5, 90: #efdfe1, 95: #fdedef, 98: #fff8f8, 99: #fffbff, 100: #ffffff, 4: #140c0e, 6: #191113, 12: #261d20, 17: #31282a, 22: #3c3235, 24: #413739, 87: #e6d6d9, 92: #f5e4e7, 94: #faeaed, 96: #fff0f2, ), neutral-variant: ( 0: #000000, 10: #25181c, 20: #3c2c31, 25: #47373b, 30: #534247, 35: #604e52, 40: #6c5a5e, 50: #867277, 60: #a18b90, 70: #bca5ab, 80: #d9c0c6, 90: #f6dce2, 95: #ffecf0, 98: #fff8f8, 99: #fffbff, 100: #ffffff, ), error: ( 0: #000000, 10: #410002, 20: #690005, 25: #7e0007, 30: #93000a, 35: #a80710, 40: #ba1a1a, 50: #de3730, 60: #ff5449, 70: #ff897d, 80: #ffb4ab, 90: #ffdad6, 95: #ffedea, 98: #fff8f7, 99: #fffbff, 100: #ffffff, ), ); $_rest: ( secondary: map.get($_palettes, secondary), neutral: map.get($_palettes, neutral), neutral-variant: map.get($_palettes, neutral-variant), error: map.get($_palettes, error), ); $primary-palette: map.merge(map.get($_palettes, primary), $_rest); $tertiary-palette: map.merge(map.get($_palettes, tertiary), $_rest);`; }
{ "end_byte": 14718, "start_byte": 12162, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/theme-color/index.spec.ts" }
components/src/material/schematics/ng-generate/theme-color/index.spec.ts_14720_18073
function getPaletteMap() { // Hue maps created from https://m3.material.io/theme-builder#/custom (using // #984061 as source color). Not using predefined M3 palettes since some neutral // hues are slightly off from generated theme. return new Map([ [ 'primary', new Map<number, string>([ [0, '#000000'], [10, '#3e001d'], [20, '#5e1133'], [25, '#6c1d3e'], [30, '#7b2949'], [35, '#893455'], [40, '#984061'], [50, '#b6587a'], [60, '#d57194'], [70, '#f48bae'], [80, '#ffb0c8'], [90, '#ffd9e2'], [95, '#ffecf0'], [98, '#fff8f8'], [99, '#fffbff'], [100, '#ffffff'], ]), ], [ 'secondary', new Map<number, string>([ [0, '#000000'], [10, '#31101d'], [20, '#4a2531'], [25, '#56303c'], [30, '#633b48'], [35, '#704653'], [40, '#7e525f'], [50, '#996a78'], [60, '#b58392'], [70, '#d29dac'], [80, '#efb8c7'], [90, '#ffd9e2'], [95, '#ffecf0'], [98, '#fff8f8'], [99, '#fffbff'], [100, '#ffffff'], ]), ], [ 'tertiary', new Map<number, string>([ [0, '#000000'], [10, '#331200'], [20, '#532200'], [25, '#642a00'], [30, '#763300'], [35, '#883d03'], [40, '#974810'], [50, '#b66028'], [60, '#d6783e'], [70, '#f69256'], [80, '#ffb68e'], [90, '#ffdbc9'], [95, '#ffede5'], [98, '#fff8f6'], [99, '#fffbff'], [100, '#ffffff'], ]), ], [ 'neutral', new Map<number, string>([ [0, '#000000'], [10, '#22191c'], [20, '#372e30'], [25, '#43393b'], [30, '#4f4446'], [35, '#5b5052'], [40, '#675b5e'], [50, '#807477'], [60, '#9b8d90'], [70, '#b6a8aa'], [80, '#d2c3c5'], [90, '#efdfe1'], [95, '#fdedef'], [98, '#fff8f8'], [99, '#fffbff'], [100, '#ffffff'], [4, '#140c0e'], [6, '#191113'], [12, '#261d20'], [17, '#31282a'], [22, '#3c3235'], [24, '#413739'], [87, '#e6d6d9'], [92, '#f5e4e7'], [94, '#faeaed'], [96, '#fff0f2'], ]), ], [ 'neutral-variant', new Map<number, string>([ [0, '#000000'], [10, '#25181c'], [20, '#3c2c31'], [25, '#47373b'], [30, '#534247'], [35, '#604e52'], [40, '#6c5a5e'], [50, '#867277'], [60, '#a18b90'], [70, '#bca5ab'], [80, '#d9c0c6'], [90, '#f6dce2'], [95, '#ffecf0'], [98, '#fff8f8'], [99, '#fffbff'], [100, '#ffffff'], ]), ], [ 'error', new Map<number, string>([ [0, '#000000'], [10, '#410002'], [20, '#690005'], [25, '#7e0007'], [30, '#93000a'], [35, '#a80710'], [40, '#ba1a1a'], [50, '#de3730'], [60, '#ff5449'], [70, '#ff897d'], [80, '#ffb4ab'], [90, '#ffdad6'], [95, '#ffedea'], [98, '#fff8f7'], [99, '#fffbff'], [100, '#ffffff'], ]), ], ]); }
{ "end_byte": 18073, "start_byte": 14720, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/theme-color/index.spec.ts" }
components/src/material/schematics/ng-generate/theme-color/README.md_0_5108
# Material 3 Custom Theme schematic ```shell ng generate @angular/material:theme-color ``` This schematic allows users to create new Material 3 theme palettes based on custom colors by using [Material Color Utilities](https://github.com/material-foundation/material-color-utilities). The generated [color palettes](https://m3.material.io/styles/color/roles) are optimized to have enough contrast to be more accessible. See [Science of Color Design](https://material.io/blog/science-of-color-design) for more information about Material's color design. For more customization, custom colors can be also be provided for the secondary, tertiary, and neutral palette colors. It is recommended to choose colors that are contrastful, Material has more detailed guidance for [accessible design](https://m3.material.io/foundations/accessible-design/patterns). The output of the schematic will create a file named `_theme-colors.scss` at the specified directory or the project root with the generated palettes. The exported palettes (`$primary-palette` and `$tertiary-palette`) can be provided to the `theme` mixin within your theme file to use the custom colors. ```scss @use '@angular/material' as mat; @use './path/to/my-theme'; // location of generated file html { @include mat.theme( color: ( primary: my-theme.$primary-palette, tertiary: my-theme.$tertiary-palette, ), typography: Roboto, density: 0, ) } ``` ## High contrast override mixins High contrast override theme mixins are also generated in the file if specified. These mixins override the system level variables with high contrast equivalent values from your theme. This is helpful for users who prefer more contrastful colors for either preference or accessibility reasons. ### Creating one theme for light and dark mode As of v19, the `theme` mixin can create one theme that detects and adapts to a user if they have light or dark theme with the [`light-dark` function](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/light-dark). Apply the `high-contrast-overrides(color-scheme)` mixin wrapped inside `@media (prefers-contrast: more)`. ```scss @use '@angular/material'; @use './path/to/my-theme'; // location of generated file html { // Must specify color-scheme for theme mixin to automatically work color-scheme: light; // Create one theme that works automatically for light and dark theme @include material.theme(( color: ( primary: my-theme.$primary-palette, tertiary: my-theme.$tertiary-palette, ), typography: Roboto, density: 0, )); // Use high contrast values when users prefer contrast @media (prefers-contrast: more) { @include my-theme.high-contrast-overrides(color-scheme); } } ``` ### Creating separate themes for light and dark mode You can manually define the light theme and dark theme separately. This is recommended if you need granular control over when to show each specific theme in your application. Prior to v19, this was the only way to create light and dark themes. ```scss @use '@angular/material'; @use './path/to/my-theme'; // location of generated file html { // Apply the light theme by default @include material.theme(( color: ( primary: my-theme.$primary-palette, tertiary: my-theme.$tertiary-palette, theme-type: light, ), typography: Roboto, density: 0, )); // Use high contrast light theme colors when users prefer contrast @media (prefers-contrast: more) { @include my-theme.high-contrast-overrides(light); } // Apply dark theme when users prefer a dark color scheme @media (prefers-color-scheme: dark) { @include material.theme(( color: ( primary: my-theme.$primary-palette, tertiary: my-theme.$tertiary-palette, theme-type: dark, ), )); // Use high contrast dark theme colors when users prefers a dark color scheme and contrast @media (prefers-contrast: more) { @include my-theme.high-contrast-overrides(dark); } } } ``` ## Options ### Required * `primaryColor` - Color to use for app's primary color palette (Note: the other palettes described in the Material 3 spec will be automatically chosen based on your primary palette unless specified, to ensure a harmonious color combination). ### Optional * `secondaryColor` - Color to use for app's secondary color palette. Defaults to secondary color generated from Material based on the primary. * `tertiaryColor` - Color to use for app's tertiary color palette. Defaults to tertiary color generated from Material based on the primary. * `neutralColor` - Color to use for app's neutral color palette. Defaults to neutral color generated from Material based on the primary. * `includeHighContrast` - Whether to add high contrast override mixins to generated theme file. Developers can call the mixin when they want to show a high contrast version of their theme. Defaults to false. * `directory` - Relative path to a directory within the project that the generated theme file should be created in. Defaults to the project root.
{ "end_byte": 5108, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/theme-color/README.md" }
components/src/material/schematics/ng-generate/theme-color/BUILD.bazel_0_2917
load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin") load("//tools:defaults.bzl", "esbuild", "jasmine_node_test", "pkg_npm", "spec_bundle", "ts_library") package(default_visibility = ["//visibility:public"]) STATIC_ASSETS = [ "schema.json", ] ts_library( name = "m3_theme_lib", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"] + ["rules/components/test-setup-helper.ts"], ), deps = [ "//src/cdk/schematics", "@npm//@angular-devkit/schematics", "@npm//@material/material-color-utilities", "@npm//@types/node", "@npm//sass", "@npm//typescript", ], ) esbuild( name = "m3_theme_bundle", entry_point = ":index.ts", external = [ "@angular/cdk/schematics", "@angular/material-experimental/", "@angular-devkit/schematics", "@angular-devkit/core", "typescript", ], format = "cjs", output = "index_bundled.js", platform = "node", target = "es2015", deps = [ ":m3_theme_lib", "//src/material:sass_lib", "//src/material-experimental:sass_lib", ], ) pkg_npm( name = "npm_package", srcs = STATIC_ASSETS, deps = [":m3_theme_bundle"], ) ######################################## # Testing configuration # ######################################## ts_library( name = "unit_tests_lib", testonly = True, srcs = glob(["**/*.spec.ts"] + ["rules/components/test-setup-helper.ts"]), devmode_module = "commonjs", deps = [ ":m3_theme_lib", "//src/cdk/schematics/testing", "//tools/sass:sass_lib", "@npm//@angular-devkit/schematics", "@npm//@bazel/runfiles", "@npm//@material/material-color-utilities", "@npm//@types/jasmine", "@npm//@types/node", "@npm//sass", ], ) spec_bundle( name = "unit_tests_bundle", # Exclude the `node` devkit entry-point to avoid bundling native modules like # `chokidar` and `fsevents`. These rely on native bindings and break with ESBuild. external = ["@angular-devkit/core/node"], platform = "node", target = "es2020", deps = [":unit_tests_lib"], ) copy_to_bin( name = "unit_tests_assets", testonly = True, srcs = STATIC_ASSETS, ) jasmine_node_test( name = "unit_tests", data = [ ":m3_theme_bundle", ":unit_tests_assets", "//src/material/schematics:collection_assets", "//src/material/schematics:ng_generate_assets", ], shard_count = 10, deps = [ ":unit_tests_bundle", # Runtime dependencies needed by the test and actual migration sources. These need # to be specified explicitly here because they are not captured by the bundling. "@npm//@schematics/angular", "//src/material:sass_lib", "//src/material-experimental:sass_lib", ], )
{ "end_byte": 2917, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/theme-color/BUILD.bazel" }
components/src/material/schematics/ng-generate/theme-color/schema.d.ts_0_922
/** * @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 interface Schema { /** * Color to generate M3 theme, represents the primary color palette. */ primaryColor: string; /** * Color to override the secondary color palette. */ secondaryColor?: string; /** * Color to override the tertiary color palette. */ tertiaryColor?: string; /** * Color to override the neutral color palette. */ neutralColor?: string; /** * Whether to create high contrast override theme mixins. */ includeHighContrast?: boolean; /* * Workspace-relative path to a directory where the file with the custom M3 * theme will be generated. * * If not set, the file will be generated at the project root. */ directory?: string; }
{ "end_byte": 922, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/theme-color/schema.d.ts" }
components/src/material/schematics/ng-generate/theme-color/index.ts_0_6916
/** * @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, Tree} from '@angular-devkit/schematics'; import {Schema} from './schema'; import { argbFromHex, hexFromArgb, TonalPalette, Hct, DynamicScheme, DislikeAnalyzer, TemperatureCache, } from '@material/material-color-utilities'; // For each color tonal palettes are created using the following hue tones. The // tonal palettes then get used to create the different color roles (ex. // on-primary) https://m3.material.io/styles/color/system/how-the-system-works const HUE_TONES = [0, 10, 20, 25, 30, 35, 40, 50, 60, 70, 80, 90, 95, 98, 99, 100]; // Map of neutral hues to the previous/next hues that // can be used to estimate them, in case they're missing. const NEUTRAL_HUES = new Map<number, {prev: number; next: number}>([ [4, {prev: 0, next: 10}], [6, {prev: 0, next: 10}], [12, {prev: 10, next: 20}], [17, {prev: 10, next: 20}], [22, {prev: 20, next: 25}], [24, {prev: 20, next: 25}], [87, {prev: 80, next: 90}], [92, {prev: 90, next: 95}], [94, {prev: 90, next: 95}], [96, {prev: 95, next: 98}], ]); // Note: Some of the color tokens refer to additional hue tones, but this only // applies for the neutral color palette (ex. surface container is neutral // palette's 94 tone). https://m3.material.io/styles/color/static/baseline const NEUTRAL_HUE_TONES = [...HUE_TONES, ...NEUTRAL_HUES.keys()]; /** * Gets color tonal palettes generated by Material from the provided color. * @param primaryPalette Tonal palette that represents primary. * @param secondaryPalette Tonal palette that represents secondary. * @param tertiaryPalette Tonal palette that represents tertiary. * @param neutralPalette Tonal palette that represents neutral. * @param neutralVariantPalette Tonal palette that represents neutral variant. * @param isDark Boolean to represent if the scheme is for a dark or light theme. * @param contrastLevel Number between -1 and 1 for the contrast level. 0 is the standard contrast * and 1 represents high contrast. * @returns Dynamic scheme for provided theme and contrast level */ function getMaterialDynamicScheme( primaryPalette: TonalPalette, secondaryPalette: TonalPalette, tertiaryPalette: TonalPalette, neutralPalette: TonalPalette, neutralVariantPalette: TonalPalette, isDark: boolean, contrastLevel: number, ): DynamicScheme { return new DynamicScheme({ sourceColorArgb: primaryPalette.keyColor.toInt(), variant: 6, // Variant.FIDELITY, used number representation since enum is not accessible outside of @material/material-color-utilities contrastLevel: contrastLevel, isDark: isDark, primaryPalette: primaryPalette, secondaryPalette: secondaryPalette, tertiaryPalette: tertiaryPalette, neutralPalette: neutralPalette, neutralVariantPalette: neutralVariantPalette, }); } /** * Gets the scss representation of the provided color palettes. * @param colorPalettes Map of colors and their hue tones and values. * @returns String of the color palettes scss. */ function getColorPalettesSCSS(colorPalettes: Map<string, Map<number, string>>): string { let scss = '(\n'; for (const [variant, palette] of colorPalettes!.entries()) { scss += ' ' + variant + ': (\n'; for (const [key, value] of palette.entries()) { scss += ' ' + key + ': ' + value + ',\n'; } scss += ' ),\n'; } scss += ');'; return scss; } /** * Gets map of all the color tonal palettes with their tones and colors from provided palettes. * @param primaryPalette Tonal palette that represents primary. * @param secondaryPalette Tonal palette that represents secondary. * @param tertiaryPalette Tonal palette that represents tertiary. * @param neutralPalette Tonal palette that represents neutral. * @param neutralVariantPalette Tonal palette that represents neutral variant. * @param errorPalette Tonal palette that represents error. * @returns Map with the colors and their hue tones and values. */ function getMapFromColorTonalPalettes( primaryPalette: TonalPalette, secondaryPalette: TonalPalette, tertiaryPalette: TonalPalette, neutralPalette: TonalPalette, neutralVariantPalette: TonalPalette, errorPalette: TonalPalette, ) { const tonalPalettes = { primary: primaryPalette, secondary: secondaryPalette, tertiary: tertiaryPalette, neutral: neutralPalette, neutralVariant: neutralVariantPalette, error: errorPalette, }; const palettes: Map<string, Map<number, string>> = new Map(); for (const [key, palette] of Object.entries(tonalPalettes)) { const paletteKey = key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); const tones = paletteKey === 'neutral' ? NEUTRAL_HUE_TONES : HUE_TONES; const colorPalette: Map<number, string> = new Map(); for (const tone of tones) { const color = hexFromArgb(palette.tone(tone)); colorPalette.set(tone, color); } palettes.set(paletteKey, colorPalette); } return palettes; } /** * Gets the generated scss from the provided color palettes and theme types. * @param colorPalettes Map of colors and their hue tones and values. * @param colorComment Comment with original hex colors used to generate palettes. * @returns String of the generated theme scss. */ export function generateSCSSTheme( colorPalettes: Map<string, Map<number, string>>, colorComment: string, ): string { let scss = [ "// This file was generated by running 'ng generate @angular/material:theme-color'.", '// Proceed with caution if making changes to this file.', '', "@use 'sass:map';", "@use '@angular/material' as mat;", '', '// Note: ' + colorComment, '$_palettes: ' + getColorPalettesSCSS(colorPalettes), '', '$_rest: (', ' secondary: map.get($_palettes, secondary),', ' neutral: map.get($_palettes, neutral),', ' neutral-variant: map.get($_palettes, neutral-variant),', ' error: map.get($_palettes, error),', ');', '', '$primary-palette: map.merge(map.get($_palettes, primary), $_rest);', '$tertiary-palette: map.merge(map.get($_palettes, tertiary), $_rest);', ]; return scss.join('\n'); } /** * Gets map of system variables and their high contrast values. * @param primaryPalette Tonal palette that represents primary. * @param secondaryPalette Tonal palette that represents secondary. * @param tertiaryPalette Tonal palette that represents tertiary. * @param neutralPalette Tonal palette that represents neutral. * @param neutralVariantPalette Tonal palette that represents neutral variant. * @param isDark Boolean to represent if the scheme is for a dark or light theme. * @returns Map of system variables names and their high contrast values. */
{ "end_byte": 6916, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/theme-color/index.ts" }
components/src/material/schematics/ng-generate/theme-color/index.ts_6917_14228
function getHighContrastOverides( primaryPalette: TonalPalette, secondaryPalette: TonalPalette, tertiaryPalette: TonalPalette, neutralPalette: TonalPalette, neutralVariantPalette: TonalPalette, isDark: boolean, ): Map<string, string> { const scheme = getMaterialDynamicScheme( primaryPalette, secondaryPalette, tertiaryPalette, neutralPalette, neutralVariantPalette, isDark, 1.0, // 1.0 is the maximum contrast level ); const overrides = new Map<string, string>(); // Set system variables with values from primary palette overrides.set('primary', hexFromArgb(scheme.primary)); overrides.set('on-primary', hexFromArgb(scheme.onPrimary)); overrides.set('primary-container', hexFromArgb(scheme.primaryContainer)); overrides.set('on-primary-container', hexFromArgb(scheme.onPrimaryContainer)); overrides.set('inverse-primary', hexFromArgb(scheme.inversePrimary)); overrides.set('primary-fixed', hexFromArgb(scheme.primaryFixed)); overrides.set('primary-fixed-dim', hexFromArgb(scheme.primaryFixedDim)); overrides.set('on-primary-fixed', hexFromArgb(scheme.onPrimaryFixed)); overrides.set('on-primary-fixed-variant', hexFromArgb(scheme.onPrimaryFixedVariant)); // Set system variables with values from secondary palette overrides.set('secondary', hexFromArgb(scheme.secondary)); overrides.set('on-secondary', hexFromArgb(scheme.onSecondary)); overrides.set('secondary-container', hexFromArgb(scheme.secondaryContainer)); overrides.set('on-secondary-container', hexFromArgb(scheme.onSecondaryContainer)); overrides.set('secondary-fixed', hexFromArgb(scheme.secondaryFixed)); overrides.set('secondary-fixed-dim', hexFromArgb(scheme.secondaryFixedDim)); overrides.set('on-secondary-fixed', hexFromArgb(scheme.onSecondaryFixed)); overrides.set('on-secondary-fixed-variant', hexFromArgb(scheme.onSecondaryFixedVariant)); // Set system variables with values from tertiary palette overrides.set('tertiary', hexFromArgb(scheme.tertiary)); overrides.set('on-tertiary', hexFromArgb(scheme.onTertiary)); overrides.set('tertiary-container', hexFromArgb(scheme.tertiaryContainer)); overrides.set('on-tertiary-container', hexFromArgb(scheme.onTertiaryContainer)); overrides.set('tertiary-fixed', hexFromArgb(scheme.tertiaryFixed)); overrides.set('tertiary-fixed-dim', hexFromArgb(scheme.tertiaryFixedDim)); overrides.set('on-tertiary-fixed', hexFromArgb(scheme.onTertiaryFixed)); overrides.set('on-tertiary-fixed-variant', hexFromArgb(scheme.onTertiaryFixedVariant)); // Set system variables with values from neutral palette overrides.set('background', hexFromArgb(scheme.background)); overrides.set('on-background', hexFromArgb(scheme.onBackground)); overrides.set('surface', hexFromArgb(scheme.surface)); overrides.set('surface-dim', hexFromArgb(scheme.surfaceDim)); overrides.set('surface-bright', hexFromArgb(scheme.surfaceBright)); overrides.set('surface-container-lowest', hexFromArgb(scheme.surfaceContainerLowest)); overrides.set('surface-container', hexFromArgb(scheme.surfaceContainer)); overrides.set('surface-container-high', hexFromArgb(scheme.surfaceContainerHigh)); overrides.set('surface-container-highest', hexFromArgb(scheme.surfaceContainerHighest)); overrides.set('on-surface', hexFromArgb(scheme.onSurface)); overrides.set('shadow', hexFromArgb(scheme.shadow)); overrides.set('scrim', hexFromArgb(scheme.scrim)); overrides.set('surface-tint', hexFromArgb(scheme.surfaceTint)); overrides.set('inverse-surface', hexFromArgb(scheme.inverseSurface)); overrides.set('inverse-on-surface', hexFromArgb(scheme.inverseOnSurface)); overrides.set('outline', hexFromArgb(scheme.outline)); overrides.set('outline-variant', hexFromArgb(scheme.outlineVariant)); // Set system variables with values from error palette overrides.set('error', hexFromArgb(scheme.error)); overrides.set('on-error', hexFromArgb(scheme.onError)); overrides.set('error-container', hexFromArgb(scheme.errorContainer)); overrides.set('on-error-container', hexFromArgb(scheme.onErrorContainer)); // Set system variables with values from neutral variant palette overrides.set('surface-variant', hexFromArgb(scheme.surfaceVariant)); overrides.set('on-surface-variant', hexFromArgb(scheme.onSurfaceVariant)); return overrides; } /** * Gets the scss representation of the high contrast override mixins. * @param primaryPalette Tonal palette that represents primary. * @param secondaryPalette Tonal palette that represents secondary. * @param tertiaryPalette Tonal palette that represents tertiary. * @param neutralPalette Tonal palette that represents neutral. * @param neutralVariantPalette Tonal palette that represents neutral variant. * @returns String of the generated high contrast mixins scss. */ function generateHighContrastOverrideMixinsSCSS( primaryPalette: TonalPalette, secondaryPalette: TonalPalette, tertiaryPalette: TonalPalette, neutralPalette: TonalPalette, neutralVariantPalette: TonalPalette, ): string { const lightOverrides = getHighContrastOverides( primaryPalette, secondaryPalette, tertiaryPalette, neutralPalette, neutralVariantPalette, /** isDark **/ false, ); const darkOverrides = getHighContrastOverides( primaryPalette, secondaryPalette, tertiaryPalette, neutralPalette, neutralVariantPalette, /** isDark **/ true, ); // Create private function to grab correct values based on theme-type let scss = '\n'; scss += '\n@function _high-contrast-value($light, $dark, $theme-type) {\n'; scss += ' @if ($theme-type == light) {\n'; scss += ' @return $light;\n'; scss += ' }\n'; scss += ' @if ($theme-type == dark) {\n'; scss += ' @return $dark;\n'; scss += ' }\n'; scss += ' @if ($theme-type == color-scheme) {\n'; scss += ' @return light-dark(#{$light}, #{$dark});\n'; scss += ' }\n'; scss += " \n @error 'Unknown theme-type #{$theme-type}. Expected light, dark, or color-scheme';\n"; scss += '}\n'; // Create high contrast mixin with theme-type input that can be light, dark, or color-scheme. scss += '\n@mixin high-contrast-overrides($theme-type) {\n'; scss += ' @include mat.theme-overrides((\n'; for (const [key, value] of lightOverrides!.entries()) { scss += ' ' + key + ': _high-contrast-value(' + value + ', ' + darkOverrides.get(key) + ', $theme-type),\n'; } scss += ' ))\n'; scss += ' }\n'; return scss; } /** * Gets Hct representation of Hex color. * @param color Hex color. * @returns Hct color. */ function getHctFromHex(color: string): Hct { try { return Hct.fromInt(argbFromHex(color)); } catch (e) { throw new Error( 'Cannot parse the specified color ' + color + '. Please verify it is a hex color (ex. #ffffff or ffffff).', ); } } /** * Creates theme file for provided scss. * @param scss scss for the theme file. * @param tree Directory tree. * @param directory Directory path to place generated theme file. */ function createThemeFile(scss: string, tree: Tree, directory?: string) { const filePath = directory ? directory + '_theme-colors.scss' : '_theme-colors.scss'; tree.create(filePath, scss); }
{ "end_byte": 14228, "start_byte": 6917, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/theme-color/index.ts" }
components/src/material/schematics/ng-generate/theme-color/index.ts_14230_17477
export default function (options: Schema): Rule { return async (tree: Tree, context: SchematicContext) => { let colorComment = 'Color palettes are generated from primary: ' + options.primaryColor; // Create tonal palettes for each color and custom color overrides if applicable. Used for both // standard contrast and high contrast schemes since they share the same tonal palettes. // The math to generate the palettes follows how palettes are generated for SchemeFidelity // (https://github.com/material-foundation/material-color-utilities/blob/main/typescript/scheme/scheme_fidelity.ts). // Cannot create object directly since we allow users to enter custom colors for palettes and // palettes are readonly for a DynamicScheme. const primaryColorHct = getHctFromHex(options.primaryColor); const primaryPalette = TonalPalette.fromHct(primaryColorHct); let secondaryPalette; if (options.secondaryColor) { colorComment += ', secondary: ' + options.secondaryColor; secondaryPalette = TonalPalette.fromHct(getHctFromHex(options.secondaryColor)); } else { secondaryPalette = TonalPalette.fromHueAndChroma( primaryColorHct.hue, Math.max(primaryColorHct.chroma - 32.0, primaryColorHct.chroma * 0.5), ); } let tertiaryPalette; if (options.tertiaryColor) { colorComment += ', tertiary: ' + options.tertiaryColor; tertiaryPalette = TonalPalette.fromHct(getHctFromHex(options.tertiaryColor)); } else { tertiaryPalette = TonalPalette.fromInt( DislikeAnalyzer.fixIfDisliked( new TemperatureCache(primaryColorHct).analogous(3, 6)[2], ).toInt(), ); } let neutralPalette; if (options.neutralColor) { colorComment += ', neutral: ' + options.neutralColor; neutralPalette = TonalPalette.fromHct(getHctFromHex(options.neutralColor)); } else { neutralPalette = TonalPalette.fromHueAndChroma( primaryColorHct.hue, primaryColorHct.chroma / 8.0, ); } const neutralVariantPalette = TonalPalette.fromHueAndChroma( primaryColorHct.hue, primaryColorHct.chroma / 8.0 + 4.0, ); // Create material dynamic scheme to generate the error tonal palette const errorPalette = getMaterialDynamicScheme( primaryPalette, secondaryPalette, tertiaryPalette, neutralPalette, neutralVariantPalette, false, 0, ).errorPalette; // Create the generated SCSS file with the exportable palette users can use in their `theme` // mixin call. const colorPalettes = getMapFromColorTonalPalettes( primaryPalette, secondaryPalette, tertiaryPalette, neutralPalette, neutralVariantPalette, errorPalette, ); let themeScss = generateSCSSTheme(colorPalettes, colorComment); // Add high contrast overrides mixins to generated file if specified if (options.includeHighContrast) { themeScss += generateHighContrastOverrideMixinsSCSS( primaryPalette, secondaryPalette, tertiaryPalette, neutralPalette, neutralVariantPalette, ); } createThemeFile(themeScss, tree, options.directory); }; }
{ "end_byte": 17477, "start_byte": 14230, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/theme-color/index.ts" }
components/src/material/schematics/ng-add/schema.ts_0_625
/** * @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 interface Schema { /** Name of the project. */ project: string; /** Whether the Angular browser animations module should be included and enabled. */ animations: 'enabled' | 'disabled' | 'excluded'; /** Name of pre-built theme to install. */ theme: 'azure-blue' | 'rose-red' | 'magenta-violet' | 'cyan-orange' | 'custom'; /** Whether to set up global typography styles. */ typography: boolean; }
{ "end_byte": 625, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-add/schema.ts" }
components/src/material/schematics/ng-add/index.spec.ts_0_666
import {normalize, workspaces, logging} from '@angular-devkit/core'; import {Tree} from '@angular-devkit/schematics'; import {SchematicTestRunner} from '@angular-devkit/schematics/testing'; import { getProjectFromWorkspace, getProjectIndexFiles, getProjectStyleFile, getProjectTargetOptions, } from '@angular/cdk/schematics'; import {createTestApp, createTestLibrary, getFileContent} from '@angular/cdk/schematics/testing'; import {getWorkspace} from '@schematics/angular/utility/workspace'; import {COLLECTION_PATH} from '../paths'; import {addPackageToPackageJson} from './package-config'; interface PackageJson { dependencies: Record<string, string>; }
{ "end_byte": 666, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-add/index.spec.ts" }
components/src/material/schematics/ng-add/index.spec.ts_668_9503
describe('ng-add schematic', () => { const baseOptions = {project: 'material'}; let runner: SchematicTestRunner; let appTree: Tree; let errorOutput: string[]; let warnOutput: string[]; beforeEach(async () => { runner = new SchematicTestRunner('schematics', COLLECTION_PATH); appTree = await createTestApp(runner, {standalone: false}); errorOutput = []; warnOutput = []; runner.logger.subscribe((e: logging.LogEntry) => { if (e.level === 'error') { errorOutput.push(e.message); } else if (e.level === 'warn') { warnOutput.push(e.message); } }); }); /** Expects the given file to be in the styles of the specified workspace project. */ function expectProjectStyleFile(project: workspaces.ProjectDefinition, filePath: string) { expect(getProjectTargetOptions(project, 'build')['styles']) .withContext(`Expected "${filePath}" to be added to the project styles in the workspace.`) .toContain(filePath); } /** Removes the specified dependency from the /package.json in the given tree. */ function removePackageJsonDependency(tree: Tree, dependencyName: string) { const packageContent = JSON.parse(getFileContent(tree, '/package.json')) as PackageJson; delete packageContent.dependencies[dependencyName]; tree.overwrite('/package.json', JSON.stringify(packageContent, null, 2)); } it('should update package.json', async () => { // By default, the Angular workspace schematic sets up "@angular/animations". In order // to verify that we would set up the dependency properly if someone doesn't have the // animations installed already, we remove the animations dependency explicitly. removePackageJsonDependency(appTree, '@angular/animations'); const tree = await runner.runSchematic('ng-add', baseOptions, appTree); const packageJson = JSON.parse(getFileContent(tree, '/package.json')) as PackageJson; const dependencies = packageJson.dependencies; const angularCoreVersion = dependencies['@angular/core']; expect(dependencies['@angular/material']).toBe('~0.0.0-PLACEHOLDER'); expect(dependencies['@angular/cdk']).toBe('~0.0.0-PLACEHOLDER'); expect(dependencies['@angular/forms']) .withContext('Expected the @angular/forms package to have the same version as @angular/core.') .toBe(angularCoreVersion); expect(dependencies['@angular/animations']) .withContext( 'Expected the @angular/animations package to have the same ' + 'version as @angular/core.', ) .toBe(angularCoreVersion); expect(Object.keys(dependencies)) .withContext('Expected the modified "dependencies" to be sorted alphabetically.') .toEqual(Object.keys(dependencies).sort()); expect(runner.tasks.some(task => task.name === 'node-package')) .withContext('Expected the package manager to be scheduled in order to update lock files.') .toBe(true); expect(runner.tasks.some(task => task.name === 'run-schematic')) .withContext('Expected the setup-project schematic to be scheduled.') .toBe(true); }); it('should respect version range from CLI ng-add command', async () => { // Simulates the behavior of the CLI `ng add` command. The command inserts the // requested package version into the `package.json` before the actual schematic runs. addPackageToPackageJson(appTree, '@angular/material', '^9.0.0'); const tree = await runner.runSchematic('ng-add', baseOptions, appTree); const packageJson = JSON.parse(getFileContent(tree, '/package.json')) as PackageJson; const dependencies = packageJson.dependencies; expect(dependencies['@angular/material']).toBe('^9.0.0'); expect(dependencies['@angular/cdk']).toBe('^9.0.0'); }); it('should add default theme', async () => { const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); expectProjectStyleFile(project, '@angular/material/prebuilt-themes/azure-blue.css'); }); it('should support adding a custom theme', async () => { // TODO(devversion): do not re-create test app here. appTree = await createTestApp(runner, {style: 'scss'}); const tree = await runner.runSchematic( 'ng-add-setup-project', {...baseOptions, theme: 'custom'}, appTree, ); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); const expectedStylesPath = normalize(`/${project.root}/src/styles.scss`); const buffer = tree.read(expectedStylesPath); const themeContent = buffer!.toString(); expect(themeContent).toContain(`@use '@angular/material' as mat;`); expect(themeContent).toContain(`$material-theme: mat.define-theme((`); }); it('should create a custom theme file if no SCSS file could be found', async () => { // TODO(devversion): do not re-create test app here. appTree = await createTestApp(runner, {style: 'css'}); const tree = await runner.runSchematic( 'ng-add-setup-project', {...baseOptions, theme: 'custom'}, appTree, ); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); const expectedStylesPath = normalize(`/${project.root}/src/custom-theme.scss`); expect(tree.files) .withContext('Expected a custom theme file to be created') .toContain(expectedStylesPath); expectProjectStyleFile(project, 'projects/material/src/custom-theme.scss'); }); it('should add font links', async () => { const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); const indexFiles = getProjectIndexFiles(project); expect(indexFiles.length).toBe(1); indexFiles.forEach(indexPath => { const buffer = tree.read(indexPath)!; const htmlContent = buffer.toString(); // Ensure that the indentation has been determined properly. We want to make sure that // the created links properly align with the existing HTML. Default CLI projects use an // indentation of two columns. expect(htmlContent).toContain( ' <link href="https://fonts.googleapis.com/icon?family=Material+Icons"', ); expect(htmlContent).toContain( ' <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@' + '300;400;500&display=swap"', ); }); }); it('should add material app styles', async () => { const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); const defaultStylesPath = getProjectStyleFile(project)!; const htmlContent = tree.read(defaultStylesPath)!.toString(); expect(htmlContent).toContain('html, body { height: 100%; }'); expect(htmlContent).toContain( 'body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }', ); }); it('should add provideAnimationsAsync to the project module', async () => { const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const fileContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(fileContent).toContain('provideAnimationsAsync()'); expect(fileContent).toContain( `import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';`, ); }); it('should add the provideAnimationsAsync to a bootstrapApplication call', async () => { appTree.delete('/projects/material/src/app/app.module.ts'); appTree.create( '/projects/material/src/app/app.config.ts', ` export const appConfig = { providers: [{ provide: 'foo', useValue: 1 }] }; `, ); appTree.overwrite( '/projects/material/src/main.ts', ` import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { appConfig } from './app/app.config'; bootstrapApplication(AppComponent, appConfig); `, ); const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const fileContent = getFileContent(tree, '/projects/material/src/app/app.config.ts'); expect(fileContent).toContain( `import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';`, ); expect(fileContent).toContain(`[{ provide: 'foo', useValue: 1 }, provideAnimationsAsync()]`); });
{ "end_byte": 9503, "start_byte": 668, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-add/index.spec.ts" }
components/src/material/schematics/ng-add/index.spec.ts_9507_19084
it("should add the provideAnimationAsync('noop') to the project module if animations are disabled", async () => { const tree = await runner.runSchematic( 'ng-add-setup-project', {...baseOptions, animations: 'disabled'}, appTree, ); const fileContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(fileContent).toContain(`provideAnimationsAsync('noop')`); expect(fileContent).toContain( `import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';`, ); }); it('should not add any animations code if animations are excluded', async () => { const tree = await runner.runSchematic( 'ng-add-setup-project', {...baseOptions, animations: 'excluded'}, appTree, ); const fileContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(fileContent).not.toContain('provideAnimationsAsync'); expect(fileContent).not.toContain('@angular/platform-browser/animations'); expect(fileContent).not.toContain('@angular/animations'); }); describe('custom project builders', () => { /** Overwrites a target builder for the workspace in the given tree */ function overwriteTargetBuilder(tree: Tree, targetName: 'build' | 'test', newBuilder: string) { const config = { version: 1, projects: { material: { projectType: 'application', root: 'projects/material', sourceRoot: 'projects/material/src', prefix: 'app', architect: { build: { builder: '@angular-devkit/build-angular:application', options: { outputPath: 'dist/material', index: 'projects/material/src/index.html', browser: 'projects/material/src/main.ts', styles: ['projects/material/src/styles.css'], }, }, test: { builder: '@angular-devkit/build-angular:karma', options: { outputPath: 'dist/material', index: 'projects/material/src/index.html', browser: 'projects/material/src/main.ts', styles: ['projects/material/src/styles.css'], }, }, }, }, }, }; config.projects.material.architect[targetName].builder = newBuilder; tree.overwrite('/angular.json', JSON.stringify(config, null, 2)); } it('should throw an error if the "build" target has been changed', async () => { overwriteTargetBuilder(appTree, 'build', 'thirdparty-builder'); await expectAsync( runner.runSchematic('ng-add-setup-project', baseOptions, appTree), ).toBeRejected(); }); it('should warn if the "test" target has been changed', async () => { overwriteTargetBuilder(appTree, 'test', 'thirdparty-test-builder'); await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); expect(errorOutput.length).toBe(0); expect(warnOutput.length).toBe(1); expect(warnOutput[0]).toMatch( /not using the default builders.*cannot add the configured theme/, ); }); }); describe('theme files', () => { /** Path to the default prebuilt theme file that will be added when running ng-add. */ const defaultPrebuiltThemePath = '@angular/material/prebuilt-themes/azure-blue.css'; /** Writes a specific style file to the workspace in the given tree */ function writeStyleFileToWorkspace(tree: Tree, stylePath: string) { tree.overwrite( '/angular.json', JSON.stringify( { version: 1, projects: { material: { projectType: 'application', root: 'projects/material', sourceRoot: 'projects/material/src', prefix: 'app', architect: { build: { builder: '@angular-devkit/build-angular:application', options: { outputPath: 'dist/material', index: 'projects/material/src/index.html', browser: 'projects/material/src/main.ts', styles: ['projects/material/src/styles.css', stylePath], }, }, }, }, }, }, null, 2, ), ); } it('should replace existing prebuilt theme files', async () => { const existingThemePath = '@angular/material/prebuilt-themes/purple-green.css'; writeStyleFileToWorkspace(appTree, existingThemePath); const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); const styles = getProjectTargetOptions(project, 'build')['styles']; expect(styles) .not.withContext('Expected the existing prebuilt theme file to be removed.') .toContain(existingThemePath); expect(styles) .withContext('Expected the default prebuilt theme to be added.') .toContain(defaultPrebuiltThemePath); }); it('should not replace existing custom theme files', async () => { writeStyleFileToWorkspace(appTree, './projects/material/custom-theme.scss'); const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); const styles = getProjectTargetOptions(project, 'build')['styles']; expect(styles) .not.withContext('Expected the default prebuilt theme to be not configured.') .toContain(defaultPrebuiltThemePath); expect(errorOutput.length).toBe(1); expect(errorOutput[0]).toMatch(/Could not add the selected theme/); }); it('should not add a theme file multiple times', async () => { writeStyleFileToWorkspace(appTree, defaultPrebuiltThemePath); const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); const styles = getProjectTargetOptions(project, 'build')['styles']; expect(styles) .withContext( 'Expected the "styles.css" file and default prebuilt theme to be ' + 'the only styles', ) .toEqual(['projects/material/src/styles.css', defaultPrebuiltThemePath]); }); it('should not overwrite existing custom theme files', async () => { appTree.create('/projects/material/custom-theme.scss', 'custom-theme'); const tree = await runner.runSchematic( 'ng-add-setup-project', {...baseOptions, theme: 'custom'}, appTree, ); expect(tree.readContent('/projects/material/custom-theme.scss')) .withContext('Expected the old custom theme content to be unchanged.') .toBe('custom-theme'); }); }); it('should add the global typography class if the body has no classes', async () => { const tree = await runner.runSchematic( 'ng-add-setup-project', { ...baseOptions, typography: true, }, appTree, ); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); const indexFiles = getProjectIndexFiles(project); expect(indexFiles.length).toBe(1); indexFiles.forEach(indexPath => { const buffer = tree.read(indexPath)!; expect(buffer.toString()).toContain('<body class="mat-typography">'); }); }); it('should add the global typography class if the body has existing classes', async () => { appTree.overwrite( 'projects/material/src/index.html', ` <html> <head></head> <body class="one two"></body> </html> `, ); const tree = await runner.runSchematic( 'ng-add-setup-project', { ...baseOptions, typography: true, }, appTree, ); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); const indexFiles = getProjectIndexFiles(project); expect(indexFiles.length).toBe(1); indexFiles.forEach(indexPath => { const buffer = tree.read(indexPath)!; expect(buffer.toString()).toContain('<body class="one two mat-typography">'); }); }); it('should not add the global typography class if it exists already', async () => { appTree.overwrite( 'projects/material/src/index.html', ` <html> <head></head> <body class="one mat-typography two"></body> </html> `, ); const tree = await runner.runSchematic( 'ng-add-setup-project', { ...baseOptions, typography: true, }, appTree, ); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); const indexFiles = getProjectIndexFiles(project); expect(indexFiles.length).toBe(1); indexFiles.forEach(indexPath => { const buffer = tree.read(indexPath)!; expect(buffer.toString()).toContain('<body class="one mat-typography two">'); }); });
{ "end_byte": 19084, "start_byte": 9507, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-add/index.spec.ts" }
components/src/material/schematics/ng-add/index.spec.ts_19088_28573
it('should not add the global typography class if the user did not opt into it', async () => { appTree.overwrite( 'projects/material/src/index.html', ` <html> <head></head> <body class="one two"></body> </html> `, ); const tree = await runner.runSchematic( 'ng-add-setup-project', { ...baseOptions, typography: false, }, appTree, ); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); const indexFiles = getProjectIndexFiles(project); expect(indexFiles.length).toBe(1); indexFiles.forEach(indexPath => { const buffer = tree.read(indexPath)!; expect(buffer.toString()).toContain('<body class="one two">'); }); }); describe('using browser builder', () => { beforeEach(() => { const config = { version: 1, projects: { material: { projectType: 'application', root: 'projects/material', sourceRoot: 'projects/material/src', prefix: 'app', architect: { build: { builder: '@angular-devkit/build-angular:browser', options: { outputPath: 'dist/material', index: 'projects/material/src/index.html', main: 'projects/material/src/main.ts', styles: ['projects/material/src/styles.css'], }, }, test: { builder: '@angular-devkit/build-angular:karma', options: { outputPath: 'dist/material', index: 'projects/material/src/index.html', browser: 'projects/material/src/main.ts', styles: ['projects/material/src/styles.css'], }, }, }, }, }, }; appTree.overwrite('/angular.json', JSON.stringify(config, null, 2)); }); it('should add a theme', async () => { const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); expectProjectStyleFile(project, '@angular/material/prebuilt-themes/azure-blue.css'); }); it('should add material app styles', async () => { const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); const defaultStylesPath = getProjectStyleFile(project)!; const htmlContent = tree.read(defaultStylesPath)!.toString(); expect(htmlContent).toContain('html, body { height: 100%; }'); expect(htmlContent).toContain( 'body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }', ); }); it('should add the provideAnimationsAsync to the project module', async () => { const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const fileContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(fileContent).toContain('provideAnimationsAsync()'); expect(fileContent).toContain( `import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';`, ); }); }); describe('using browser-esbuild builder', () => { beforeEach(() => { const config = { version: 1, projects: { material: { projectType: 'application', root: 'projects/material', sourceRoot: 'projects/material/src', prefix: 'app', architect: { build: { builder: '@angular-devkit/build-angular:browser-esbuild', options: { outputPath: 'dist/material', index: 'projects/material/src/index.html', main: 'projects/material/src/main.ts', styles: ['projects/material/src/styles.css'], }, }, test: { builder: '@angular-devkit/build-angular:karma', options: { outputPath: 'dist/material', index: 'projects/material/src/index.html', browser: 'projects/material/src/main.ts', styles: ['projects/material/src/styles.css'], }, }, }, }, }, }; appTree.overwrite('/angular.json', JSON.stringify(config, null, 2)); }); it('should add a theme', async () => { const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); expectProjectStyleFile(project, '@angular/material/prebuilt-themes/azure-blue.css'); }); it('should add material app styles', async () => { const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); const defaultStylesPath = getProjectStyleFile(project)!; const htmlContent = tree.read(defaultStylesPath)!.toString(); expect(htmlContent).toContain('html, body { height: 100%; }'); expect(htmlContent).toContain( 'body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }', ); }); it('should add the provideAnimationsAsync to the project module', async () => { const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const fileContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(fileContent).toContain('provideAnimationsAsync()'); expect(fileContent).toContain( `import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';`, ); }); }); describe('using lower dependency builder', () => { beforeEach(() => { const config = { version: 1, projects: { material: { projectType: 'application', root: 'projects/material', sourceRoot: 'projects/material/src', prefix: 'app', architect: { build: { builder: '@angular/build:application', options: { outputPath: 'dist/material', index: 'projects/material/src/index.html', browser: 'projects/material/src/main.ts', styles: ['projects/material/src/styles.css'], }, }, }, }, }, }; appTree.overwrite('/angular.json', JSON.stringify(config, null, 2)); }); it('should add a theme', async () => { const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); expectProjectStyleFile(project, '@angular/material/prebuilt-themes/azure-blue.css'); }); it('should add material app styles', async () => { const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const workspace = await getWorkspace(tree); const project = getProjectFromWorkspace(workspace, baseOptions.project); const defaultStylesPath = getProjectStyleFile(project)!; const htmlContent = tree.read(defaultStylesPath)!.toString(); expect(htmlContent).toContain('html, body { height: 100%; }'); expect(htmlContent).toContain( 'body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }', ); }); it('should add the provideAnimationsAsync to the project module', async () => { const tree = await runner.runSchematic('ng-add-setup-project', baseOptions, appTree); const fileContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(fileContent).toContain('provideAnimationsAsync()'); expect(fileContent).toContain( `import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';`, ); }); }); }); describe('ng-add schematic - library project', () => { let runner: SchematicTestRunner; let libraryTree: Tree; let errorOutput: string[]; let warnOutput: string[]; beforeEach(async () => { runner = new SchematicTestRunner('schematics', require.resolve('../collection.json')); libraryTree = await createTestLibrary(runner); errorOutput = []; warnOutput = []; runner.logger.subscribe((e: logging.LogEntry) => { if (e.level === 'error') { errorOutput.push(e.message); } else if (e.level === 'warn') { warnOutput.push(e.message); } }); }); it('should warn if a library project is targeted', async () => { await runner.runSchematic('ng-add-setup-project', {project: 'material'}, libraryTree); expect(errorOutput.length).toBe(0); expect(warnOutput.length).toBe(1); expect(warnOutput[0]).toMatch(/There is no additional setup required/); }); });
{ "end_byte": 28573, "start_byte": 19088, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-add/index.spec.ts" }
components/src/material/schematics/ng-add/package-config.ts_0_1762
/** * @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 {Tree} from '@angular-devkit/schematics'; interface PackageJson { dependencies: Record<string, string>; } /** * Sorts the keys of the given object. * @returns A new object instance with sorted keys */ function sortObjectByKeys(obj: Record<string, string>) { return Object.keys(obj) .sort() .reduce( (result, key) => { result[key] = obj[key]; return result; }, {} as Record<string, string>, ); } /** Adds a package to the package.json in the given host tree. */ export function addPackageToPackageJson(host: Tree, pkg: string, version: string): Tree { if (host.exists('package.json')) { const sourceText = host.read('package.json')!.toString('utf-8'); const json = JSON.parse(sourceText) as PackageJson; if (!json.dependencies) { json.dependencies = {}; } if (!json.dependencies[pkg]) { json.dependencies[pkg] = version; json.dependencies = sortObjectByKeys(json.dependencies); } host.overwrite('package.json', JSON.stringify(json, null, 2)); } return host; } /** Gets the version of the specified package by looking at the package.json in the given tree. */ export function getPackageVersionFromPackageJson(tree: Tree, name: string): string | null { if (!tree.exists('package.json')) { return null; } const packageJson = JSON.parse(tree.read('package.json')!.toString('utf8')) as PackageJson; if (packageJson.dependencies && packageJson.dependencies[name]) { return packageJson.dependencies[name]; } return null; }
{ "end_byte": 1762, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-add/package-config.ts" }
components/src/material/schematics/ng-add/index.ts_0_3276
/** * @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, Tree} from '@angular-devkit/schematics'; import {NodePackageInstallTask, RunSchematicTask} from '@angular-devkit/schematics/tasks'; import {addPackageToPackageJson, getPackageVersionFromPackageJson} from './package-config'; import {Schema} from './schema'; /** * Version range that will be used for the Angular CDK and Angular Material if this * schematic has been run outside of the CLI `ng add` command. In those cases, there * can be no dependency on `@angular/material` in the `package.json` file, and we need * to manually insert the dependency based on the build version placeholder. * * Note that the fallback version range does not use caret, but tilde because that is * the default for Angular framework dependencies in CLI projects. */ const fallbackMaterialVersionRange = `~0.0.0-PLACEHOLDER`; /** * Schematic factory entry-point for the `ng-add` schematic. The ng-add schematic will be * automatically executed if developers run `ng add @angular/material`. * * Since the Angular Material schematics depend on the schematic utility functions from the CDK, * we need to install the CDK before loading the schematic files that import from the CDK. */ export default function (options: Schema): Rule { return (host: Tree, context: SchematicContext) => { // Version tag of the `@angular/core` dependency that has been loaded from the `package.json` // of the CLI project. This tag should be preferred because all Angular dependencies should // have the same version tag if possible. const ngCoreVersionTag = getPackageVersionFromPackageJson(host, '@angular/core'); const materialVersionRange = getPackageVersionFromPackageJson(host, '@angular/material'); const angularDependencyVersion = ngCoreVersionTag || `0.0.0-NG`; // The CLI inserts `@angular/material` into the `package.json` before this schematic runs. // This means that we do not need to insert Angular Material into `package.json` files again. // In some cases though, it could happen that this schematic runs outside of the CLI `ng add` // command, or Material is only listed a dev dependency. If that is the case, we insert a // version based on the current build version (substituted version placeholder). if (materialVersionRange === null) { addPackageToPackageJson(host, '@angular/material', fallbackMaterialVersionRange); } addPackageToPackageJson( host, '@angular/cdk', materialVersionRange || fallbackMaterialVersionRange, ); addPackageToPackageJson(host, '@angular/forms', angularDependencyVersion); addPackageToPackageJson(host, '@angular/animations', angularDependencyVersion); // Since the Angular Material schematics depend on the schematic utility functions from the // CDK, we need to install the CDK before loading the schematic files that import from the CDK. const installTaskId = context.addTask(new NodePackageInstallTask()); context.addTask(new RunSchematicTask('ng-add-setup-project', options), [installTaskId]); }; }
{ "end_byte": 3276, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-add/index.ts" }
components/src/material/schematics/ng-add/setup-project.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 {chain, noop, Rule, SchematicContext, Tree, callRule} from '@angular-devkit/schematics'; import {getProjectFromWorkspace, getProjectStyleFile} from '@angular/cdk/schematics'; import {getWorkspace} from '@schematics/angular/utility/workspace'; import {addRootProvider} from '@schematics/angular/utility'; import {ProjectType} from '@schematics/angular/utility/workspace-models'; import {of as observableOf} from 'rxjs'; import {catchError} from 'rxjs/operators'; import {addFontsToIndex} from './fonts/material-fonts'; import {Schema} from './schema'; import {addThemeToAppStyles, addTypographyClass} from './theming/theming'; /** * Scaffolds the basics of a Angular Material application, this includes: * - Add Packages to package.json * - Adds pre-built themes to styles.ext * - Adds Browser Animation to app.module */ export default function (options: Schema): Rule { return async (host: Tree, context: SchematicContext) => { const workspace = await getWorkspace(host); const project = getProjectFromWorkspace(workspace, options.project); if (project.extensions['projectType'] === ProjectType.Application) { return chain([ addAnimations(options), addThemeToAppStyles(options), addFontsToIndex(options), addMaterialAppStyles(options), addTypographyClass(options), ]); } context.logger.warn( 'Angular Material has been set up in your workspace. There is no additional setup ' + 'required for consuming Angular Material in your library project.\n\n' + 'If you intended to run the schematic on a different project, pass the `--project` ' + 'option.', ); return; }; } /** * Adds custom Material styles to the project style file. The custom CSS sets up the Roboto font * and reset the default browser body margin. */ function addMaterialAppStyles(options: Schema) { return async (host: Tree, context: SchematicContext) => { const workspace = await getWorkspace(host); const project = getProjectFromWorkspace(workspace, options.project); const styleFilePath = getProjectStyleFile(project); const logger = context.logger; if (!styleFilePath) { logger.error(`Could not find the default style file for this project.`); logger.info(`Consider manually adding the Roboto font to your CSS.`); logger.info(`More information at https://fonts.google.com/specimen/Roboto`); return; } const buffer = host.read(styleFilePath); if (!buffer) { logger.error( `Could not read the default style file within the project ` + `(${styleFilePath})`, ); logger.info(`Please consider manually setting up the Roboto font.`); return; } const htmlContent = buffer.toString(); const insertion = '\n' + `html, body { height: 100%; }\n` + `body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }\n`; if (htmlContent.includes(insertion)) { return; } const recorder = host.beginUpdate(styleFilePath); recorder.insertLeft(htmlContent.length, insertion); host.commitUpdate(recorder); }; } /** Adds the animations package to the project based on the conffiguration. */ function addAnimations(options: Schema): Rule { return (host: Tree, context: SchematicContext) => { const animationsRule = options.animations === 'excluded' ? noop() : addRootProvider(options.project, ({code, external}) => { return code`${external( 'provideAnimationsAsync', '@angular/platform-browser/animations/async', )}(${options.animations === 'disabled' ? `'noop'` : ''})`; }); // The `addRootProvider` rule can throw in some custom scenarios (see #28640). // Add some error handling around it so the setup isn't interrupted. return callRule(animationsRule, host, context).pipe( catchError(() => { context.logger.error( 'Failed to add animations to project. Continuing with the Angular Material setup.', ); context.logger.info( 'Read more about setting up the animations manually: https://angular.dev/guide/animations', ); return observableOf(host); }), ); }; }
{ "end_byte": 4487, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-add/setup-project.ts" }
components/src/material/schematics/ng-add/theming/create-custom-theme.ts_0_1396
/** * @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 */ /** Create custom theme for the given application configuration. */ export function createCustomTheme(name: string = 'app') { return ` // Custom Theming for Angular Material // For more information: https://material.angular.io/guide/theming @use '@angular/material' as mat; // Plus imports for other components in your app. // Define the theme object. $${name}-theme: mat.define-theme(( color: ( theme-type: light, primary: mat.$azure-palette, tertiary: mat.$blue-palette, ), density: ( scale: 0, ) )); // Include theme styles for core and each component used in your app. // Alternatively, you can import and @include the theme mixins for each component // that you are using. :root { @include mat.all-component-themes($${name}-theme); } // Comment out the line below if you want to use the pre-defined typography utility classes. // For more information: https://material.angular.io/guide/typography#using-typography-styles-in-your-application. // @include mat.typography-hierarchy($${name}-theme); // Comment out the line below if you want to use the deprecated \`color\` inputs. // @include mat.color-variants-backwards-compatibility($${name}-theme); `; }
{ "end_byte": 1396, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-add/theming/create-custom-theme.ts" }
components/src/material/schematics/ng-add/theming/theming.ts_0_7966
/** * @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 {normalize, logging, workspaces} from '@angular-devkit/core'; import { chain, noop, Rule, SchematicContext, SchematicsException, Tree, } from '@angular-devkit/schematics'; import { addBodyClass, getProjectFromWorkspace, getProjectStyleFile, getProjectTargetOptions, getProjectIndexFiles, getProjectTestTargets, getProjectBuildTargets, } from '@angular/cdk/schematics'; import {InsertChange} from '@schematics/angular/utility/change'; import {getWorkspace, updateWorkspace} from '@schematics/angular/utility/workspace'; import {join} from 'path'; import {Schema} from '../schema'; import {createCustomTheme} from './create-custom-theme'; /** Path segment that can be found in paths that refer to a prebuilt theme. */ const prebuiltThemePathSegment = '@angular/material/prebuilt-themes'; /** Default file name of the custom theme that can be generated. */ const defaultCustomThemeFilename = 'custom-theme.scss'; /** Add pre-built styles to the main project style file. */ export function addThemeToAppStyles(options: Schema): Rule { return (host: Tree, context: SchematicContext) => { const themeName = options.theme || 'azure-blue'; return themeName === 'custom' ? insertCustomTheme(options.project, host, context.logger) : insertPrebuiltTheme(options.project, themeName, context.logger); }; } /** Adds the global typography class to the body element. */ export function addTypographyClass(options: Schema): Rule { return async (host: Tree) => { const workspace = await getWorkspace(host); const project = getProjectFromWorkspace(workspace, options.project); const projectIndexFiles = getProjectIndexFiles(project); if (!projectIndexFiles.length) { throw new SchematicsException('No project index HTML file could be found.'); } if (options.typography) { projectIndexFiles.forEach(path => addBodyClass(host, path, 'mat-typography')); } }; } /** * Insert a custom theme to project style file. If no valid style file could be found, a new * Scss file for the custom theme will be created. */ async function insertCustomTheme( projectName: string, host: Tree, logger: logging.LoggerApi, ): Promise<Rule> { const workspace = await getWorkspace(host); const project = getProjectFromWorkspace(workspace, projectName); const stylesPath = getProjectStyleFile(project, 'scss'); const themeContent = createCustomTheme(projectName); if (!stylesPath) { if (!project.sourceRoot) { throw new SchematicsException( `Could not find source root for project: "${projectName}". ` + `Please make sure that the "sourceRoot" property is set in the workspace config.`, ); } // Normalize the path through the devkit utilities because we want to avoid having // unnecessary path segments and windows backslash delimiters. const customThemePath = normalize(join(project.sourceRoot, defaultCustomThemeFilename)); if (host.exists(customThemePath)) { logger.warn(`Cannot create a custom Angular Material theme because ${customThemePath} already exists. Skipping custom theme generation.`); return noop(); } host.create(customThemePath, themeContent); return addThemeStyleToTarget(projectName, 'build', customThemePath, logger); } const insertion = new InsertChange(stylesPath, 0, themeContent); const recorder = host.beginUpdate(stylesPath); recorder.insertLeft(insertion.pos, insertion.toAdd); host.commitUpdate(recorder); return noop(); } /** Insert a pre-built theme into the angular.json file. */ function insertPrebuiltTheme(project: string, theme: string, logger: logging.LoggerApi): Rule { const themePath = `@angular/material/prebuilt-themes/${theme}.css`; return chain([ addThemeStyleToTarget(project, 'build', themePath, logger), addThemeStyleToTarget(project, 'test', themePath, logger), ]); } /** Adds a theming style entry to the given project target options. */ function addThemeStyleToTarget( projectName: string, targetName: 'test' | 'build', assetPath: string, logger: logging.LoggerApi, ): Rule { return updateWorkspace(workspace => { const project = getProjectFromWorkspace(workspace, projectName); // Do not update the builder options in case the target does not use the default CLI builder. if (!validateDefaultTargetBuilder(project, targetName, logger)) { return; } const targetOptions = getProjectTargetOptions(project, targetName); const styles = targetOptions['styles'] as (string | {input: string})[]; if (!styles) { targetOptions['styles'] = [assetPath]; } else { const existingStyles = styles.map(s => (typeof s === 'string' ? s : s.input)); for (let [index, stylePath] of existingStyles.entries()) { // If the given asset is already specified in the styles, we don't need to do anything. if (stylePath === assetPath) { return; } // In case a prebuilt theme is already set up, we can safely replace the theme with the new // theme file. If a custom theme is set up, we are not able to safely replace the custom // theme because these files can contain custom styles, while prebuilt themes are // always packaged and considered replaceable. if (stylePath.includes(defaultCustomThemeFilename)) { logger.error( `Could not add the selected theme to the CLI project ` + `configuration because there is already a custom theme file referenced.`, ); logger.info(`Please manually add the following style file to your configuration:`); logger.info(` ${assetPath}`); return; } else if (stylePath.includes(prebuiltThemePathSegment)) { styles.splice(index, 1); } } styles.unshift(assetPath); } }); } /** * Validates that the specified project target is configured with the default builders which are * provided by the Angular CLI. If the configured builder does not match the default builder, * this function can either throw or just show a warning. */ function validateDefaultTargetBuilder( project: workspaces.ProjectDefinition, targetName: 'build' | 'test', logger: logging.LoggerApi, ) { const targets = targetName === 'test' ? getProjectTestTargets(project) : getProjectBuildTargets(project); const isDefaultBuilder = targets.length > 0; // Because the build setup for the Angular CLI can be customized by developers, we can't know // where to put the theme file in the workspace configuration if custom builders are being // used. In case the builder has been changed for the "build" target, we throw an error and // exit because setting up a theme is a primary goal of `ng-add`. Otherwise if just the "test" // builder has been changed, we warn because a theme is not mandatory for running tests // with Material. See: https://github.com/angular/components/issues/14176 if (!isDefaultBuilder && targetName === 'build') { throw new SchematicsException( `Your project is not using the default builders for ` + `"${targetName}". The Angular Material schematics cannot add a theme to the workspace ` + `configuration if the builder has been changed.`, ); } else if (!isDefaultBuilder) { // for non-build targets we gracefully report the error without actually aborting the // setup schematic. This is because a theme is not mandatory for running tests. logger.warn( `Your project is not using the default builders for "${targetName}". This ` + `means that we cannot add the configured theme to the "${targetName}" target.`, ); } return isDefaultBuilder; }
{ "end_byte": 7966, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-add/theming/theming.ts" }
components/src/material/schematics/ng-add/fonts/material-fonts.ts_0_1346
/** * @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, SchematicsException, Tree} from '@angular-devkit/schematics'; import { appendHtmlElementToHead, getProjectFromWorkspace, getProjectIndexFiles, } from '@angular/cdk/schematics'; import {getWorkspace} from '@schematics/angular/utility/workspace'; import {Schema} from '../schema'; /** Adds the Material Design fonts to the index HTML file. */ export function addFontsToIndex(options: Schema): Rule { return async (host: Tree) => { const workspace = await getWorkspace(host); const project = getProjectFromWorkspace(workspace, options.project); const projectIndexFiles = getProjectIndexFiles(project); if (!projectIndexFiles.length) { throw new SchematicsException('No project index HTML file could be found.'); } const fonts = [ 'https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap', 'https://fonts.googleapis.com/icon?family=Material+Icons', ]; projectIndexFiles.forEach(indexFilePath => { fonts.forEach(font => { appendHtmlElementToHead(host, indexFilePath, `<link href="${font}" rel="stylesheet">`); }); }); }; }
{ "end_byte": 1346, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/schematics/ng-add/fonts/material-fonts.ts" }
components/src/material/prebuilt-themes/BUILD.bazel_0_1705
package(default_visibility = ["//visibility:public"]) # We use these genrules to put the prebuilt themes into the bazel-generated npm # package in the right spot. The *right* thing to do would be to move them, but # we would need to update references for Google apps. ## **NOTE**: When adding/removing prebuilt themes from here, make sure to update # the `material/package.json` exports field. genrule( name = "indigo-pink", srcs = ["//src/material/core:theming/prebuilt/indigo-pink.css"], outs = ["indigo-pink.css"], cmd = "cp $< $@", ) genrule( name = "deeppurple-amber", srcs = ["//src/material/core:theming/prebuilt/deeppurple-amber.css"], outs = ["deeppurple-amber.css"], cmd = "cp $< $@", ) genrule( name = "pink-bluegrey", srcs = ["//src/material/core:theming/prebuilt/pink-bluegrey.css"], outs = ["pink-bluegrey.css"], cmd = "cp $< $@", ) genrule( name = "purple-green", srcs = ["//src/material/core:theming/prebuilt/purple-green.css"], outs = ["purple-green.css"], cmd = "cp $< $@", ) genrule( name = "azure-blue", srcs = ["//src/material/core:theming/prebuilt/azure-blue.css"], outs = ["azure-blue.css"], cmd = "cp $< $@", ) genrule( name = "rose-red", srcs = ["//src/material/core:theming/prebuilt/rose-red.css"], outs = ["rose-red.css"], cmd = "cp $< $@", ) genrule( name = "cyan-orange", srcs = ["//src/material/core:theming/prebuilt/cyan-orange.css"], outs = ["cyan-orange.css"], cmd = "cp $< $@", ) genrule( name = "magenta-violet", srcs = ["//src/material/core:theming/prebuilt/magenta-violet.css"], outs = ["magenta-violet.css"], cmd = "cp $< $@", )
{ "end_byte": 1705, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/prebuilt-themes/BUILD.bazel" }
components/src/material/badge/badge.scss_0_4347
@use 'sass:color'; @use '@angular/cdk'; @use '../core/tokens/m2/mat/badge' as tokens-mat-badge; @use '../core/tokens/token-utils'; $default-size: 22px !default; $small-size: $default-size - 6; $large-size: $default-size + 6; @mixin _badge-size($size) { @include token-utils.use-tokens(tokens-mat-badge.$prefix, tokens-mat-badge.get-token-slots()) { $prefix: if($size == 'medium', '', $size + '-size-'); $legacy-size-var-name: 'legacy-#{$prefix}container-size'; $size-var-name: '#{$prefix}container-size'; .mat-badge-content { // The M2 badge is implemented incorrectly because it uses `width` and `height` for its // size which causes the text to be truncated. For M3 we want to fix this by emitting // two declarations: // * `legacy-container-size` token - targets width/height as in M2. In M3 the token is // emitted as `unset`. // * `container-size` token - In M2 the token is emitted as `unset` to preserve the legacy // behavior while in M3 it targets `min-width` and `min-height` which allows the badge to // grow with the content. @include token-utils.create-token-slot(width, $legacy-size-var-name); @include token-utils.create-token-slot(height, $legacy-size-var-name); @include token-utils.create-token-slot(min-width, $size-var-name); @include token-utils.create-token-slot(min-height, $size-var-name); @include token-utils.create-token-slot(line-height, '#{$prefix}line-height'); @include token-utils.create-token-slot(padding, '#{$prefix}container-padding'); @include token-utils.create-token-slot(font-size, '#{$prefix}text-size'); @include token-utils.create-token-slot(margin, '#{$prefix}container-offset'); } &.mat-badge-overlap .mat-badge-content { @include token-utils.create-token-slot(margin, '#{$prefix}container-overlap-offset'); } } } .mat-badge { position: relative; // The badge should make sure its host is overflow visible so that the badge content // can be rendered outside of the element. Some components such as <mat-icon> explicitly // style `overflow: hidden` so this requires extra specificity so that it does not // depend on style load order. &.mat-badge { overflow: visible; } } .mat-badge-content { position: absolute; text-align: center; display: inline-block; transition: transform 200ms ease-in-out; transform: scale(0.6); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; box-sizing: border-box; pointer-events: none; @include token-utils.use-tokens(tokens-mat-badge.$prefix, tokens-mat-badge.get-token-slots()) { @include token-utils.create-token-slot(background-color, background-color); @include token-utils.create-token-slot(color, text-color); @include token-utils.create-token-slot(font-family, text-font); @include token-utils.create-token-slot(font-weight, text-weight); @include token-utils.create-token-slot(border-radius, container-shape); .mat-badge-above & { bottom: 100%; } .mat-badge-below & { top: 100%; } .mat-badge-before & { right: 100%; } [dir='rtl'] .mat-badge-before & { right: auto; left: 100%; } .mat-badge-after & { left: 100%; } [dir='rtl'] .mat-badge-after & { left: auto; right: 100%; } } @include cdk.high-contrast { outline: solid 1px; border-radius: 0; } } .mat-badge-disabled .mat-badge-content { @include token-utils.use-tokens(tokens-mat-badge.$prefix, tokens-mat-badge.get-token-slots()) { @include token-utils.create-token-slot(background-color, disabled-state-background-color); @include token-utils.create-token-slot(color, disabled-state-text-color); } } .mat-badge-hidden .mat-badge-content { display: none; } .ng-animate-disabled .mat-badge-content, .mat-badge-content._mat-animation-noopable { transition: none; } // The active class is added after the element is added // so it can animate scale to default .mat-badge-content.mat-badge-active { // Scale to `none` instead of `1` to avoid blurry text in some browsers. transform: none; } .mat-badge-small { @include _badge-size('small'); } .mat-badge-medium { @include _badge-size('medium'); } .mat-badge-large { @include _badge-size('large'); }
{ "end_byte": 4347, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/badge/badge.scss" }
components/src/material/badge/badge.spec.ts_0_10017
import {ComponentFixture, TestBed} from '@angular/core/testing'; import {Component, DebugElement, ViewEncapsulation, ViewChild, signal} from '@angular/core'; import {By} from '@angular/platform-browser'; import {MatBadge, MatBadgeModule} from './index'; import {ThemePalette} from '@angular/material/core'; describe('MatBadge', () => { let fixture: ComponentFixture<any>; let badgeHostNativeElement: HTMLElement; let badgeHostDebugElement: DebugElement; describe('on an interative host', () => { let testComponent: BadgeOnInteractiveElement; beforeEach(() => { TestBed.configureTestingModule({ imports: [ MatBadgeModule, BadgeOnInteractiveElement, PreExistingBadge, NestedBadge, BadgeOnTemplate, ], }); fixture = TestBed.createComponent(BadgeOnInteractiveElement); testComponent = fixture.debugElement.componentInstance; fixture.detectChanges(); badgeHostDebugElement = fixture.debugElement.query(By.directive(MatBadge))!; badgeHostNativeElement = badgeHostDebugElement.nativeElement; }); it('should update the badge based on attribute', () => { const badgeElement = badgeHostNativeElement.querySelector('.mat-badge-content')!; expect(badgeElement.textContent).toContain('1'); testComponent.badgeContent.set('22'); fixture.detectChanges(); expect(badgeElement.textContent).toContain('22'); }); it('should be able to pass in falsy values to the badge content', () => { const badgeElement = badgeHostNativeElement.querySelector('.mat-badge-content')!; expect(badgeElement.textContent).toContain('1'); testComponent.badgeContent.set(0); fixture.detectChanges(); expect(badgeElement.textContent).toContain('0'); }); it('should treat null and undefined as empty strings in the badge content', () => { const badgeElement = badgeHostNativeElement.querySelector('.mat-badge-content')!; expect(badgeElement.textContent).toContain('1'); testComponent.badgeContent.set(null); fixture.detectChanges(); expect(badgeElement.textContent?.trim()).toBe(''); testComponent.badgeContent.set(undefined); fixture.detectChanges(); expect(badgeElement.textContent?.trim()).toBe(''); }); it('should apply class based on color attribute', () => { testComponent.badgeColor.set('primary'); fixture.detectChanges(); expect(badgeHostNativeElement.classList.contains('mat-badge-primary')).toBe(true); testComponent.badgeColor.set('accent'); fixture.detectChanges(); expect(badgeHostNativeElement.classList.contains('mat-badge-accent')).toBe(true); testComponent.badgeColor.set('warn'); fixture.detectChanges(); expect(badgeHostNativeElement.classList.contains('mat-badge-warn')).toBe(true); testComponent.badgeColor.set(undefined); fixture.detectChanges(); expect(badgeHostNativeElement.classList).not.toContain('mat-badge-accent'); }); it('should update the badge position on direction change', () => { expect(badgeHostNativeElement.classList.contains('mat-badge-above')).toBe(true); expect(badgeHostNativeElement.classList.contains('mat-badge-after')).toBe(true); testComponent.badgeDirection.set('below before'); fixture.detectChanges(); expect(badgeHostNativeElement.classList.contains('mat-badge-below')).toBe(true); expect(badgeHostNativeElement.classList.contains('mat-badge-before')).toBe(true); }); it('should change visibility to hidden', () => { expect(badgeHostNativeElement.classList.contains('mat-badge-hidden')).toBe(false); testComponent.badgeHidden.set(true); fixture.detectChanges(); expect(badgeHostNativeElement.classList.contains('mat-badge-hidden')).toBe(true); }); it('should change badge sizes', () => { expect(badgeHostNativeElement.classList.contains('mat-badge-medium')).toBe(true); testComponent.badgeSize.set('small'); fixture.detectChanges(); expect(badgeHostNativeElement.classList.contains('mat-badge-small')).toBe(true); testComponent.badgeSize.set('large'); fixture.detectChanges(); expect(badgeHostNativeElement.classList.contains('mat-badge-large')).toBe(true); }); it('should change badge overlap', () => { expect(badgeHostNativeElement.classList.contains('mat-badge-overlap')).toBe(false); testComponent.badgeOverlap.set(true); fixture.detectChanges(); expect(badgeHostNativeElement.classList.contains('mat-badge-overlap')).toBe(true); }); it('should toggle `aria-describedby` depending on whether the badge has a description', () => { expect(badgeHostNativeElement.hasAttribute('aria-describedby')).toBeFalse(); testComponent.badgeDescription.set('Describing a badge'); fixture.detectChanges(); const describedById = badgeHostNativeElement.getAttribute('aria-describedby') || ''; const description = document.getElementById(describedById)?.textContent; expect(description).toBe('Describing a badge'); testComponent.badgeDescription.set(''); fixture.detectChanges(); expect(badgeHostNativeElement.hasAttribute('aria-describedby')).toBeFalse(); }); it('should toggle visibility based on whether the badge has content', () => { const classList = badgeHostNativeElement.classList; expect(classList.contains('mat-badge-hidden')).toBe(false); testComponent.badgeContent.set(''); fixture.detectChanges(); expect(classList.contains('mat-badge-hidden')).toBe(true); testComponent.badgeContent.set('hello'); fixture.detectChanges(); expect(classList.contains('mat-badge-hidden')).toBe(false); testComponent.badgeContent.set(' '); fixture.detectChanges(); expect(classList.contains('mat-badge-hidden')).toBe(true); testComponent.badgeContent.set(0); fixture.detectChanges(); expect(classList.contains('mat-badge-hidden')).toBe(false); }); it('should apply view encapsulation on create badge content', () => { const badge = badgeHostNativeElement.querySelector('.mat-badge-content')!; let encapsulationAttr: Attr | undefined; for (let i = 0; i < badge.attributes.length; i++) { if (badge.attributes[i].name.startsWith('_ngcontent-')) { encapsulationAttr = badge.attributes[i]; break; } } expect(encapsulationAttr).toBeTruthy(); }); it('should toggle a class depending on the badge disabled state', () => { const element: HTMLElement = badgeHostDebugElement.nativeElement; expect(element.classList).not.toContain('mat-badge-disabled'); testComponent.badgeDisabled.set(true); fixture.detectChanges(); expect(element.classList).toContain('mat-badge-disabled'); }); it('should clear any pre-existing badges', () => { const preExistingFixture = TestBed.createComponent(PreExistingBadge); preExistingFixture.detectChanges(); expect(preExistingFixture.nativeElement.querySelectorAll('.mat-badge-content').length).toBe( 1, ); }); it('should not clear badge content from child elements', () => { const preExistingFixture = TestBed.createComponent(NestedBadge); preExistingFixture.detectChanges(); expect(preExistingFixture.nativeElement.querySelectorAll('.mat-badge-content').length).toBe( 2, ); }); it('should expose the badge element', () => { const badgeElement = badgeHostNativeElement.querySelector('.mat-badge-content')!; expect(fixture.componentInstance.badgeInstance.getBadgeElement()).toBe(badgeElement); }); it('should throw if badge is not attached to an element node', () => { expect(() => { TestBed.createComponent(BadgeOnTemplate); }).toThrowError(/matBadge must be attached to an element node/); }); it('should not insert an inline description', () => { expect(badgeHostNativeElement.nextSibling) .withContext('The badge host should not have an inline sibling description') .toBeNull(); }); }); describe('on an non-interactive host', () => { let testComponent: BadgeOnNonInteractiveElement; beforeEach(() => { TestBed.configureTestingModule({ imports: [MatBadgeModule, BadgeOnNonInteractiveElement], }); fixture = TestBed.createComponent(BadgeOnNonInteractiveElement); testComponent = fixture.debugElement.componentInstance; fixture.detectChanges(); badgeHostDebugElement = fixture.debugElement.query(By.directive(MatBadge))!; badgeHostNativeElement = badgeHostDebugElement.nativeElement; }); it('should insert the description inline after the host', () => { testComponent.description.set('Extra info'); fixture.detectChanges(); const inlineDescription = badgeHostNativeElement.querySelector('.cdk-visually-hidden')!; expect(inlineDescription) .withContext('A visually hidden description element should exist') .toBeDefined(); expect(inlineDescription.textContent) .withContext('The badge host next sibling should contain its description') .toBe('Extra info'); testComponent.description.set('Different info'); fixture.detectChanges(); expect(inlineDescription.textContent) .withContext('The inline description should update') .toBe('Different info'); }); it('should not apply aria-describedby for non-interactive hosts', () => { testComponent.description.set('Extra info'); fixture.detectChanges(); expect(badgeHostNativeElement.hasAttribute('aria-description')) .withContext('Non-interactive hosts should not have aria-describedby') .toBeFalse(); }); }); }); /** Test component that contains a MatBadge. */
{ "end_byte": 10017, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/badge/badge.spec.ts" }
components/src/material/badge/badge.spec.ts_10018_11901
@Component({ // Explicitly set the view encapsulation since we have a test that checks for it. encapsulation: ViewEncapsulation.Emulated, styles: 'button { color: hotpink; }', template: ` <button [matBadge]="badgeContent()" [matBadgeColor]="badgeColor()" [matBadgePosition]="badgeDirection()" [matBadgeHidden]="badgeHidden()" [matBadgeSize]="badgeSize()" [matBadgeOverlap]="badgeOverlap()" [matBadgeDescription]="badgeDescription()" [matBadgeDisabled]="badgeDisabled()"> home </button> `, standalone: true, imports: [MatBadgeModule], }) class BadgeOnInteractiveElement { @ViewChild(MatBadge) badgeInstance: MatBadge; badgeColor = signal<ThemePalette>(undefined); badgeContent = signal<string | number | undefined | null>('1'); badgeDirection = signal('above after'); badgeHidden = signal(false); badgeSize = signal('medium'); badgeOverlap = signal(false); badgeDescription = signal<string | undefined>(undefined); badgeDisabled = signal(false); } @Component({ template: '<span matBadge="7" [matBadgeDescription]="description()">Hello</span>', standalone: true, imports: [MatBadgeModule], }) class BadgeOnNonInteractiveElement { description = signal(''); } @Component({ template: ` <span matBadge="Hello"> home <div class="mat-badge-content">Pre-existing badge</div> </span> `, standalone: true, imports: [MatBadgeModule], }) class PreExistingBadge {} @Component({ template: ` <span matBadge="Hello"> home <span matBadge="Hi">Something</span> </span> `, standalone: true, imports: [MatBadgeModule], }) class NestedBadge {} @Component({ template: ` <ng-template matBadge="1">Notifications</ng-template>`, standalone: true, imports: [MatBadgeModule], }) class BadgeOnTemplate {}
{ "end_byte": 11901, "start_byte": 10018, "url": "https://github.com/angular/components/blob/main/src/material/badge/badge.spec.ts" }
components/src/material/badge/public-api.ts_0_302
/** * @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 './badge-module'; export {MatBadge, MatBadgePosition, MatBadgeSize} from './badge';
{ "end_byte": 302, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/badge/public-api.ts" }
components/src/material/badge/badge.ts_0_1948
/** * @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 {AriaDescriber, InteractivityChecker} from '@angular/cdk/a11y'; import {DOCUMENT} from '@angular/common'; import { booleanAttribute, ChangeDetectionStrategy, Component, Directive, ElementRef, inject, Input, NgZone, OnDestroy, OnInit, Renderer2, ViewEncapsulation, ANIMATION_MODULE_TYPE, } from '@angular/core'; import {ThemePalette} from '@angular/material/core'; import {_CdkPrivateStyleLoader, _VisuallyHiddenLoader} from '@angular/cdk/private'; let nextId = 0; /** Allowed position options for matBadgePosition */ export type MatBadgePosition = | 'above after' | 'above before' | 'below before' | 'below after' | 'before' | 'after' | 'above' | 'below'; /** Allowed size options for matBadgeSize */ export type MatBadgeSize = 'small' | 'medium' | 'large'; const BADGE_CONTENT_CLASS = 'mat-badge-content'; /** * Component used to load the structural styles of the badge. * @docs-private */ @Component({ styleUrl: 'badge.css', encapsulation: ViewEncapsulation.None, template: '', changeDetection: ChangeDetectionStrategy.OnPush, }) export class _MatBadgeStyleLoader {} /** Directive to display a text badge. */ @Directive({ selector: '[matBadge]', host: { 'class': 'mat-badge', '[class.mat-badge-overlap]': 'overlap', '[class.mat-badge-above]': 'isAbove()', '[class.mat-badge-below]': '!isAbove()', '[class.mat-badge-before]': '!isAfter()', '[class.mat-badge-after]': 'isAfter()', '[class.mat-badge-small]': 'size === "small"', '[class.mat-badge-medium]': 'size === "medium"', '[class.mat-badge-large]': 'size === "large"', '[class.mat-badge-hidden]': 'hidden || !content', '[class.mat-badge-disabled]': 'disabled', }, }) export
{ "end_byte": 1948, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/badge/badge.ts" }
components/src/material/badge/badge.ts_1949_10672
class MatBadge implements OnInit, OnDestroy { private _ngZone = inject(NgZone); private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef); private _ariaDescriber = inject(AriaDescriber); private _renderer = inject(Renderer2); private _animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true}); /** * Theme color of the badge. 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('matBadgeColor') get color(): ThemePalette { return this._color; } set color(value: ThemePalette) { this._setColor(value); this._color = value; } private _color: ThemePalette = 'primary'; /** Whether the badge should overlap its contents or not */ @Input({alias: 'matBadgeOverlap', transform: booleanAttribute}) overlap: boolean = true; /** Whether the badge is disabled. */ @Input({alias: 'matBadgeDisabled', transform: booleanAttribute}) disabled: boolean; /** * Position the badge should reside. * Accepts any combination of 'above'|'below' and 'before'|'after' */ @Input('matBadgePosition') position: MatBadgePosition = 'above after'; /** The content for the badge */ @Input('matBadge') get content(): string | number | undefined | null { return this._content; } set content(newContent: string | number | undefined | null) { this._updateRenderedContent(newContent); } private _content: string | number | undefined | null; /** Message used to describe the decorated element via aria-describedby */ @Input('matBadgeDescription') get description(): string { return this._description; } set description(newDescription: string) { this._updateDescription(newDescription); } private _description: string; /** Size of the badge. Can be 'small', 'medium', or 'large'. */ @Input('matBadgeSize') size: MatBadgeSize = 'medium'; /** Whether the badge is hidden. */ @Input({alias: 'matBadgeHidden', transform: booleanAttribute}) hidden: boolean; /** Unique id for the badge */ _id: number = nextId++; /** Visible badge element. */ private _badgeElement: HTMLElement | undefined; /** Inline badge description. Used when the badge is applied to non-interactive host elements. */ private _inlineBadgeDescription: HTMLElement | undefined; /** Whether the OnInit lifecycle hook has run yet */ private _isInitialized = false; /** InteractivityChecker to determine if the badge host is focusable. */ private _interactivityChecker = inject(InteractivityChecker); private _document = inject(DOCUMENT); constructor(...args: unknown[]); constructor() { inject(_CdkPrivateStyleLoader).load(_MatBadgeStyleLoader); inject(_CdkPrivateStyleLoader).load(_VisuallyHiddenLoader); if (typeof ngDevMode === 'undefined' || ngDevMode) { const nativeElement = this._elementRef.nativeElement; if (nativeElement.nodeType !== nativeElement.ELEMENT_NODE) { throw Error('matBadge must be attached to an element node.'); } // Heads-up for developers to avoid putting matBadge on <mat-icon> // as it is aria-hidden by default docs mention this at: // https://material.angular.io/components/badge/overview#accessibility if ( nativeElement.tagName.toLowerCase() === 'mat-icon' && nativeElement.getAttribute('aria-hidden') === 'true' ) { console.warn( `Detected a matBadge on an "aria-hidden" "<mat-icon>". ` + `Consider setting aria-hidden="false" in order to surface the information assistive technology.` + `\n${nativeElement.outerHTML}`, ); } } } /** Whether the badge is above the host or not */ isAbove(): boolean { return this.position.indexOf('below') === -1; } /** Whether the badge is after the host or not */ isAfter(): boolean { return this.position.indexOf('before') === -1; } /** * Gets the element into which the badge's content is being rendered. Undefined if the element * hasn't been created (e.g. if the badge doesn't have content). */ getBadgeElement(): HTMLElement | undefined { return this._badgeElement; } ngOnInit() { // We may have server-side rendered badge that we need to clear. // We need to do this in ngOnInit because the full content of the component // on which the badge is attached won't necessarily be in the DOM until this point. this._clearExistingBadges(); if (this.content && !this._badgeElement) { this._badgeElement = this._createBadgeElement(); this._updateRenderedContent(this.content); } this._isInitialized = true; } ngOnDestroy() { // ViewEngine only: when creating a badge through the Renderer, Angular remembers its index. // We have to destroy it ourselves, otherwise it'll be retained in memory. if (this._renderer.destroyNode) { this._renderer.destroyNode(this._badgeElement); this._inlineBadgeDescription?.remove(); } this._ariaDescriber.removeDescription(this._elementRef.nativeElement, this.description); } /** Gets whether the badge's host element is interactive. */ private _isHostInteractive(): boolean { // Ignore visibility since it requires an expensive style caluclation. return this._interactivityChecker.isFocusable(this._elementRef.nativeElement, { ignoreVisibility: true, }); } /** Creates the badge element */ private _createBadgeElement(): HTMLElement { const badgeElement = this._renderer.createElement('span'); const activeClass = 'mat-badge-active'; badgeElement.setAttribute('id', `mat-badge-content-${this._id}`); // The badge is aria-hidden because we don't want it to appear in the page's navigation // flow. Instead, we use the badge to describe the decorated element with aria-describedby. badgeElement.setAttribute('aria-hidden', 'true'); badgeElement.classList.add(BADGE_CONTENT_CLASS); if (this._animationMode === 'NoopAnimations') { badgeElement.classList.add('_mat-animation-noopable'); } this._elementRef.nativeElement.appendChild(badgeElement); // animate in after insertion if (typeof requestAnimationFrame === 'function' && this._animationMode !== 'NoopAnimations') { this._ngZone.runOutsideAngular(() => { requestAnimationFrame(() => { badgeElement.classList.add(activeClass); }); }); } else { badgeElement.classList.add(activeClass); } return badgeElement; } /** Update the text content of the badge element in the DOM, creating the element if necessary. */ private _updateRenderedContent(newContent: string | number | undefined | null): void { const newContentNormalized: string = `${newContent ?? ''}`.trim(); // Don't create the badge element if the directive isn't initialized because we want to // append the badge element to the *end* of the host element's content for backwards // compatibility. if (this._isInitialized && newContentNormalized && !this._badgeElement) { this._badgeElement = this._createBadgeElement(); } if (this._badgeElement) { this._badgeElement.textContent = newContentNormalized; } this._content = newContentNormalized; } /** Updates the host element's aria description via AriaDescriber. */ private _updateDescription(newDescription: string): void { // Always start by removing the aria-describedby; we will add a new one if necessary. this._ariaDescriber.removeDescription(this._elementRef.nativeElement, this.description); // NOTE: We only check whether the host is interactive here, which happens during // when then badge content changes. It is possible that the host changes // interactivity status separate from one of these. However, watching the interactivity // status of the host would require a `MutationObserver`, which is likely more code + overhead // than it's worth; from usages inside Google, we see that the vats majority of badges either // never change interactivity, or also set `matBadgeHidden` based on the same condition. if (!newDescription || this._isHostInteractive()) { this._removeInlineDescription(); } this._description = newDescription; // We don't add `aria-describedby` for non-interactive hosts elements because we // instead insert the description inline. if (this._isHostInteractive()) { this._ariaDescriber.describe(this._elementRef.nativeElement, newDescription); } else { this._updateInlineDescription(); } }
{ "end_byte": 10672, "start_byte": 1949, "url": "https://github.com/angular/components/blob/main/src/material/badge/badge.ts" }
components/src/material/badge/badge.ts_10676_12095
private _updateInlineDescription() { // Create the inline description element if it doesn't exist if (!this._inlineBadgeDescription) { this._inlineBadgeDescription = this._document.createElement('span'); this._inlineBadgeDescription.classList.add('cdk-visually-hidden'); } this._inlineBadgeDescription.textContent = this.description; this._badgeElement?.appendChild(this._inlineBadgeDescription); } private _removeInlineDescription() { this._inlineBadgeDescription?.remove(); this._inlineBadgeDescription = undefined; } /** Adds css theme class given the color to the component host */ private _setColor(colorPalette: ThemePalette) { const classList = this._elementRef.nativeElement.classList; classList.remove(`mat-badge-${this._color}`); if (colorPalette) { classList.add(`mat-badge-${colorPalette}`); } } /** Clears any existing badges that might be left over from server-side rendering. */ private _clearExistingBadges() { // Only check direct children of this host element in order to avoid deleting // any badges that might exist in descendant elements. const badges = this._elementRef.nativeElement.querySelectorAll( `:scope > .${BADGE_CONTENT_CLASS}`, ); for (const badgeElement of Array.from(badges)) { if (badgeElement !== this._badgeElement) { badgeElement.remove(); } } } }
{ "end_byte": 12095, "start_byte": 10676, "url": "https://github.com/angular/components/blob/main/src/material/badge/badge.ts" }
components/src/material/badge/_badge-theme.scss_0_4624
@use 'sass:color'; @use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @use '../core/typography/typography'; @use '../core/tokens/m2/mat/badge' as tokens-mat-badge; @use '../core/tokens/token-utils'; @use '../core/style/sass-utils'; /// Outputs base theme styles (styles not dependent on the color, typography, or density settings) /// for the mat-badge. /// @param {Map} $theme The theme to generate base styles for. @mixin base($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, base)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mat-badge.$prefix, tokens-mat-badge.get-unthemable-tokens() ); } } } /// Outputs color theme styles for the mat-badge. /// @param {Map} $theme The theme to generate color styles for. /// @param {ArgList} Additional optional arguments (only supported for M3 themes): /// $color-variant: The color variant to use for the badge: primary, secondary, tertiary, /// or error (If not specified, default error color will be used). @mixin color($theme, $options...) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, color), $options...); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mat-badge.$prefix, tokens-mat-badge.get-color-tokens($theme) ); } .mat-badge-accent { @include token-utils.create-token-values( tokens-mat-badge.$prefix, tokens-mat-badge.private-get-color-palette-color-tokens($theme, accent) ); } .mat-badge-warn { @include token-utils.create-token-values( tokens-mat-badge.$prefix, tokens-mat-badge.private-get-color-palette-color-tokens($theme, warn) ); } } } /// Outputs typography theme styles for the mat-badge. /// @param {Map} $theme The theme to generate typography styles for. @mixin typography($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, typography)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mat-badge.$prefix, tokens-mat-badge.get-typography-tokens($theme) ); } } } /// Outputs density theme styles for the mat-badge. /// @param {Map} $theme The theme to generate density styles for. @mixin density($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, density)); } @else { } } /// Defines the tokens that will be available in the `overrides` mixin and for docs extraction. @function _define-overrides() { @return ( ( namespace: tokens-mat-badge.$prefix, tokens: tokens-mat-badge.get-token-slots(), ), ); } /// Outputs the CSS variable values for the given tokens. /// @param {Map} $tokens The token values to emit. @mixin overrides($tokens: ()) { @include token-utils.batch-create-token-values($tokens, _define-overrides()...); } /// Outputs all (base, color, typography, and density) theme styles for the mat-badge. /// @param {Map} $theme The theme to generate styles for. /// @param {ArgList} Additional optional arguments (only supported for M3 themes): /// $color-variant: The color variant to use for the badge: primary, secondary, tertiary, /// or error (If not specified, default error color will be used). @mixin theme($theme, $options...) { @include theming.private-check-duplicate-theme-styles($theme, 'mat-badge') { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme), $options...); } @else { @include base($theme); @if inspection.theme-has($theme, color) { @include color($theme); } @if inspection.theme-has($theme, density) { @include density($theme); } @if inspection.theme-has($theme, typography) { @include typography($theme); } } } } @mixin _theme-from-tokens($tokens, $options...) { @include validation.selector-defined( 'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector' ); $mat-badge-tokens: token-utils.get-tokens-for($tokens, tokens-mat-badge.$prefix, $options...); @include token-utils.create-token-values(tokens-mat-badge.$prefix, $mat-badge-tokens); }
{ "end_byte": 4624, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/badge/_badge-theme.scss" }
components/src/material/badge/BUILD.bazel_0_1588
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 = "badge", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), assets = [ ":badge_scss", ] + glob(["**/*.html"]), deps = [ "//src:dev_mode_types", "//src/cdk/a11y", "//src/cdk/private", "//src/material/core", "@npm//@angular/animations", "@npm//@angular/common", "@npm//@angular/core", "@npm//@angular/platform-browser", ], ) sass_binary( name = "badge_scss", src = "badge.scss", deps = [ "//src/cdk:sass_lib", "//src/material/core:core_scss_lib", ], ) sass_library( name = "badge_scss_lib", srcs = glob(["**/_*.scss"]), deps = [ "//src/cdk:sass_lib", "//src/material/core:core_scss_lib", ], ) ng_test_library( name = "unit_test_sources", srcs = glob( ["**/*.spec.ts"], exclude = ["**/*.e2e.spec.ts"], ), deps = [ ":badge", "//src/material/core", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_test_sources"], ) markdown_to_html( name = "overview", srcs = [":badge.md"], ) extract_tokens( name = "tokens", srcs = [":badge_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "end_byte": 1588, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/badge/BUILD.bazel" }
components/src/material/badge/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/badge/index.ts" }
components/src/material/badge/badge-module.ts_0_673
/** * @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 {A11yModule} from '@angular/cdk/a11y'; import {MatBadge, _MatBadgeStyleLoader} from './badge'; @NgModule({ // Note: we _shouldn't_ have to import `_MatBadgeStyleLoader`, // but it seems to be necessary for tests. imports: [A11yModule, MatCommonModule, MatBadge, _MatBadgeStyleLoader], exports: [MatBadge, MatCommonModule], }) export class MatBadgeModule {}
{ "end_byte": 673, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/badge/badge-module.ts" }
components/src/material/badge/badge.md_0_2593
Badges are small status descriptors for UI elements. A badge consists of a small circle, typically containing a number or other short set of characters, that appears in proximity to another object. Badges must always be applied to [block-level elements][block-level]. [block-level]: https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements <!-- example(badge-overview) --> ### Badge position By default, the badge will be placed `above after`. The direction can be changed by defining the attribute `matBadgePosition` follow by `above|below` and `before|after`. <!-- example({"example":"badge-overview", "file":"badge-overview-example.html", "region":"mat-badge-position"}) --> The overlap of the badge in relation to its inner contents can also be defined using the `matBadgeOverlap` tag. Typically, you want the badge to overlap an icon and not a text phrase. By default it will overlap. <!-- example({"example":"badge-overview", "file":"badge-overview-example.html", "region":"mat-badge-overlap"}) --> ### Badge sizing The badge has 3 sizes: `small`, `medium` and `large`. By default, the badge is set to `medium`. Badges that are `small` do not show the label text. This can be useful in contexts such as showing there are unread notifications but not needing to show the exact amount. You can change the size by adding `matBadgeSize` to the host element. <!-- example({"example":"badge-overview", "file":"badge-overview-example.html", "region":"mat-badge-size"}) --> ### Badge visibility The badge visibility can be toggled programmatically by defining `matBadgeHidden`. <!-- example({"example":"badge-overview", "file":"badge-overview-example.html", "region":"mat-badge-hide"}) --> ### Accessibility You must provide a meaningful description via `matBadgeDescription`. When attached to an interactive element, `MatBadge` applies this description to its host via `aria-describedby`. When attached to a non-interactive element, `MatBadge` appends a visually-hidden, inline description element. The badge determines interactivity based on whether the host element is focusable. When applying a badge to a `<mat-icon>`, it is important to know that `<mat-icon>` is `aria-hidden="true"` by default. If the combination of icon and badge communicates meaningful information, always surface this information in another way. [See the guidance on indicator icons for more information](https://material.angular.io/components/icon/overview#indicator-icons).
{ "end_byte": 2593, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/badge/badge.md" }
components/src/material/badge/testing/badge-harness.spec.ts_0_5201
import {HarnessLoader} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {Component} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {MatBadgeModule, MatBadgePosition, MatBadgeSize} from '@angular/material/badge'; import {MatBadgeHarness} from './badge-harness'; describe('MatBadgeHarness', () => { let fixture: ComponentFixture<BadgeHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ imports: [MatBadgeModule, BadgeHarnessTest], }); fixture = TestBed.createComponent(BadgeHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); it('should load all badge harnesses', async () => { const badges = await loader.getAllHarnesses(MatBadgeHarness); expect(badges.length).toBe(6); }); it('should be able to get the text of a badge', async () => { const badge = await loader.getHarness(MatBadgeHarness.with({selector: '#simple'})); expect(await badge.getText()).toBe('Simple badge'); fixture.componentInstance.simpleContent = 'Changed simple badge'; fixture.changeDetectorRef.markForCheck(); expect(await badge.getText()).toBe('Changed simple badge'); }); it('should load badge with exact text', async () => { const badges = await loader.getAllHarnesses(MatBadgeHarness.with({text: 'Simple badge'})); expect(badges.length).toBe(1); expect(await badges[0].getText()).toBe('Simple badge'); }); it('should load badge with regex label match', async () => { const badges = await loader.getAllHarnesses(MatBadgeHarness.with({text: /sized|disabled/i})); expect(badges.length).toBe(2); expect(await badges[0].getText()).toBe('Sized badge'); expect(await badges[1].getText()).toBe('Disabled badge'); }); it('should get whether a badge is overlapping', async () => { const badge = await loader.getHarness(MatBadgeHarness.with({selector: '#overlapping'})); expect(await badge.isOverlapping()).toBe(true); fixture.componentInstance.overlap = false; fixture.changeDetectorRef.markForCheck(); expect(await badge.isOverlapping()).toBe(false); }); it('should get whether a badge is disabled', async () => { const badge = await loader.getHarness(MatBadgeHarness.with({selector: '#disabled'})); expect(await badge.isDisabled()).toBe(true); fixture.componentInstance.disabled = false; fixture.changeDetectorRef.markForCheck(); expect(await badge.isDisabled()).toBe(false); }); it('should get whether a badge is hidden', async () => { const badge = await loader.getHarness(MatBadgeHarness.with({selector: '#hidden'})); expect(await badge.isHidden()).toBe(true); fixture.componentInstance.hidden = false; fixture.changeDetectorRef.markForCheck(); expect(await badge.isHidden()).toBe(false); }); it('should get the position of a badge', async () => { const instance = fixture.componentInstance; const badge = await loader.getHarness(MatBadgeHarness.with({selector: '#positioned'})); expect(await badge.getPosition()).toBe('above after'); instance.position = 'below'; fixture.changeDetectorRef.markForCheck(); expect(await badge.getPosition()).toBe('below after'); instance.position = 'below before'; fixture.changeDetectorRef.markForCheck(); expect(await badge.getPosition()).toBe('below before'); instance.position = 'above'; fixture.changeDetectorRef.markForCheck(); expect(await badge.getPosition()).toBe('above after'); instance.position = 'above before'; fixture.changeDetectorRef.markForCheck(); expect(await badge.getPosition()).toBe('above before'); }); it('should get the size of a badge', async () => { const instance = fixture.componentInstance; const badge = await loader.getHarness(MatBadgeHarness.with({selector: '#sized'})); expect(await badge.getSize()).toBe('medium'); instance.size = 'small'; fixture.changeDetectorRef.markForCheck(); expect(await badge.getSize()).toBe('small'); instance.size = 'large'; fixture.changeDetectorRef.markForCheck(); expect(await badge.getSize()).toBe('large'); }); }); @Component({ template: ` <button id="simple" [matBadge]="simpleContent">Simple</button> <button id="positioned" matBadge="Positioned badge" [matBadgePosition]="position">Positioned</button> <button id="sized" matBadge="Sized badge" [matBadgeSize]="size">Sized</button> <button id="overlapping" matBadge="Overlapping badge" [matBadgeOverlap]="overlap">Overlapping</button> <button id="hidden" matBadge="Hidden badge" [matBadgeHidden]="hidden">Hidden</button> <button id="disabled" matBadge="Disabled badge" [matBadgeDisabled]="disabled">Disabled</button> `, standalone: true, imports: [MatBadgeModule], }) class BadgeHarnessTest { simpleContent = 'Simple badge'; position: MatBadgePosition = 'above after'; size: MatBadgeSize = 'medium'; overlap = true; hidden = true; disabled = true; }
{ "end_byte": 5201, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/badge/testing/badge-harness.spec.ts" }
components/src/material/badge/testing/badge-harness-filters.ts_0_356
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {BaseHarnessFilters} from '@angular/cdk/testing'; export interface BadgeHarnessFilters extends BaseHarnessFilters { text?: string | RegExp; }
{ "end_byte": 356, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/badge/testing/badge-harness-filters.ts" }
components/src/material/badge/testing/badge-harness.ts_0_2659
/** * @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 {MatBadgePosition, MatBadgeSize} from '@angular/material/badge'; import {BadgeHarnessFilters} from './badge-harness-filters'; /** Harness for interacting with a standard Material badge in tests. */ export class MatBadgeHarness extends ComponentHarness { static hostSelector = '.mat-badge'; /** * Gets a `HarnessPredicate` that can be used to search for a badge with specific attributes. * @param options Options for narrowing the search: * - `text` finds a badge host with a particular text. * @return a `HarnessPredicate` configured with the given options. */ static with(options: BadgeHarnessFilters = {}): HarnessPredicate<MatBadgeHarness> { return new HarnessPredicate(MatBadgeHarness, options).addOption( 'text', options.text, (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text), ); } private _badgeElement = this.locatorFor('.mat-badge-content'); /** Gets a promise for the badge text. */ async getText(): Promise<string> { return (await this._badgeElement()).text(); } /** Gets whether the badge is overlapping the content. */ async isOverlapping(): Promise<boolean> { return (await this.host()).hasClass('mat-badge-overlap'); } /** Gets the position of the badge. */ async getPosition(): Promise<MatBadgePosition> { const host = await this.host(); let result = ''; if (await host.hasClass('mat-badge-above')) { result += 'above'; } else if (await host.hasClass('mat-badge-below')) { result += 'below'; } if (await host.hasClass('mat-badge-before')) { result += ' before'; } else if (await host.hasClass('mat-badge-after')) { result += ' after'; } return result.trim() as MatBadgePosition; } /** Gets the size of the badge. */ async getSize(): Promise<MatBadgeSize> { const host = await this.host(); if (await host.hasClass('mat-badge-small')) { return 'small'; } else if (await host.hasClass('mat-badge-large')) { return 'large'; } return 'medium'; } /** Gets whether the badge is hidden. */ async isHidden(): Promise<boolean> { return (await this.host()).hasClass('mat-badge-hidden'); } /** Gets whether the badge is disabled. */ async isDisabled(): Promise<boolean> { return (await this.host()).hasClass('mat-badge-disabled'); } }
{ "end_byte": 2659, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/badge/testing/badge-harness.ts" }
components/src/material/badge/testing/public-api.ts_0_278
/** * @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 './badge-harness'; export * from './badge-harness-filters';
{ "end_byte": 278, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/badge/testing/public-api.ts" }
components/src/material/badge/testing/BUILD.bazel_0_752
load("//tools:defaults.bzl", "ng_test_library", "ng_web_test_suite", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "testing", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "//src/cdk/testing", "//src/material/badge", ], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), ) ng_test_library( name = "unit_tests_lib", srcs = glob(["**/*.spec.ts"]), deps = [ ":testing", "//src/cdk/testing", "//src/cdk/testing/testbed", "//src/material/badge", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_tests_lib"], )
{ "end_byte": 752, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/badge/testing/BUILD.bazel" }
components/src/material/badge/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/badge/testing/index.ts" }