@rdlabo/ionic-angular-kit 0.0.26 → 21.2.0-10

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.
@@ -1,5 +1,5 @@
1
1
  import * as i0 from '@angular/core';
2
- import { inject, Injectable, InjectionToken, makeEnvironmentProviders, ElementRef, Injector, input, computed, HostListener, Directive } from '@angular/core';
2
+ import { inject, Injectable, InjectionToken, makeEnvironmentProviders, ElementRef, Injector, input, computed, HostListener, Directive, afterNextRender } from '@angular/core';
3
3
  import { Storage } from '@ionic/storage-angular';
4
4
  import { ModalController, PopoverController, ToastController, AlertController, LoadingController, NavController } from '@ionic/angular/standalone';
5
5
  import { Capacitor } from '@capacitor/core';
@@ -157,6 +157,57 @@ const kitRecallEmail = (store) => store.get(KIT_LAST_AUTH_EMAIL_KEY);
157
157
  */
158
158
  const kitForgetEmail = (store) => store.remove(KIT_LAST_AUTH_EMAIL_KEY);
159
159
 
160
+ /**
161
+ * Canonical storage keys persisted via {@link KitStorageService} that fleet apps often need to
162
+ * keep across a sign-out `clear()`.
163
+ *
164
+ * @remarks
165
+ * `KIT_LAST_AUTH_EMAIL_KEY` lives in `kit-auth-email-store` and is exported from the package root.
166
+ * Import both keys from `@rdlabo/ionic-angular-kit` alongside {@link kitClearStoragePreservingKeys}.
167
+ */
168
+ /**
169
+ * Light/dark preference for `provideKitTheme` / `KitThemeController`.
170
+ *
171
+ * @remarks
172
+ * Pass this as `provideKitTheme({ storageKey: KIT_THEME_STORAGE_KEY, … })` and include it in
173
+ * {@link kitClearStoragePreservingKeys} so logout does not reset the user's theme.
174
+ */
175
+ const KIT_THEME_STORAGE_KEY = 'theme';
176
+
177
+ /**
178
+ * Clear a key/value store while restoring selected keys afterward.
179
+ *
180
+ * @remarks
181
+ * Fleet apps often call `storage.clear()` on sign-out to drop session/token state. Values that
182
+ * should survive logout (for example {@link KIT_LAST_AUTH_EMAIL_KEY}) are passed in `keys`.
183
+ * Missing keys are skipped — only non-null values are written back.
184
+ */
185
+ /**
186
+ * Wipe the store, then restore the given keys to their pre-clear values (when present).
187
+ *
188
+ * @param store - the app's storage (e.g. `KitStorageService`)
189
+ * @param keys - keys whose values should survive the clear
190
+ *
191
+ * @example
192
+ * ```ts
193
+ * import { KIT_LAST_AUTH_EMAIL_KEY, KIT_THEME_STORAGE_KEY, kitClearStoragePreservingKeys } from '@rdlabo/ionic-angular-kit';
194
+ *
195
+ * await kitSignOut(auth, {
196
+ * success: () =>
197
+ * kitClearStoragePreservingKeys(this.storage, [KIT_LAST_AUTH_EMAIL_KEY, KIT_THEME_STORAGE_KEY]),
198
+ * });
199
+ * ```
200
+ */
201
+ const kitClearStoragePreservingKeys = async (store, keys) => {
202
+ const preserved = await Promise.all(keys.map(async (key) => ({ key, value: await store.get(key) })));
203
+ await store.clear();
204
+ for (const { key, value } of preserved) {
205
+ if (value !== null) {
206
+ await store.set(key, value);
207
+ }
208
+ }
209
+ };
210
+
160
211
  /**
161
212
  * Injection token carrying the {@link KitOverlayConfig} for `KitOverlayController`.
162
213
  *
@@ -651,6 +702,157 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
651
702
  }]
652
703
  }] });
653
704
 
705
+ /**
706
+ * Singleton "maintenance lock" overlay: backdrop-locked, no dismiss buttons, auto-clears via SSE.
707
+ *
708
+ * @remarks
709
+ * Mirrors {@link KitReloadAlertController} as a de-duped stateful controller, but the user cannot
710
+ * cancel or reload out of it — only the server `event: ended` on {@link KitMaintenanceOptions.waitUrl}
711
+ * (or an explicit {@link dismiss}) clears it. Uses Ionic's `AlertController` (not a feature modal)
712
+ * so the kit stays free of page components / i18n; all copy is supplied by the caller.
713
+ *
714
+ * Wire from {@link KitHttpConfig.onMaintenance} when the API returns `503` with
715
+ * `error.error?.code === 'MAINTENANCE'`.
716
+ *
717
+ * @example
718
+ * ```ts
719
+ * provideKitHttp(() => {
720
+ * const maintenance = inject(KitMaintenanceController);
721
+ * return {
722
+ * getAuthHeaders: async () => ({}),
723
+ * onMaintenance: () =>
724
+ * void maintenance.present({
725
+ * header: 'メンテナンス中です',
726
+ * message: 'しばらくお待ちください。終了次第、自動で閉じます。',
727
+ * waitUrl: environment.api + 'public/maintenance/wait',
728
+ * }),
729
+ * };
730
+ * });
731
+ * ```
732
+ */
733
+ class KitMaintenanceController {
734
+ #alertCtrl = inject(AlertController);
735
+ #alert = null;
736
+ #source = null;
737
+ #reconnectTimer = null;
738
+ #reconnectAttempt = 0;
739
+ #waitUrl = null;
740
+ /** When true, EventSource errors must not schedule reconnect (ended / dismiss). */
741
+ #closed = false;
742
+ /**
743
+ * Present the lock overlay and start waiting on the maintenance SSE, unless one is already showing.
744
+ *
745
+ * @param options - overlay copy plus the wait SSE URL
746
+ */
747
+ async present(options) {
748
+ if (this.#alert || document.querySelector('ion-alert.kit-maintenance-alert')) {
749
+ return;
750
+ }
751
+ this.#closed = false;
752
+ this.#waitUrl = options.waitUrl;
753
+ const alert = await this.#alertCtrl.create({
754
+ header: options.header,
755
+ message: options.message,
756
+ backdropDismiss: false,
757
+ // No buttons — dismissal is server-driven via SSE (or an explicit dismiss()).
758
+ buttons: [],
759
+ cssClass: 'kit-maintenance-alert',
760
+ });
761
+ this.#alert = alert;
762
+ void alert.onDidDismiss().then(() => {
763
+ if (this.#alert === alert) {
764
+ this.#alert = null;
765
+ }
766
+ this.#stopWait();
767
+ });
768
+ await alert.present();
769
+ this.#startWait(options.waitUrl);
770
+ }
771
+ /**
772
+ * Dismiss the tracked overlay and tear down the wait SSE.
773
+ *
774
+ * @remarks
775
+ * Normally called when the wait stream emits `ended`. A no-op when nothing is showing.
776
+ */
777
+ async dismiss() {
778
+ this.#stopWait();
779
+ const alert = this.#alert;
780
+ this.#alert = null;
781
+ await alert?.dismiss();
782
+ }
783
+ #startWait(waitUrl) {
784
+ this.#stopSourceOnly();
785
+ if (this.#closed) {
786
+ return;
787
+ }
788
+ const source = new EventSource(waitUrl);
789
+ this.#source = source;
790
+ source.addEventListener('ended', () => {
791
+ void this.dismiss();
792
+ });
793
+ source.addEventListener('ping', () => {
794
+ // Keepalive — resets reconnect backoff so a lively stream does not treat the next pause as failure.
795
+ this.#reconnectAttempt = 0;
796
+ });
797
+ source.onerror = () => {
798
+ // EventSource auto-reconnects, but after a deploy the old isolate may hang; force a clean
799
+ // reconnect with exponential backoff once the browser surfaces an error.
800
+ if (this.#closed || this.#waitUrl !== waitUrl) {
801
+ return;
802
+ }
803
+ this.#stopSourceOnly();
804
+ this.#scheduleReconnect();
805
+ };
806
+ source.onopen = () => {
807
+ this.#reconnectAttempt = 0;
808
+ };
809
+ }
810
+ #scheduleReconnect() {
811
+ if (this.#closed || !this.#waitUrl) {
812
+ return;
813
+ }
814
+ if (this.#reconnectTimer) {
815
+ clearTimeout(this.#reconnectTimer);
816
+ }
817
+ const delay = Math.min(30_000, 500 * 2 ** this.#reconnectAttempt);
818
+ this.#reconnectAttempt += 1;
819
+ const waitUrl = this.#waitUrl;
820
+ this.#reconnectTimer = setTimeout(() => {
821
+ this.#reconnectTimer = null;
822
+ if (!this.#closed && this.#waitUrl === waitUrl) {
823
+ this.#startWait(waitUrl);
824
+ }
825
+ }, delay);
826
+ }
827
+ #stopWait() {
828
+ this.#closed = true;
829
+ this.#waitUrl = null;
830
+ this.#reconnectAttempt = 0;
831
+ if (this.#reconnectTimer) {
832
+ clearTimeout(this.#reconnectTimer);
833
+ this.#reconnectTimer = null;
834
+ }
835
+ this.#stopSourceOnly();
836
+ }
837
+ #stopSourceOnly() {
838
+ const source = this.#source;
839
+ this.#source = null;
840
+ if (source) {
841
+ source.onerror = null;
842
+ source.onopen = null;
843
+ source.close();
844
+ }
845
+ }
846
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitMaintenanceController, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
847
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitMaintenanceController, providedIn: 'root' }); }
848
+ }
849
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitMaintenanceController, decorators: [{
850
+ type: Injectable,
851
+ args: [{
852
+ providedIn: 'root',
853
+ }]
854
+ }] });
855
+
654
856
  /**
655
857
  * Present the fleet's canonical "sign-in / token exchange failed" alert.
656
858
  *
@@ -1178,6 +1380,17 @@ const MAX_RETRIES = 2;
1178
1380
  * @internal
1179
1381
  */
1180
1382
  const DEFAULT_TIMEOUT_MS = 60_000;
1383
+ /**
1384
+ * True when the error is the fleet maintenance short-circuit (`503` + body `code: 'MAINTENANCE'`).
1385
+ *
1386
+ * @remarks
1387
+ * Matches Angular `HttpErrorResponse` as `error.error?.code === 'MAINTENANCE'` (body top-level
1388
+ * `code`). Must not be retried and must not fall through to {@link KitHttpConfig.onServerBusy}.
1389
+ *
1390
+ * @param error - The failed response.
1391
+ * @returns Whether this is a maintenance response.
1392
+ */
1393
+ const isMaintenanceError = (error) => error.status === 503 && error.error?.code === 'MAINTENANCE';
1181
1394
  /**
1182
1395
  * Parse a `Retry-After` header (delta-seconds or an HTTP-date) into milliseconds, or `null` when it
1183
1396
  * is absent or unparseable.
@@ -1259,6 +1472,9 @@ const dispatchError = (config, req, error) => {
1259
1472
  else if (status === 429) {
1260
1473
  config.onRateLimited?.(retryAfterSeconds);
1261
1474
  }
1475
+ else if (isMaintenanceError(error)) {
1476
+ config.onMaintenance?.();
1477
+ }
1262
1478
  else if ([502, 503, 504].includes(status)) {
1263
1479
  config.onServerBusy?.(status, retryAfterSeconds);
1264
1480
  }
@@ -1283,8 +1499,8 @@ const dispatchError = (config, req, error) => {
1283
1499
  * When the device is offline it stops retrying immediately.
1284
1500
  * 5. On the final error, `offlineFallback` is consulted first; otherwise the error is classified by
1285
1501
  * status (see {@link dispatchError}): `401`→`onUnauthorized`, `403`→`onForbidden`, `0`→
1286
- * `onNetworkError` (when connected), `429`→`onRateLimited`, `502`/`503`/`504`→`onServerBusy`, and
1287
- * `400`/`422`/`500` with a body message→`onServerError`.
1502
+ * `onNetworkError` (when connected), `429`→`onRateLimited`, maintenance `503`→`onMaintenance`,
1503
+ * other `502`/`503`/`504`→`onServerBusy`, and `400`/`422`/`500` with a body message→`onServerError`.
1288
1504
  *
1289
1505
  * @param request - The outgoing request.
1290
1506
  * @param next - The next handler in the interceptor chain.
@@ -1325,7 +1541,8 @@ const kitAuthInterceptor = (request, next) => {
1325
1541
  return throwError(() => error);
1326
1542
  }
1327
1543
  // Only replay idempotent requests, and only on a transient status.
1328
- if (!retryable || !RETRYABLE_STATUSES.includes(error.status)) {
1544
+ // Maintenance 503 is intentional — never retry; go straight to onMaintenance.
1545
+ if (!retryable || !RETRYABLE_STATUSES.includes(error.status) || isMaintenanceError(error)) {
1329
1546
  return throwError(() => error);
1330
1547
  }
1331
1548
  // Short linear backoff (500ms, 1000ms, …) plus jitter to de-correlate a fleet of
@@ -1472,29 +1689,66 @@ const objectEqual = (a, b) => {
1472
1689
  return JSON.stringify(sortDeep(a)) === JSON.stringify(sortDeep(b));
1473
1690
  };
1474
1691
 
1692
+ const isDisableable = (element) => element instanceof HTMLElement && 'disabled' in element;
1693
+ const getIonicSubmitButtons = (form) => Array.from(document.querySelectorAll('ion-button[type="submit"]')).filter((button) => {
1694
+ if (!isDisableable(button))
1695
+ return false;
1696
+ const associatedForm = button.form;
1697
+ return (associatedForm === form ||
1698
+ (typeof associatedForm === 'string' && associatedForm === form.id) ||
1699
+ (form.id !== '' && button.getAttribute('form') === form.id) ||
1700
+ button.closest('form') === form);
1701
+ });
1702
+ const getDisableTargets = (event) => {
1703
+ const submitter = 'submitter' in event ? event.submitter : null;
1704
+ const form = event.target instanceof HTMLFormElement ? event.target : null;
1705
+ const targets = [];
1706
+ if (event.type === 'submit' && form) {
1707
+ targets.push(...getIonicSubmitButtons(form));
1708
+ }
1709
+ if (isDisableable(submitter)) {
1710
+ const root = submitter.getRootNode();
1711
+ const target = root instanceof ShadowRoot ? root.host : submitter;
1712
+ if (isDisableable(target))
1713
+ targets.push(target);
1714
+ }
1715
+ if (targets.length === 0 && isDisableable(event.currentTarget))
1716
+ targets.push(event.currentTarget);
1717
+ if (targets.length === 0 && isDisableable(event.target))
1718
+ targets.push(event.target);
1719
+ return [...new Set(targets)];
1720
+ };
1475
1721
  /**
1476
- * Disable the button that triggered an event while an async operation runs, re-enabling it after.
1722
+ * Disable the controls that triggered an event while an async operation runs.
1477
1723
  *
1478
1724
  * @remarks
1479
- * Prevents the common double-submit / double-tap bug: the `event.target` button is disabled, the
1480
- * work is awaited, and the button is re-enabled — even if the work rejects (the rejection is
1481
- * swallowed here so the button always recovers; handle errors inside `work` if you need to react).
1482
- *
1483
- * @param event - The DOM event whose `target` is the button to disable (e.g. a click event).
1484
- * @param work - The async operation to run while the button is disabled.
1485
- * @returns A Promise that resolves once the work has settled and the button has been re-enabled.
1725
+ * For a click event, the clicked control is disabled. For a submit event, the submitter is
1726
+ * disabled and the browser's default form navigation is prevented. Ionic's external
1727
+ * `ion-button[form]` uses a hidden native submitter, so buttons associated with the submitted form
1728
+ * are resolved through their `form` property and disabled instead. Rejections are swallowed so
1729
+ * controls always recover; handle errors inside `work` when the caller needs to react.
1730
+ *
1731
+ * @param event - The click or submit event that triggered the operation.
1732
+ * @param work - The async operation to run while the controls are disabled.
1733
+ * @returns A Promise that resolves once the work has settled and the controls have been restored.
1486
1734
  * @example
1487
- * ```ts
1488
- * async submit(event: Event): Promise<void> {
1489
- * await disableHandler(event, this.save());
1490
- * }
1735
+ * ```html
1736
+ * <form #formRef (submit)="helper.disableHandler($event, save())"></form>
1737
+ * <ion-button type="submit" [form]="formRef">Save</ion-button>
1491
1738
  * ```
1492
1739
  */
1493
1740
  const disableHandler = async (event, work) => {
1494
- const target = event.target;
1495
- target.disabled = true;
1496
- await work.catch(() => undefined);
1497
- target.disabled = false;
1741
+ if (event.type === 'submit')
1742
+ event.preventDefault();
1743
+ const targets = getDisableTargets(event);
1744
+ const disabledStates = targets.map((target) => target.disabled);
1745
+ targets.forEach((target) => (target.disabled = true));
1746
+ try {
1747
+ await work.catch(() => undefined);
1748
+ }
1749
+ finally {
1750
+ targets.forEach((target, index) => (target.disabled = disabledStates[index]));
1751
+ }
1498
1752
  };
1499
1753
 
1500
1754
  /**
@@ -1556,6 +1810,16 @@ const kitCreateDidEnter = (el) => {
1556
1810
  }).pipe(startWith(false));
1557
1811
  };
1558
1812
 
1813
+ /**
1814
+ * Component host を ViewModel 用に絞り込み、初回 render 後の mount hook を登録する。
1815
+ */
1816
+ function mountViewModel(host, onMount) {
1817
+ if (onMount) {
1818
+ afterNextRender(onMount);
1819
+ }
1820
+ return host;
1821
+ }
1822
+
1559
1823
  /*
1560
1824
  * Public API Surface of @rdlabo/ionic-angular-kit
1561
1825
  */
@@ -1565,5 +1829,5 @@ const kitCreateDidEnter = (el) => {
1565
1829
  * Generated bundle index. Do not edit.
1566
1830
  */
1567
1831
 
1568
- export { KIT_AUTH_CONFIG, KIT_HTTP_CONFIG, KIT_LAST_AUTH_EMAIL_KEY, KIT_OVERLAY_CONFIG, KitAuthInputDirective, KitLoadingController, KitOverlayController, KitReloadAlertController, KitStorageService, arrayConcatById, disableHandler, kitAuthInterceptor, kitChangeEventDisabled, kitCreateDidEnter, kitForgetEmail, kitImpact, kitIsValidEmail, kitKeyboardInit, kitPresentAuthFailedAlert, kitPresentLanguageActionSheet, kitRecallEmail, kitRememberEmail, kitRequireAuthorizedGuard, kitRequireConfirmingGuard, kitRequiredUnauthorizedGuard, objectEqual, provideKitAuth, provideKitHttp, provideKitOverlay };
1832
+ export { KIT_AUTH_CONFIG, KIT_HTTP_CONFIG, KIT_LAST_AUTH_EMAIL_KEY, KIT_OVERLAY_CONFIG, KIT_THEME_STORAGE_KEY, KitAuthInputDirective, KitLoadingController, KitMaintenanceController, KitOverlayController, KitReloadAlertController, KitStorageService, arrayConcatById, disableHandler, isMaintenanceError, kitAuthInterceptor, kitChangeEventDisabled, kitClearStoragePreservingKeys, kitCreateDidEnter, kitForgetEmail, kitImpact, kitIsValidEmail, kitKeyboardInit, kitPresentAuthFailedAlert, kitPresentLanguageActionSheet, kitRecallEmail, kitRememberEmail, kitRequireAuthorizedGuard, kitRequireConfirmingGuard, kitRequiredUnauthorizedGuard, mountViewModel, objectEqual, provideKitAuth, provideKitHttp, provideKitOverlay };
1569
1833
  //# sourceMappingURL=rdlabo-ionic-angular-kit.mjs.map