@dflat-core/web 1.7.2095 → 1.7.2097

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,11 +3,11 @@ import { EnsureModuleLoadedOnceGuard, Utilities } from "@dflat-core/web/core";
3
3
  import { ApiErrorTypes, BroadcastMessage, CoreModelModule, DashboardActivityMessage, DashboardCacheChangedMessage, DashboardLoadProgressMessage, DictionnaryWrapper, FormChangedMessage, Notification, PresentationChangedMessage, User, UserUpdatedMessage } from "@dflat-core/web/core-model";
4
4
  import { CommonModule } from "@angular/common";
5
5
  import * as i3 from "@angular/common/http";
6
- import { HttpErrorResponse, HttpHeaders, provideHttpClient, withInterceptorsFromDi, withXhr } from "@angular/common/http";
6
+ import { HttpClient, HttpErrorResponse, HttpHeaders, provideHttpClient, withInterceptorsFromDi, withXhr } from "@angular/common/http";
7
7
  import * as i0 from "@angular/core";
8
- import { EventEmitter, Inject, Injectable, InjectionToken, NgModule, Optional, SkipSelf } from "@angular/core";
8
+ import { EventEmitter, Inject, Injectable, InjectionToken, NgModule, Optional, Pipe, SkipSelf, computed, inject, signal } from "@angular/core";
9
9
  import jwt_decode from "jwt-decode";
10
- import { BehaviorSubject, ReplaySubject, Subject, empty, throwError, timer } from "rxjs";
10
+ import { BehaviorSubject, ReplaySubject, Subject, empty, firstValueFrom, throwError, timeout, timer } from "rxjs";
11
11
  import { catchError, filter, finalize, map, shareReplay } from "rxjs/operators";
12
12
  import * as i4 from "@angular/router";
13
13
  import * as i1 from "@angular/platform-browser";
@@ -2252,6 +2252,360 @@ i0.ɵɵngDeclareClassMetadata({
2252
2252
  }]
2253
2253
  }]
2254
2254
  });
2255
- export { AppConfiguration, AppKeys, ApplicationMenuService, AuthGuard, AuthInterceptor, AuthService, AuthTokenType, BreadcrumbService, BusMessageService, CanActivateGuard, CoreServicesModule, ExternalLoginService, FilterService, GeolocationService, HeadersService, HubService, InitCacheService, LocalStoreManager, MODULE_MENU_SERVICES, MenuItem, MenuService, MessagesService, NotificationMqService, NotificationsService, PermissionService, ScreenService, ServerUrl, UserService, trimChar };
2255
+ function formatMessage(message, params, culture) {
2256
+ if (message == null) return "";
2257
+ if (message.indexOf("{") < 0) return message;
2258
+ try {
2259
+ return render(message, params ?? {}, culture, null);
2260
+ } catch {
2261
+ return message;
2262
+ }
2263
+ }
2264
+ function render(message, params, culture, count) {
2265
+ let result = "";
2266
+ let i = 0;
2267
+ while (i < message.length) {
2268
+ const c = message[i];
2269
+ if (c === "#" && count !== null) {
2270
+ result += formatNumber(count, culture);
2271
+ i++;
2272
+ } else if (c === "{") {
2273
+ const end = matchingBrace(message, i);
2274
+ result += renderArgument(message.substring(i + 1, end), params, culture, count);
2275
+ i = end + 1;
2276
+ } else {
2277
+ result += c;
2278
+ i++;
2279
+ }
2280
+ }
2281
+ return result;
2282
+ }
2283
+ function renderArgument(body, params, culture, count) {
2284
+ const firstComma = body.indexOf(",");
2285
+ if (firstComma < 0) {
2286
+ const name = body.trim();
2287
+ const value = params[name];
2288
+ return value === void 0 || value === null ? `{${name}}` : String(value);
2289
+ }
2290
+ const name = body.substring(0, firstComma).trim();
2291
+ const rest = body.substring(firstComma + 1);
2292
+ const secondComma = rest.indexOf(",");
2293
+ const type = (secondComma < 0 ? rest : rest.substring(0, secondComma)).trim();
2294
+ const options = parseOptions(secondComma < 0 ? "" : rest.substring(secondComma + 1));
2295
+ const value = params[name];
2296
+ if (type === "plural") {
2297
+ const n = Number(value);
2298
+ return render(options.get(`=${n}`) ?? options.get(new Intl.PluralRules(culture).select(n)) ?? options.get("other") ?? "", params, culture, n);
2299
+ }
2300
+ if (type === "select") return render(options.get(String(value)) ?? options.get("other") ?? "", params, culture, count);
2301
+ return value === void 0 || value === null ? `{${name}}` : String(value);
2302
+ }
2303
+ function parseOptions(text) {
2304
+ const options = /* @__PURE__ */ new Map();
2305
+ let i = 0;
2306
+ while (i < text.length) {
2307
+ while (i < text.length && /\s/.test(text[i])) i++;
2308
+ const start = i;
2309
+ while (i < text.length && text[i] !== "{" && !/\s/.test(text[i])) i++;
2310
+ const key = text.substring(start, i);
2311
+ while (i < text.length && text[i] !== "{") i++;
2312
+ if (i >= text.length) break;
2313
+ const end = matchingBrace(text, i);
2314
+ options.set(key, text.substring(i + 1, end));
2315
+ i = end + 1;
2316
+ }
2317
+ return options;
2318
+ }
2319
+ function matchingBrace(text, start) {
2320
+ let depth = 0;
2321
+ for (let i = start; i < text.length; i++) if (text[i] === "{") depth++;
2322
+ else if (text[i] === "}") {
2323
+ depth--;
2324
+ if (depth === 0) return i;
2325
+ }
2326
+ throw new Error("Accolade non fermée");
2327
+ }
2328
+ function formatNumber(n, culture) {
2329
+ try {
2330
+ return new Intl.NumberFormat(culture).format(n);
2331
+ } catch {
2332
+ return String(n);
2333
+ }
2334
+ }
2335
+ var TranslationStore = class TranslationStore {
2336
+ constructor() {
2337
+ this.memory = /* @__PURE__ */ new Map();
2338
+ this.database = null;
2339
+ }
2340
+ static {
2341
+ this.DATABASE = "dflat-translations";
2342
+ }
2343
+ static {
2344
+ this.STORE = "dictionaries";
2345
+ }
2346
+ async get(culture) {
2347
+ const db = await this.open();
2348
+ if (!db) return this.memory.get(culture) ?? null;
2349
+ return new Promise((resolve) => {
2350
+ try {
2351
+ const request = db.transaction(TranslationStore.STORE, "readonly").objectStore(TranslationStore.STORE).get(culture);
2352
+ request.onsuccess = () => resolve(request.result ?? this.memory.get(culture) ?? null);
2353
+ request.onerror = () => resolve(this.memory.get(culture) ?? null);
2354
+ } catch {
2355
+ resolve(this.memory.get(culture) ?? null);
2356
+ }
2357
+ });
2358
+ }
2359
+ async set(dictionary) {
2360
+ this.memory.set(dictionary.culture, dictionary);
2361
+ const db = await this.open();
2362
+ if (!db) return;
2363
+ await new Promise((resolve) => {
2364
+ try {
2365
+ const transaction = db.transaction(TranslationStore.STORE, "readwrite");
2366
+ transaction.objectStore(TranslationStore.STORE).put(dictionary, dictionary.culture);
2367
+ transaction.oncomplete = () => resolve();
2368
+ transaction.onerror = () => resolve();
2369
+ } catch {
2370
+ resolve();
2371
+ }
2372
+ });
2373
+ }
2374
+ open() {
2375
+ if (!this.database) this.database = new Promise((resolve) => {
2376
+ try {
2377
+ if (typeof indexedDB === "undefined") {
2378
+ resolve(null);
2379
+ return;
2380
+ }
2381
+ const request = indexedDB.open(TranslationStore.DATABASE, 1);
2382
+ request.onupgradeneeded = () => request.result.createObjectStore(TranslationStore.STORE);
2383
+ request.onsuccess = () => resolve(request.result);
2384
+ request.onerror = () => resolve(null);
2385
+ request.onblocked = () => resolve(null);
2386
+ } catch {
2387
+ resolve(null);
2388
+ }
2389
+ });
2390
+ return this.database;
2391
+ }
2392
+ };
2393
+ const DFLAT_TRANSLATION_CONFIG = new InjectionToken("DFLAT_TRANSLATION_CONFIG");
2394
+ var TranslationService = class TranslationService {
2395
+ constructor() {
2396
+ this.http = inject(HttpClient);
2397
+ this.config = inject(DFLAT_TRANSLATION_CONFIG, { optional: true }) ?? {};
2398
+ this.store = new TranslationStore();
2399
+ this.dictionary = signal(null, ...ngDevMode ? [{ debugName: "dictionary" }] : /* istanbul ignore next */ []);
2400
+ this.languageList = signal(null, ...ngDevMode ? [{ debugName: "languageList" }] : /* istanbul ignore next */ []);
2401
+ this.culture = computed(() => this.dictionary()?.culture ?? null, ...ngDevMode ? [{ debugName: "culture" }] : /* istanbul ignore next */ []);
2402
+ this.version = computed(() => this.dictionary()?.version ?? null, ...ngDevMode ? [{ debugName: "version" }] : /* istanbul ignore next */ []);
2403
+ this.languages = computed(() => this.languageList()?.languages ?? [], ...ngDevMode ? [{ debugName: "languages" }] : /* istanbul ignore next */ []);
2404
+ }
2405
+ static {
2406
+ this.currentCulture = null;
2407
+ }
2408
+ static {
2409
+ this.CHOSEN_CULTURE_KEY = "dflat_culture";
2410
+ }
2411
+ get apiUrl() {
2412
+ return `${ServerUrl.apiUrl}/translations`;
2413
+ }
2414
+ async init() {
2415
+ const requested = this.chosenCulture() ?? this.browserCulture();
2416
+ const local = requested ? await this.store.get(requested) : null;
2417
+ if (local) {
2418
+ this.apply(local);
2419
+ this.refresh(requested);
2420
+ return;
2421
+ }
2422
+ await this.load(requested, this.config.startupTimeoutMs ?? 5e3);
2423
+ }
2424
+ async use(culture) {
2425
+ this.saveChosenCulture(culture);
2426
+ const local = await this.store.get(culture);
2427
+ if (local) {
2428
+ this.apply(local);
2429
+ this.refresh(culture);
2430
+ return;
2431
+ }
2432
+ await this.load(culture, null);
2433
+ }
2434
+ async loadLanguages() {
2435
+ if (!this.languageList()) try {
2436
+ this.languageList.set(await firstValueFrom(this.http.get(`${this.apiUrl}/languages`)));
2437
+ } catch {
2438
+ return null;
2439
+ }
2440
+ return this.languageList();
2441
+ }
2442
+ translate(key, params) {
2443
+ const dictionary = this.dictionary();
2444
+ const message = dictionary?.entries?.[key];
2445
+ if (message === void 0) return key;
2446
+ return formatMessage(message, params, dictionary.culture);
2447
+ }
2448
+ has(key) {
2449
+ return this.dictionary()?.entries?.[key] !== void 0;
2450
+ }
2451
+ async refresh(culture) {
2452
+ try {
2453
+ const current = await firstValueFrom(this.http.get(`${this.apiUrl}/${encodeURIComponent(culture ?? "")}/version`));
2454
+ const shown = this.dictionary();
2455
+ if (shown && shown.culture === current.culture && shown.version === current.version) return;
2456
+ await this.download(current.culture, current.version);
2457
+ } catch {}
2458
+ }
2459
+ async load(culture, timeoutMs) {
2460
+ try {
2461
+ const version = this.http.get(`${this.apiUrl}/${encodeURIComponent(culture ?? "")}/version`);
2462
+ const current = await firstValueFrom(timeoutMs ? version.pipe(timeout(timeoutMs)) : version);
2463
+ await this.download(current.culture, current.version);
2464
+ } catch {
2465
+ const bundled = await this.loadBundle(culture ?? this.config.defaultCulture ?? "fr-FR") ?? await this.loadBundle(this.config.defaultCulture ?? "fr-FR");
2466
+ if (bundled) this.apply(bundled);
2467
+ }
2468
+ }
2469
+ async download(culture, version) {
2470
+ const dictionary = await firstValueFrom(this.http.get(`${this.apiUrl}/${encodeURIComponent(culture)}?v=${encodeURIComponent(version)}`));
2471
+ await this.store.set(dictionary);
2472
+ this.apply(dictionary);
2473
+ }
2474
+ async loadBundle(culture) {
2475
+ if (!this.config.bundlePath) return null;
2476
+ try {
2477
+ return await firstValueFrom(this.http.get(this.config.bundlePath.replace("{culture}", culture)));
2478
+ } catch {
2479
+ return null;
2480
+ }
2481
+ }
2482
+ apply(dictionary) {
2483
+ this.dictionary.set(dictionary);
2484
+ TranslationService.currentCulture = dictionary.culture;
2485
+ if (typeof document !== "undefined" && document.documentElement) document.documentElement.lang = dictionary.culture;
2486
+ }
2487
+ chosenCulture() {
2488
+ try {
2489
+ return localStorage.getItem(TranslationService.CHOSEN_CULTURE_KEY);
2490
+ } catch {
2491
+ return null;
2492
+ }
2493
+ }
2494
+ saveChosenCulture(culture) {
2495
+ try {
2496
+ localStorage.setItem(TranslationService.CHOSEN_CULTURE_KEY, culture);
2497
+ } catch {}
2498
+ }
2499
+ browserCulture() {
2500
+ if (typeof navigator === "undefined") return null;
2501
+ return navigator.languages?.[0] ?? navigator.language ?? null;
2502
+ }
2503
+ static {
2504
+ this.ɵfac = i0.ɵɵngDeclareFactory({
2505
+ minVersion: "12.0.0",
2506
+ version: "22.2.1",
2507
+ ngImport: i0,
2508
+ type: TranslationService,
2509
+ deps: [],
2510
+ target: i0.ɵɵFactoryTarget.Injectable
2511
+ });
2512
+ }
2513
+ static {
2514
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
2515
+ minVersion: "12.0.0",
2516
+ version: "22.2.1",
2517
+ ngImport: i0,
2518
+ type: TranslationService,
2519
+ providedIn: "root"
2520
+ });
2521
+ }
2522
+ };
2523
+ i0.ɵɵngDeclareClassMetadata({
2524
+ minVersion: "12.0.0",
2525
+ version: "22.2.1",
2526
+ ngImport: i0,
2527
+ type: TranslationService,
2528
+ decorators: [{
2529
+ type: Injectable,
2530
+ args: [{ providedIn: "root" }]
2531
+ }]
2532
+ });
2533
+ var TranslatePipe = class TranslatePipe {
2534
+ constructor() {
2535
+ this.translation = inject(TranslationService);
2536
+ }
2537
+ transform(key, params) {
2538
+ if (!key) return "";
2539
+ return this.translation.translate(key, params);
2540
+ }
2541
+ static {
2542
+ this.ɵfac = i0.ɵɵngDeclareFactory({
2543
+ minVersion: "12.0.0",
2544
+ version: "22.2.1",
2545
+ ngImport: i0,
2546
+ type: TranslatePipe,
2547
+ deps: [],
2548
+ target: i0.ɵɵFactoryTarget.Pipe
2549
+ });
2550
+ }
2551
+ static {
2552
+ this.ɵpipe = i0.ɵɵngDeclarePipe({
2553
+ minVersion: "14.0.0",
2554
+ version: "22.2.1",
2555
+ ngImport: i0,
2556
+ type: TranslatePipe,
2557
+ isStandalone: true,
2558
+ name: "t",
2559
+ pure: false
2560
+ });
2561
+ }
2562
+ };
2563
+ i0.ɵɵngDeclareClassMetadata({
2564
+ minVersion: "12.0.0",
2565
+ version: "22.2.1",
2566
+ ngImport: i0,
2567
+ type: TranslatePipe,
2568
+ decorators: [{
2569
+ type: Pipe,
2570
+ args: [{
2571
+ name: "t",
2572
+ standalone: true,
2573
+ pure: false
2574
+ }]
2575
+ }]
2576
+ });
2577
+ var AcceptLanguageInterceptor = class AcceptLanguageInterceptor {
2578
+ intercept(req, next) {
2579
+ const culture = TranslationService.currentCulture;
2580
+ if (culture && req.url.startsWith(ServerUrl.apiUrl) && !req.headers.has("Accept-Language")) req = req.clone({ setHeaders: { "Accept-Language": culture } });
2581
+ return next.handle(req);
2582
+ }
2583
+ static {
2584
+ this.ɵfac = i0.ɵɵngDeclareFactory({
2585
+ minVersion: "12.0.0",
2586
+ version: "22.2.1",
2587
+ ngImport: i0,
2588
+ type: AcceptLanguageInterceptor,
2589
+ deps: [],
2590
+ target: i0.ɵɵFactoryTarget.Injectable
2591
+ });
2592
+ }
2593
+ static {
2594
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
2595
+ minVersion: "12.0.0",
2596
+ version: "22.2.1",
2597
+ ngImport: i0,
2598
+ type: AcceptLanguageInterceptor
2599
+ });
2600
+ }
2601
+ };
2602
+ i0.ɵɵngDeclareClassMetadata({
2603
+ minVersion: "12.0.0",
2604
+ version: "22.2.1",
2605
+ ngImport: i0,
2606
+ type: AcceptLanguageInterceptor,
2607
+ decorators: [{ type: Injectable }]
2608
+ });
2609
+ export { AcceptLanguageInterceptor, AppConfiguration, AppKeys, ApplicationMenuService, AuthGuard, AuthInterceptor, AuthService, AuthTokenType, BreadcrumbService, BusMessageService, CanActivateGuard, CoreServicesModule, DFLAT_TRANSLATION_CONFIG, ExternalLoginService, FilterService, GeolocationService, HeadersService, HubService, InitCacheService, LocalStoreManager, MODULE_MENU_SERVICES, MenuItem, MenuService, MessagesService, NotificationMqService, NotificationsService, PermissionService, ScreenService, ServerUrl, TranslatePipe, TranslationService, TranslationStore, UserService, formatMessage, trimChar };
2256
2610
 
2257
2611
  //# sourceMappingURL=dflat-core-web-core-services.mjs.map