Skip to content

Commit

Permalink
chore: Money add migration (#6832)
Browse files Browse the repository at this point in the history
  • Loading branch information
vladimirpotekhin authored Feb 20, 2024
1 parent 7b824fe commit e2356ae
Show file tree
Hide file tree
Showing 7 changed files with 211 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,14 @@ export const IDENTIFIERS_TO_REPLACE: ReplacementIdentifier[] = [
from: {name: 'TuiPortalModule', moduleSpecifier: '@taiga-ui/cdk'},
to: {name: 'TuiDropdownPortalDirective', moduleSpecifier: '@taiga-ui/core'},
},
{
from: {name: 'TuiAmountModule', moduleSpecifier: '@taiga-ui/experimental'},
to: {name: 'TuiAmountPipe', moduleSpecifier: '@taiga-ui/addon-commerce'},
},
{
from: {name: 'TuiMoneyModule', moduleSpecifier: '@taiga-ui/addon-commerce'},
to: {name: 'TuiAmountPipe', moduleSpecifier: '@taiga-ui/addon-commerce'},
},
{
from: {name: 'TuiResizeModule', moduleSpecifier: '@taiga-ui/cdk'},
to: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,8 @@ export const TAGS_TO_REPLACE: ReplacementTag[] = [
addAttributes: ['decimal="never"', '[step]="1"'],
filterFn: element => element.attrs.every(attr => attr.name !== '[step]'),
},
{
from: 'tui-money',
to: 'span',
},
];
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
migrateBadgedContent,
migrateCheckbox,
migrateExpandable,
migrateMoney,
migratePreventDefault,
migrateRadio,
migrateToggle,
Expand Down Expand Up @@ -89,6 +90,7 @@ export function migrateTemplates(fileSystem: DevkitFileSystem, options: TuiSchem
migrateExpandable,
migrateBadgedContent,
migratePreventDefault,
migrateMoney,
] as const;

const progressLog = setupProgressLogger({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ export * from './migrate-avatar';
export * from './migrate-badge';
export * from './migrate-badged-content';
export * from './migrate-expandable';
export * from './migrate-money';
export * from './migrate-prevent-default';
export * from './toggles';
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import {UpdateRecorder} from '@angular-devkit/schematics';
import {tuiCleanObject} from '@taiga-ui/cdk';
import {addImportToClosestModule} from '@taiga-ui/cdk/schematics';
import {TemplateResource} from '@taiga-ui/cdk/schematics/ng-update/interfaces';
import {removeAttrs} from '@taiga-ui/cdk/schematics/ng-update/v4/steps/utils/remove-attrs';
import {findElementsByTagName} from '@taiga-ui/cdk/schematics/utils/templates/elements';
import {findAttr, isBinding} from '@taiga-ui/cdk/schematics/utils/templates/inputs';
import {
getTemplateFromTemplateResource,
getTemplateOffset,
} from '@taiga-ui/cdk/schematics/utils/templates/template-resource';
import {DevkitFileSystem} from 'ng-morph';
import {Attribute} from 'parse5';

export function migrateMoney({
resource,
recorder,
fileSystem,
}: {
fileSystem: DevkitFileSystem;
recorder: UpdateRecorder;
resource: TemplateResource;
}): void {
const template = getTemplateFromTemplateResource(resource, fileSystem);
const templateOffset = getTemplateOffset(resource);

const elements = findElementsByTagName(template, 'tui-money');

elements.forEach(({attrs, sourceCodeLocation}) => {
if (!sourceCodeLocation) {
return;
}

const valueAttr = findAttr(attrs, 'value');
const currencyAttr = findAttr(attrs, 'currency');
const decimalAttr = findAttr(attrs, 'decimal');
const precisionAttr = findAttr(attrs, 'precision');
const signAttr = findAttr(attrs, 'sign');

if (!valueAttr) {
return;
}

const insertTo = sourceCodeLocation?.endTag.startOffset;
const value = isBinding(valueAttr) ? valueAttr.value : `'${valueAttr.value}'`;
const currency =
currencyAttr && isBinding(currencyAttr)
? currencyAttr?.value
: `'${currencyAttr?.value}'`;

recorder.insertRight(
templateOffset + insertTo,
`{{ ${value} | tuiAmount ${currencyAttr ? `: ${currency}` : ': "RUB"'} | async }}`,
);

if (decimalAttr || precisionAttr) {
addImportToClosestModule(
resource.componentPath,
'TuiNumberFormatDirective',
'@taiga-ui/core',
);

const format = JSON.stringify(
tuiCleanObject({
decimal: decimalAttr?.value,
precision: precisionAttr?.value,
}),
);

const formatPart = `[tuiNumberFormat]='${format}'`;

const insertTo = (sourceCodeLocation?.startTag.startOffset || 0) + 1;

recorder.insertRight(templateOffset + insertTo, formatPart);
}

const attrsToRemove = [
valueAttr,
currencyAttr,
decimalAttr,
precisionAttr,
signAttr,
].filter((attr): attr is Attribute => attr !== undefined);

removeAttrs(attrsToRemove, sourceCodeLocation, recorder, templateOffset);
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import {HostTree} from '@angular-devkit/schematics';
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing';
import {TuiSchema} from '@taiga-ui/cdk/schematics/ng-add/schema';
import {
createProject,
createSourceFile,
resetActiveProject,
saveActiveProject,
setActiveProject,
} from 'ng-morph';
import {join} from 'path';

import {createAngularJson} from '../../../utils/create-angular-json';

const collectionPath = join(__dirname, '../../../migration.json');

const COMPONENT_BEFORE = `
import { TuiMoneyModule } from "@taiga-ui/addon-commerce";
@Component({
standalone: true,
templateUrl: './test.template.html',
imports: [TuiMoneyModule]
})
export class TestComponent {
}`;

const COMPONENT_AFTER = `import { TuiNumberFormatDirective } from "@taiga-ui/core";
import { TuiAmountPipe } from "@taiga-ui/addon-commerce";
@Component({
standalone: true,
templateUrl: './test.template.html',
imports: [TuiAmountPipe, TuiNumberFormatDirective]
})
export class TestComponent {
}`;

const TEMPLATE_BEFORE = `
<tui-money class="money" [value]="123" [currency]="currency"></tui-money>
<tui-money class="money" [value]="123"></tui-money>
<tui-money customDirective decimal="always" [value]="value"></tui-money>
`;

const TEMPLATE_AFTER = `
<span class="money">{{ 123 | tuiAmount : currency | async }}</span>
<span class="money">{{ 123 | tuiAmount : "RUB" | async }}</span>
<span [tuiNumberFormat]='{"decimal":"always"}' customDirective>{{ value | tuiAmount : "RUB" | async }}</span>
`;

describe('ng-update', () => {
let host: UnitTestTree;
let runner: SchematicTestRunner;

beforeEach(() => {
host = new UnitTestTree(new HostTree());
runner = new SchematicTestRunner('schematics', collectionPath);

setActiveProject(createProject(host));

createMainFiles();

saveActiveProject();
});

it('should migrate Money in template', async () => {
const tree = await runner.runSchematic(
'updateToV4',
{'skip-logs': process.env['TUI_CI'] === 'true'} as Partial<TuiSchema>,
host,
);

expect(tree.readContent('test/app/test.template.html')).toEqual(TEMPLATE_AFTER);
});

it('should migrate Money references in ts files', async () => {
const tree = await runner.runSchematic(
'updateToV4',
{'skip-logs': process.env['TUI_CI'] === 'true'} as Partial<TuiSchema>,
host,
);

expect(tree.readContent('test/app/test.component.ts')).toEqual(COMPONENT_AFTER);
});

afterEach(() => resetActiveProject());
});

function createMainFiles(): void {
createSourceFile('test/app/test.component.ts', COMPONENT_BEFORE);

createSourceFile('test/app/test.template.html', TEMPLATE_BEFORE);

createAngularJson();
createSourceFile(
'package.json',
'{"dependencies": {"@angular/core": "~13.0.0", "@taiga-ui/addon-commerce": "~3.42.0"}}',
);
}
4 changes: 4 additions & 0 deletions projects/cdk/schematics/utils/templates/inputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,7 @@ import {Attribute} from 'parse5';
export function findAttr(attrs: Attribute[], name: string): Attribute | undefined {
return attrs.find(attr => attr.name === name || attr.name === `[${name}]`);
}

export function isBinding(attr: Attribute): boolean {
return attr.name.startsWith('[');
}

0 comments on commit e2356ae

Please sign in to comment.