Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use generics in generator-angular #27550

Merged
merged 27 commits into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 18 additions & 153 deletions generators/angular/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { camelCase } from 'lodash-es';
import chalk from 'chalk';
import { isFileStateModified } from 'mem-fs-editor/state';

import BaseApplicationGenerator from '../base-application/index.js';
import { GENERATOR_ANGULAR, GENERATOR_CLIENT, GENERATOR_LANGUAGES } from '../generator-list.js';
import { defaultLanguage } from '../languages/support/index.js';
import { clientFrameworkTypes } from '../../lib/jhipster/index.js';
import { generateEntityClientEnumImports as getClientEnumImportsFormat } from '../client/support/index.js';
import { createNeedleCallback, mutateData } from '../base/support/index.js';
import { writeEslintClientRootConfigFile } from '../javascript/generators/eslint/support/tasks.js';
import type { PostWritingEntitiesTaskParam } from '../../lib/types/application/tasks.js';
import type { TaskTypes as DefaultTaskTypes } from '../../lib/types/application/tasks.js';
import { cleanupEntitiesFiles, postWriteEntitiesFiles, writeEntitiesFiles } from './entity-files-angular.js';
import { writeFiles } from './files-angular.js';
import cleanupOldFilesTask from './cleanup.js';
Expand All @@ -41,12 +39,11 @@ import {
isTranslatedAngularFile,
translateAngularFilesTransform,
} from './support/index.js';
import type { AngularApplication, AngularEntity } from './types.js';

const { ANGULAR } = clientFrameworkTypes;

export default class AngularGenerator extends BaseApplicationGenerator {
localEntities?: any[];

export default class AngularGenerator extends BaseApplicationGenerator<DefaultTaskTypes<AngularEntity, AngularApplication>> {
async beforeQueue() {
if (!this.fromBlueprint) {
await this.composeWithBlueprints();
Expand Down Expand Up @@ -88,7 +85,6 @@ export default class AngularGenerator extends BaseApplicationGenerator {
webappEnumerationsDir: app => `${app.clientSrcDir}app/entities/enumerations/`,
angularLocaleId: app => app.nativeLanguageDefinition.angularLocale ?? defaultLanguage.angularLocale!,
});

application.addPrettierExtensions?.(['html', 'css', 'scss']);
},
async javaNodeBuildPaths({ application }) {
Expand All @@ -104,10 +100,16 @@ export default class AngularGenerator extends BaseApplicationGenerator {
},
addNeedles({ source, application }) {
source.addEntitiesToClient = param => {
this.addEntitiesToModule(param);
this.addEntitiesToMenu(param);
const routeTemplatePath = `${param.application.clientSrcDir}app/entities/entity.routes.ts`;
const ignoreNonExistingRoute = chalk.yellow(`Route(s) not added to ${routeTemplatePath}.`);
const addRouteCallback = addEntitiesRoute(param);
this.editFile(routeTemplatePath, { ignoreNonExisting: ignoreNonExistingRoute }, addRouteCallback);

const filePath = `${application.clientSrcDir}app/layouts/navbar/navbar.component.html`;
const ignoreNonExisting = chalk.yellow('Reference to entities not added to menu.');
const editCallback = addToEntitiesMenu(param);
this.editFile(filePath, { ignoreNonExisting }, editCallback);
};

source.addAdminRoute = (args: Omit<Parameters<typeof addRoute>[0], 'needle'>) =>
this.editFile(
`${application.srcMainWebapp}app/admin/admin.routes.ts`,
Expand Down Expand Up @@ -202,6 +204,9 @@ export default class AngularGenerator extends BaseApplicationGenerator {
...(entity.entityReadAuthority?.split(',') ?? []),
]),
});
entity.generateEntityClientEnumImports = fields => {
return getClientEnumImportsFormat(fields, ANGULAR);
};
},
});
}
Expand Down Expand Up @@ -234,7 +239,6 @@ export default class AngularGenerator extends BaseApplicationGenerator {
returnValue = fieldDefaultValue;
}
}

return returnValue;
},
} as any);
Expand All @@ -248,9 +252,9 @@ export default class AngularGenerator extends BaseApplicationGenerator {

get default() {
return this.asDefaultTaskGroup({
loadEntities() {
loadEntities({ application }) {
const entities = this.sharedData.getEntities().map(({ entity }) => entity);
this.localEntities = entities.filter(entity => !entity.builtIn && !entity.skipClient);
application.angularEntities = entities.filter(entity => !entity.builtIn && !entity.skipClient) as AngularEntity[];
},
queueTranslateTransform({ control, application }) {
const { enableTranslation, jhiPrefix } = application;
Expand All @@ -260,7 +264,7 @@ export default class AngularGenerator extends BaseApplicationGenerator {
filter: file => isFileStateModified(file) && file.path.startsWith(this.destinationPath()) && isTranslatedAngularFile(file),
refresh: false,
},
translateAngularFilesTransform(control.getWebappTranslation, { enableTranslation, jhiPrefix }),
translateAngularFilesTransform(control.getWebappTranslation!, { enableTranslation, jhiPrefix }),
);
},
});
Expand Down Expand Up @@ -387,143 +391,4 @@ export default class AngularGenerator extends BaseApplicationGenerator {
get [BaseApplicationGenerator.END]() {
return this.delegateTasksToBlueprint(() => this.end);
}

/**
* @private
* Add new scss style to the angular application in "vendor.scss".
*
* @param {string} style - scss to add in the file
* @param {string} comment - comment to add before css code
*
* example:
*
* style = '.success {\n @extend .message;\n border-color: green;\n}'
* comment = 'Message'
*
* * ==========================================================================
* Message
* ========================================================================== *
* .success {
* @extend .message;
* border-color: green;
* }
*
*/
addVendorSCSSStyle(style, comment?) {
this.needleApi.clientAngular.addVendorSCSSStyle(style, comment);
}

/**
* @private
* Add a new lazy loaded module to admin routing file.
*
* @param {string} route - The route for the module. For example 'entity-audit'.
* @param {string} modulePath - The path to the module file. For example './entity-audit/entity-audit.module'.
* @param {string} moduleName - The name of the module. For example 'EntityAuditModule'.
* @param {string} pageTitle - The translation key if i18n is enabled or the text if i18n is disabled for the page title in the browser.
* For example 'entityAudit.home.title' for i18n enabled or 'Entity audit' for i18n disabled.
* If undefined then application global page title is used in the browser title bar.
*/
addAdminRoute(route, modulePath, moduleName, pageTitle) {
this.needleApi.clientAngular.addAdminRoute(route, modulePath, moduleName, pageTitle);
}

/**
* @private
* Add a new module in the TS modules file.
*
* @param {string} appName - Angular2 application name.
* @param {string} angularName - The name of the new admin item.
* @param {string} folderName - The name of the folder.
* @param {string} fileName - The name of the file.
* @param {boolean} enableTranslation - If translations are enabled or not.
* @param {string} clientFramework - The name of the client framework.
*/
addAngularModule(appName, angularName, folderName, fileName, enableTranslation) {
this.needleApi.clientAngular.addModule(appName, angularName, folderName, fileName, enableTranslation);
}

/**
* @private
* Add a new icon to icon imports.
*
* @param {string} iconName - The name of the Font Awesome icon.
*/
addIcon(iconName) {
this.needleApi.clientAngular.addIcon(iconName);
}

/**
* Add a new menu element to the admin menu.
*
* @param {string} routerName - The name of the Angular router that is added to the admin menu.
* @param {string} iconName - The name of the Font Awesome icon that will be displayed.
* @param {boolean} enableTranslation - If translations are enabled or not
* @param {string} translationKeyMenu - i18n key for entry in the admin menu
*/
addElementToAdminMenu(routerName, iconName, enableTranslation, translationKeyMenu = camelCase(routerName), jhiPrefix?) {
this.needleApi.clientAngular.addElementToAdminMenu(routerName, iconName, enableTranslation, translationKeyMenu, jhiPrefix);
}

addEntitiesToMenu({ application, entities }: Pick<PostWritingEntitiesTaskParam, 'application' | 'entities'>) {
const filePath = `${application.clientSrcDir}app/layouts/navbar/navbar.component.html`;
const ignoreNonExisting = chalk.yellow('Reference to entities not added to menu.');
const editCallback = addToEntitiesMenu({ application, entities });

this.editFile(filePath, { ignoreNonExisting }, editCallback);
}

addEntitiesToModule(param: Pick<PostWritingEntitiesTaskParam, 'application' | 'entities'>) {
const filePath = `${param.application.clientSrcDir}app/entities/entity.routes.ts`;
const ignoreNonExisting = chalk.yellow(`Route(s) not added to ${filePath}.`);
const addRouteCallback = addEntitiesRoute(param);
this.editFile(filePath, { ignoreNonExisting }, addRouteCallback);
}

/**
* @private
* Add new scss style to the angular application in "global.scss
*
* @param {string} style - css to add in the file
* @param {string} comment - comment to add before css code
*
* example:
*
* style = '.jhipster {\n color: #baa186;\n}'
* comment = 'New JHipster color'
*
* * ==========================================================================
* New JHipster color
* ========================================================================== *
* .jhipster {
* color: #baa186;
* }
*
*/
addMainSCSSStyle(style, comment?) {
this.needleApi.clientAngular.addGlobalSCSSStyle(style, comment);
}

/**
* Returns the typescript import section of enums referenced by all fields of the entity.
* @param fields returns the import of enums that are referenced by the fields
* @returns {typeImports:Map} the fields that potentially contains some enum types
*/
generateEntityClientEnumImports(fields) {
return getClientEnumImportsFormat(fields, ANGULAR);
}

/**
* @private
* Add a new menu element, at the root of the menu.
*
* @param {string} routerName - The name of the router that is added to the menu.
* @param {string} iconName - The name of the Font Awesome icon that will be displayed.
* @param {boolean} enableTranslation - If translations are enabled or not
* @param {string} clientFramework - The name of the client framework
* @param {string} translationKeyMenu - i18n key for entry in the menu
*/
addElementToMenu(routerName, iconName, enableTranslation, _clientFramework?, translationKeyMenu = camelCase(routerName)) {
this.needleApi.clientAngular.addElementToMenu(routerName, iconName, enableTranslation, translationKeyMenu);
}
}
11 changes: 4 additions & 7 deletions generators/angular/support/translate-angular.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,9 @@ export type ReplacerOptions = { jhiPrefix: string; enableTranslation: boolean };
* Replace translation key with translation values
*
* @param {import('../generator-base.js')} generator
* @param getWebappTranslation
* @param {string} content
* @param {string} regexSource regular expression to find keys
* @param {object} [options]
* @param {number} [options.keyIndex]
* @param {number} [options.replacementIndex]
* @param {any} [options.escape]
* @returns {string}
*/
function replaceTranslationKeysWithText(
Expand Down Expand Up @@ -305,7 +302,7 @@ export const createTranslationReplacer = (getWebappTranslation: GetWebappTransla
{ prefixPattern: '>\\s*', suffixPattern: '\\s*<' },
);
}
return function replaceAngularTranslations(content, filePath) {
return function replaceAngularTranslations(content: string, filePath: string) {
if (filePath.endsWith('.html')) {
if (!enableTranslation) {
content = content.replace(new RegExp(TRANSLATE_REGEX, 'g'), '');
Expand All @@ -318,7 +315,7 @@ export const createTranslationReplacer = (getWebappTranslation: GetWebappTransla
content = htmlJhiTranslateStringifyReplacer(content);
}
if (/(:?\.html|.ts)$/.test(filePath)) {
content = translationReplacer?.(content, filePath);
content = translationReplacer ? translationReplacer?.(content, filePath) : content;
}
if (!enableTranslation) {
if (/(:?route|module)\.ts$/.test(filePath)) {
Expand All @@ -335,7 +332,7 @@ export const createTranslationReplacer = (getWebappTranslation: GetWebappTransla
const minimatch = new Minimatch('**/*{.html,.ts}');
export const isTranslatedAngularFile = file => minimatch.match(file.path);

export const translateAngularFilesTransform = (getWebappTranslation, opts: ReplacerOptions | boolean) => {
export const translateAngularFilesTransform = (getWebappTranslation: GetWebappTranslationCallback, opts: ReplacerOptions | boolean) => {
const translate = createTranslationReplacer(getWebappTranslation, opts);
return passthrough(file => {
file.contents = Buffer.from(translate(file.contents.toString(), file.path));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
limitations under the License.
-%>
<%
const enumImports = this.generateEntityClientEnumImports(fields);
const enumImports = generateEntityClientEnumImports(fields);
%>
<%_ if (anyFieldIsDateDerived) { _%>
import dayjs from 'dayjs/esm';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
limitations under the License.
-%>
<%_
const enumImports = this.generateEntityClientEnumImports(fields);
const enumImports = generateEntityClientEnumImports(fields);
_%>
<%_ if (anyFieldIsDateDerived) { _%>
import dayjs from 'dayjs/esm';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
-%>
<%_
const tsKeyId = primaryKey.tsSampleValues[0];
const enumImports = this.generateEntityClientEnumImports(fields);
const enumImports = generateEntityClientEnumImports(fields);
_%>
import { TestBed } from '@angular/core/testing';
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ import { <%= uniqueRel.otherEntityAngularName %>Service } from 'app/entities/<%=
}
}
_%>
<%_ const enumImports = this.generateEntityClientEnumImports(fields); _%>
<%_ const enumImports = generateEntityClientEnumImports(fields); _%>
<%_ enumImports.forEach( (importedPath, importedType) => { _%>
import { <%- importedType %> } from '<%- importedPath %>';
<%_ }); _%>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import NavbarItem from 'app/layouts/navbar/navbar-item.model';

export const EntityNavbarItems: NavbarItem[] = [
<%_ for (const entity of this.localEntities) { _%>
<%_ for (const entity of angularEntities) { _%>
{
name: '<%= entity.entityAngularName %>',
route: '/<%= entity.entityPage %>',
Expand Down
32 changes: 32 additions & 0 deletions generators/angular/types-partial.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Copyright 2013-2024 the original author or authors from the JHipster project.
*
* This file is part of the JHipster project, see https://www.jhipster.tech/
* for more information.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @deprecated Will be deprecated and merged into types.d/AngularApplication
*/
export type PartialAngularApplication = {
angularLocaleId: string;
};

/**
* @deprecated Will be deprecated and merged into types.d/AngularEntity
*/
export type PartialAngularEntity = {
entityAngularAuthorities?: string;
entityAngularReadAuthorities?: string;
};
Loading
Loading