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

hapify generator angular models components #578

Draft
wants to merge 6 commits into
base: STAK-709/angular-generators
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,5 +74,6 @@ export default {
'<rootDir>/apps/pwa',
'<rootDir>/libs/nestjs/password',
'<rootDir>/libs/hapify/core',
'<rootDir>/libs/hapify/generators/angular-models-components',
],
};
3 changes: 3 additions & 0 deletions libs/hapify/generators/angular-models-components/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": [["@nrwl/web/babel", { "useBuiltIns": "usage" }]]
}
18 changes: 18 additions & 0 deletions libs/hapify/generators/angular-models-components/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": ["../../../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}
13 changes: 13 additions & 0 deletions libs/hapify/generators/angular-models-components/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# hapify-generators-angular-models-components

This library was generated with [Nx](https://nx.dev).

## Running unit tests

Run `nx test hapify-generators-angular-models-components` to execute the unit
tests via [Jest](https://jestjs.io).

## Running lint

Run `nx lint hapify-generators-angular-models-components` to execute the lint
via [ESLint](https://eslint.org/).
17 changes: 17 additions & 0 deletions libs/hapify/generators/angular-models-components/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/* eslint-disable */
export default {
displayName: 'hapify-generators-angular-models-components',
preset: '../../../../jest.preset.js',
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
},
},
testEnvironment: 'node',
transform: {
'^.+\\.[tj]sx?$': 'ts-jest',
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory:
'../../../../coverage/libs/hapify/generators/angular-models-components',
};
39 changes: 39 additions & 0 deletions libs/hapify/generators/angular-models-components/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
"name": "hapify-generators-angular-models-components",
"projectType": "library",
"sourceRoot": "libs/hapify/generators/angular-models-components/src",
"tags": [],
"targets": {
"lint": {
"executor": "@nrwl/linter:eslint",
"options": {
"lintFilePatterns": [
"libs/hapify/generators/angular-models-components/**/*.ts"
]
},
"outputs": ["{options.outputFile}"]
},
"test": {
"executor": "@nrwl/jest:jest",
"options": {
"jestConfig": "libs/hapify/generators/angular-models-components/jest.config.ts",
"passWithNoTests": true
},
"outputs": ["coverage/libs/hapify/generators/angular-models-components"]
},
"ts-morph-generate": {
"executor": "nx:run-commands",
"options": {
"commands": [
{
"command": "npx ts-node -r tsconfig-paths/register --project ./tsconfig.lib.json ./src/start.ts",
"forwardAllArgs": false
}
],
"cwd": "libs/hapify/generators/angular-models-components",
"parallel": false
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './lib/generate';
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import * as path from 'path';

import { Project } from 'ts-morph';

import { generateComponentSourceFile } from './generators/components/component.generator';
import { generateModuleSourceFile } from './generators/module.generators';
import { generateStorySourceFile } from './generators/stories/story.generator';
import { generateTemplateSourceFile } from './generators/templates/template.generator';
import {
generateDirectoryIndexExporter,
generateFileIndexExporter,
} from './utils/index.generator';

import { kebab, Project as Models } from '@trxn/hapify-core';

export type AngularServiceGeneratorConfig = {
outputDirectory: string;
tsConfigFilePath: string;
generatedDirectory: string;
projectScope: string;
};

export function generate(
project: Project,
dataModel: Models,
config: AngularServiceGeneratorConfig,
) {
const {
generatedDirectory,
tsConfigFilePath,
outputDirectory,
projectScope,
} = config;
const absoluteTsConfigFilePath = path.resolve(
outputDirectory,
tsConfigFilePath,
);
const absoluteGeneratedDirectory = path.resolve(
outputDirectory,
generatedDirectory,
);

project.addSourceFilesFromTsConfig(absoluteTsConfigFilePath);

const projectEntity = `${absoluteGeneratedDirectory}/components`;

// Clear generation directory
project.getDirectory(absoluteGeneratedDirectory)?.clear();

// Generate source files for each field of every model: directive, validator, service
dataModel.models.forEach((model) => {
model.fields.forEach((field) => {
if (field.name === 'Id') return;
// Generate component.ts
generateComponentSourceFile(project, model, field, projectEntity,projectScope)
// Generate component.stories.ts
generateStorySourceFile(project, model, field, projectEntity, projectScope)
// Generate index.ts for export
generateFileIndexExporter(project, `${projectEntity}/${kebab(model.name)}-${kebab(field.name)}`);
// Generate component.html
generateTemplateSourceFile(project, model, field, projectEntity, projectScope)
});
});

// Generate module
generateModuleSourceFile(project, absoluteGeneratedDirectory);

// Generate index.ts for export
generateDirectoryIndexExporter(project, projectEntity);


// for each directory, generate index.ts for export
generateFileIndexExporter(
project,
absoluteGeneratedDirectory
);
generateDirectoryIndexExporter(
project,
absoluteGeneratedDirectory
);

// Save project to file system
project.saveSync();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@


import { plural } from 'pluralize';
import {
ClassDeclarationStructure,
MethodDeclarationStructure,
OptionalKind,
Project,
PropertyDeclarationStructure,
StructureKind,
} from 'ts-morph';

import { generateConstructor } from './constructor.generator';
import { generateDecorator } from './decorator.generator';
import { generateImports } from './imports.generator';

import { camel, Field, kebab, Model, pascal } from '@trxn/hapify-core';
import { generateFilePath } from '../../utils/file.generator';

export function generateComponentClass(
model: Model,
field: Field,
projectScope: string,
): ClassDeclarationStructure {
const className = `${pascal(model.name)}${pascal(field.name)}Component`;

const methods: OptionalKind<MethodDeclarationStructure>[] = [
{
name: 'get validator',
hasOverrideKeyword: true,
returnType: '(control: AbstractControl) => ValidationErrors | null',
statements: [
`return this.${camel(model.name)}${pascal(
field.name,
)}Validator.validate;`,
],
},
];

const properties: OptionalKind<PropertyDeclarationStructure>[] = [
{
name: 'control',
type: 'FormControl',
initializer: "new FormControl('')",
},
];

return {
kind: StructureKind.Class,
name: className,
isExported: true,
decorators: generateDecorator(model, field, projectScope),
properties,
extends: 'BaseControlValueAccessorComponent',
implements: ['OnInit'],
methods,
ctors: generateConstructor(model, field),
};
}

export function generateComponentSourceFile(
project: Project,
model: Model,
field: Field,
path: string,
projectScope: string,
) {
const filePath: string = generateFilePath(model.name, field.name, 'component.ts', path);

const sourceFile = project.createSourceFile(filePath);

const directiveClass = generateComponentClass(model, field, projectScope);

const imports = generateImports(model, field, projectScope);

sourceFile.addImportDeclarations(imports);

sourceFile.addClass(directiveClass);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@

import {
ConstructorDeclarationStructure,
OptionalKind,
ParameterDeclarationStructure,
Scope,
} from 'ts-morph';

import { camel, Field, Model, pascal } from '@trxn/hapify-core';

export const generateConstructor = (model: Model, field: Field): OptionalKind<ConstructorDeclarationStructure>[] => {

const parameters: OptionalKind<ParameterDeclarationStructure>[] = [
{
name: `${camel(model.name)}${pascal(
field.name,
)}Validator`,
type: `${pascal(model.name)}${pascal(field.name)}Validator`,
scope: Scope.Public,
},
{
name: 'ngControl',
type: 'NgControl',
hasQuestionToken: true,
decorators: [
{
name: 'Self()',
},
{
name: 'Optional()',
},
],
scope: Scope.Public,
hasOverrideKeyword: true,
},
];

return [
{
parameters,
statements: [
`super(ngControl);`,
],
},
];

};
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { plural } from "pluralize";
import { DecoratorStructure, OptionalKind } from "ts-morph";

import { Field, kebab, Model } from '@trxn/hapify-core';

// TODO: add import for AngularModelsValidatorsModule
export const generateDecorator = (model: Model, field: Field, projectScope:string): OptionalKind<DecoratorStructure>[] => [
{
name: 'Component',
arguments: [
`{
standalone: true,
imports: [
AngularModelsValidatorsModule,
CommonModule,
ReactiveFormsModule,
FormsModule,
],
selector: '${projectScope}-${kebab(model.name)}-${kebab(plural(field.name))}',
templateUrl: './${kebab(model.name)}-${kebab(plural(field.name))}.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [],
}`,
],
},
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@


import { ImportDeclarationStructure, OptionalKind } from 'ts-morph';

import { generateImport } from '../../utils/import.generator';

import { Field, Model, pascal } from '@trxn/hapify-core';

export const generateImports = (model: Model, field: Field, projectScope:string): OptionalKind<ImportDeclarationStructure>[] => [
generateImport(
'@angular/core',
['ChangeDetectionStrategy', 'Component', 'OnInit', 'Optional', 'Self'],
),
generateImport(
'@angular/forms',
[
'AbstractControl',
'FormControl',
'FormsModule',
'NgControl',
'ReactiveFormsModule',
'ValidationErrors',
],
),
generateImport(
`@${projectScope}/angular-models-validators`,
[`${pascal(model.name)}${pascal(field.name)}Validator`],
),
generateImport(
'@trxn/angular-tools',
['BaseControlValueAccessorComponent'],
),
generateImport(
'@trxn/angular-ui',
[`${pascal(model.name)}${pascal(field.name)}UiComponent`],
),
// TODO: add proper validator import depending on the field type
// generateImport(
// `../../angular-models-validators.module`,
// [`AngularModelsValidatorsModule`],
// ),
generateImport('@angular/common', ['CommonModule']),
]

Loading