diff --git a/src/app/app.component.ts b/src/app/app.component.ts index 19b8696818fdd102a39627999877f289c3b9e176..4aab33e64430b4ba0815af21f3186485ea4c0dc5 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -654,12 +654,12 @@ export class AppComponent implements OnInit, OnDestroy, Observer { }); } - public loadSessionFile(f: File, info?: any) { + public async loadSessionFile(f: File, info?: any) { // notes merge detection: was there already some notes ? const existingNotes = Session.getInstance().documentation; // load - this.formulaireService.loadSession(f, info) - .then((data) => { + try { + const data = await this.formulaireService.loadSession(f, info) if (data.hasErrors) { this.notificationsService.notify(this.intlService.localizeText("ERROR_PROBLEM_LOADING_SESSION"), 3500); } else { @@ -678,13 +678,12 @@ export class AppComponent implements OnInit, OnDestroy, Observer { } } } - }) - .catch((err) => { + } catch(err) { this.notificationsService.notify(this.intlService.localizeText("ERROR_LOADING_SESSION"), 3500); console.error("error loading session - ", err); // rollback to ensure session is clean this.doEmptySession(); - }); + } } /** diff --git a/src/app/components/app-setup/app-setup.component.ts b/src/app/components/app-setup/app-setup.component.ts index 85b0d4512ae6dcdbddd9cd44990c14f9ff3da40d..9e2c917ef0465be0ba4514cc4bb524fbccc4f4c9 100644 --- a/src/app/components/app-setup/app-setup.component.ts +++ b/src/app/components/app-setup/app-setup.component.ts @@ -133,12 +133,11 @@ export class ApplicationSetupComponent implements Observer, OnInit { }); } - public restoreDefaultValues() { + public async restoreDefaultValues() { const text = this.intlService.localizeText("INFO_SNACKBAR_DEFAULT_SETTINGS_RESTORED"); - this.appSetupService.restoreDefaultValues().then(() => { - this.snackBar.open(text, "OK", { - duration: 2500 - }); + await this.appSetupService.restoreDefaultValues(); + this.snackBar.open(text, "OK", { + duration: 2500 }); } diff --git a/src/app/components/calculator-list/calculator-list.component.ts b/src/app/components/calculator-list/calculator-list.component.ts index fa269332b15a9dd7fcd715b5ddd2ff4d6838c00d..c8482f556beaedcf372c1c91917abbf23f9f0981 100644 --- a/src/app/components/calculator-list/calculator-list.component.ts +++ b/src/app/components/calculator-list/calculator-list.component.ts @@ -110,53 +110,49 @@ export class CalculatorListComponent implements OnInit { } } - public create(t: CalculatorType) { - const p: Promise<FormulaireDefinition> = ServiceFactory.instance.formulaireService.createFormulaire(t); - p.then(f => { - this.router.navigate(["/calculator", f.uid]); - return f; - }).then(f => { - // on ajoute un ouvrage après l'ouverture du module de calcul "ouvrages parallèles" - if (f instanceof FormulaireParallelStructure) { - for (const e of f.allFormElements) { - if (e instanceof FieldsetContainer) { - e.addFromTemplate(0); - break; - } + public async create(t: CalculatorType) { + const f: FormulaireDefinition = await ServiceFactory.instance.formulaireService.createFormulaire(t); + await this.router.navigate(["/calculator", f.uid]); + // on ajoute un ouvrage après l'ouverture du module de calcul "ouvrages parallèles" + if (f instanceof FormulaireParallelStructure) { + for (const e of f.allFormElements) { + if (e instanceof FieldsetContainer) { + e.addFromTemplate(0); + break; } } - // on ajoute un ouvrage après l'ouverture du module de calcul "passe à bassins" - if (f instanceof FormulairePab) { - for (const e of f.allFormElements) { - if (e instanceof FieldsetContainer) { - e.addFromTemplate(0); - break; - } + } + // on ajoute un ouvrage après l'ouverture du module de calcul "passe à bassins" + if (f instanceof FormulairePab) { + for (const e of f.allFormElements) { + if (e instanceof FieldsetContainer) { + e.addFromTemplate(0); + break; } } - // adding GUI for default apron, in MacroRugoCompound - if (f instanceof FormulaireMacrorugoCompound) { - for (const e of f.allFormElements) { - if (e instanceof FieldsetContainer) { - e.addFromTemplate(0, 0, f.currentNub.getChildren()[0]); - break; - } + } + // adding GUI for default apron, in MacroRugoCompound + if (f instanceof FormulaireMacrorugoCompound) { + for (const e of f.allFormElements) { + if (e instanceof FieldsetContainer) { + e.addFromTemplate(0, 0, f.currentNub.getChildren()[0]); + break; } } - // on ajoute un YAXN après l'ouverture du module de calcul "somme / produit de puissances" - if (f instanceof FormulaireSPP) { - for (const e of f.allFormElements) { - if (e instanceof FieldsetContainer) { - e.addFromTemplate(0); - break; - } + } + // on ajoute un YAXN après l'ouverture du module de calcul "somme / produit de puissances" + if (f instanceof FormulaireSPP) { + for (const e of f.allFormElements) { + if (e instanceof FieldsetContainer) { + e.addFromTemplate(0); + break; } } + } - if (this.appSetupService.enableEmptyFieldsOnFormInit) { - f.emptyFields(); - } - }); + if (this.appSetupService.enableEmptyFieldsOnFormInit) { + f.emptyFields(); + } } public get nbOpenCalculators() { @@ -199,14 +195,15 @@ export class CalculatorListComponent implements OnInit { ]; } - public loadExample(path: string) { + public async loadExample(path: string) { const realPath = "app/examples/" + path; - this.httpService.httpGetBlobRequestPromise(realPath).then((d) => { + try { + const d = await this.httpService.httpGetBlobRequestPromise(realPath); const f: any = new Blob([d], { type: "application/json" }); this.appComponent.loadSessionFile(f); - }).catch((e) => { + } catch(e) { console.error("could not load session file", e); - }); + } } public get uitextWelcomeTitle() { diff --git a/src/app/components/dialog-load-session/dialog-load-session.component.ts b/src/app/components/dialog-load-session/dialog-load-session.component.ts index a8f7aa8170bd9f4921dd8a0dcde1a70e79dde4a4..291de8698821ed377d9bb6a05c657edbb1e223e7 100644 --- a/src/app/components/dialog-load-session/dialog-load-session.component.ts +++ b/src/app/components/dialog-load-session/dialog-load-session.component.ts @@ -138,7 +138,7 @@ export class DialogLoadSessionComponent { this.checkLinkedParamsAndModelsDependencies(); } - public onFileSelected(event: any) { + public async onFileSelected(event: any) { if (event.target.files && event.target.files.length) { this.file = event.target.files[0]; // reinit file infos @@ -149,23 +149,22 @@ export class DialogLoadSessionComponent { this.loadingComplete = false; const formService = ServiceFactory.instance.formulaireService; - formService.calculatorInfosFromSessionFile(this.file).then( - calcInfos => { - this.fileFormatVersion = calcInfos.formatVersion; - this.calculators = calcInfos.nubs; - for (const n of this.calculators) { - n.selected = true; - // if no title was given, generate a default one - if (! n.title) { - n.title = decode(formService.getLocalisedShortTitleFromCalculatorType(n.type)); - } + try { + const calcInfos: any = await formService.calculatorInfosFromSessionFile(this.file); + this.fileFormatVersion = calcInfos.formatVersion; + this.calculators = calcInfos.nubs; + for (const n of this.calculators) { + n.selected = true; + // if no title was given, generate a default one + if (! n.title) { + n.title = decode(formService.getLocalisedShortTitleFromCalculatorType(n.type)); } - this.loadingComplete = true; } - ).catch((err) => { + this.loadingComplete = true; + } catch(err) { console.error(err); this.loadingError = true; - }); + } } } diff --git a/src/app/components/fixedvar-results/results.component.ts b/src/app/components/fixedvar-results/results.component.ts index e1829e929bf3b587e1d41e3859b592e12931034a..ab70880f0779fc05081c8da0a90d06965eefeee0 100644 --- a/src/app/components/fixedvar-results/results.component.ts +++ b/src/app/components/fixedvar-results/results.component.ts @@ -27,21 +27,19 @@ export class ResultsComponentDirective { } } - public setFullscreen(element): Promise<void> { + public async setFullscreen(element): Promise<void> { const sf = <Screenfull>screenfull; if (sf.isEnabled) { - return sf.request(element).then(() => { - this.fullscreenChange(true); - }); + await sf.request(element); + this.fullscreenChange(true); } } - public exitFullscreen(): Promise<void> { + public async exitFullscreen(): Promise<void> { const sf = <Screenfull>screenfull; if (sf.isEnabled) { - return sf.exit().then(() => { - this.fullscreenChange(false); - }); + await sf.exit(); + this.fullscreenChange(false); } } diff --git a/src/app/components/generic-calculator/calculator.component.ts b/src/app/components/generic-calculator/calculator.component.ts index c0fa6f0a3f1ec8571c1b7a6f8f2ce1f8c6efc0ad..b32796c5c3e4206dd6c2e87ea2f1d35fe49b0d6c 100644 --- a/src/app/components/generic-calculator/calculator.component.ts +++ b/src/app/components/generic-calculator/calculator.component.ts @@ -692,10 +692,10 @@ export class GenericCalculatorComponent implements OnInit, DoCheck, AfterViewChe disableClose: false } ); - dialogRef.afterClosed().subscribe(result => { + dialogRef.afterClosed().subscribe(async result => { if (result) { if (result.generate) { - this.formulaireService.createFormulaire(CalculatorType.Pab).then((f: FormulaireDefinition) => { + const f: FormulaireDefinition = await this.formulaireService.createFormulaire(CalculatorType.Pab); const pab = (f.currentNub as Pab); const params = pab.prms; // paramètres hydrauliques @@ -707,7 +707,6 @@ export class GenericCalculatorComponent implements OnInit, DoCheck, AfterViewChe pab.addCloisonsFromModel(this._formulaire.currentNub as Cloisons, result.nbBassins); // go to new PAB this.router.navigate(["/calculator", f.uid]); - }); } } }); @@ -804,7 +803,7 @@ export class GenericCalculatorComponent implements OnInit, DoCheck, AfterViewChe * @param Ys tirant(s) d'eau * @param Ifs pente(s) */ - private generateBiefSP(Ys: number | number[], Ifs: number | number[]) { + private async generateBiefSP(Ys: number | number[], Ifs: number | number[]) { const bief = (this._formulaire.currentNub as Bief); const serialisedSection = bief.section.serialise(); const sectionCopy = Session.getInstance().unserialiseSingleNub(serialisedSection, false).nub; @@ -822,18 +821,15 @@ export class GenericCalculatorComponent implements OnInit, DoCheck, AfterViewChe } } - this.formulaireService.createFormulaire(CalculatorType.SectionParametree, secParam) - .then((f: FormulaireDefinition) => { + const f: FormulaireDefinition = await this.formulaireService.createFormulaire(CalculatorType.SectionParametree, secParam); const sp = (f.currentNub as SectionParametree); sp.section.prms.Y.setValues(Ys); sp.section.prms.If.setValues(Ifs); // calculate f.doCompute(); // go to new SP - this.router.navigate(["/calculator", f.uid]).then(); + this.router.navigate(["/calculator", f.uid]); } - ); - } public get generateRuSpEnabled(): boolean { return this.hasResults && ! this._formulaire.currentNub.result.hasErrorMessages(); @@ -850,7 +846,7 @@ export class GenericCalculatorComponent implements OnInit, DoCheck, AfterViewChe /** * Génère une SectionParametree à partir du module RegimeUniforme en cours */ - public generateRuSp() { + public async generateRuSp() { const ru = (this._formulaire.currentNub as RegimeUniforme); // copy section const serialisedSection = ru.section.serialise(); @@ -866,14 +862,11 @@ export class GenericCalculatorComponent implements OnInit, DoCheck, AfterViewChe } Session.getInstance().registerNub(secParam); - this.formulaireService.createFormulaire(CalculatorType.SectionParametree, secParam) - .then((f: FormulaireDefinition) => { + const f: FormulaireDefinition = await this.formulaireService.createFormulaire(CalculatorType.SectionParametree, secParam); // calculate f.doCompute(); // go to new SP } - ); - } public get generatePARSimulationEnabled(): boolean { const parCalage = (this._formulaire.currentNub as Par); @@ -971,7 +964,7 @@ export class GenericCalculatorComponent implements OnInit, DoCheck, AfterViewChe * Creates a new Formulaire with a ParSimulation Nub, using given * values as parameters */ - protected doGenerateParSimWithValues(v: any) { + protected async doGenerateParSimWithValues(v: any) { const parCalage = (this._formulaire.currentNub as Par); const psim = new ParSimulationParams( round(v.Q, 3), round(v.Z1, 3), round(v.Z2, 3), @@ -984,14 +977,11 @@ export class GenericCalculatorComponent implements OnInit, DoCheck, AfterViewChe parSimulation.parType = parCalage.parType; Session.getInstance().registerNub(parSimulation); - this.formulaireService.createFormulaire(CalculatorType.ParSimulation, parSimulation) - .then((f: FormulaireDefinition) => { + const f: FormulaireDefinition = await this.formulaireService.createFormulaire(CalculatorType.ParSimulation, parSimulation); // calculate f.doCompute(); // go to new ParSimulation - this.router.navigate(["/calculator", f.uid]).then(); - } - ); + this.router.navigate(["/calculator", f.uid]); } public saveCalculator() { @@ -1018,11 +1008,10 @@ export class GenericCalculatorComponent implements OnInit, DoCheck, AfterViewChe /** * Duplicates the current calculator form */ - public cloneCalculator() { + public async cloneCalculator() { const serialisedNub: string = this._formulaire.currentNub.serialise({ title: this._formulaire.calculatorName }); const nubPointer = Session.getInstance().unserialiseSingleNub(serialisedNub); - this.formulaireService.createFormulaire(nubPointer.nub.calcType, nubPointer.nub, nubPointer.meta.title).then((f) => { + const f = await this.formulaireService.createFormulaire(nubPointer.nub.calcType, nubPointer.nub, nubPointer.meta.title); this.router.navigate(["/calculator", f.uid]); - }); } } diff --git a/src/app/components/select-model-field-line/select-model-field-line.component.ts b/src/app/components/select-model-field-line/select-model-field-line.component.ts index 592e3032e496ee1ec51c3e534a6d2cf99bf87218..f8887783567e54a3f3b05808e368c3fa5709672d 100644 --- a/src/app/components/select-model-field-line/select-model-field-line.component.ts +++ b/src/app/components/select-model-field-line/select-model-field-line.component.ts @@ -77,18 +77,15 @@ export class SelectModelFieldLineComponent implements OnInit { * Creates a new Nub of type _select.calcType, to be used as a model * when no other is available */ - public createModel() { - this._formService.createFormulaire(this._select.calcType).then(f => { - this.router.navigate(["/calculator", f.uid]); - return f; - }).then(f => { - // on ajoute un ouvrage aux modulex de type "parallèle" - for (const e of f.allFormElements) { - if (e instanceof FieldsetContainer) { - e.addFromTemplate(0); - break; - } + public async createModel() { + const f = await this._formService.createFormulaire(this._select.calcType); + this.router.navigate(["/calculator", f.uid]); + // on ajoute un ouvrage aux modulex de type "parallèle" + for (const e of f.allFormElements) { + if (e instanceof FieldsetContainer) { + e.addFromTemplate(0); + break; } - }); + } } } diff --git a/src/app/services/app-setup.service.ts b/src/app/services/app-setup.service.ts index 2850c2c7ba63aec24f1c6c3e1967bc4371d8fa83..7a2d2a30b9f4d8f14ddbf019cab78397211b92c1 100644 --- a/src/app/services/app-setup.service.ts +++ b/src/app/services/app-setup.service.ts @@ -114,13 +114,12 @@ export class ApplicationSetupService extends Observable { /** * Restore configuration values */ - public restoreDefaultValues(): Promise<any> { - return this.readValuesFromConfig().then(() => { - // notify I18nService - this.notifyObservers({ - action: "languagePreferenceChanged", - languages: [ this.language ] - }); + public async restoreDefaultValues(): Promise<any> { + await this.readValuesFromConfig() + // notify I18nService + this.notifyObservers({ + action: "languagePreferenceChanged", + languages: [ this.language ] }); } @@ -171,18 +170,17 @@ export class ApplicationSetupService extends Observable { /** * Read configuration values from config (async) */ - private readValuesFromConfig(): Promise<any> { - return this.httpService.httpGetRequestPromise(this.CONFIG_FILE_PATH).then((data: any) => { - // get all config values (volontarily non-generic to prevent side-effects) - this.displayPrecision = data.params.displayPrecision; - this.computePrecision = data.params.computePrecision; - this.maxIterations = data.params.maxIterations; - this.enableNotifications = data.params.enableNotifications; - this.enableHotkeys = data.params.enableHotkeys; - this.enableEmptyFieldsOnFormInit = data.params.enableEmptyFieldsOnFormInit; - this.language = data.params.language; - // load themes for calculators list page - this.themes = data.themes; - }); + private async readValuesFromConfig(): Promise<any> { + const data: any = await this.httpService.httpGetRequestPromise(this.CONFIG_FILE_PATH); + // get all config values (volontarily non-generic to prevent side-effects) + this.displayPrecision = data.params.displayPrecision; + this.computePrecision = data.params.computePrecision; + this.maxIterations = data.params.maxIterations; + this.enableNotifications = data.params.enableNotifications; + this.enableHotkeys = data.params.enableHotkeys; + this.enableEmptyFieldsOnFormInit = data.params.enableEmptyFieldsOnFormInit; + this.language = data.params.language; + // load themes for calculators list page + this.themes = data.themes; } } diff --git a/src/app/services/formulaire.service.ts b/src/app/services/formulaire.service.ts index 101572ca12f6d88a4cc3658d284cf375357e3f4b..e4bb9b0b92539c3123c20bcb515cad9ee8c4fdb9 100644 --- a/src/app/services/formulaire.service.ts +++ b/src/app/services/formulaire.service.ts @@ -83,11 +83,12 @@ export class FormulaireService extends Observable { * Loads the localisation file dedicated to calculator type ct; tries the current * language then the fallback language; uses cache if available */ - public loadLocalisation(calc: CalculatorType): Promise<any> { + public async loadLocalisation(calc: CalculatorType): Promise<any> { const lang = this._intlService.currentLanguage; - return this.loadLocalisationForLang(calc, lang).then((localisation) => { + try { + const localisation = await this.loadLocalisationForLang(calc, lang); return localisation as StringMap; - }).catch((e) => { + } catch(e) { console.error(e); // try default lang (the one in the config file) ? const fallbackLang = this.appSetupService.fallbackLanguage; @@ -95,14 +96,14 @@ export class FormulaireService extends Observable { console.error(`trying fallback language: ${fallbackLang}`); return this.loadLocalisationForLang(calc, fallbackLang); } - }); + } } /** * Loads the localisation file dedicated to calculator type ct for language lang; * keeps it in cache for subsequent calls () */ - private loadLocalisationForLang(calc: CalculatorType, lang: string): Promise<any> { + private async loadLocalisationForLang(calc: CalculatorType, lang: string): Promise<any> { const ct = String(calc); // already in cache ? if (Object.keys(this._languageCache).includes(ct) && Object.keys(this._languageCache[calc]).includes(lang)) { @@ -111,27 +112,27 @@ export class FormulaireService extends Observable { }); } else { const f: string = this.getConfigPathPrefix(calc) + lang + ".json"; - return this._httpService.httpGetRequestPromise(f).then((localisation) => { + try { + const localisation = await this._httpService.httpGetRequestPromise(f); this._languageCache[ct] = this._languageCache[ct] || {}; this._languageCache[ct][lang] = localisation; return localisation as StringMap; - }).catch((e) => { + } catch(e) { throw new Error(`LOCALISATION_FILE_NOT_FOUND "${f}"`); - }); } } + } /** * Loads localisation file corresponding to current language then updates all form strings, * only if form language was not already set to current language */ - public loadUpdateFormulaireLocalisation(f: FormulaireDefinition): Promise<FormulaireDefinition> { + public async loadUpdateFormulaireLocalisation(f: FormulaireDefinition): Promise<FormulaireDefinition> { const requiredLang = this._intlService.currentLanguage; if (requiredLang !== f.currentLanguage) { - return this.loadLocalisation(f.calculatorType).then(localisation => { + const localisation = await this.loadLocalisation(f.calculatorType); f.updateLocalisation(localisation, requiredLang); return f; - }); } } @@ -322,13 +323,12 @@ export class FormulaireService extends Observable { * @param nub nub existant à associer au formulaire (chargement de session / duplication de module) * @param calculatorName nom du module, à afficher dans l'interface */ - public createFormulaire(ct: CalculatorType, nub?: Nub, calculatorName?: string): Promise<FormulaireDefinition> { + public async createFormulaire(ct: CalculatorType, nub?: Nub, calculatorName?: string): Promise<FormulaireDefinition> { // Crée un formulaire du bon type const f: FormulaireDefinition = this.newFormulaire(ct); this._formulaires.push(f); // Charge la configuration dépendamment du type - const prom: Promise<any> = this.loadConfig(ct); - return prom.then(s => { + const s: any = await this.loadConfig(ct); f.preparseConfig(s); // Associe le Nub fourni (chargement de session / duplication de module), sinon en crée un nouveau @@ -413,16 +413,11 @@ export class FormulaireService extends Observable { newDownWall.addChild(newDownwallDevice); f.pabNub.downWall = newDownWall; } - - return f; - - }).then(fi => { this.notifyObservers({ "action": "createForm", - "form": fi - }); - return fi; + "form": f }); + return f; } /** @@ -640,10 +635,13 @@ export class FormulaireService extends Observable { * obtient des infos (nom, uid des modules de calcul, dépendances) d'un fichier session * @param f fichier session */ - public calculatorInfosFromSessionFile(f: File): Promise<{ nubs: any[], formatVersion: string }> { - return this.readSingleFile(f).then(s => { + public async calculatorInfosFromSessionFile(f: File): Promise<{ nubs: any[], formatVersion: string }> { + const s = await this.readSingleFile(f); // return value - const res: { nubs: any[], formatVersion: string } = { + const res: { + nubs: any[]; + formatVersion: string; + } = { nubs: [], formatVersion: "" }; @@ -661,7 +659,7 @@ export class FormulaireService extends Observable { // list linked params dependencies for each Nub if (e.parameters) { e.parameters.forEach((p) => { - if (p.targetNub && ! nubInfo.requires.includes(p.targetNub)) { + if (p.targetNub && !nubInfo.requires.includes(p.targetNub)) { nubInfo.requires.push(p.targetNub); } }); @@ -680,7 +678,6 @@ export class FormulaireService extends Observable { res.formatVersion = data.header.format_version; } return res; - }); } public saveForm(f: FormulaireDefinition) { diff --git a/src/app/services/internationalisation.service.ts b/src/app/services/internationalisation.service.ts index 67b16fa79146da163c47a048203c82101ce17d83..50e1e4cbef1ac9710c0a619e3e65d8c96f300e83 100644 --- a/src/app/services/internationalisation.service.ts +++ b/src/app/services/internationalisation.service.ts @@ -59,7 +59,7 @@ export class I18nService extends Observable implements Observer { * * @param code ISO 639-1 language code */ - public setLanguage(code: string) { + public async setLanguage(code: string) { // is language supported ? if (! Object.keys(this._availableLanguages).includes(code)) { throw new Error(`LANGUAGE_UNSUPPORTED "${code}"`); @@ -70,11 +70,10 @@ export class I18nService extends Observable implements Observer { this._Messages = undefined; // reload all messages const that = this; - this.httpGetMessages(code).then((res: any) => { - that._Messages = res; - // propagate language change to all application - that.notifyObservers(undefined); - }); + const res: any = await this.httpGetMessages(code); + that._Messages = res; + // propagate language change to all application + that.notifyObservers(undefined); } } @@ -82,12 +81,10 @@ export class I18nService extends Observable implements Observer { * Loads localized messages from JSON files for the given language * (general messages files, not calculator-specific ones) */ - private httpGetMessages(lang: string): Promise<void> { + private async httpGetMessages(lang: string): Promise<any> { const fileName = "messages." + lang + ".json"; const filePath = "locale/" + fileName; - return this.httpService.httpGetRequestPromise(filePath).then((res: any) => { - return res; - }); + return await this.httpService.httpGetRequestPromise(filePath); } private getMessageFromCode(c: MessageCode): string {