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

refactor!: template-calc service #2793

Merged
merged 2 commits into from
Feb 17, 2025
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,21 @@ import { ICalcContext, TemplateCalcService } from "./template-calc.service";
import { MockDataEvaluationService } from "src/app/shared/services/data/data-evaluation.service.mock.spec";

export class MockTemplateCalcService extends TemplateCalcService {
constructor() {
constructor(mockCalcContext: Partial<ICalcContext> = {}) {
super(new MockDataEvaluationService(), new MockLocalStorageService());
}

public getCalcContext(): ICalcContext {
return {
thisCtxt: {},
globalConstants: {},
globalFunctions: {},
// merge any mock calc context with defaults
super["calcContext"] = {
thisCtxt: {
// ensure default calc included as allows `@calc(...)` to be triggered via `this.calc(...)`
calc: (v: any) => v,
...mockCalcContext.thisCtxt,
},
globalConstants: {
...mockCalcContext.globalConstants,
},
globalFunctions: {
...mockCalcContext.globalFunctions,
},
};
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,92 @@
import { TestBed } from "@angular/core/testing";
import { TemplateCalcService } from "./template-calc.service";
import { MockDataEvaluationService } from "src/app/shared/services/data/data-evaluation.service.mock.spec";
import { MockLocalStorageService } from "src/app/shared/services/local-storage/local-storage.service.mock.spec";
import { DataEvaluationService } from "src/app/shared/services/data/data-evaluation.service";
import { LocalStorageService } from "src/app/shared/services/local-storage/local-storage.service";
import { CORE_CALC_FUNCTIONS } from "./template-calc-functions/core-calc-functions";
import { PLH_CALC_FUNCTIONS } from "./template-calc-functions/plh-calc-functions";

/**
* Call standalone tests via:
* yarn ng test --include src/app/shared/components/template/services/template-calc.service.spec.ts
*/
describe("TemplateCalcService", () => {
let service: TemplateCalcService;

beforeEach(async () => {
TestBed.configureTestingModule({
providers: [
{
provide: DataEvaluationService,
useValue: new MockDataEvaluationService(),
},
{
provide: LocalStorageService,
useValue: new MockLocalStorageService(),
},
],
});
service = TestBed.inject(TemplateCalcService);
await service.ready();
});

it("should be created", () => {
expect(service).toBeTruthy();
});

it("[Deprecated] populates window.calc with calc functions", () => {
const { calc } = service["windowWithCalc"];
expect(Object.keys(calc)).toEqual([
...Object.keys(CORE_CALC_FUNCTIONS),
...Object.keys(PLH_CALC_FUNCTIONS),
]);
});

it("populates window.date_fns with date_fns lib", () => {
const { date_fns } = service["windowWithCalc"];
expect(date_fns.hoursToMilliseconds(1)).toEqual(3600000);
});

it("Gets calc context", () => {
const calcContext = service.getCalcContext();
const { globalConstants, globalFunctions, thisCtxt } = calcContext;
// global constants and functions are passed by service
expect(globalConstants).toEqual({});
// global functions should be same as window but without 3rd party
expect(Object.keys(globalFunctions)).toEqual([
...Object.keys(CORE_CALC_FUNCTIONS),
...Object.keys(PLH_CALC_FUNCTIONS),
]);
// By default a handful of specific app data context fields always populated
expect(Object.keys(thisCtxt)).toEqual([
"calc",
"app_day",
"app_first_launch",
"app_user_id",
"device_info",
]);
});

it("evaluates @calc statements", async () => {
const res = await service.evaluate("@calc(2*2)");
expect(res).toEqual(4);
});

it("evaluates @calc statements with window functions", async () => {
const res = await service.evaluate("@calc(window.date_fns.hoursToMilliseconds(1))", {});
expect(res).toEqual(3600000);
});

it("evaluates @calc statements with local context", async () => {
// NOTE - `@local` expression should be converted to `this.local` in template-parser
const res = await service.evaluate("@calc(this.local.test_string)", {
local: { test_string: "hello" },
});
expect(res).toEqual("hello");
});
});

/**
* TODO - Add testing data and methods
*
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IFunctionHashmap, IConstantHashmap } from "src/app/shared/utils";
import { IFunctionHashmap, IConstantHashmap, evaluateJSExpression } from "src/app/shared/utils";
import { Injectable } from "@angular/core";
import { Device, DeviceInfo } from "@capacitor/device";
import * as date_fns from "date-fns";
Expand All @@ -7,6 +7,22 @@ import { AsyncServiceBase } from "src/app/shared/services/asyncService.base";
import { PLH_CALC_FUNCTIONS } from "./template-calc-functions/plh-calc-functions";
import { CORE_CALC_FUNCTIONS } from "./template-calc-functions/core-calc-functions";
import { LocalStorageService } from "src/app/shared/services/local-storage/local-storage.service";
import type { FlowTypes } from "packages/data-models";

/** Window context with additional calc service properties attached */
type IWindowWithCalc = Window & {
/**
* @deprecated 0.18.0 Prefer to call directly instead of via window
*
* ✔️ `@calc(pick_random([1,2,3]))`
* ❌ `@calc(window.calc.pick_random([1,2,3]))`
*
* All user-defined calc available globally
* */
calc: IFunctionHashmap;
/** Specific data_fns lib available globally */
date_fns: typeof date_fns;
};

@Injectable({ providedIn: "root" })
export class TemplateCalcService extends AsyncServiceBase {
Expand All @@ -27,6 +43,11 @@ export class TemplateCalcService extends AsyncServiceBase {
super("TemplateCalc");
this.registerInitFunction(this.initialise);
}

private get windowWithCalc() {
return window as any as IWindowWithCalc;
}

private async initialise() {
this.ensureSyncServicesReady([this.localStorageService]);
await this.ensureAsyncServicesReady([this.dataEvaluationService]);
Expand All @@ -41,10 +62,23 @@ export class TemplateCalcService extends AsyncServiceBase {
this.calcContext = this.generateCalcContext();
}
// Assign all calc functions also to window object to allow calling between functions
(window as any).calc = this.calcFunctions;
this.windowWithCalc.calc = this.calcFunctions;
return this.calcContext;
}

/**
* Evaluate inner expression provided by `@calc(...)` expression
* The expression is evaluated as JS, with additional access to global constants, function and
* evaluation context variables
* */
public evaluate(expression: string, evalContext: FlowTypes.TemplateRowEvalContext = {}) {
const calcContext = this.getCalcContext();
const calcExpression = expression.replace(/@/gi, "this.");
const { thisCtxt, globalFunctions, globalConstants } = calcContext;
const mergedContext = { ...thisCtxt, ...evalContext };
return evaluateJSExpression(calcExpression, mergedContext, globalFunctions, globalConstants);
}

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note - this method has been adapted from the template-variable service which currently handles evaluation. It will be used as part of the refactor in #2772

/**
* Main export for use in evaluation statements. Includes all functions listed below
* alongside additional a base for variables found at `this.`
Expand Down Expand Up @@ -91,9 +125,7 @@ export class TemplateCalcService extends AsyncServiceBase {
* ```
*/
private generateGlobalConstants() {
const globalConstants: IConstantHashmap = {
test_var: "hello",
};
const globalConstants: IConstantHashmap = {};
return globalConstants;
}

Expand All @@ -105,7 +137,7 @@ export class TemplateCalcService extends AsyncServiceBase {
* ```
*/
private addWindowCalcFunctions() {
(window as any).date_fns = date_fns;
this.windowWithCalc.date_fns = date_fns;
}
}

Expand All @@ -116,6 +148,8 @@ export class TemplateCalcService extends AsyncServiceBase {
*/
export interface ICalcContext {
thisCtxt: {
/** assign `this.calc` variable to handle replaced `this.calc(...)` expressions */
calc: (v) => any;
[name: string]: any;
};
globalFunctions: IFunctionHashmap;
Expand Down
Loading