From 5c7b774a5df344a3b8a72d914b259b22e6ddfd1e Mon Sep 17 00:00:00 2001 From: Andrei Vorobev <738482+vorobey@users.noreply.github.com> Date: Thu, 5 Nov 2026 15:57:57 +0200 Subject: [PATCH 01/14] Zoneless app creation support, zone detection when add layout --- .../src/applications/application.angular.js | 8 +- .../src/add-app-template/index.ts | 3 +- .../src/add-app-template/schema.json | 4 + .../src/add-layout/README.md | 3 + .../add-layout/files/src/app/app.config.ts | 3 +- .../src/add-layout/index.ts | 41 +++++++++- .../src/add-layout/index_spec.ts | 82 ++++++++++++++++++- .../src/add-layout/schema.json | 4 + .../devextreme-schematics/src/utility/zone.ts | 30 +++++++ 9 files changed, 164 insertions(+), 14 deletions(-) create mode 100644 packages/devextreme-schematics/src/utility/zone.ts diff --git a/packages/devextreme-cli/src/applications/application.angular.js b/packages/devextreme-cli/src/applications/application.angular.js index c67bd6022..5932a3049 100644 --- a/packages/devextreme-cli/src/applications/application.angular.js +++ b/packages/devextreme-cli/src/applications/application.angular.js @@ -13,7 +13,6 @@ const modifyJson = require('../utility/modify-json-file'); const schematicsVersion = latestVersions['devextreme-schematics'] || 'latest'; const minNgCliVersion = new semver('21.0.0'); -const ngCliWithZoneless = new semver('21.0.0'); async function runSchematicCommand(schematicCommand, options, evaluatingOptions) { const collectionName = 'devextreme-schematics'; @@ -100,7 +99,6 @@ const bumpAngular = (appPath, versionTag) => { const create = async(appName, options) => { const layout = await getLayoutInfo(options.layout); - const currentNgVersion = ngVersion.getNgCliVersion().version; const depsVersionTag = extractDepsVersionTag(options); const commandArguments = [ @@ -115,10 +113,6 @@ const create = async(appName, options) => { '--ai-config=none' ]; - if(ngCliWithZoneless.compare(currentNgVersion) <= 0) { - commandArguments.push('--zoneless=false'); - } - await runNgCommand(commandArguments, options); const appPath = path.join(process.cwd(), appName); @@ -130,6 +124,7 @@ const create = async(appName, options) => { options.resolveConflicts = 'override'; options.updateBudgets = true; options.layout = layout; + options.zoneless = true; addTemplate(appName, options, { cwd: appPath }); @@ -143,6 +138,7 @@ const addTemplate = async(appName, options, evaluatingOptions) => { ...options, globalNgCliVersion: ngVersion.getNgCliVersion().version }; + console.log('Schematic options:', schematicOptions); runSchematicCommand('add-app-template', schematicOptions, evaluatingOptions); }; diff --git a/packages/devextreme-schematics/src/add-app-template/index.ts b/packages/devextreme-schematics/src/add-app-template/index.ts index 3b17c5486..20ba485a1 100644 --- a/packages/devextreme-schematics/src/add-app-template/index.ts +++ b/packages/devextreme-schematics/src/add-app-template/index.ts @@ -16,7 +16,8 @@ export default function(options: any): Rule { project: options.project, skipInstall: true, updateBudgets: options.updateBudgets, - globalNgCliVersion: options.globalNgCliVersion + globalNgCliVersion: options.globalNgCliVersion, + zoneless: options.zoneless }) ]; diff --git a/packages/devextreme-schematics/src/add-app-template/schema.json b/packages/devextreme-schematics/src/add-app-template/schema.json index 53a6a0789..d024960c8 100644 --- a/packages/devextreme-schematics/src/add-app-template/schema.json +++ b/packages/devextreme-schematics/src/add-app-template/schema.json @@ -53,6 +53,10 @@ "updateBudgets": { "type": "boolean", "visible": false + }, + "zoneless": { + "type": "boolean", + "description": "Specifies whether the application uses zoneless change detection. Detected from the project if not set." } } } diff --git a/packages/devextreme-schematics/src/add-layout/README.md b/packages/devextreme-schematics/src/add-layout/README.md index 0e91a5812..dd1891215 100644 --- a/packages/devextreme-schematics/src/add-layout/README.md +++ b/packages/devextreme-schematics/src/add-layout/README.md @@ -16,3 +16,6 @@ A schematic that adds a DevExtreme layout to a DevExtreme Angular application. - skip-install (boolean) Specifies whether to skip the dependency package installation +- zoneless (boolean) + Specifies whether the application uses zoneless change detection. Detected from the project if not set + diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts index 9e771f76a..d3d907886 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts @@ -1,4 +1,4 @@ -import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core'; +import { ApplicationConfig } from '@angular/core'; import { provideRouter, withHashLocation } from '@angular/router'; import { routes } from './app.routes'; import { @@ -10,7 +10,6 @@ import { export const appConfig: ApplicationConfig = { providers: [ - provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes, withHashLocation()), AuthGuardService, AuthService, diff --git a/packages/devextreme-schematics/src/add-layout/index.ts b/packages/devextreme-schematics/src/add-layout/index.ts index 6b7fccc81..645b6a076 100644 --- a/packages/devextreme-schematics/src/add-layout/index.ts +++ b/packages/devextreme-schematics/src/add-layout/index.ts @@ -67,6 +67,7 @@ import { getWorkspace } from '@schematics/angular/utility/workspace'; import { Change } from '@schematics/angular/utility/change'; import { isAngularVersionHigherThan } from '../utility/angular-version'; +import { isZonelessApp } from '../utility/zone'; import { NodePackageInstallTask, RunSchematicTask } from '@angular-devkit/schematics/tasks'; const routes = [ @@ -181,6 +182,8 @@ async function addPolyfills(host: Tree, project: string, polyfills: string[]) { if (!buildOptions.polyfills) { buildOptions.polyfills = []; + } else if (!Array.isArray(buildOptions.polyfills)) { + buildOptions.polyfills = [buildOptions.polyfills]; } polyfills.forEach((polyfill) => { @@ -270,7 +273,29 @@ function hasRouting(host: Tree, sourcePath: string) { return host.exists(sourcePath + 'app.routes.ts'); } -function addPackagesToDependency(globalNgCliVersion: string) { +function addZoneChangeDetection(appPath: string) { + const appConfigPath = join(appPath, 'app.config.ts'); + + return chain([ + modifyFileRule(appConfigPath, (source: SourceFile) => [ + insertImport(source, appConfigPath, 'provideZoneChangeDetection', '@angular/core') + ]), + (host: Tree) => { + const content = host.read(appConfigPath)?.toString(); + + if (content && !content.includes('provideZoneChangeDetection(')) { + host.overwrite(appConfigPath, content.replace( + /providers:\s*\[/, + '$&\n provideZoneChangeDetection({ eventCoalescing: true }),' + )); + } + + return host; + } + ]); +} + +function addPackagesToDependency(globalNgCliVersion: string, zoneless: boolean) { const version = new SemVer(globalNgCliVersion.replace(/\^|\~/g, '')); return (host: Tree) => { @@ -283,7 +308,7 @@ function addPackagesToDependency(globalNgCliVersion: string) { ? 'next' : `^${version.major}.0.0` }); - if (!zonejs) { + if (!zoneless && !zonejs) { addPackageJsonDependency(host, { type: NodeDependencyType.Default, name: 'zone.js', @@ -385,6 +410,7 @@ function setPostfix(host: Tree, name: string) { } export default function(options: any): Rule { + console.log('Running add-layout schematic with options:', options); return async (host: Tree) => { const project = await getProjectName(host, options.project); const workspace = await getWorkspace(host); @@ -397,6 +423,7 @@ export default function(options: any): Rule { const override = options.resolveConflicts === 'override'; const componentName = override ? 'app' : getComponentName(host, appPath); const pathToCss = sourcePath?.replace(/\/?(\w)+\/?/g, '../'); + const zoneless = options.zoneless ?? await isZonelessApp(host, project, appPath); const templateOptions = { name: setPostfix(host, componentName), @@ -427,10 +454,16 @@ export default function(options: any): Rule { addBuildThemeScript(), () => addCustomThemeStyles(host, options, sourcePath) as any, addViewportToBody(sourcePath), - addPackagesToDependency(options.globalNgCliVersion), - () => addPolyfills(host, options.project, ['zone.js']) + addPackagesToDependency(options.globalNgCliVersion, zoneless), ]; + if (!zoneless) { + rules.push( + addZoneChangeDetection(appPath), + () => addPolyfills(host, options.project, ['zone.js']) as any + ); + } + if (options.updateBudgets) { rules.push(() => updateBudgets(host, options) as any); } diff --git a/packages/devextreme-schematics/src/add-layout/index_spec.ts b/packages/devextreme-schematics/src/add-layout/index_spec.ts index 04c3009ca..da03eae56 100644 --- a/packages/devextreme-schematics/src/add-layout/index_spec.ts +++ b/packages/devextreme-schematics/src/add-layout/index_spec.ts @@ -33,7 +33,7 @@ describe('layout', () => { const options: any = { layout: 'side-nav-outer-toolbar', resolveConflicts: 'override', - globalNgCliVersion: '^17.2.0' + globalNgCliVersion: '^21.0.0' }; const angularSchematicsCollection = require.resolve('../../node_modules/@schematics/angular/collection.json'); @@ -321,4 +321,84 @@ describe('layout', () => { expect(content).toContain('"inputFile": "src/themes/metadata.base.json",'); expect(content).toContain('"inputFile": "projects/testApp2/src/themes/metadata.base.json",'); }); + + describe('change detection', () => { + const zoneOptions = { ...options, resolveConflicts: 'override' }; + + const setPolyfills = (polyfills: string | string[]) => { + modifyJSONFile(appTree, './angular.json', config => { + config.projects.testApp.architect.build.options.polyfills = polyfills; + return config; + }); + }; + + const expectZoneApp = (tree: UnitTestTree) => { + const packageConfig = JSON.parse(tree.readContent('package.json')); + const appConfig = tree.readContent('/src/app/app.config.ts'); + + expect(packageConfig.dependencies['zone.js']).toBeDefined(); + expect(appConfig).toMatch(/import { ApplicationConfig, provideZoneChangeDetection } from '@angular\/core';/); + expect(appConfig).toMatch(/providers: \[\s+provideZoneChangeDetection\({ eventCoalescing: true }\),/); + }; + + it('should not add zone.js to a zoneless app', async () => { + const runner = new SchematicTestRunner('schematics', collectionPath); + const tree = await runner.runSchematic('add-layout', zoneOptions, appTree); + + const packageConfig = JSON.parse(tree.readContent('package.json')); + const angularContent = JSON.parse(tree.readContent('/angular.json')); + const polyfills = angularContent.projects.testApp.architect.build.options.polyfills || []; + + expect(packageConfig.dependencies['zone.js']).toBeUndefined(); + expect(polyfills).not.toContain('zone.js'); + expect(tree.readContent('/src/app/app.config.ts')).not.toContain('provideZoneChangeDetection'); + }); + + it('should keep zone change detection if zone.js is in polyfills', async () => { + setPolyfills(['zone.js']); + + const runner = new SchematicTestRunner('schematics', collectionPath); + const tree = await runner.runSchematic('add-layout', zoneOptions, appTree); + + expectZoneApp(tree); + }); + + it('should keep zone change detection if zone.js is imported in a polyfills file', async () => { + setPolyfills('src/polyfills.ts'); + appTree.create('/src/polyfills.ts', `import 'zone.js';`); + + const runner = new SchematicTestRunner('schematics', collectionPath); + const tree = await runner.runSchematic('add-layout', zoneOptions, appTree); + + expectZoneApp(tree); + const angularContent = JSON.parse(tree.readContent('/angular.json')); + expect(angularContent.projects.testApp.architect.build.options.polyfills) + .toEqual(['src/polyfills.ts', 'zone.js']); + }); + + it('should keep zone change detection if app config provides it', async () => { + appTree.create('/src/app/app.config.ts', [ + `import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';`, + `export const appConfig: ApplicationConfig = {`, + ` providers: [provideZoneChangeDetection()]`, + `};` + ].join('\n')); + + const runner = new SchematicTestRunner('schematics', collectionPath); + const tree = await runner.runSchematic('add-layout', zoneOptions, appTree); + + expectZoneApp(tree); + }); + + it('should prefer the zoneless option over detection', async () => { + setPolyfills(['zone.js']); + + const runner = new SchematicTestRunner('schematics', collectionPath); + const tree = await runner.runSchematic('add-layout', { ...zoneOptions, zoneless: true }, appTree); + + const packageConfig = JSON.parse(tree.readContent('package.json')); + expect(packageConfig.dependencies['zone.js']).toBeUndefined(); + expect(tree.readContent('/src/app/app.config.ts')).not.toContain('provideZoneChangeDetection'); + }); + }); }); diff --git a/packages/devextreme-schematics/src/add-layout/schema.json b/packages/devextreme-schematics/src/add-layout/schema.json index bfc3f8e0c..948333b94 100644 --- a/packages/devextreme-schematics/src/add-layout/schema.json +++ b/packages/devextreme-schematics/src/add-layout/schema.json @@ -47,6 +47,10 @@ "updateBudgets": { "type": "boolean" }, + "zoneless": { + "type": "boolean", + "description": "Specifies whether the application uses zoneless change detection. Detected from the project if not set." + }, "globalNgCliVersion": { "type":"string", "default": "17.2.0" diff --git a/packages/devextreme-schematics/src/utility/zone.ts b/packages/devextreme-schematics/src/utility/zone.ts new file mode 100644 index 000000000..c4097aff5 --- /dev/null +++ b/packages/devextreme-schematics/src/utility/zone.ts @@ -0,0 +1,30 @@ +import { Tree } from '@angular-devkit/schematics'; +import { getWorkspace } from '@schematics/angular/utility/workspace'; +import { join } from 'path'; + +function readFile(host: Tree, path?: string) { + console.log('Reading file:', path); + return path && host.exists(path) ? host.read(path)!.toString() : ''; +} + +export async function isZonelessApp(host: Tree, projectName: string, appPath: string) { + const workspace = await getWorkspace(host); + const buildOptions = workspace.projects.get(projectName)?.targets.get('build')?.options || {}; + const mainPath = (buildOptions.browser || buildOptions.main) as string | undefined; + const bootstrapSource = readFile(host, join(appPath, 'app.config.ts')) + readFile(host, mainPath); + + if (/provideZoneChangeDetection\s*\(/.test(bootstrapSource)) { + return false; + } + + if (/provideZonelessChangeDetection\s*\(/.test(bootstrapSource)) { + return true; + } + + const polyfills = buildOptions.polyfills; + const polyfillList = (Array.isArray(polyfills) ? polyfills : [polyfills]).filter(Boolean) as string[]; + + return !polyfillList.some((polyfill) => + polyfill === 'zone.js' || /['"]zone\.js['"]/.test(readFile(host, polyfill)) + ); +} From 7955c411509d9a957d9e4a34f15e38f8e0d7353f Mon Sep 17 00:00:00 2001 From: Andrei Vorobev <738482+vorobey@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:50:13 +0200 Subject: [PATCH 02/14] remove public option for zoneless --- .../src/applications/application.angular.js | 2 -- .../src/add-app-template/index.ts | 3 +-- .../src/add-app-template/schema.json | 4 ---- .../devextreme-schematics/src/add-layout/README.md | 4 ---- .../devextreme-schematics/src/add-layout/index.ts | 3 +-- .../src/add-layout/index_spec.ts | 13 +------------ .../src/add-layout/schema.json | 4 ---- packages/devextreme-schematics/src/utility/zone.ts | 1 - 8 files changed, 3 insertions(+), 31 deletions(-) diff --git a/packages/devextreme-cli/src/applications/application.angular.js b/packages/devextreme-cli/src/applications/application.angular.js index 5932a3049..bee5bddf8 100644 --- a/packages/devextreme-cli/src/applications/application.angular.js +++ b/packages/devextreme-cli/src/applications/application.angular.js @@ -124,7 +124,6 @@ const create = async(appName, options) => { options.resolveConflicts = 'override'; options.updateBudgets = true; options.layout = layout; - options.zoneless = true; addTemplate(appName, options, { cwd: appPath }); @@ -138,7 +137,6 @@ const addTemplate = async(appName, options, evaluatingOptions) => { ...options, globalNgCliVersion: ngVersion.getNgCliVersion().version }; - console.log('Schematic options:', schematicOptions); runSchematicCommand('add-app-template', schematicOptions, evaluatingOptions); }; diff --git a/packages/devextreme-schematics/src/add-app-template/index.ts b/packages/devextreme-schematics/src/add-app-template/index.ts index 20ba485a1..3b17c5486 100644 --- a/packages/devextreme-schematics/src/add-app-template/index.ts +++ b/packages/devextreme-schematics/src/add-app-template/index.ts @@ -16,8 +16,7 @@ export default function(options: any): Rule { project: options.project, skipInstall: true, updateBudgets: options.updateBudgets, - globalNgCliVersion: options.globalNgCliVersion, - zoneless: options.zoneless + globalNgCliVersion: options.globalNgCliVersion }) ]; diff --git a/packages/devextreme-schematics/src/add-app-template/schema.json b/packages/devextreme-schematics/src/add-app-template/schema.json index d024960c8..53a6a0789 100644 --- a/packages/devextreme-schematics/src/add-app-template/schema.json +++ b/packages/devextreme-schematics/src/add-app-template/schema.json @@ -53,10 +53,6 @@ "updateBudgets": { "type": "boolean", "visible": false - }, - "zoneless": { - "type": "boolean", - "description": "Specifies whether the application uses zoneless change detection. Detected from the project if not set." } } } diff --git a/packages/devextreme-schematics/src/add-layout/README.md b/packages/devextreme-schematics/src/add-layout/README.md index dd1891215..fa76c4b38 100644 --- a/packages/devextreme-schematics/src/add-layout/README.md +++ b/packages/devextreme-schematics/src/add-layout/README.md @@ -15,7 +15,3 @@ A schematic that adds a DevExtreme layout to a DevExtreme Angular application. - skip-install (boolean) Specifies whether to skip the dependency package installation - -- zoneless (boolean) - Specifies whether the application uses zoneless change detection. Detected from the project if not set - diff --git a/packages/devextreme-schematics/src/add-layout/index.ts b/packages/devextreme-schematics/src/add-layout/index.ts index 645b6a076..9197c21da 100644 --- a/packages/devextreme-schematics/src/add-layout/index.ts +++ b/packages/devextreme-schematics/src/add-layout/index.ts @@ -410,7 +410,6 @@ function setPostfix(host: Tree, name: string) { } export default function(options: any): Rule { - console.log('Running add-layout schematic with options:', options); return async (host: Tree) => { const project = await getProjectName(host, options.project); const workspace = await getWorkspace(host); @@ -423,7 +422,7 @@ export default function(options: any): Rule { const override = options.resolveConflicts === 'override'; const componentName = override ? 'app' : getComponentName(host, appPath); const pathToCss = sourcePath?.replace(/\/?(\w)+\/?/g, '../'); - const zoneless = options.zoneless ?? await isZonelessApp(host, project, appPath); + const zoneless = await isZonelessApp(host, project, appPath); const templateOptions = { name: setPostfix(host, componentName), diff --git a/packages/devextreme-schematics/src/add-layout/index_spec.ts b/packages/devextreme-schematics/src/add-layout/index_spec.ts index da03eae56..b14300fff 100644 --- a/packages/devextreme-schematics/src/add-layout/index_spec.ts +++ b/packages/devextreme-schematics/src/add-layout/index_spec.ts @@ -180,7 +180,7 @@ describe('layout', () => { const tree = await runner.runSchematic('add-layout', options, appTree); const packageConfig = JSON.parse(tree.readContent('package.json')); - expect(packageConfig.dependencies['@angular/cdk']).toBe('^17.0.0'); + expect(packageConfig.dependencies['@angular/cdk']).toBe('^21.0.0'); }); it('should update budgets if updateBudgets option is true', async () => { @@ -389,16 +389,5 @@ describe('layout', () => { expectZoneApp(tree); }); - - it('should prefer the zoneless option over detection', async () => { - setPolyfills(['zone.js']); - - const runner = new SchematicTestRunner('schematics', collectionPath); - const tree = await runner.runSchematic('add-layout', { ...zoneOptions, zoneless: true }, appTree); - - const packageConfig = JSON.parse(tree.readContent('package.json')); - expect(packageConfig.dependencies['zone.js']).toBeUndefined(); - expect(tree.readContent('/src/app/app.config.ts')).not.toContain('provideZoneChangeDetection'); - }); }); }); diff --git a/packages/devextreme-schematics/src/add-layout/schema.json b/packages/devextreme-schematics/src/add-layout/schema.json index 948333b94..bfc3f8e0c 100644 --- a/packages/devextreme-schematics/src/add-layout/schema.json +++ b/packages/devextreme-schematics/src/add-layout/schema.json @@ -47,10 +47,6 @@ "updateBudgets": { "type": "boolean" }, - "zoneless": { - "type": "boolean", - "description": "Specifies whether the application uses zoneless change detection. Detected from the project if not set." - }, "globalNgCliVersion": { "type":"string", "default": "17.2.0" diff --git a/packages/devextreme-schematics/src/utility/zone.ts b/packages/devextreme-schematics/src/utility/zone.ts index c4097aff5..6ac0dbf63 100644 --- a/packages/devextreme-schematics/src/utility/zone.ts +++ b/packages/devextreme-schematics/src/utility/zone.ts @@ -3,7 +3,6 @@ import { getWorkspace } from '@schematics/angular/utility/workspace'; import { join } from 'path'; function readFile(host: Tree, path?: string) { - console.log('Reading file:', path); return path && host.exists(path) ? host.read(path)!.toString() : ''; } From 2dfaf7b4a550be11ea8ae737c2a6e1fdc8f5644a Mon Sep 17 00:00:00 2001 From: Andrei Vorobev <738482+vorobey@users.noreply.github.com> Date: Thu, 5 Nov 2026 18:12:06 +0200 Subject: [PATCH 03/14] changes for angular templates --- .../side-nav-inner-toolbar.component.html | 22 ++++----- .../side-nav-inner-toolbar.component.ts | 48 +++++++++---------- .../side-nav-outer-toolbar.component.html | 18 +++---- .../side-nav-outer-toolbar.component.ts | 46 +++++++++--------- .../change-password-form.component.html | 4 +- .../change-password-form.component.ts | 8 ++-- .../create-account-form.component.html | 4 +- .../create-account-form.component.ts | 8 ++-- .../components/header/header.component.ts | 6 +-- .../login-form/login-form.component.html | 4 +- .../login-form/login-form.component.ts | 8 ++-- .../reset-password-form.component.html | 4 +- .../reset-password-form.component.ts | 8 ++-- .../src/app/shared/services/screen.service.ts | 17 +++++-- 14 files changed, 108 insertions(+), 97 deletions(-) diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-inner-toolbar/side-nav-inner-toolbar.component.html b/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-inner-toolbar/side-nav-inner-toolbar.component.html index f09ae4664..60f03c304 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-inner-toolbar/side-nav-inner-toolbar.component.html +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-inner-toolbar/side-nav-inner-toolbar.component.html @@ -1,22 +1,22 @@ - @if (minMenuSize !== 0) { + @if (minMenuSize() !== 0) { + [menuToggleEnabled]="minMenuSize() === 0" + (menuToggle)="menuOpened.set(!menuOpened())"> diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-inner-toolbar/side-nav-inner-toolbar.component.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-inner-toolbar/side-nav-inner-toolbar.component.ts index defb82861..5908449ad 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-inner-toolbar/side-nav-inner-toolbar.component.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-inner-toolbar/side-nav-inner-toolbar.component.ts @@ -1,4 +1,4 @@ -import { Component, OnInit, Input, ViewChild } from '@angular/core'; +import { Component, OnInit, Input, ViewChild, signal } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; import { CommonModule } from '@angular/common'; @@ -27,32 +27,32 @@ import { ThemeService } from '../../shared/services/theme.service'; }) export class SideNavInnerToolbarComponent implements OnInit { @ViewChild(DxScrollViewComponent, { static: true }) scrollView!: DxScrollViewComponent; - selectedRoute = ''; + selectedRoute = signal(''); - menuOpened!: boolean; - temporaryMenuOpened = false; + menuOpened = signal(false); + temporaryMenuOpened = signal(false); @Input() title!: string; - menuMode: DxDrawerTypes.OpenedStateMode = 'shrink'; - menuRevealMode: DxDrawerTypes.RevealMode = 'expand'; - minMenuSize = 0; - shaderEnabled = false; - swatchClassName = 'dx-swatch-additional'; + menuMode = signal('shrink'); + menuRevealMode = signal('expand'); + minMenuSize = signal(0); + shaderEnabled = signal(false); + swatchClassName = signal('dx-swatch-additional'); constructor(protected themeService: ThemeService, private screen: ScreenService, private router: Router) { themeService.isDark.subscribe((isDark) => { - this.swatchClassName = 'dx-swatch-additional' + (isDark ? '-dark' : ''); + this.swatchClassName.set('dx-swatch-additional' + (isDark ? '-dark' : '')); }) } ngOnInit() { - this.menuOpened = this.screen.sizes['screen-large']; + this.menuOpened.set(this.screen.sizes['screen-large']); this.router.events.subscribe(val => { if (val instanceof NavigationEnd) { - this.selectedRoute = val.urlAfterRedirects.split('?')[0]; + this.selectedRoute.set(val.urlAfterRedirects.split('?')[0]); } }); @@ -65,30 +65,30 @@ export class SideNavInnerToolbarComponent implements OnInit { const isXSmall = this.screen.sizes['screen-x-small']; const isLarge = this.screen.sizes['screen-large']; - this.menuMode = isLarge ? 'shrink' : 'overlap'; - this.menuRevealMode = isXSmall ? 'slide' : 'expand'; - this.minMenuSize = isXSmall ? 0 : 60; - this.shaderEnabled = !isLarge; + this.menuMode.set(isLarge ? 'shrink' : 'overlap'); + this.menuRevealMode.set(isXSmall ? 'slide' : 'expand'); + this.minMenuSize.set(isXSmall ? 0 : 60); + this.shaderEnabled.set(!isLarge); } toggleMenu = (e: DxToolbarTypes.ItemClickEvent) => { - this.menuOpened = !this.menuOpened; + this.menuOpened.update((opened) => !opened); e.event?.stopPropagation(); } get hideMenuAfterNavigation() { - return this.menuMode === 'overlap' || this.temporaryMenuOpened; + return this.menuMode() === 'overlap' || this.temporaryMenuOpened(); } get showMenuAfterClick() { - return !this.menuOpened; + return !this.menuOpened(); } navigationChanged(event: DxTreeViewTypes.ItemClickEvent) { const path = (event.itemData as any).path; const pointerEvent = event.event; - if (path && this.menuOpened) { + if (path && this.menuOpened()) { if (event.node?.selected) { pointerEvent?.preventDefault(); } else { @@ -97,8 +97,8 @@ export class SideNavInnerToolbarComponent implements OnInit { } if (this.hideMenuAfterNavigation) { - this.temporaryMenuOpened = false; - this.menuOpened = false; + this.temporaryMenuOpened.set(false); + this.menuOpened.set(false); pointerEvent?.stopPropagation(); } } else { @@ -108,8 +108,8 @@ export class SideNavInnerToolbarComponent implements OnInit { navigationClick() { if (this.showMenuAfterClick) { - this.temporaryMenuOpened = true; - this.menuOpened = true; + this.temporaryMenuOpened.set(true); + this.menuOpened.set(true); } } } diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-outer-toolbar/side-nav-outer-toolbar.component.html b/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-outer-toolbar/side-nav-outer-toolbar.component.html index 095d540bc..8b9f40732 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-outer-toolbar/side-nav-outer-toolbar.component.html +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-outer-toolbar/side-nav-outer-toolbar.component.html @@ -1,24 +1,24 @@ diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-outer-toolbar/side-nav-outer-toolbar.component.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-outer-toolbar/side-nav-outer-toolbar.component.ts index 75f70eca9..b3199ade7 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-outer-toolbar/side-nav-outer-toolbar.component.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/layouts/side-nav-outer-toolbar/side-nav-outer-toolbar.component.ts @@ -1,4 +1,4 @@ -import { Component, OnInit, Input, ViewChild } from '@angular/core'; +import { Component, OnInit, Input, ViewChild, signal } from '@angular/core'; import { CommonModule } from '@angular/common'; import { Router, NavigationEnd } from '@angular/router'; @@ -19,32 +19,32 @@ import { ScreenService, ThemeService } from '../../shared/services'; }) export class SideNavOuterToolbarComponent implements OnInit { @ViewChild(DxScrollViewComponent, { static: true }) scrollView!: DxScrollViewComponent; - selectedRoute = ''; + selectedRoute = signal(''); - menuOpened!: boolean; - temporaryMenuOpened = false; + menuOpened = signal(false); + temporaryMenuOpened = signal(false); @Input() title!: string; - menuMode: DxDrawerTypes.OpenedStateMode = 'shrink'; - menuRevealMode: DxDrawerTypes.RevealMode = 'expand'; - minMenuSize = 0; - shaderEnabled = false; - swatchClassName = 'dx-swatch-additional'; + menuMode = signal('shrink'); + menuRevealMode = signal('expand'); + minMenuSize = signal(0); + shaderEnabled = signal(false); + swatchClassName = signal('dx-swatch-additional'); constructor(protected themeService: ThemeService, private screen: ScreenService, private router: Router) { themeService.isDark.subscribe((isDark) => { - this.swatchClassName = 'dx-swatch-additional' + (isDark ? '-dark' : ''); + this.swatchClassName.set('dx-swatch-additional' + (isDark ? '-dark' : '')); }) } ngOnInit() { - this.menuOpened = this.screen.sizes['screen-large']; + this.menuOpened.set(this.screen.sizes['screen-large']); this.router.events.subscribe(val => { if (val instanceof NavigationEnd) { - this.selectedRoute = val.urlAfterRedirects.split('?')[0]; + this.selectedRoute.set(val.urlAfterRedirects.split('?')[0]); } }); @@ -57,25 +57,25 @@ export class SideNavOuterToolbarComponent implements OnInit { const isXSmall = this.screen.sizes['screen-x-small']; const isLarge = this.screen.sizes['screen-large']; - this.menuMode = isLarge ? 'shrink' : 'overlap'; - this.menuRevealMode = isXSmall ? 'slide' : 'expand'; - this.minMenuSize = isXSmall ? 0 : 60; - this.shaderEnabled = !isLarge; + this.menuMode.set(isLarge ? 'shrink' : 'overlap'); + this.menuRevealMode.set(isXSmall ? 'slide' : 'expand'); + this.minMenuSize.set(isXSmall ? 0 : 60); + this.shaderEnabled.set(!isLarge); } get hideMenuAfterNavigation() { - return this.menuMode === 'overlap' || this.temporaryMenuOpened; + return this.menuMode() === 'overlap' || this.temporaryMenuOpened(); } get showMenuAfterClick() { - return !this.menuOpened; + return !this.menuOpened(); } navigationChanged(event: DxTreeViewTypes.ItemClickEvent) { const path = (event.itemData as any).path; const pointerEvent = event.event; - if (path && this.menuOpened) { + if (path && this.menuOpened()) { if (event.node?.selected) { pointerEvent?.preventDefault(); } else { @@ -84,8 +84,8 @@ export class SideNavOuterToolbarComponent implements OnInit { } if (this.hideMenuAfterNavigation) { - this.temporaryMenuOpened = false; - this.menuOpened = false; + this.temporaryMenuOpened.set(false); + this.menuOpened.set(false); pointerEvent?.stopPropagation(); } } else { @@ -95,8 +95,8 @@ export class SideNavOuterToolbarComponent implements OnInit { navigationClick() { if (this.showMenuAfterClick) { - this.temporaryMenuOpened = true; - this.menuOpened = true; + this.temporaryMenuOpened.set(true); + this.menuOpened.set(true); } } } diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/change-password-form/change-password-form.component.html b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/change-password-form/change-password-form.component.html index 4b1c42e7d..be7e10fb2 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/change-password-form/change-password-form.component.html +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/change-password-form/change-password-form.component.html @@ -1,5 +1,5 @@
- + @@ -23,7 +23,7 @@
- @if (loading) { + @if (loading()) { } @else {
Continue
diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/change-password-form/change-password-form.component.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/change-password-form/change-password-form.component.ts index b262481f9..df97a11d6 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/change-password-form/change-password-form.component.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/change-password-form/change-password-form.component.ts @@ -1,5 +1,5 @@ import { CommonModule } from '@angular/common'; -import { Component, OnInit } from '@angular/core'; +import { Component, OnInit, signal } from '@angular/core'; import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { ValidationCallbackData } from 'devextreme-angular/common'; import { DxFormModule } from 'devextreme-angular/ui/form'; @@ -20,7 +20,7 @@ import { AuthService } from '../../services'; ] }) export class ChangePasswordFormComponent implements OnInit { - loading = false; + loading = signal(false); formData: any = {}; recoveryCode: string = ''; @@ -35,10 +35,10 @@ export class ChangePasswordFormComponent implements OnInit { async onSubmit(e: Event) { e.preventDefault(); const { password } = this.formData; - this.loading = true; + this.loading.set(true); const result = await this.authService.changePassword(password, this.recoveryCode); - this.loading = false; + this.loading.set(false); if (result.isOk) { this.router.navigate(['/login-form']); diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/create-account-form/create-account-form.component.html b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/create-account-form/create-account-form.component.html index 5e7ae555f..e1ad51fc3 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/create-account-form/create-account-form.component.html +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/create-account-form/create-account-form.component.html @@ -1,5 +1,5 @@ - + @@ -37,7 +37,7 @@
- @if (loading) { + @if (loading()) { } @else {
Create a new account
diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/create-account-form/create-account-form.component.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/create-account-form/create-account-form.component.ts index f2e49fbde..54179a724 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/create-account-form/create-account-form.component.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/create-account-form/create-account-form.component.ts @@ -1,5 +1,5 @@ import { CommonModule } from '@angular/common'; -import { Component } from '@angular/core'; +import { Component, signal } from '@angular/core'; import { Router, RouterModule } from '@angular/router'; import { ValidationCallbackData } from 'devextreme-angular/common'; import { DxFormModule } from 'devextreme-angular/ui/form'; @@ -21,7 +21,7 @@ import { AuthService } from '../../services'; ] }) export class CreateAccountFormComponent { - loading = false; + loading = signal(false); formData: any = {}; constructor(private authService: AuthService, private router: Router) { } @@ -29,10 +29,10 @@ export class CreateAccountFormComponent { async onSubmit(e: Event) { e.preventDefault(); const { email, password } = this.formData; - this.loading = true; + this.loading.set(true); const result = await this.authService.createAccount(email, password); - this.loading = false; + this.loading.set(false); if (result.isOk) { this.router.navigate(['/login-form']); diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/header/header.component.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/header/header.component.ts index 6f88303e5..510774d57 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/header/header.component.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/header/header.component.ts @@ -1,4 +1,4 @@ -import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core'; +import { Component, Input, Output, EventEmitter, OnInit, signal } from '@angular/core'; import { Router } from '@angular/router'; import { CommonModule } from '@angular/common'; import { DxButtonModule } from 'devextreme-angular/ui/button'; @@ -32,7 +32,7 @@ export class HeaderComponent implements OnInit { @Input() title!: string; - user: IUser | null = { email: '' }; + user = signal({ email: '' }); userMenuItems = [{ text: 'Profile', @@ -52,7 +52,7 @@ export class HeaderComponent implements OnInit { constructor(private authService: AuthService, private router: Router) { } ngOnInit() { - this.authService.getUser().then((e) => this.user = e.data); + this.authService.getUser().then((e) => this.user.set(e.data)); } toggleMenu = () => { diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/login-form/login-form.component.html b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/login-form/login-form.component.html index 7f5e1269a..91f2f1fcf 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/login-form/login-form.component.html +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/login-form/login-form.component.html @@ -1,5 +1,5 @@ - + @@ -27,7 +27,7 @@
- @if (loading) { + @if (loading()) { } @else {
Sign In
diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/login-form/login-form.component.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/login-form/login-form.component.ts index 142a7e92b..30d983cd2 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/login-form/login-form.component.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/login-form/login-form.component.ts @@ -1,5 +1,5 @@ import { CommonModule } from '@angular/common'; -import { Component } from '@angular/core'; +import { Component, signal } from '@angular/core'; import { Router, RouterModule } from '@angular/router'; import { DxFormModule } from 'devextreme-angular/ui/form'; import { DxButtonModule } from 'devextreme-angular/ui/button'; @@ -22,7 +22,7 @@ import { AuthService } from '../../services'; ] }) export class LoginFormComponent { - loading = false; + loading = signal(false); formData: any = {}; constructor(private authService: AuthService, private router: Router) { } @@ -30,11 +30,11 @@ export class LoginFormComponent { async onSubmit(e: Event) { e.preventDefault(); const { email, password } = this.formData; - this.loading = true; + this.loading.set(true); const result = await this.authService.logIn(email, password); if (!result.isOk) { - this.loading = false; + this.loading.set(false); notify(result.message, 'error', 2000); } } diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/reset-password-form/reset-password-form.component.html b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/reset-password-form/reset-password-form.component.html index 59dc77f04..faa442468 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/reset-password-form/reset-password-form.component.html +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/reset-password-form/reset-password-form.component.html @@ -1,5 +1,5 @@ - + @@ -17,7 +17,7 @@
- @if (loading) { + @if (loading()) { } @else {
Reset my password
diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/reset-password-form/reset-password-form.component.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/reset-password-form/reset-password-form.component.ts index 61765c29b..525824694 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/reset-password-form/reset-password-form.component.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/components/reset-password-form/reset-password-form.component.ts @@ -1,5 +1,5 @@ import { CommonModule } from '@angular/common'; -import { Component } from '@angular/core'; +import { Component, signal } from '@angular/core'; import { Router, RouterModule } from '@angular/router'; import { DxFormModule } from 'devextreme-angular/ui/form'; import { DxLoadIndicatorModule } from 'devextreme-angular/ui/load-indicator'; @@ -21,7 +21,7 @@ const notificationText = 'We\'ve sent a link to reset your password. Check your ] }) export class ResetPasswordFormComponent { - loading = false; + loading = signal(false); formData: any = {}; constructor(private authService: AuthService, private router: Router) { } @@ -29,10 +29,10 @@ export class ResetPasswordFormComponent { async onSubmit(e: Event) { e.preventDefault(); const { email } = this.formData; - this.loading = true; + this.loading.set(true); const result = await this.authService.resetPassword(email); - this.loading = false; + this.loading.set(false); if (result.isOk) { this.router.navigate(['/login-form']); diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts index 16de9f2ce..d5c07faf4 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts @@ -1,14 +1,21 @@ -import { Output, Injectable, EventEmitter } from '@angular/core'; +import { Output, Injectable, EventEmitter, WritableSignal, signal } from '@angular/core'; import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'; @Injectable() export class ScreenService { @Output() changed = new EventEmitter(); + private readonly _sizes: WritableSignal>; + constructor(private breakpointObserver: BreakpointObserver) { + this._sizes = signal(this.calculateSizes()); + this.breakpointObserver .observe([Breakpoints.XSmall, Breakpoints.Small, Breakpoints.Medium, Breakpoints.Large]) - .subscribe(() => this.changed.next(true)); + .subscribe(() => { + this._sizes.set(this.calculateSizes()); + this.changed.next(true); + }); } private isLargeScreen() { @@ -18,7 +25,7 @@ export class ScreenService { return isLarge || isXLarge; } - public get sizes(): Record { + private calculateSizes(): Record { return { 'screen-x-small': this.breakpointObserver.isMatched(Breakpoints.XSmall), 'screen-small': this.breakpointObserver.isMatched(Breakpoints.Small), @@ -26,4 +33,8 @@ export class ScreenService { 'screen-large': this.isLargeScreen(), }; } + + public get sizes(): Record { + return this._sizes(); + } } From 59b42ff46a59fdf4644bc8f54f43463de393f671 Mon Sep 17 00:00:00 2001 From: Andrei Vorobev <738482+vorobey@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:51:21 +0200 Subject: [PATCH 04/14] added e2e verify test --- packages/devextreme-cli/testing/verifying.js | 34 ++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/packages/devextreme-cli/testing/verifying.js b/packages/devextreme-cli/testing/verifying.js index 28bdad1c3..b81cf893c 100644 --- a/packages/devextreme-cli/testing/verifying.js +++ b/packages/devextreme-cli/testing/verifying.js @@ -36,9 +36,39 @@ const verifyThemesAreBuilt = (env) => { return missing.map(outputFile => `${env.engine}: '${outputFile}' was not generated on the application creation`); }; +const verifyZoneless = (env) => { + if(env.engine !== 'angular') { + return []; + } + + const problems = []; + const { dependencies = {}, devDependencies = {} } = readJson(path.join(env.appPath, 'package.json')); + + if('zone.js' in dependencies || 'zone.js' in devDependencies) { + problems.push(`${env.engine}: package.json has the 'zone.js' dependency`); + } + + const { projects } = readJson(path.join(env.appPath, 'angular.json')); + Object.keys(projects).forEach(projectName => { + const polyfills = projects[projectName].architect.build.options.polyfills || []; + + if([].concat(polyfills).includes('zone.js')) { + problems.push(`${env.engine}: angular.json has the 'zone.js' polyfill in the '${projectName}' project`); + } + }); + + const appConfig = fs.readFileSync(path.join(env.appPath, 'src/app/app.config.ts'), 'utf8'); + if(appConfig.includes('provideZoneChangeDetection')) { + problems.push(`${env.engine}: app.config.ts uses provideZoneChangeDetection`); + } + + return problems; +}; + const verify = (env) => [ ...verifyNoInstallScripts(env), - ...verifyThemesAreBuilt(env) + ...verifyThemesAreBuilt(env), + ...verifyZoneless(env) ]; (function verifyProcess() { @@ -56,5 +86,5 @@ const verify = (env) => [ process.exit(1); } - console.log('The generated applications need no install scripts.'); + console.log('The generated applications passed verification.'); })(); From 948b3568f1185a78f98a44811b52597f2a6e0e1b Mon Sep 17 00:00:00 2001 From: Andrei Vorobev <738482+vorobey@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:32:24 +0200 Subject: [PATCH 05/14] schematics: remove globalNgCliVersion --- .../src/applications/application.angular.js | 3 +-- .../devextreme-cli/src/utility/ng-version.js | 18 +------------ .../src/add-app-template/index.ts | 3 +-- .../src/add-app-template/schema.json | 4 --- .../src/add-layout/index.ts | 21 ++++++++++----- .../src/add-layout/index_spec.ts | 27 ++++++++++++++----- .../src/add-layout/schema.json | 4 --- .../src/utility/angular-version.ts | 6 ++--- 8 files changed, 40 insertions(+), 46 deletions(-) diff --git a/packages/devextreme-cli/src/applications/application.angular.js b/packages/devextreme-cli/src/applications/application.angular.js index bee5bddf8..6863bc1e2 100644 --- a/packages/devextreme-cli/src/applications/application.angular.js +++ b/packages/devextreme-cli/src/applications/application.angular.js @@ -134,8 +134,7 @@ const create = async(appName, options) => { const addTemplate = async(appName, options, evaluatingOptions) => { const schematicOptions = { ...(appName && { project: appName }), - ...options, - globalNgCliVersion: ngVersion.getNgCliVersion().version + ...options }; runSchematicCommand('add-app-template', schematicOptions, evaluatingOptions); }; diff --git a/packages/devextreme-cli/src/utility/ng-version.js b/packages/devextreme-cli/src/utility/ng-version.js index e9330e919..f323a07c9 100644 --- a/packages/devextreme-cli/src/utility/ng-version.js +++ b/packages/devextreme-cli/src/utility/ng-version.js @@ -14,22 +14,6 @@ const getLocalNgVersion = () => { } }; -const getPublicNgVersion = () => { - const version = execSync('npm view @angular/cli@v21-lts version').toString(); - return new semver(version); -}; - -const getNgCliVersion = () => { - let ngCliVersion = getLocalNgVersion(); - if(!ngCliVersion) { - ngCliVersion = getPublicNgVersion(); - } - - return ngCliVersion; -}; - module.exports = { - getLocalNgVersion, - getPublicNgVersion, - getNgCliVersion + getLocalNgVersion }; diff --git a/packages/devextreme-schematics/src/add-app-template/index.ts b/packages/devextreme-schematics/src/add-app-template/index.ts index 3b17c5486..1d3cb7f22 100644 --- a/packages/devextreme-schematics/src/add-app-template/index.ts +++ b/packages/devextreme-schematics/src/add-app-template/index.ts @@ -15,8 +15,7 @@ export default function(options: any): Rule { resolveConflicts: options.resolveConflicts, project: options.project, skipInstall: true, - updateBudgets: options.updateBudgets, - globalNgCliVersion: options.globalNgCliVersion + updateBudgets: options.updateBudgets }) ]; diff --git a/packages/devextreme-schematics/src/add-app-template/schema.json b/packages/devextreme-schematics/src/add-app-template/schema.json index 53a6a0789..a9ee6d485 100644 --- a/packages/devextreme-schematics/src/add-app-template/schema.json +++ b/packages/devextreme-schematics/src/add-app-template/schema.json @@ -41,10 +41,6 @@ "description": "The DevExtreme version", "default": "26.1.5" }, - "globalNgCliVersion": { - "type":"string", - "default": "^17.2.0" - }, "empty": { "type": "boolean", "description": "Specifies whether to skip sample views generation", diff --git a/packages/devextreme-schematics/src/add-layout/index.ts b/packages/devextreme-schematics/src/add-layout/index.ts index 9197c21da..0f08f4e6d 100644 --- a/packages/devextreme-schematics/src/add-layout/index.ts +++ b/packages/devextreme-schematics/src/add-layout/index.ts @@ -22,7 +22,7 @@ import { strings } from '@angular-devkit/core'; import { join, basename } from 'path'; -import { SemVer } from 'semver'; +import { coerce } from 'semver'; import { getApplicationPath, @@ -295,24 +295,31 @@ function addZoneChangeDetection(appPath: string) { ]); } -function addPackagesToDependency(globalNgCliVersion: string, zoneless: boolean) { - const version = new SemVer(globalNgCliVersion.replace(/\^|\~/g, '')); +function getCdkVersion(angularCoreVersion: string = '') { + if (angularCoreVersion.includes('next') || angularCoreVersion.includes('-rc')) { + return 'next'; + } + + const version = coerce(angularCoreVersion); + return version ? `^${version.major}.0.0` : 'latest'; +} +function addPackagesToDependency(zoneless: boolean) { return (host: Tree) => { const zonejs = getPackageJsonDependency(host, 'zone.js'); + const angularCore = getPackageJsonDependency(host, '@angular/core'); addPackageJsonDependency(host, { type: NodeDependencyType.Default, name: '@angular/cdk', - version: version.raw.includes('next') || version.raw.includes('-rc') - ? 'next' : `^${version.major}.0.0` + version: getCdkVersion(angularCore?.version) }); if (!zoneless && !zonejs) { addPackageJsonDependency(host, { type: NodeDependencyType.Default, name: 'zone.js', - version: version.major > 18 ? '~0.16.0' : '~0.14.0' + version: '~0.16.0' }); } @@ -453,7 +460,7 @@ export default function(options: any): Rule { addBuildThemeScript(), () => addCustomThemeStyles(host, options, sourcePath) as any, addViewportToBody(sourcePath), - addPackagesToDependency(options.globalNgCliVersion, zoneless), + addPackagesToDependency(zoneless), ]; if (!zoneless) { diff --git a/packages/devextreme-schematics/src/add-layout/index_spec.ts b/packages/devextreme-schematics/src/add-layout/index_spec.ts index b14300fff..9780bfe33 100644 --- a/packages/devextreme-schematics/src/add-layout/index_spec.ts +++ b/packages/devextreme-schematics/src/add-layout/index_spec.ts @@ -32,8 +32,7 @@ describe('layout', () => { const options: any = { layout: 'side-nav-outer-toolbar', - resolveConflicts: 'override', - globalNgCliVersion: '^21.0.0' + resolveConflicts: 'override' }; const angularSchematicsCollection = require.resolve('../../node_modules/@schematics/angular/collection.json'); @@ -175,12 +174,26 @@ describe('layout', () => { expect(packageConfig.dependencies['@angular/cdk']).toBeDefined(); }); - it('should choose angular/cdk version such as angular/cli', async () => { - const runner = new SchematicTestRunner('schematics', collectionPath); - const tree = await runner.runSchematic('add-layout', options, appTree); - const packageConfig = JSON.parse(tree.readContent('package.json')); + [ + { angularCore: '~21.2.0', cdk: '^21.0.0' }, + { angularCore: '^22.0.0', cdk: '^22.0.0' }, + { angularCore: '22.1.0-rc.1', cdk: 'next' }, + { angularCore: 'next', cdk: 'next' }, + ].forEach(({ angularCore, cdk }) => { + it(`should choose angular/cdk ${cdk} for angular/core ${angularCore}`, async () => { + removePackageJsonDependency(appTree, '@angular/core'); + addPackageJsonDependency(appTree, { + type: NodeDependencyType.Default, + name: '@angular/core', + version: angularCore + }); - expect(packageConfig.dependencies['@angular/cdk']).toBe('^21.0.0'); + const runner = new SchematicTestRunner('schematics', collectionPath); + const tree = await runner.runSchematic('add-layout', options, appTree); + const packageConfig = JSON.parse(tree.readContent('package.json')); + + expect(packageConfig.dependencies['@angular/cdk']).toBe(cdk); + }); }); it('should update budgets if updateBudgets option is true', async () => { diff --git a/packages/devextreme-schematics/src/add-layout/schema.json b/packages/devextreme-schematics/src/add-layout/schema.json index bfc3f8e0c..2d13f4a18 100644 --- a/packages/devextreme-schematics/src/add-layout/schema.json +++ b/packages/devextreme-schematics/src/add-layout/schema.json @@ -46,10 +46,6 @@ }, "updateBudgets": { "type": "boolean" - }, - "globalNgCliVersion": { - "type":"string", - "default": "17.2.0" } } } diff --git a/packages/devextreme-schematics/src/utility/angular-version.ts b/packages/devextreme-schematics/src/utility/angular-version.ts index 2c79b91eb..3af30ac5c 100644 --- a/packages/devextreme-schematics/src/utility/angular-version.ts +++ b/packages/devextreme-schematics/src/utility/angular-version.ts @@ -1,13 +1,13 @@ import { Tree } from '@angular-devkit/schematics'; -import { SemVer } from 'semver'; +import { coerce } from 'semver'; export function getAngularVersion(host: Tree): number { const packageJson = JSON.parse(host.read('package.json')?.toString() || '{}'); const angularCore = packageJson.dependencies?.['@angular/core']; if (angularCore) { - const version = new SemVer(angularCore.replace(/\^|\~/g, '')); - return version.major; + const version = coerce(angularCore); + return version ? version.major : Number.MAX_SAFE_INTEGER; } throw new Error('Angular version not found'); From 05b00bcc72761d53768ece503191c05d33efd0c3 Mon Sep 17 00:00:00 2001 From: Andrei Vorobev <738482+vorobey@users.noreply.github.com> Date: Mon, 9 Nov 2026 10:05:23 +0200 Subject: [PATCH 06/14] schematics: drop rc versions support --- packages/devextreme-schematics/src/add-layout/index.ts | 2 +- packages/devextreme-schematics/src/add-layout/index_spec.ts | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/devextreme-schematics/src/add-layout/index.ts b/packages/devextreme-schematics/src/add-layout/index.ts index 0f08f4e6d..d79784b39 100644 --- a/packages/devextreme-schematics/src/add-layout/index.ts +++ b/packages/devextreme-schematics/src/add-layout/index.ts @@ -296,7 +296,7 @@ function addZoneChangeDetection(appPath: string) { } function getCdkVersion(angularCoreVersion: string = '') { - if (angularCoreVersion.includes('next') || angularCoreVersion.includes('-rc')) { + if (angularCoreVersion.includes('next')) { return 'next'; } diff --git a/packages/devextreme-schematics/src/add-layout/index_spec.ts b/packages/devextreme-schematics/src/add-layout/index_spec.ts index 9780bfe33..5b6543571 100644 --- a/packages/devextreme-schematics/src/add-layout/index_spec.ts +++ b/packages/devextreme-schematics/src/add-layout/index_spec.ts @@ -177,7 +177,6 @@ describe('layout', () => { [ { angularCore: '~21.2.0', cdk: '^21.0.0' }, { angularCore: '^22.0.0', cdk: '^22.0.0' }, - { angularCore: '22.1.0-rc.1', cdk: 'next' }, { angularCore: 'next', cdk: 'next' }, ].forEach(({ angularCore, cdk }) => { it(`should choose angular/cdk ${cdk} for angular/core ${angularCore}`, async () => { From 6dbfeab6ed421fc8d1d3188fe40de78a645a552f Mon Sep 17 00:00:00 2001 From: Andrei Vorobev <738482+vorobey@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:41:59 +0200 Subject: [PATCH 07/14] schematics: add layout respects user's app.config --- .../src/add-layout/index.ts | 168 +++++++++++------- .../src/add-layout/index_spec.ts | 113 +++++++----- .../src/utility/change.ts | 6 +- .../devextreme-schematics/src/utility/zone.ts | 29 --- 4 files changed, 179 insertions(+), 137 deletions(-) delete mode 100644 packages/devextreme-schematics/src/utility/zone.ts diff --git a/packages/devextreme-schematics/src/add-layout/index.ts b/packages/devextreme-schematics/src/add-layout/index.ts index d79784b39..2a321dd0d 100644 --- a/packages/devextreme-schematics/src/add-layout/index.ts +++ b/packages/devextreme-schematics/src/add-layout/index.ts @@ -15,7 +15,19 @@ import { } from '@angular-devkit/schematics'; import { - SourceFile + ArrayLiteralExpression, + Expression, + Node, + ScriptTarget, + SourceFile, + StringLiteral, + createSourceFile, + forEachChild, + isArrayLiteralExpression, + isCallExpression, + isImportDeclaration, + isNamedImports, + isPropertyAssignment } from '@schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { strings } from '@angular-devkit/core'; @@ -67,7 +79,6 @@ import { getWorkspace } from '@schematics/angular/utility/workspace'; import { Change } from '@schematics/angular/utility/change'; import { isAngularVersionHigherThan } from '../utility/angular-version'; -import { isZonelessApp } from '../utility/zone'; import { NodePackageInstallTask, RunSchematicTask } from '@angular-devkit/schematics/tasks'; const routes = [ @@ -174,30 +185,6 @@ async function updateBudgets(host: Tree, options: any) { return host; } -async function addPolyfills(host: Tree, project: string, polyfills: string[]) { - const projectName = await getProjectName(host, project); - - modifyJSONFile(host, './angular.json', config => { - const buildOptions: Record = config.projects[projectName]['architect']['build']['options']; - - if (!buildOptions.polyfills) { - buildOptions.polyfills = []; - } else if (!Array.isArray(buildOptions.polyfills)) { - buildOptions.polyfills = [buildOptions.polyfills]; - } - - polyfills.forEach((polyfill) => { - if (!buildOptions.polyfills.includes(polyfill)) { - buildOptions.polyfills.push(polyfill); - } - }); - - return config; - }); - - return host; -} - function addViewportToBody(sourcePath: string = '') { return (host: Tree) => { const indexPath = join(sourcePath, 'index.html'); @@ -273,26 +260,94 @@ function hasRouting(host: Tree, sourcePath: string) { return host.exists(sourcePath + 'app.routes.ts'); } -function addZoneChangeDetection(appPath: string) { - const appConfigPath = join(appPath, 'app.config.ts'); - - return chain([ - modifyFileRule(appConfigPath, (source: SourceFile) => [ - insertImport(source, appConfigPath, 'provideZoneChangeDetection', '@angular/core') - ]), - (host: Tree) => { - const content = host.read(appConfigPath)?.toString(); - - if (content && !content.includes('provideZoneChangeDetection(')) { - host.overwrite(appConfigPath, content.replace( - /providers:\s*\[/, - '$&\n provideZoneChangeDetection({ eventCoalescing: true }),' - )); - } +function getNamedImports(source: SourceFile) { + return source.statements + .filter(isImportDeclaration) + .flatMap((declaration) => { + const bindings = declaration.importClause?.namedBindings; + const location = (declaration.moduleSpecifier as StringLiteral).text; - return host; + return bindings && isNamedImports(bindings) + ? bindings.elements.map((element) => ({ name: element.name.text, location })) + : []; + }); +} + +function findProvidersArray(source: SourceFile) { + let providers: ArrayLiteralExpression | undefined; + + const visit = (node: Node) => { + if (providers) { + return; + } + + if ( + isPropertyAssignment(node) + && node.name.getText() === 'providers' + && isArrayLiteralExpression(node.initializer) + ) { + providers = node.initializer; + return; + } + + forEachChild(node, visit); + }; + + visit(source); + + return providers; +} + +function getProviderName(node: Expression) { + return isCallExpression(node) ? node.expression.getText() : node.getText(); +} + +function mergeAppConfig(host: Tree, filePath: string, templateContent: string) { + const source = getSourceFile(host, filePath); + const providers = source && findProvidersArray(source); + const templateSource = createSourceFile(filePath, templateContent, ScriptTarget.Latest, true); + const templateProviders = findProvidersArray(templateSource); + + if (!source || !providers || !templateProviders) { + return false; + } + + const elements = providers.elements; + const providerNames = elements.map(getProviderName); + const router = elements.find((element) => getProviderName(element) === 'provideRouter'); + const missingProviders = templateProviders.elements + .filter((element) => !providerNames.includes(getProviderName(element))) + .map((element) => element.getText()); + const recorder = host.beginUpdate(filePath); + + if (router && isCallExpression(router) && !router.getText().includes('withHashLocation')) { + recorder.insertLeft( + router.arguments.end, + router.arguments.length ? ', withHashLocation()' : 'routes, withHashLocation()' + ); + } + + if (missingProviders.length) { + const lastElement = elements[elements.length - 1]; + const getPosition = (pos: number) => source.getLineAndCharacterOfPosition(pos); + + if (!lastElement) { + recorder.insertLeft(providers.getStart() + 1, `\n ${missingProviders.join(',\n ')}\n `); + } else if (getPosition(lastElement.getStart()).line === getPosition(providers.getStart()).line) { + recorder.insertLeft(lastElement.end, `, ${missingProviders.join(', ')}`); + } else { + const indent = ' '.repeat(getPosition(lastElement.getStart()).character); + recorder.insertLeft(lastElement.end, `,\n${indent}${missingProviders.join(`,\n${indent}`)}`); } - ]); + } + + host.commitUpdate(recorder); + + for (const { name, location } of getNamedImports(templateSource)) { + applyChanges(host, [insertImport(getSourceFile(host, filePath)!, filePath, name, location)], filePath); + } + + return true; } function getCdkVersion(angularCoreVersion: string = '') { @@ -304,9 +359,8 @@ function getCdkVersion(angularCoreVersion: string = '') { return version ? `^${version.major}.0.0` : 'latest'; } -function addPackagesToDependency(zoneless: boolean) { +function addPackagesToDependency() { return (host: Tree) => { - const zonejs = getPackageJsonDependency(host, 'zone.js'); const angularCore = getPackageJsonDependency(host, '@angular/core'); addPackageJsonDependency(host, { @@ -315,14 +369,6 @@ function addPackagesToDependency(zoneless: boolean) { version: getCdkVersion(angularCore?.version) }); - if (!zoneless && !zonejs) { - addPackageJsonDependency(host, { - type: NodeDependencyType.Default, - name: 'zone.js', - version: '~0.16.0' - }); - } - return host; }; } @@ -429,7 +475,6 @@ export default function(options: any): Rule { const override = options.resolveConflicts === 'override'; const componentName = override ? 'app' : getComponentName(host, appPath); const pathToCss = sourcePath?.replace(/\/?(\w)+\/?/g, '../'); - const zoneless = await isZonelessApp(host, project, appPath); const templateOptions = { name: setPostfix(host, componentName), @@ -450,6 +495,10 @@ export default function(options: any): Rule { return currentContent; } + if (basename(filePath) === 'app.config.ts' && mergeAppConfig(host, filePath, templateContent)) { + return currentContent; + } + return templateContent; }; @@ -460,16 +509,9 @@ export default function(options: any): Rule { addBuildThemeScript(), () => addCustomThemeStyles(host, options, sourcePath) as any, addViewportToBody(sourcePath), - addPackagesToDependency(zoneless), + addPackagesToDependency(), ]; - if (!zoneless) { - rules.push( - addZoneChangeDetection(appPath), - () => addPolyfills(host, options.project, ['zone.js']) as any - ); - } - if (options.updateBudgets) { rules.push(() => updateBudgets(host, options) as any); } diff --git a/packages/devextreme-schematics/src/add-layout/index_spec.ts b/packages/devextreme-schematics/src/add-layout/index_spec.ts index 5b6543571..a57402baa 100644 --- a/packages/devextreme-schematics/src/add-layout/index_spec.ts +++ b/packages/devextreme-schematics/src/add-layout/index_spec.ts @@ -335,71 +335,98 @@ describe('layout', () => { }); describe('change detection', () => { - const zoneOptions = { ...options, resolveConflicts: 'override' }; - - const setPolyfills = (polyfills: string | string[]) => { - modifyJSONFile(appTree, './angular.json', config => { - config.projects.testApp.architect.build.options.polyfills = polyfills; - return config; - }); - }; - - const expectZoneApp = (tree: UnitTestTree) => { - const packageConfig = JSON.parse(tree.readContent('package.json')); - const appConfig = tree.readContent('/src/app/app.config.ts'); - - expect(packageConfig.dependencies['zone.js']).toBeDefined(); - expect(appConfig).toMatch(/import { ApplicationConfig, provideZoneChangeDetection } from '@angular\/core';/); - expect(appConfig).toMatch(/providers: \[\s+provideZoneChangeDetection\({ eventCoalescing: true }\),/); - }; - it('should not add zone.js to a zoneless app', async () => { const runner = new SchematicTestRunner('schematics', collectionPath); - const tree = await runner.runSchematic('add-layout', zoneOptions, appTree); - - const packageConfig = JSON.parse(tree.readContent('package.json')); + const tree = await runner.runSchematic('add-layout', options, appTree); const angularContent = JSON.parse(tree.readContent('/angular.json')); - const polyfills = angularContent.projects.testApp.architect.build.options.polyfills || []; - expect(packageConfig.dependencies['zone.js']).toBeUndefined(); - expect(polyfills).not.toContain('zone.js'); + expect(JSON.parse(tree.readContent('package.json')).dependencies['zone.js']).toBeUndefined(); + expect(angularContent.projects.testApp.architect.build.options.polyfills || []).not.toContain('zone.js'); expect(tree.readContent('/src/app/app.config.ts')).not.toContain('provideZoneChangeDetection'); }); - it('should keep zone change detection if zone.js is in polyfills', async () => { - setPolyfills(['zone.js']); + it('should keep zone change detection provided in app config', async () => { + appTree.create('/src/app/app.config.ts', [ + `import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';`, + `export const appConfig: ApplicationConfig = {`, + ` providers: [provideZoneChangeDetection({ eventCoalescing: true })]`, + `};` + ].join('\n')); const runner = new SchematicTestRunner('schematics', collectionPath); - const tree = await runner.runSchematic('add-layout', zoneOptions, appTree); + const tree = await runner.runSchematic('add-layout', options, appTree); + const appConfig = tree.readContent('/src/app/app.config.ts'); - expectZoneApp(tree); + expect(appConfig).toContain(`import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';`); + expect(appConfig).toContain('provideZoneChangeDetection({ eventCoalescing: true })'); }); + }); - it('should keep zone change detection if zone.js is imported in a polyfills file', async () => { - setPolyfills('src/polyfills.ts'); - appTree.create('/src/polyfills.ts', `import 'zone.js';`); + describe('app config', () => { + const createAppConfig = (content: string[]) => { + appTree.create('/src/app/app.config.ts', content.join('\n')); + }; + + it('should merge layout providers into existing app config', async () => { + createAppConfig([ + `import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';`, + `import { provideHttpClient } from '@angular/common/http';`, + `import { provideRouter } from '@angular/router';`, + `import { routes } from './app.routes';`, + ``, + `export const appConfig: ApplicationConfig = {`, + ` providers: [`, + ` provideBrowserGlobalErrorListeners(),`, + ` provideHttpClient(),`, + ` provideRouter(routes),`, + ` ]`, + `};` + ]); const runner = new SchematicTestRunner('schematics', collectionPath); - const tree = await runner.runSchematic('add-layout', zoneOptions, appTree); + const tree = await runner.runSchematic('add-layout', options, appTree); + const appConfig = tree.readContent('/src/app/app.config.ts'); - expectZoneApp(tree); - const angularContent = JSON.parse(tree.readContent('/angular.json')); - expect(angularContent.projects.testApp.architect.build.options.polyfills) - .toEqual(['src/polyfills.ts', 'zone.js']); + expect(appConfig).toContain('provideBrowserGlobalErrorListeners(),'); + expect(appConfig).toContain('provideHttpClient(),'); + expect(appConfig).toContain('provideRouter(routes, withHashLocation()),'); + expect(appConfig).toMatch(/import { provideRouter, withHashLocation } from '@angular\/router';/); + expect(appConfig).toMatch( + /import { AppInfoService, AuthGuardService, AuthService, ScreenService } from '.\/shared\/services';/ + ); + expect(appConfig).toMatch(new RegExp([ + 'provideRouter\\(routes, withHashLocation\\(\\)\\),', + 'AuthGuardService,', + 'AuthService,', + 'ScreenService,', + 'AppInfoService,', + '\\]' + ].join('\\s+'))); + expect(appConfig.match(/import { routes }/g)).toHaveLength(1); }); - it('should keep zone change detection if app config provides it', async () => { - appTree.create('/src/app/app.config.ts', [ - `import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';`, + it('should not duplicate existing providers', async () => { + createAppConfig([ + `import { ApplicationConfig } from '@angular/core';`, + `import { provideRouter, withHashLocation } from '@angular/router';`, + `import { routes } from './app.routes';`, + `import { AuthService } from './shared/services';`, + ``, `export const appConfig: ApplicationConfig = {`, - ` providers: [provideZoneChangeDetection()]`, + ` providers: [provideRouter(routes, withHashLocation()), AuthService]`, `};` - ].join('\n')); + ]); const runner = new SchematicTestRunner('schematics', collectionPath); - const tree = await runner.runSchematic('add-layout', zoneOptions, appTree); + const tree = await runner.runSchematic('add-layout', options, appTree); + const appConfig = tree.readContent('/src/app/app.config.ts'); - expectZoneApp(tree); + expect(appConfig).toContain('providers: [provideRouter(routes, withHashLocation()), AuthService, ' + + 'AuthGuardService, ScreenService, AppInfoService]'); + expect(appConfig).toContain( + `import { AuthService, AppInfoService, AuthGuardService, ScreenService } from './shared/services';` + ); + expect(appConfig.match(/from '@angular\/router'/g)).toHaveLength(1); }); }); }); diff --git a/packages/devextreme-schematics/src/utility/change.ts b/packages/devextreme-schematics/src/utility/change.ts index 09b4303b6..8dbccb583 100644 --- a/packages/devextreme-schematics/src/utility/change.ts +++ b/packages/devextreme-schematics/src/utility/change.ts @@ -11,8 +11,10 @@ const newLine = ` export function applyChanges(host: Tree, changes: Change[], filePath: string) { const recorder = host.beginUpdate(filePath); - changes.forEach((change: InsertChange) => { - recorder.insertLeft(change.pos, change.toAdd); + changes.forEach((change) => { + if (change instanceof InsertChange) { + recorder.insertLeft(change.pos, change.toAdd); + } }); host.commitUpdate(recorder); diff --git a/packages/devextreme-schematics/src/utility/zone.ts b/packages/devextreme-schematics/src/utility/zone.ts deleted file mode 100644 index 6ac0dbf63..000000000 --- a/packages/devextreme-schematics/src/utility/zone.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Tree } from '@angular-devkit/schematics'; -import { getWorkspace } from '@schematics/angular/utility/workspace'; -import { join } from 'path'; - -function readFile(host: Tree, path?: string) { - return path && host.exists(path) ? host.read(path)!.toString() : ''; -} - -export async function isZonelessApp(host: Tree, projectName: string, appPath: string) { - const workspace = await getWorkspace(host); - const buildOptions = workspace.projects.get(projectName)?.targets.get('build')?.options || {}; - const mainPath = (buildOptions.browser || buildOptions.main) as string | undefined; - const bootstrapSource = readFile(host, join(appPath, 'app.config.ts')) + readFile(host, mainPath); - - if (/provideZoneChangeDetection\s*\(/.test(bootstrapSource)) { - return false; - } - - if (/provideZonelessChangeDetection\s*\(/.test(bootstrapSource)) { - return true; - } - - const polyfills = buildOptions.polyfills; - const polyfillList = (Array.isArray(polyfills) ? polyfills : [polyfills]).filter(Boolean) as string[]; - - return !polyfillList.some((polyfill) => - polyfill === 'zone.js' || /['"]zone\.js['"]/.test(readFile(host, polyfill)) - ); -} From 8cd6e68d1d04d1220cd75d8c631ddcbc34cb6abb Mon Sep 17 00:00:00 2001 From: Andrei Vorobev <738482+vorobey@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:16:23 +0200 Subject: [PATCH 08/14] fix add router arguments --- .../src/add-layout/index.ts | 26 ++++++++++--------- .../src/add-layout/index_spec.ts | 24 +++++++++++++++++ 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/packages/devextreme-schematics/src/add-layout/index.ts b/packages/devextreme-schematics/src/add-layout/index.ts index 2a321dd0d..60bb17655 100644 --- a/packages/devextreme-schematics/src/add-layout/index.ts +++ b/packages/devextreme-schematics/src/add-layout/index.ts @@ -1,7 +1,7 @@ import { - Rule, - SchematicContext, - Tree, + type Rule, + type SchematicContext, + type Tree, apply, url, move, @@ -10,17 +10,17 @@ import { forEach, mergeWith, callRule, - FileEntry, + type FileEntry, template } from '@angular-devkit/schematics'; import { - ArrayLiteralExpression, - Expression, - Node, + type ArrayLiteralExpression, + type Expression, + type Node, ScriptTarget, - SourceFile, - StringLiteral, + type SourceFile, + type StringLiteral, createSourceFile, forEachChild, isArrayLiteralExpression, @@ -76,7 +76,7 @@ import { import { insertImport } from '@schematics/angular/utility/ast-utils'; import { getWorkspace } from '@schematics/angular/utility/workspace'; -import { Change } from '@schematics/angular/utility/change'; +import type { Change } from '@schematics/angular/utility/change'; import { isAngularVersionHigherThan } from '../utility/angular-version'; import { NodePackageInstallTask, RunSchematicTask } from '@angular-devkit/schematics/tasks'; @@ -321,9 +321,11 @@ function mergeAppConfig(host: Tree, filePath: string, templateContent: string) { const recorder = host.beginUpdate(filePath); if (router && isCallExpression(router) && !router.getText().includes('withHashLocation')) { + const lastArgument = router.arguments[router.arguments.length - 1]; + recorder.insertLeft( - router.arguments.end, - router.arguments.length ? ', withHashLocation()' : 'routes, withHashLocation()' + lastArgument ? lastArgument.end : router.arguments.end, + lastArgument ? ', withHashLocation()' : 'routes, withHashLocation()' ); } diff --git a/packages/devextreme-schematics/src/add-layout/index_spec.ts b/packages/devextreme-schematics/src/add-layout/index_spec.ts index a57402baa..bc281c485 100644 --- a/packages/devextreme-schematics/src/add-layout/index_spec.ts +++ b/packages/devextreme-schematics/src/add-layout/index_spec.ts @@ -405,6 +405,30 @@ describe('layout', () => { expect(appConfig.match(/import { routes }/g)).toHaveLength(1); }); + it('should add hash location to router with trailing comma in arguments', async () => { + createAppConfig([ + `import { ApplicationConfig } from '@angular/core';`, + `import { provideRouter, withComponentInputBinding } from '@angular/router';`, + `import { routes } from './app.routes';`, + ``, + `export const appConfig: ApplicationConfig = {`, + ` providers: [`, + ` provideRouter(`, + ` routes,`, + ` withComponentInputBinding(),`, + ` ),`, + ` ]`, + `};` + ]); + + const runner = new SchematicTestRunner('schematics', collectionPath); + const tree = await runner.runSchematic('add-layout', options, appTree); + const appConfig = tree.readContent('/src/app/app.config.ts'); + + expect(appConfig).toContain('withComponentInputBinding(), withHashLocation(),'); + expect(appConfig).not.toMatch(/,\s*,/); + }); + it('should not duplicate existing providers', async () => { createAppConfig([ `import { ApplicationConfig } from '@angular/core';`, From d9fcabd5196e6f0aa95f1967fddfef552f3440ec Mon Sep 17 00:00:00 2001 From: Andrei Vorobev <738482+vorobey@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:35:08 +0200 Subject: [PATCH 09/14] fix copilot comments --- .../src/add-layout/index.ts | 58 +++++++++++-------- .../src/add-layout/index_spec.ts | 20 +++++++ 2 files changed, 55 insertions(+), 23 deletions(-) diff --git a/packages/devextreme-schematics/src/add-layout/index.ts b/packages/devextreme-schematics/src/add-layout/index.ts index 60bb17655..e69926ddf 100644 --- a/packages/devextreme-schematics/src/add-layout/index.ts +++ b/packages/devextreme-schematics/src/add-layout/index.ts @@ -27,7 +27,9 @@ import { isCallExpression, isImportDeclaration, isNamedImports, - isPropertyAssignment + isObjectLiteralExpression, + isPropertyAssignment, + isVariableStatement } from '@schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { strings } from '@angular-devkit/core'; @@ -273,40 +275,50 @@ function getNamedImports(source: SourceFile) { }); } -function findProvidersArray(source: SourceFile) { - let providers: ArrayLiteralExpression | undefined; +function getProviderName(node: Expression) { + if (isCallExpression(node)) { + return node.expression.getText(); + } - const visit = (node: Node) => { - if (providers) { - return; - } + if (isObjectLiteralExpression(node)) { + const provide = node.properties.find((property) => + isPropertyAssignment(property) && property.name.getText() === 'provide' + ); - if ( - isPropertyAssignment(node) - && node.name.getText() === 'providers' - && isArrayLiteralExpression(node.initializer) - ) { - providers = node.initializer; - return; + if (provide && isPropertyAssignment(provide)) { + return provide.initializer.getText(); } + } - forEachChild(node, visit); - }; + return node.getText(); +} - visit(source); +function findAppConfigProviders(source: SourceFile) { + const declarations = source.statements + .filter(isVariableStatement) + .flatMap((statement) => [...statement.declarationList.declarations]); + const appConfig = declarations.find((declaration) => declaration.type?.getText() === 'ApplicationConfig') + ?? declarations.find((declaration) => declaration.name.getText() === 'appConfig'); + const config = appConfig?.initializer; - return providers; -} + if (!config || !isObjectLiteralExpression(config)) { + return; + } -function getProviderName(node: Expression) { - return isCallExpression(node) ? node.expression.getText() : node.getText(); + const providers = config.properties.find((property) => + isPropertyAssignment(property) && property.name.getText() === 'providers' + ); + + return providers && isPropertyAssignment(providers) && isArrayLiteralExpression(providers.initializer) + ? providers.initializer + : undefined; } function mergeAppConfig(host: Tree, filePath: string, templateContent: string) { const source = getSourceFile(host, filePath); - const providers = source && findProvidersArray(source); + const providers = source && findAppConfigProviders(source); const templateSource = createSourceFile(filePath, templateContent, ScriptTarget.Latest, true); - const templateProviders = findProvidersArray(templateSource); + const templateProviders = findAppConfigProviders(templateSource); if (!source || !providers || !templateProviders) { return false; diff --git a/packages/devextreme-schematics/src/add-layout/index_spec.ts b/packages/devextreme-schematics/src/add-layout/index_spec.ts index bc281c485..68799c37c 100644 --- a/packages/devextreme-schematics/src/add-layout/index_spec.ts +++ b/packages/devextreme-schematics/src/add-layout/index_spec.ts @@ -452,5 +452,25 @@ describe('layout', () => { ); expect(appConfig.match(/from '@angular\/router'/g)).toHaveLength(1); }); + + it('should keep custom provider registered by provide token', async () => { + createAppConfig([ + `import { ApplicationConfig } from '@angular/core';`, + `import { AuthService } from './shared/services';`, + `import { CustomAuthService } from './custom-auth.service';`, + ``, + `export const appConfig: ApplicationConfig = {`, + ` providers: [{ provide: AuthService, useClass: CustomAuthService }]`, + `};` + ]); + + const runner = new SchematicTestRunner('schematics', collectionPath); + const tree = await runner.runSchematic('add-layout', options, appTree); + const appConfig = tree.readContent('/src/app/app.config.ts'); + + expect(appConfig).toContain('{ provide: AuthService, useClass: CustomAuthService }'); + expect(appConfig).not.toMatch(/[,[]\s*AuthService\s*[,\]]/); + expect(appConfig).toContain('ScreenService'); + }); }); }); From 0dbe2443ca2e8671e094640ad6d49dc3157c3752 Mon Sep 17 00:00:00 2001 From: Andrei Vorobev <738482+vorobey@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:09:56 +0200 Subject: [PATCH 10/14] fix add typerrs --- packages/devextreme-schematics/src/add-layout/index.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/packages/devextreme-schematics/src/add-layout/index.ts b/packages/devextreme-schematics/src/add-layout/index.ts index e69926ddf..114a11e74 100644 --- a/packages/devextreme-schematics/src/add-layout/index.ts +++ b/packages/devextreme-schematics/src/add-layout/index.ts @@ -15,14 +15,11 @@ import { } from '@angular-devkit/schematics'; import { - type ArrayLiteralExpression, type Expression, - type Node, ScriptTarget, type SourceFile, type StringLiteral, createSourceFile, - forEachChild, isArrayLiteralExpression, isCallExpression, isImportDeclaration, From 7e244c8c3b2dbf2eda1846517f832bf89702389f Mon Sep 17 00:00:00 2001 From: Andrei Vorobev <738482+vorobey@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:47:52 +0200 Subject: [PATCH 11/14] make thin app.config --- .../add-layout/files/src/app/app.config.ts | 10 - .../app/shared/services/app-info.service.ts | 2 +- .../src/app/shared/services/auth.service.ts | 4 +- .../src/app/shared/services/screen.service.ts | 2 +- .../src/add-layout/index.ts | 177 ++++++++++------ .../src/add-layout/index_spec.ts | 189 +++++++++++++----- 6 files changed, 255 insertions(+), 129 deletions(-) diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts index d3d907886..88310e182 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts @@ -1,19 +1,9 @@ import { ApplicationConfig } from '@angular/core'; import { provideRouter, withHashLocation } from '@angular/router'; import { routes } from './app.routes'; -import { - AppInfoService, - AuthGuardService, - AuthService, - ScreenService, -} from './shared/services'; export const appConfig: ApplicationConfig = { providers: [ provideRouter(routes, withHashLocation()), - AuthGuardService, - AuthService, - ScreenService, - AppInfoService, ] }; diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/app-info.service.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/app-info.service.ts index bf39e60a6..bd7390b38 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/app-info.service.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/app-info.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; -@Injectable() +@Injectable({ providedIn: 'root' }) export class AppInfoService { constructor() {} diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts index 162c00558..7328e6e3d 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts @@ -12,7 +12,7 @@ const defaultUser = { avatarUrl: 'https://js.devexpress.com/Demos/WidgetsGallery/JSDemos/images/employees/06.png' }; -@Injectable() +@Injectable({ providedIn: 'root' }) export class AuthService { private _user: IUser | null = defaultUser; get loggedIn(): boolean { @@ -118,7 +118,7 @@ export class AuthService { } } -@Injectable() +@Injectable({ providedIn: 'root' }) export class AuthGuardService implements CanActivate { constructor(private router: Router, private authService: AuthService) { } diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts index d5c07faf4..def101b36 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts @@ -1,7 +1,7 @@ import { Output, Injectable, EventEmitter, WritableSignal, signal } from '@angular/core'; import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'; -@Injectable() +@Injectable({ providedIn: 'root' }) export class ScreenService { @Output() changed = new EventEmitter(); diff --git a/packages/devextreme-schematics/src/add-layout/index.ts b/packages/devextreme-schematics/src/add-layout/index.ts index 114a11e74..c07c9edfb 100644 --- a/packages/devextreme-schematics/src/add-layout/index.ts +++ b/packages/devextreme-schematics/src/add-layout/index.ts @@ -15,17 +15,18 @@ import { } from '@angular-devkit/schematics'; import { - type Expression, - ScriptTarget, + type CallExpression, + type Node, type SourceFile, type StringLiteral, - createSourceFile, + forEachChild, isArrayLiteralExpression, isCallExpression, isImportDeclaration, isNamedImports, isObjectLiteralExpression, isPropertyAssignment, + isSpreadElement, isVariableStatement } from '@schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript'; @@ -259,35 +260,28 @@ function hasRouting(host: Tree, sourcePath: string) { return host.exists(sourcePath + 'app.routes.ts'); } -function getNamedImports(source: SourceFile) { - return source.statements - .filter(isImportDeclaration) - .flatMap((declaration) => { - const bindings = declaration.importClause?.namedBindings; - const location = (declaration.moduleSpecifier as StringLiteral).text; +const appRoutesLocation = './app.routes'; +const routerProvider = 'provideRouter(routes, withHashLocation())'; - return bindings && isNamedImports(bindings) - ? bindings.elements.map((element) => ({ name: element.name.text, location })) - : []; - }); -} - -function getProviderName(node: Expression) { - if (isCallExpression(node)) { - return node.expression.getText(); - } +function findCall(source: SourceFile, name: string) { + let call: CallExpression | undefined; - if (isObjectLiteralExpression(node)) { - const provide = node.properties.find((property) => - isPropertyAssignment(property) && property.name.getText() === 'provide' - ); + const visit = (node: Node) => { + if (call) { + return; + } - if (provide && isPropertyAssignment(provide)) { - return provide.initializer.getText(); + if (isCallExpression(node) && node.expression.getText() === name) { + call = node; + return; } - } - return node.getText(); + forEachChild(node, visit); + }; + + visit(source); + + return call; } function findAppConfigProviders(source: SourceFile) { @@ -311,56 +305,110 @@ function findAppConfigProviders(source: SourceFile) { : undefined; } -function mergeAppConfig(host: Tree, filePath: string, templateContent: string) { - const source = getSourceFile(host, filePath); - const providers = source && findAppConfigProviders(source); - const templateSource = createSourceFile(filePath, templateContent, ScriptTarget.Latest, true); - const templateProviders = findAppConfigProviders(templateSource); +function isImportedFrom(source: SourceFile, name: string, location: string) { + return source.statements.some((statement) => { + const bindings = isImportDeclaration(statement) && statement.importClause?.namedBindings; - if (!source || !providers || !templateProviders) { - return false; + return !!bindings + && isNamedImports(bindings) + && (statement.moduleSpecifier as StringLiteral).text === location + && bindings.elements.some((element) => element.name.text === name); + }); +} + +function addImports(host: Tree, filePath: string, imports: { name: string, location: string }[]) { + for (const { name, location } of imports) { + applyChanges(host, [insertImport(getSourceFile(host, filePath)!, filePath, name, location)], filePath); + } +} + +function addHashLocation(host: Tree, filePath: string, router: CallExpression) { + const lastArgument = router.arguments[router.arguments.length - 1]; + + if (!lastArgument || router.getText().includes('withHashLocation')) { + return; } - const elements = providers.elements; - const providerNames = elements.map(getProviderName); - const router = elements.find((element) => getProviderName(element) === 'provideRouter'); - const missingProviders = templateProviders.elements - .filter((element) => !providerNames.includes(getProviderName(element))) - .map((element) => element.getText()); const recorder = host.beginUpdate(filePath); + recorder.insertLeft(lastArgument.end, ', withHashLocation()'); + host.commitUpdate(recorder); - if (router && isCallExpression(router) && !router.getText().includes('withHashLocation')) { - const lastArgument = router.arguments[router.arguments.length - 1]; + addImports(host, filePath, [{ name: 'withHashLocation', location: '@angular/router' }]); +} + +function addRouterProvider(host: Tree, filePath: string, source: SourceFile) { + const providers = findAppConfigProviders(source); + const canAddRouter = providers + && !providers.elements.some(isSpreadElement) + && !/\broutes\b/.test(source.getText()); - recorder.insertLeft( - lastArgument ? lastArgument.end : router.arguments.end, - lastArgument ? ', withHashLocation()' : 'routes, withHashLocation()' - ); + if (!providers || !canAddRouter) { + return false; } - if (missingProviders.length) { - const lastElement = elements[elements.length - 1]; - const getPosition = (pos: number) => source.getLineAndCharacterOfPosition(pos); - - if (!lastElement) { - recorder.insertLeft(providers.getStart() + 1, `\n ${missingProviders.join(',\n ')}\n `); - } else if (getPosition(lastElement.getStart()).line === getPosition(providers.getStart()).line) { - recorder.insertLeft(lastElement.end, `, ${missingProviders.join(', ')}`); - } else { - const indent = ' '.repeat(getPosition(lastElement.getStart()).character); - recorder.insertLeft(lastElement.end, `,\n${indent}${missingProviders.join(`,\n${indent}`)}`); - } + const elements = providers.elements; + const lastElement = elements[elements.length - 1]; + const getPosition = (pos: number) => source.getLineAndCharacterOfPosition(pos); + const recorder = host.beginUpdate(filePath); + + if (!lastElement) { + recorder.insertLeft(providers.getStart() + 1, `\n ${routerProvider}\n `); + } else if (getPosition(lastElement.getStart()).line === getPosition(providers.getStart()).line) { + recorder.insertLeft(lastElement.end, `, ${routerProvider}`); + } else { + const indent = ' '.repeat(getPosition(lastElement.getStart()).character); + recorder.insertLeft(lastElement.end, `,\n${indent}${routerProvider}`); } host.commitUpdate(recorder); - for (const { name, location } of getNamedImports(templateSource)) { - applyChanges(host, [insertImport(getSourceFile(host, filePath)!, filePath, name, location)], filePath); - } + addImports(host, filePath, [ + { name: 'provideRouter', location: '@angular/router' }, + { name: 'withHashLocation', location: '@angular/router' }, + { name: 'routes', location: appRoutesLocation }, + ]); return true; } +function updateAppConfig(appPath: string): Rule { + const filePath = join(appPath, 'app.config.ts'); + + return (host: Tree, context: SchematicContext) => { + const source = getSourceFile(host, filePath); + + if (!source) { + return host; + } + + const router = findCall(source, 'provideRouter'); + + if (!router) { + if (!addRouterProvider(host, filePath, source)) { + context.logger.warn( + `Could not register the router in ${filePath}. ` + + `Add "${routerProvider}" with "routes" imported from '${appRoutesLocation}' to the application providers.` + ); + } + + return host; + } + + addHashLocation(host, filePath, router); + + const routesArgument = router.arguments[0]; + + if (!routesArgument || !isImportedFrom(source, routesArgument.getText(), appRoutesLocation)) { + context.logger.warn( + `DevExtreme layout routes were added to ${join(appPath, 'app.routes.ts')}, ` + + `but the router in ${filePath} uses other routes. Add the layout routes to the routes passed to provideRouter.` + ); + } + + return host; + }; +} + function getCdkVersion(angularCoreVersion: string = '') { if (angularCoreVersion.includes('next')) { return 'next'; @@ -486,6 +534,7 @@ export default function(options: any): Rule { const override = options.resolveConflicts === 'override'; const componentName = override ? 'app' : getComponentName(host, appPath); const pathToCss = sourcePath?.replace(/\/?(\w)+\/?/g, '../'); + const hasAppConfig = host.exists(join(appPath, 'app.config.ts')); const templateOptions = { name: setPostfix(host, componentName), @@ -506,7 +555,7 @@ export default function(options: any): Rule { return currentContent; } - if (basename(filePath) === 'app.config.ts' && mergeAppConfig(host, filePath, templateContent)) { + if (basename(filePath) === 'app.config.ts') { return currentContent; } @@ -523,6 +572,10 @@ export default function(options: any): Rule { addPackagesToDependency(), ]; + if (hasAppConfig) { + rules.push(updateAppConfig(appPath)); + } + if (options.updateBudgets) { rules.push(() => updateBudgets(host, options) as any); } diff --git a/packages/devextreme-schematics/src/add-layout/index_spec.ts b/packages/devextreme-schematics/src/add-layout/index_spec.ts index 68799c37c..611b42aba 100644 --- a/packages/devextreme-schematics/src/add-layout/index_spec.ts +++ b/packages/devextreme-schematics/src/add-layout/index_spec.ts @@ -367,7 +367,30 @@ describe('layout', () => { appTree.create('/src/app/app.config.ts', content.join('\n')); }; - it('should merge layout providers into existing app config', async () => { + const runLayout = async () => { + const runner = new SchematicTestRunner('schematics', collectionPath); + const warnings: string[] = []; + + runner.logger.subscribe((entry) => { + if (entry.level === 'warn') { + warnings.push(entry.message); + } + }); + + const tree = await runner.runSchematic('add-layout', options, appTree); + + return { appConfig: tree.readContent('/src/app/app.config.ts'), tree, warnings }; + }; + + it('should create app config from template if it does not exist', async () => { + const { appConfig, warnings } = await runLayout(); + + expect(appConfig).toContain('provideRouter(routes, withHashLocation())'); + expect(appConfig).not.toContain('./shared/services'); + expect(warnings).toEqual([]); + }); + + it('should add hash location to existing router and keep user providers', async () => { createAppConfig([ `import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';`, `import { provideHttpClient } from '@angular/common/http';`, @@ -383,94 +406,154 @@ describe('layout', () => { `};` ]); - const runner = new SchematicTestRunner('schematics', collectionPath); - const tree = await runner.runSchematic('add-layout', options, appTree); - const appConfig = tree.readContent('/src/app/app.config.ts'); + const { appConfig, warnings } = await runLayout(); - expect(appConfig).toContain('provideBrowserGlobalErrorListeners(),'); - expect(appConfig).toContain('provideHttpClient(),'); - expect(appConfig).toContain('provideRouter(routes, withHashLocation()),'); - expect(appConfig).toMatch(/import { provideRouter, withHashLocation } from '@angular\/router';/); - expect(appConfig).toMatch( - /import { AppInfoService, AuthGuardService, AuthService, ScreenService } from '.\/shared\/services';/ - ); - expect(appConfig).toMatch(new RegExp([ - 'provideRouter\\(routes, withHashLocation\\(\\)\\),', - 'AuthGuardService,', - 'AuthService,', - 'ScreenService,', - 'AppInfoService,', - '\\]' - ].join('\\s+'))); + expect(appConfig).toContain([ + ` providers: [`, + ` provideBrowserGlobalErrorListeners(),`, + ` provideHttpClient(),`, + ` provideRouter(routes, withHashLocation()),`, + ` ]`, + ].join('\n')); + expect(appConfig).toContain(`import { provideRouter, withHashLocation } from '@angular/router';`); expect(appConfig.match(/import { routes }/g)).toHaveLength(1); + expect(warnings).toEqual([]); }); - it('should add hash location to router with trailing comma in arguments', async () => { + it('should not change app config with hash location router', async () => { + const content = [ + `import { ApplicationConfig } from '@angular/core';`, + `import { provideRouter, withHashLocation } from '@angular/router';`, + `import { routes } from './app.routes';`, + ``, + `export const appConfig: ApplicationConfig = {`, + ` providers: [provideRouter(routes, withHashLocation())]`, + `};` + ]; + createAppConfig(content); + + const { appConfig, warnings } = await runLayout(); + + expect(appConfig).toBe(content.join('\n')); + expect(warnings).toEqual([]); + }); + + it('should add hash location to router call with trailing comma', async () => { createAppConfig([ `import { ApplicationConfig } from '@angular/core';`, - `import { provideRouter, withComponentInputBinding } from '@angular/router';`, + `import { provideRouter } from '@angular/router';`, `import { routes } from './app.routes';`, ``, `export const appConfig: ApplicationConfig = {`, - ` providers: [`, - ` provideRouter(`, - ` routes,`, - ` withComponentInputBinding(),`, - ` ),`, - ` ]`, + ` providers: [provideRouter(routes,)]`, `};` ]); - const runner = new SchematicTestRunner('schematics', collectionPath); - const tree = await runner.runSchematic('add-layout', options, appTree); - const appConfig = tree.readContent('/src/app/app.config.ts'); + const { appConfig } = await runLayout(); - expect(appConfig).toContain('withComponentInputBinding(), withHashLocation(),'); - expect(appConfig).not.toMatch(/,\s*,/); + expect(appConfig).toContain('provideRouter(routes, withHashLocation(),)'); }); - it('should not duplicate existing providers', async () => { + it('should add hash location to router outside of providers literal', async () => { createAppConfig([ `import { ApplicationConfig } from '@angular/core';`, - `import { provideRouter, withHashLocation } from '@angular/router';`, + `import { provideHttpClient } from '@angular/common/http';`, + `import { provideRouter } from '@angular/router';`, `import { routes } from './app.routes';`, - `import { AuthService } from './shared/services';`, + ``, + `const appProviders = [provideHttpClient(), provideRouter(routes)];`, ``, `export const appConfig: ApplicationConfig = {`, - ` providers: [provideRouter(routes, withHashLocation()), AuthService]`, + ` providers: appProviders`, `};` ]); - const runner = new SchematicTestRunner('schematics', collectionPath); - const tree = await runner.runSchematic('add-layout', options, appTree); - const appConfig = tree.readContent('/src/app/app.config.ts'); + const { appConfig, warnings } = await runLayout(); - expect(appConfig).toContain('providers: [provideRouter(routes, withHashLocation()), AuthService, ' - + 'AuthGuardService, ScreenService, AppInfoService]'); expect(appConfig).toContain( - `import { AuthService, AppInfoService, AuthGuardService, ScreenService } from './shared/services';` + 'const appProviders = [provideHttpClient(), provideRouter(routes, withHashLocation())];' ); - expect(appConfig.match(/from '@angular\/router'/g)).toHaveLength(1); + expect(appConfig).toContain('providers: appProviders'); + expect(warnings).toEqual([]); }); - it('should keep custom provider registered by provide token', async () => { + it('should add router to app config without routing', async () => { createAppConfig([ + `import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';`, + ``, + `export const appConfig: ApplicationConfig = {`, + ` providers: [`, + ` provideBrowserGlobalErrorListeners(),`, + ` ]`, + `};` + ]); + + const { appConfig, tree, warnings } = await runLayout(); + + expect(appConfig).toContain([ + ` provideBrowserGlobalErrorListeners(),`, + ` provideRouter(routes, withHashLocation()),`, + ].join('\n')); + expect(appConfig).toContain(`import { provideRouter, withHashLocation } from '@angular/router';`); + expect(appConfig).toContain(`import { routes } from './app.routes';`); + expect(tree.files).toContain('/src/app/app.routes.ts'); + expect(warnings).toEqual([]); + }); + + it('should warn and keep app config if routes name is taken', async () => { + const content = [ `import { ApplicationConfig } from '@angular/core';`, - `import { AuthService } from './shared/services';`, - `import { CustomAuthService } from './custom-auth.service';`, + ``, + `const routes = [];`, ``, `export const appConfig: ApplicationConfig = {`, - ` providers: [{ provide: AuthService, useClass: CustomAuthService }]`, + ` providers: []`, + `};` + ]; + createAppConfig(content); + + const { appConfig, warnings } = await runLayout(); + + expect(appConfig).toBe(content.join('\n')); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain('Could not register the router'); + }); + + it('should warn and keep app config if providers are not a literal array', async () => { + const content = [ + `import { ApplicationConfig } from '@angular/core';`, + `import { appProviders } from './app.providers';`, + ``, + `export const appConfig: ApplicationConfig = {`, + ` providers: [...appProviders]`, + `};` + ]; + createAppConfig(content); + + const { appConfig, warnings } = await runLayout(); + + expect(appConfig).toBe(content.join('\n')); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain('Could not register the router'); + }); + + it('should warn if router uses other routes', async () => { + createAppConfig([ + `import { ApplicationConfig } from '@angular/core';`, + `import { provideRouter } from '@angular/router';`, + `import { myRoutes } from './my.routes';`, + ``, + `export const appConfig: ApplicationConfig = {`, + ` providers: [provideRouter(myRoutes)]`, `};` ]); - const runner = new SchematicTestRunner('schematics', collectionPath); - const tree = await runner.runSchematic('add-layout', options, appTree); - const appConfig = tree.readContent('/src/app/app.config.ts'); + const { appConfig, warnings } = await runLayout(); - expect(appConfig).toContain('{ provide: AuthService, useClass: CustomAuthService }'); - expect(appConfig).not.toMatch(/[,[]\s*AuthService\s*[,\]]/); - expect(appConfig).toContain('ScreenService'); + expect(appConfig).toContain('provideRouter(myRoutes, withHashLocation())'); + expect(appConfig).not.toContain('./app.routes'); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain('uses other routes'); }); }); }); From e245e3dc2b19804202cf90aac780f2992edb5238 Mon Sep 17 00:00:00 2001 From: Andrei Vorobev <738482+vorobey@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:25:17 +0200 Subject: [PATCH 12/14] Revert app.config merge approach in add-layout Reverts 6dbfeab, 8cd6e68, d9fcabd, 0dbe244, 7e244c8. The team decided to keep overwriting app.config.ts with the template. Co-Authored-By: Claude Opus 5.5 --- .../add-layout/files/src/app/app.config.ts | 10 + .../app/shared/services/app-info.service.ts | 2 +- .../src/app/shared/services/auth.service.ts | 4 +- .../src/app/shared/services/screen.service.ts | 2 +- .../src/add-layout/index.ts | 234 +++++------------ .../src/add-layout/index_spec.ts | 236 +++--------------- .../src/utility/change.ts | 6 +- .../devextreme-schematics/src/utility/zone.ts | 29 +++ 8 files changed, 150 insertions(+), 373 deletions(-) create mode 100644 packages/devextreme-schematics/src/utility/zone.ts diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts index 88310e182..d3d907886 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts @@ -1,9 +1,19 @@ import { ApplicationConfig } from '@angular/core'; import { provideRouter, withHashLocation } from '@angular/router'; import { routes } from './app.routes'; +import { + AppInfoService, + AuthGuardService, + AuthService, + ScreenService, +} from './shared/services'; export const appConfig: ApplicationConfig = { providers: [ provideRouter(routes, withHashLocation()), + AuthGuardService, + AuthService, + ScreenService, + AppInfoService, ] }; diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/app-info.service.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/app-info.service.ts index bd7390b38..bf39e60a6 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/app-info.service.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/app-info.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; -@Injectable({ providedIn: 'root' }) +@Injectable() export class AppInfoService { constructor() {} diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts index 7328e6e3d..162c00558 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts @@ -12,7 +12,7 @@ const defaultUser = { avatarUrl: 'https://js.devexpress.com/Demos/WidgetsGallery/JSDemos/images/employees/06.png' }; -@Injectable({ providedIn: 'root' }) +@Injectable() export class AuthService { private _user: IUser | null = defaultUser; get loggedIn(): boolean { @@ -118,7 +118,7 @@ export class AuthService { } } -@Injectable({ providedIn: 'root' }) +@Injectable() export class AuthGuardService implements CanActivate { constructor(private router: Router, private authService: AuthService) { } diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts index def101b36..d5c07faf4 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts @@ -1,7 +1,7 @@ import { Output, Injectable, EventEmitter, WritableSignal, signal } from '@angular/core'; import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'; -@Injectable({ providedIn: 'root' }) +@Injectable() export class ScreenService { @Output() changed = new EventEmitter(); diff --git a/packages/devextreme-schematics/src/add-layout/index.ts b/packages/devextreme-schematics/src/add-layout/index.ts index c07c9edfb..d79784b39 100644 --- a/packages/devextreme-schematics/src/add-layout/index.ts +++ b/packages/devextreme-schematics/src/add-layout/index.ts @@ -1,7 +1,7 @@ import { - type Rule, - type SchematicContext, - type Tree, + Rule, + SchematicContext, + Tree, apply, url, move, @@ -10,24 +10,12 @@ import { forEach, mergeWith, callRule, - type FileEntry, + FileEntry, template } from '@angular-devkit/schematics'; import { - type CallExpression, - type Node, - type SourceFile, - type StringLiteral, - forEachChild, - isArrayLiteralExpression, - isCallExpression, - isImportDeclaration, - isNamedImports, - isObjectLiteralExpression, - isPropertyAssignment, - isSpreadElement, - isVariableStatement + SourceFile } from '@schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { strings } from '@angular-devkit/core'; @@ -76,9 +64,10 @@ import { import { insertImport } from '@schematics/angular/utility/ast-utils'; import { getWorkspace } from '@schematics/angular/utility/workspace'; -import type { Change } from '@schematics/angular/utility/change'; +import { Change } from '@schematics/angular/utility/change'; import { isAngularVersionHigherThan } from '../utility/angular-version'; +import { isZonelessApp } from '../utility/zone'; import { NodePackageInstallTask, RunSchematicTask } from '@angular-devkit/schematics/tasks'; const routes = [ @@ -185,6 +174,30 @@ async function updateBudgets(host: Tree, options: any) { return host; } +async function addPolyfills(host: Tree, project: string, polyfills: string[]) { + const projectName = await getProjectName(host, project); + + modifyJSONFile(host, './angular.json', config => { + const buildOptions: Record = config.projects[projectName]['architect']['build']['options']; + + if (!buildOptions.polyfills) { + buildOptions.polyfills = []; + } else if (!Array.isArray(buildOptions.polyfills)) { + buildOptions.polyfills = [buildOptions.polyfills]; + } + + polyfills.forEach((polyfill) => { + if (!buildOptions.polyfills.includes(polyfill)) { + buildOptions.polyfills.push(polyfill); + } + }); + + return config; + }); + + return host; +} + function addViewportToBody(sourcePath: string = '') { return (host: Tree) => { const indexPath = join(sourcePath, 'index.html'); @@ -260,153 +273,26 @@ function hasRouting(host: Tree, sourcePath: string) { return host.exists(sourcePath + 'app.routes.ts'); } -const appRoutesLocation = './app.routes'; -const routerProvider = 'provideRouter(routes, withHashLocation())'; - -function findCall(source: SourceFile, name: string) { - let call: CallExpression | undefined; - - const visit = (node: Node) => { - if (call) { - return; - } - - if (isCallExpression(node) && node.expression.getText() === name) { - call = node; - return; - } - - forEachChild(node, visit); - }; - - visit(source); - - return call; -} - -function findAppConfigProviders(source: SourceFile) { - const declarations = source.statements - .filter(isVariableStatement) - .flatMap((statement) => [...statement.declarationList.declarations]); - const appConfig = declarations.find((declaration) => declaration.type?.getText() === 'ApplicationConfig') - ?? declarations.find((declaration) => declaration.name.getText() === 'appConfig'); - const config = appConfig?.initializer; - - if (!config || !isObjectLiteralExpression(config)) { - return; - } - - const providers = config.properties.find((property) => - isPropertyAssignment(property) && property.name.getText() === 'providers' - ); - - return providers && isPropertyAssignment(providers) && isArrayLiteralExpression(providers.initializer) - ? providers.initializer - : undefined; -} - -function isImportedFrom(source: SourceFile, name: string, location: string) { - return source.statements.some((statement) => { - const bindings = isImportDeclaration(statement) && statement.importClause?.namedBindings; - - return !!bindings - && isNamedImports(bindings) - && (statement.moduleSpecifier as StringLiteral).text === location - && bindings.elements.some((element) => element.name.text === name); - }); -} - -function addImports(host: Tree, filePath: string, imports: { name: string, location: string }[]) { - for (const { name, location } of imports) { - applyChanges(host, [insertImport(getSourceFile(host, filePath)!, filePath, name, location)], filePath); - } -} - -function addHashLocation(host: Tree, filePath: string, router: CallExpression) { - const lastArgument = router.arguments[router.arguments.length - 1]; - - if (!lastArgument || router.getText().includes('withHashLocation')) { - return; - } - - const recorder = host.beginUpdate(filePath); - recorder.insertLeft(lastArgument.end, ', withHashLocation()'); - host.commitUpdate(recorder); - - addImports(host, filePath, [{ name: 'withHashLocation', location: '@angular/router' }]); -} - -function addRouterProvider(host: Tree, filePath: string, source: SourceFile) { - const providers = findAppConfigProviders(source); - const canAddRouter = providers - && !providers.elements.some(isSpreadElement) - && !/\broutes\b/.test(source.getText()); - - if (!providers || !canAddRouter) { - return false; - } - - const elements = providers.elements; - const lastElement = elements[elements.length - 1]; - const getPosition = (pos: number) => source.getLineAndCharacterOfPosition(pos); - const recorder = host.beginUpdate(filePath); - - if (!lastElement) { - recorder.insertLeft(providers.getStart() + 1, `\n ${routerProvider}\n `); - } else if (getPosition(lastElement.getStart()).line === getPosition(providers.getStart()).line) { - recorder.insertLeft(lastElement.end, `, ${routerProvider}`); - } else { - const indent = ' '.repeat(getPosition(lastElement.getStart()).character); - recorder.insertLeft(lastElement.end, `,\n${indent}${routerProvider}`); - } - - host.commitUpdate(recorder); - - addImports(host, filePath, [ - { name: 'provideRouter', location: '@angular/router' }, - { name: 'withHashLocation', location: '@angular/router' }, - { name: 'routes', location: appRoutesLocation }, - ]); - - return true; -} - -function updateAppConfig(appPath: string): Rule { - const filePath = join(appPath, 'app.config.ts'); - - return (host: Tree, context: SchematicContext) => { - const source = getSourceFile(host, filePath); - - if (!source) { - return host; - } - - const router = findCall(source, 'provideRouter'); - - if (!router) { - if (!addRouterProvider(host, filePath, source)) { - context.logger.warn( - `Could not register the router in ${filePath}. ` - + `Add "${routerProvider}" with "routes" imported from '${appRoutesLocation}' to the application providers.` - ); +function addZoneChangeDetection(appPath: string) { + const appConfigPath = join(appPath, 'app.config.ts'); + + return chain([ + modifyFileRule(appConfigPath, (source: SourceFile) => [ + insertImport(source, appConfigPath, 'provideZoneChangeDetection', '@angular/core') + ]), + (host: Tree) => { + const content = host.read(appConfigPath)?.toString(); + + if (content && !content.includes('provideZoneChangeDetection(')) { + host.overwrite(appConfigPath, content.replace( + /providers:\s*\[/, + '$&\n provideZoneChangeDetection({ eventCoalescing: true }),' + )); } return host; } - - addHashLocation(host, filePath, router); - - const routesArgument = router.arguments[0]; - - if (!routesArgument || !isImportedFrom(source, routesArgument.getText(), appRoutesLocation)) { - context.logger.warn( - `DevExtreme layout routes were added to ${join(appPath, 'app.routes.ts')}, ` - + `but the router in ${filePath} uses other routes. Add the layout routes to the routes passed to provideRouter.` - ); - } - - return host; - }; + ]); } function getCdkVersion(angularCoreVersion: string = '') { @@ -418,8 +304,9 @@ function getCdkVersion(angularCoreVersion: string = '') { return version ? `^${version.major}.0.0` : 'latest'; } -function addPackagesToDependency() { +function addPackagesToDependency(zoneless: boolean) { return (host: Tree) => { + const zonejs = getPackageJsonDependency(host, 'zone.js'); const angularCore = getPackageJsonDependency(host, '@angular/core'); addPackageJsonDependency(host, { @@ -428,6 +315,14 @@ function addPackagesToDependency() { version: getCdkVersion(angularCore?.version) }); + if (!zoneless && !zonejs) { + addPackageJsonDependency(host, { + type: NodeDependencyType.Default, + name: 'zone.js', + version: '~0.16.0' + }); + } + return host; }; } @@ -534,7 +429,7 @@ export default function(options: any): Rule { const override = options.resolveConflicts === 'override'; const componentName = override ? 'app' : getComponentName(host, appPath); const pathToCss = sourcePath?.replace(/\/?(\w)+\/?/g, '../'); - const hasAppConfig = host.exists(join(appPath, 'app.config.ts')); + const zoneless = await isZonelessApp(host, project, appPath); const templateOptions = { name: setPostfix(host, componentName), @@ -555,10 +450,6 @@ export default function(options: any): Rule { return currentContent; } - if (basename(filePath) === 'app.config.ts') { - return currentContent; - } - return templateContent; }; @@ -569,11 +460,14 @@ export default function(options: any): Rule { addBuildThemeScript(), () => addCustomThemeStyles(host, options, sourcePath) as any, addViewportToBody(sourcePath), - addPackagesToDependency(), + addPackagesToDependency(zoneless), ]; - if (hasAppConfig) { - rules.push(updateAppConfig(appPath)); + if (!zoneless) { + rules.push( + addZoneChangeDetection(appPath), + () => addPolyfills(host, options.project, ['zone.js']) as any + ); } if (options.updateBudgets) { diff --git a/packages/devextreme-schematics/src/add-layout/index_spec.ts b/packages/devextreme-schematics/src/add-layout/index_spec.ts index 611b42aba..5b6543571 100644 --- a/packages/devextreme-schematics/src/add-layout/index_spec.ts +++ b/packages/devextreme-schematics/src/add-layout/index_spec.ts @@ -335,225 +335,71 @@ describe('layout', () => { }); describe('change detection', () => { - it('should not add zone.js to a zoneless app', async () => { - const runner = new SchematicTestRunner('schematics', collectionPath); - const tree = await runner.runSchematic('add-layout', options, appTree); - const angularContent = JSON.parse(tree.readContent('/angular.json')); + const zoneOptions = { ...options, resolveConflicts: 'override' }; - expect(JSON.parse(tree.readContent('package.json')).dependencies['zone.js']).toBeUndefined(); - expect(angularContent.projects.testApp.architect.build.options.polyfills || []).not.toContain('zone.js'); - expect(tree.readContent('/src/app/app.config.ts')).not.toContain('provideZoneChangeDetection'); - }); - - it('should keep zone change detection provided in app config', async () => { - appTree.create('/src/app/app.config.ts', [ - `import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';`, - `export const appConfig: ApplicationConfig = {`, - ` providers: [provideZoneChangeDetection({ eventCoalescing: true })]`, - `};` - ].join('\n')); + const setPolyfills = (polyfills: string | string[]) => { + modifyJSONFile(appTree, './angular.json', config => { + config.projects.testApp.architect.build.options.polyfills = polyfills; + return config; + }); + }; - const runner = new SchematicTestRunner('schematics', collectionPath); - const tree = await runner.runSchematic('add-layout', options, appTree); + const expectZoneApp = (tree: UnitTestTree) => { + const packageConfig = JSON.parse(tree.readContent('package.json')); const appConfig = tree.readContent('/src/app/app.config.ts'); - expect(appConfig).toContain(`import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';`); - expect(appConfig).toContain('provideZoneChangeDetection({ eventCoalescing: true })'); - }); - }); - - describe('app config', () => { - const createAppConfig = (content: string[]) => { - appTree.create('/src/app/app.config.ts', content.join('\n')); + expect(packageConfig.dependencies['zone.js']).toBeDefined(); + expect(appConfig).toMatch(/import { ApplicationConfig, provideZoneChangeDetection } from '@angular\/core';/); + expect(appConfig).toMatch(/providers: \[\s+provideZoneChangeDetection\({ eventCoalescing: true }\),/); }; - const runLayout = async () => { + it('should not add zone.js to a zoneless app', async () => { const runner = new SchematicTestRunner('schematics', collectionPath); - const warnings: string[] = []; - - runner.logger.subscribe((entry) => { - if (entry.level === 'warn') { - warnings.push(entry.message); - } - }); - - const tree = await runner.runSchematic('add-layout', options, appTree); - - return { appConfig: tree.readContent('/src/app/app.config.ts'), tree, warnings }; - }; + const tree = await runner.runSchematic('add-layout', zoneOptions, appTree); - it('should create app config from template if it does not exist', async () => { - const { appConfig, warnings } = await runLayout(); - - expect(appConfig).toContain('provideRouter(routes, withHashLocation())'); - expect(appConfig).not.toContain('./shared/services'); - expect(warnings).toEqual([]); - }); - - it('should add hash location to existing router and keep user providers', async () => { - createAppConfig([ - `import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';`, - `import { provideHttpClient } from '@angular/common/http';`, - `import { provideRouter } from '@angular/router';`, - `import { routes } from './app.routes';`, - ``, - `export const appConfig: ApplicationConfig = {`, - ` providers: [`, - ` provideBrowserGlobalErrorListeners(),`, - ` provideHttpClient(),`, - ` provideRouter(routes),`, - ` ]`, - `};` - ]); - - const { appConfig, warnings } = await runLayout(); - - expect(appConfig).toContain([ - ` providers: [`, - ` provideBrowserGlobalErrorListeners(),`, - ` provideHttpClient(),`, - ` provideRouter(routes, withHashLocation()),`, - ` ]`, - ].join('\n')); - expect(appConfig).toContain(`import { provideRouter, withHashLocation } from '@angular/router';`); - expect(appConfig.match(/import { routes }/g)).toHaveLength(1); - expect(warnings).toEqual([]); - }); - - it('should not change app config with hash location router', async () => { - const content = [ - `import { ApplicationConfig } from '@angular/core';`, - `import { provideRouter, withHashLocation } from '@angular/router';`, - `import { routes } from './app.routes';`, - ``, - `export const appConfig: ApplicationConfig = {`, - ` providers: [provideRouter(routes, withHashLocation())]`, - `};` - ]; - createAppConfig(content); - - const { appConfig, warnings } = await runLayout(); + const packageConfig = JSON.parse(tree.readContent('package.json')); + const angularContent = JSON.parse(tree.readContent('/angular.json')); + const polyfills = angularContent.projects.testApp.architect.build.options.polyfills || []; - expect(appConfig).toBe(content.join('\n')); - expect(warnings).toEqual([]); + expect(packageConfig.dependencies['zone.js']).toBeUndefined(); + expect(polyfills).not.toContain('zone.js'); + expect(tree.readContent('/src/app/app.config.ts')).not.toContain('provideZoneChangeDetection'); }); - it('should add hash location to router call with trailing comma', async () => { - createAppConfig([ - `import { ApplicationConfig } from '@angular/core';`, - `import { provideRouter } from '@angular/router';`, - `import { routes } from './app.routes';`, - ``, - `export const appConfig: ApplicationConfig = {`, - ` providers: [provideRouter(routes,)]`, - `};` - ]); + it('should keep zone change detection if zone.js is in polyfills', async () => { + setPolyfills(['zone.js']); - const { appConfig } = await runLayout(); + const runner = new SchematicTestRunner('schematics', collectionPath); + const tree = await runner.runSchematic('add-layout', zoneOptions, appTree); - expect(appConfig).toContain('provideRouter(routes, withHashLocation(),)'); + expectZoneApp(tree); }); - it('should add hash location to router outside of providers literal', async () => { - createAppConfig([ - `import { ApplicationConfig } from '@angular/core';`, - `import { provideHttpClient } from '@angular/common/http';`, - `import { provideRouter } from '@angular/router';`, - `import { routes } from './app.routes';`, - ``, - `const appProviders = [provideHttpClient(), provideRouter(routes)];`, - ``, - `export const appConfig: ApplicationConfig = {`, - ` providers: appProviders`, - `};` - ]); + it('should keep zone change detection if zone.js is imported in a polyfills file', async () => { + setPolyfills('src/polyfills.ts'); + appTree.create('/src/polyfills.ts', `import 'zone.js';`); - const { appConfig, warnings } = await runLayout(); + const runner = new SchematicTestRunner('schematics', collectionPath); + const tree = await runner.runSchematic('add-layout', zoneOptions, appTree); - expect(appConfig).toContain( - 'const appProviders = [provideHttpClient(), provideRouter(routes, withHashLocation())];' - ); - expect(appConfig).toContain('providers: appProviders'); - expect(warnings).toEqual([]); + expectZoneApp(tree); + const angularContent = JSON.parse(tree.readContent('/angular.json')); + expect(angularContent.projects.testApp.architect.build.options.polyfills) + .toEqual(['src/polyfills.ts', 'zone.js']); }); - it('should add router to app config without routing', async () => { - createAppConfig([ - `import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';`, - ``, + it('should keep zone change detection if app config provides it', async () => { + appTree.create('/src/app/app.config.ts', [ + `import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';`, `export const appConfig: ApplicationConfig = {`, - ` providers: [`, - ` provideBrowserGlobalErrorListeners(),`, - ` ]`, + ` providers: [provideZoneChangeDetection()]`, `};` - ]); - - const { appConfig, tree, warnings } = await runLayout(); - - expect(appConfig).toContain([ - ` provideBrowserGlobalErrorListeners(),`, - ` provideRouter(routes, withHashLocation()),`, ].join('\n')); - expect(appConfig).toContain(`import { provideRouter, withHashLocation } from '@angular/router';`); - expect(appConfig).toContain(`import { routes } from './app.routes';`); - expect(tree.files).toContain('/src/app/app.routes.ts'); - expect(warnings).toEqual([]); - }); - - it('should warn and keep app config if routes name is taken', async () => { - const content = [ - `import { ApplicationConfig } from '@angular/core';`, - ``, - `const routes = [];`, - ``, - `export const appConfig: ApplicationConfig = {`, - ` providers: []`, - `};` - ]; - createAppConfig(content); - - const { appConfig, warnings } = await runLayout(); - expect(appConfig).toBe(content.join('\n')); - expect(warnings).toHaveLength(1); - expect(warnings[0]).toContain('Could not register the router'); - }); - - it('should warn and keep app config if providers are not a literal array', async () => { - const content = [ - `import { ApplicationConfig } from '@angular/core';`, - `import { appProviders } from './app.providers';`, - ``, - `export const appConfig: ApplicationConfig = {`, - ` providers: [...appProviders]`, - `};` - ]; - createAppConfig(content); - - const { appConfig, warnings } = await runLayout(); - - expect(appConfig).toBe(content.join('\n')); - expect(warnings).toHaveLength(1); - expect(warnings[0]).toContain('Could not register the router'); - }); - - it('should warn if router uses other routes', async () => { - createAppConfig([ - `import { ApplicationConfig } from '@angular/core';`, - `import { provideRouter } from '@angular/router';`, - `import { myRoutes } from './my.routes';`, - ``, - `export const appConfig: ApplicationConfig = {`, - ` providers: [provideRouter(myRoutes)]`, - `};` - ]); - - const { appConfig, warnings } = await runLayout(); + const runner = new SchematicTestRunner('schematics', collectionPath); + const tree = await runner.runSchematic('add-layout', zoneOptions, appTree); - expect(appConfig).toContain('provideRouter(myRoutes, withHashLocation())'); - expect(appConfig).not.toContain('./app.routes'); - expect(warnings).toHaveLength(1); - expect(warnings[0]).toContain('uses other routes'); + expectZoneApp(tree); }); }); }); diff --git a/packages/devextreme-schematics/src/utility/change.ts b/packages/devextreme-schematics/src/utility/change.ts index 8dbccb583..09b4303b6 100644 --- a/packages/devextreme-schematics/src/utility/change.ts +++ b/packages/devextreme-schematics/src/utility/change.ts @@ -11,10 +11,8 @@ const newLine = ` export function applyChanges(host: Tree, changes: Change[], filePath: string) { const recorder = host.beginUpdate(filePath); - changes.forEach((change) => { - if (change instanceof InsertChange) { - recorder.insertLeft(change.pos, change.toAdd); - } + changes.forEach((change: InsertChange) => { + recorder.insertLeft(change.pos, change.toAdd); }); host.commitUpdate(recorder); diff --git a/packages/devextreme-schematics/src/utility/zone.ts b/packages/devextreme-schematics/src/utility/zone.ts new file mode 100644 index 000000000..6ac0dbf63 --- /dev/null +++ b/packages/devextreme-schematics/src/utility/zone.ts @@ -0,0 +1,29 @@ +import { Tree } from '@angular-devkit/schematics'; +import { getWorkspace } from '@schematics/angular/utility/workspace'; +import { join } from 'path'; + +function readFile(host: Tree, path?: string) { + return path && host.exists(path) ? host.read(path)!.toString() : ''; +} + +export async function isZonelessApp(host: Tree, projectName: string, appPath: string) { + const workspace = await getWorkspace(host); + const buildOptions = workspace.projects.get(projectName)?.targets.get('build')?.options || {}; + const mainPath = (buildOptions.browser || buildOptions.main) as string | undefined; + const bootstrapSource = readFile(host, join(appPath, 'app.config.ts')) + readFile(host, mainPath); + + if (/provideZoneChangeDetection\s*\(/.test(bootstrapSource)) { + return false; + } + + if (/provideZonelessChangeDetection\s*\(/.test(bootstrapSource)) { + return true; + } + + const polyfills = buildOptions.polyfills; + const polyfillList = (Array.isArray(polyfills) ? polyfills : [polyfills]).filter(Boolean) as string[]; + + return !polyfillList.some((polyfill) => + polyfill === 'zone.js' || /['"]zone\.js['"]/.test(readFile(host, polyfill)) + ); +} From d80b26bd24d40394791b5e53be3fe280b6e519da Mon Sep 17 00:00:00 2001 From: Andrei Vorobev <738482+vorobey@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:37:19 +0200 Subject: [PATCH 13/14] revert and use EJS templates for app.config.ts --- .../add-layout/files/src/app/app.config.ts | 15 ++-------- .../app/shared/services/app-info.service.ts | 2 +- .../src/app/shared/services/auth.service.ts | 4 +-- .../src/app/shared/services/screen.service.ts | 2 +- .../src/add-layout/index.ts | 30 ++----------------- 5 files changed, 10 insertions(+), 43 deletions(-) diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts index d3d907886..5ba816eba 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/app.config.ts @@ -1,19 +1,10 @@ -import { ApplicationConfig } from '@angular/core'; +import { ApplicationConfig<% if (!zoneless) { %>, provideZoneChangeDetection<% } %> } from '@angular/core'; import { provideRouter, withHashLocation } from '@angular/router'; import { routes } from './app.routes'; -import { - AppInfoService, - AuthGuardService, - AuthService, - ScreenService, -} from './shared/services'; export const appConfig: ApplicationConfig = { - providers: [ + providers: [<% if (!zoneless) { %> + provideZoneChangeDetection({ eventCoalescing: true }),<% } %> provideRouter(routes, withHashLocation()), - AuthGuardService, - AuthService, - ScreenService, - AppInfoService, ] }; diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/app-info.service.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/app-info.service.ts index bf39e60a6..bd7390b38 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/app-info.service.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/app-info.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; -@Injectable() +@Injectable({ providedIn: 'root' }) export class AppInfoService { constructor() {} diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts index 162c00558..7328e6e3d 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts @@ -12,7 +12,7 @@ const defaultUser = { avatarUrl: 'https://js.devexpress.com/Demos/WidgetsGallery/JSDemos/images/employees/06.png' }; -@Injectable() +@Injectable({ providedIn: 'root' }) export class AuthService { private _user: IUser | null = defaultUser; get loggedIn(): boolean { @@ -118,7 +118,7 @@ export class AuthService { } } -@Injectable() +@Injectable({ providedIn: 'root' }) export class AuthGuardService implements CanActivate { constructor(private router: Router, private authService: AuthService) { } diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts index d5c07faf4..def101b36 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/screen.service.ts @@ -1,7 +1,7 @@ import { Output, Injectable, EventEmitter, WritableSignal, signal } from '@angular/core'; import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'; -@Injectable() +@Injectable({ providedIn: 'root' }) export class ScreenService { @Output() changed = new EventEmitter(); diff --git a/packages/devextreme-schematics/src/add-layout/index.ts b/packages/devextreme-schematics/src/add-layout/index.ts index d79784b39..012e6442b 100644 --- a/packages/devextreme-schematics/src/add-layout/index.ts +++ b/packages/devextreme-schematics/src/add-layout/index.ts @@ -273,28 +273,6 @@ function hasRouting(host: Tree, sourcePath: string) { return host.exists(sourcePath + 'app.routes.ts'); } -function addZoneChangeDetection(appPath: string) { - const appConfigPath = join(appPath, 'app.config.ts'); - - return chain([ - modifyFileRule(appConfigPath, (source: SourceFile) => [ - insertImport(source, appConfigPath, 'provideZoneChangeDetection', '@angular/core') - ]), - (host: Tree) => { - const content = host.read(appConfigPath)?.toString(); - - if (content && !content.includes('provideZoneChangeDetection(')) { - host.overwrite(appConfigPath, content.replace( - /providers:\s*\[/, - '$&\n provideZoneChangeDetection({ eventCoalescing: true }),' - )); - } - - return host; - } - ]); -} - function getCdkVersion(angularCoreVersion: string = '') { if (angularCoreVersion.includes('next')) { return 'next'; @@ -437,7 +415,8 @@ export default function(options: any): Rule { title, strings, path: pathToCss, - prefix + prefix, + zoneless }; const modifyContent = (templateContent: string, currentContent: string, filePath: string) => { @@ -464,10 +443,7 @@ export default function(options: any): Rule { ]; if (!zoneless) { - rules.push( - addZoneChangeDetection(appPath), - () => addPolyfills(host, options.project, ['zone.js']) as any - ); + rules.push(() => addPolyfills(host, options.project, ['zone.js']) as any); } if (options.updateBudgets) { From 1239898f82bf1fb7a5f8351d5ed8b4af1fefcc13 Mon Sep 17 00:00:00 2001 From: Andrei Vorobev <738482+vorobey@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:45:48 +0200 Subject: [PATCH 14/14] PR comments changes --- .../files/src/app/shared/services/auth.service.ts | 14 +++++++------- .../src/add-layout/index_spec.ts | 12 +++++++++++- .../src/utility/angular-version.ts | 6 +++--- packages/devextreme-schematics/src/utility/zone.ts | 5 +++-- 4 files changed, 24 insertions(+), 13 deletions(-) diff --git a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts index 7328e6e3d..b04249b86 100644 --- a/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts +++ b/packages/devextreme-schematics/src/add-layout/files/src/app/shared/services/auth.service.ts @@ -1,4 +1,4 @@ -import { Injectable } from '@angular/core'; +import { Injectable, signal } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot } from '@angular/router'; export interface IUser { @@ -14,9 +14,9 @@ const defaultUser = { @Injectable({ providedIn: 'root' }) export class AuthService { - private _user: IUser | null = defaultUser; + private _user = signal(defaultUser); get loggedIn(): boolean { - return !!this._user; + return !!this._user(); } private _lastAuthenticatedPath: string = defaultPath; @@ -30,12 +30,12 @@ export class AuthService { try { // Send request - this._user = { ...defaultUser, email }; + this._user.set({ ...defaultUser, email }); this.router.navigate([this._lastAuthenticatedPath]); return { isOk: true, - data: this._user + data: this._user() }; } catch { @@ -52,7 +52,7 @@ export class AuthService { return { isOk: true, - data: this._user + data: this._user() }; } catch { @@ -113,7 +113,7 @@ export class AuthService { } async logOut() { - this._user = null; + this._user.set(null); this.router.navigate(['/login-form']); } } diff --git a/packages/devextreme-schematics/src/add-layout/index_spec.ts b/packages/devextreme-schematics/src/add-layout/index_spec.ts index 5b6543571..88f09bab7 100644 --- a/packages/devextreme-schematics/src/add-layout/index_spec.ts +++ b/packages/devextreme-schematics/src/add-layout/index_spec.ts @@ -177,7 +177,7 @@ describe('layout', () => { [ { angularCore: '~21.2.0', cdk: '^21.0.0' }, { angularCore: '^22.0.0', cdk: '^22.0.0' }, - { angularCore: 'next', cdk: 'next' }, + { angularCore: '^22.0.0-next.3', cdk: 'next' }, ].forEach(({ angularCore, cdk }) => { it(`should choose angular/cdk ${cdk} for angular/core ${angularCore}`, async () => { removePackageJsonDependency(appTree, '@angular/core'); @@ -388,6 +388,16 @@ describe('layout', () => { .toEqual(['src/polyfills.ts', 'zone.js']); }); + it('should keep zone change detection if zone.js is imported in main file', async () => { + const mainPath = '/src/main.ts'; + appTree.overwrite(mainPath, `import 'zone.js';\n${appTree.readContent(mainPath)}`); + + const runner = new SchematicTestRunner('schematics', collectionPath); + const tree = await runner.runSchematic('add-layout', zoneOptions, appTree); + + expectZoneApp(tree); + }); + it('should keep zone change detection if app config provides it', async () => { appTree.create('/src/app/app.config.ts', [ `import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';`, diff --git a/packages/devextreme-schematics/src/utility/angular-version.ts b/packages/devextreme-schematics/src/utility/angular-version.ts index 3af30ac5c..9f793157d 100644 --- a/packages/devextreme-schematics/src/utility/angular-version.ts +++ b/packages/devextreme-schematics/src/utility/angular-version.ts @@ -5,9 +5,9 @@ export function getAngularVersion(host: Tree): number { const packageJson = JSON.parse(host.read('package.json')?.toString() || '{}'); const angularCore = packageJson.dependencies?.['@angular/core']; - if (angularCore) { - const version = coerce(angularCore); - return version ? version.major : Number.MAX_SAFE_INTEGER; + const version = coerce(angularCore); + if (version) { + return version.major; } throw new Error('Angular version not found'); diff --git a/packages/devextreme-schematics/src/utility/zone.ts b/packages/devextreme-schematics/src/utility/zone.ts index 6ac0dbf63..b6d63f8f9 100644 --- a/packages/devextreme-schematics/src/utility/zone.ts +++ b/packages/devextreme-schematics/src/utility/zone.ts @@ -20,10 +20,11 @@ export async function isZonelessApp(host: Tree, projectName: string, appPath: st return true; } + const hasZoneImport = (path?: string) => /['"]zone\.js['"]/.test(readFile(host, path)); const polyfills = buildOptions.polyfills; const polyfillList = (Array.isArray(polyfills) ? polyfills : [polyfills]).filter(Boolean) as string[]; - return !polyfillList.some((polyfill) => - polyfill === 'zone.js' || /['"]zone\.js['"]/.test(readFile(host, polyfill)) + return !hasZoneImport(mainPath) && !polyfillList.some((polyfill) => + polyfill === 'zone.js' || hasZoneImport(polyfill) ); }