Skip to content

Commit 9747baa

Browse files
authored
Merge pull request #9 from rdlabo-team/feat/kit-loading-and-modal-input-typing
feat(kit): KitLoadingController + inferred presentModal typing
2 parents 1cdf194 + 1c4d8ec commit 9747baa

8 files changed

Lines changed: 457 additions & 19 deletions

File tree

‎.github/workflows/lint.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ jobs:
3333
runs-on: ubuntu-latest
3434
strategy:
3535
matrix:
36-
project: [ demo, photo-editor, scroll-header, scroll-strategies]
36+
project: [ demo, kit, photo-editor, scroll-header, scroll-strategies]
3737
steps:
3838
- uses: actions/checkout@v5
3939
- uses: actions/setup-node@v5

‎package-lock.json‎

Lines changed: 34 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎projects/kit/README.md‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -127,8 +127,8 @@ export class MyPage {
127127
readonly #overlay = inject(KitOverlayController);
128128

129129
async openDetail(): Promise<void> {
130-
const result = await this.#overlay.presentModal<{ id: number }>(DetailPage, { item });
131-
// result is the data passed to modal.dismiss()
130+
const result = await this.#overlay.presentModal(DetailPage, { item });
131+
// result type is inferred from `declare static modalReturn` on DetailPage
132132
}
133133

134134
async confirm(): Promise<void> {
@@ -149,11 +149,12 @@ export class MyPage {
149149
**API**
150150

151151
```typescript
152-
presentModal<O>(
153-
component: ModalOptions['component'],
154-
componentProps?: ModalOptions['componentProps'],
155-
options?: KitModalPresentOptions, // Omit<ModalOptions, 'component'|'componentProps'> + watchKeyboard?
156-
): Promise<O | undefined>
152+
presentModal<C extends ModalOptions['component']>(
153+
component: C,
154+
...args: ModalPresentArgs<C>, // props inferred from input() fields; options?: KitModalPresentOptions
155+
): Promise<ModalReturnOf<C> | undefined>
156+
// Props inferred from the component's input() fields (required/optional).
157+
// Return type inferred from `declare static modalReturn: T` on the component (void if absent).
157158

158159
presentPopover<O>(
159160
component: PopoverOptions['component'],
@@ -182,9 +183,14 @@ alertConfirm(options: {
182183
**Best practice — the modal launcher pattern.** Never call `modalController.create(...)` inline in a component. Instead, each modal/popover page exports a typed launcher next to itself and every call site goes through `KitOverlayController`:
183184

184185
```typescript
185-
// detail.page.ts
186-
export const launchDetailPage = (overlay: KitOverlayController, props: DetailProps): Promise<DetailResult | undefined> =>
187-
overlay.presentModal<DetailResult>(DetailPage, props, { backdropDismiss: false });
186+
// detail.page.ts — component declares its return type:
187+
export class DetailPage {
188+
declare static modalReturn: DetailResult;
189+
readonly item = input.required<Item>();
190+
}
191+
192+
export const launchDetailPage = (overlay: KitOverlayController, props: { item: Item }): Promise<DetailResult | undefined> =>
193+
overlay.presentModal(DetailPage, props, { backdropDismiss: false });
188194
```
189195

190196
This centralizes presentation options, keeps component props and dismiss data type-safe, and makes every modal discoverable. A well-disciplined app has **zero** inline `controller.create()` calls.
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import { provideZonelessChangeDetection } from '@angular/core';
2+
import { TestBed } from '@angular/core/testing';
3+
import { LoadingController } from '@ionic/angular/standalone';
4+
5+
import { KitLoadingController } from './kit-loading.controller';
6+
7+
// ---------------------------------------------------------------------------
8+
// Fake loading element factories
9+
// ---------------------------------------------------------------------------
10+
function fakeLoading() {
11+
return {
12+
present: vi.fn().mockResolvedValue(undefined),
13+
dismiss: vi.fn().mockResolvedValue(undefined),
14+
};
15+
}
16+
17+
// A loading whose present() stays pending until we resolve it, to reproduce a dismiss that arrives
18+
// mid-presentation.
19+
function deferredLoading() {
20+
let resolvePresent!: () => void;
21+
const loading = {
22+
present: vi.fn().mockReturnValue(new Promise<void>((r) => (resolvePresent = r))),
23+
dismiss: vi.fn().mockResolvedValue(undefined),
24+
};
25+
return { loading, resolvePresent: () => resolvePresent() };
26+
}
27+
28+
function setup(loading: ReturnType<typeof fakeLoading> = fakeLoading()) {
29+
const loadingCtrl = { create: vi.fn().mockResolvedValue(loading) };
30+
31+
TestBed.configureTestingModule({
32+
providers: [provideZonelessChangeDetection(), KitLoadingController, { provide: LoadingController, useValue: loadingCtrl }],
33+
});
34+
35+
return { controller: TestBed.inject(KitLoadingController), loadingCtrl, loading };
36+
}
37+
38+
// ---------------------------------------------------------------------------
39+
// Tests
40+
// ---------------------------------------------------------------------------
41+
describe('KitLoadingController', () => {
42+
afterEach(() => {
43+
TestBed.resetTestingModule();
44+
});
45+
46+
it('presents a single indicator and passes options through to create', async () => {
47+
const { controller, loadingCtrl, loading } = setup();
48+
await controller.presentLoading({ message: 'Loading…' });
49+
expect(loadingCtrl.create).toHaveBeenCalledOnce();
50+
expect(loadingCtrl.create).toHaveBeenCalledWith({ message: 'Loading…' });
51+
expect(loading.present).toHaveBeenCalledOnce();
52+
await controller.dismissLoading();
53+
});
54+
55+
it('shows one indicator for concurrent presents and dismisses only after the last release', async () => {
56+
const { controller, loadingCtrl, loading } = setup();
57+
await controller.presentLoading();
58+
await controller.presentLoading();
59+
expect(loadingCtrl.create).toHaveBeenCalledOnce();
60+
61+
await controller.dismissLoading();
62+
expect(loading.dismiss).not.toHaveBeenCalled(); // one reference still outstanding
63+
64+
await controller.dismissLoading();
65+
expect(loading.dismiss).toHaveBeenCalledOnce();
66+
});
67+
68+
it('is a no-op when dismissing while nothing is loading', async () => {
69+
const { controller, loadingCtrl, loading } = setup();
70+
await controller.dismissLoading();
71+
expect(loadingCtrl.create).not.toHaveBeenCalled();
72+
expect(loading.dismiss).not.toHaveBeenCalled();
73+
});
74+
75+
it('shows nothing when a present is immediately balanced by a dismiss', async () => {
76+
const { controller, loadingCtrl } = setup();
77+
const p = controller.presentLoading();
78+
const d = controller.dismissLoading();
79+
await Promise.all([p, d]);
80+
expect(loadingCtrl.create).not.toHaveBeenCalled();
81+
});
82+
83+
it('does not orphan the indicator when dismiss arrives before present() settles', async () => {
84+
const deferred = deferredLoading();
85+
const { controller, loadingCtrl } = setup(deferred.loading);
86+
87+
const p1 = controller.presentLoading(); // create resolves, then present() is left pending
88+
// Wait until we are genuinely mid-presentation (present() called but not settled), so the dismiss
89+
// lands inside the create→present window — the exact race a naive ref-count would orphan.
90+
await vi.waitFor(() => expect(deferred.loading.present).toHaveBeenCalled());
91+
92+
const p2 = controller.dismissLoading(); // count 0 → queued behind the still-pending present
93+
deferred.resolvePresent(); // present() settles → present task finishes → queued dismiss runs
94+
await Promise.all([p1, p2]);
95+
96+
expect(loadingCtrl.create).toHaveBeenCalledOnce();
97+
expect(deferred.loading.present).toHaveBeenCalledOnce();
98+
// The key assertion: the indicator is torn down after present() settled, not left orphaned.
99+
expect(deferred.loading.dismiss).toHaveBeenCalledOnce();
100+
});
101+
102+
it('creates a fresh indicator on a new cycle after full dismissal', async () => {
103+
const { controller, loadingCtrl } = setup();
104+
await controller.presentLoading();
105+
await controller.dismissLoading();
106+
await controller.presentLoading();
107+
expect(loadingCtrl.create).toHaveBeenCalledTimes(2);
108+
await controller.dismissLoading();
109+
});
110+
111+
it('a failed present rolls back its reference and does not wedge later operations', async () => {
112+
const { controller, loadingCtrl, loading } = setup();
113+
loadingCtrl.create.mockRejectedValueOnce(new Error('boom'));
114+
115+
// The failed reference is rolled back internally — no compensating dismissLoading() is needed.
116+
await expect(controller.presentLoading()).rejects.toThrow('boom');
117+
118+
loadingCtrl.create.mockResolvedValue(loading);
119+
await controller.presentLoading();
120+
expect(loading.present).toHaveBeenCalledOnce();
121+
122+
// A single dismiss tears the indicator down: proof the counter is balanced (not stuck at 1).
123+
await controller.dismissLoading();
124+
expect(loading.dismiss).toHaveBeenCalledOnce();
125+
});
126+
});
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
import { inject, Injectable } from '@angular/core';
2+
import type { LoadingOptions } from '@ionic/angular/standalone';
3+
import { LoadingController } from '@ionic/angular/standalone';
4+
5+
/**
6+
* Reference-counted wrapper around Ionic's `LoadingController` that keeps at most one loading
7+
* indicator on screen across concurrent async work.
8+
*
9+
* @remarks
10+
* Each {@link presentLoading} increments a counter and each {@link dismissLoading} decrements it; the
11+
* indicator is presented on the `0 → 1` transition and dismissed on the `N → 0` transition. This
12+
* removes the flicker / "stuck spinner" bugs that come from every service calling
13+
* `LoadingController.create/dismiss` independently.
14+
*
15+
* All operations are serialized through an internal promise chain, so a `create → present` sequence
16+
* can never interleave with a concurrent `dismiss`. That is what makes the counter race-safe: a
17+
* dismiss that arrives while the indicator is still being presented runs *after* `present()` settles
18+
* and therefore tears the element down instead of leaving it orphaned on screen.
19+
*
20+
* Always pair every `presentLoading()` with exactly one `dismissLoading()` — a `try/finally` is the
21+
* safest shape.
22+
*
23+
* @example
24+
* ```ts
25+
* constructor(private readonly loading: KitLoadingController) {}
26+
*
27+
* async save(): Promise<void> {
28+
* await this.loading.presentLoading({ message: 'Saving…' });
29+
* try {
30+
* await this.api.save();
31+
* } finally {
32+
* await this.loading.dismissLoading();
33+
* }
34+
* }
35+
* ```
36+
*/
37+
@Injectable({
38+
providedIn: 'root',
39+
})
40+
export class KitLoadingController {
41+
readonly #loadingCtrl = inject(LoadingController);
42+
43+
/** Outstanding {@link presentLoading} calls not yet balanced by {@link dismissLoading}. */
44+
#count = 0;
45+
46+
/** The single presented loading element, or `null` when none is on screen. */
47+
#loading: HTMLIonLoadingElement | null = null;
48+
49+
/**
50+
* Serializes present/dismiss operations. Each call chains onto this promise, runs after the
51+
* previous operation has fully settled, then reads {@link #count} and acts accordingly.
52+
*/
53+
#queue: Promise<void> = Promise.resolve();
54+
55+
/**
56+
* Show the loading indicator, or join the one already on screen.
57+
*
58+
* @param options - Ionic loading options; only applied by the call that actually creates the
59+
* indicator (the `0 → 1` transition). Ignored while an indicator is already present.
60+
* @returns a Promise that resolves once the indicator is on screen (or immediately when one already is)
61+
*/
62+
async presentLoading(options: LoadingOptions = {}): Promise<void> {
63+
this.#count++;
64+
try {
65+
await this.#enqueue(async () => {
66+
// Create only on the transition into "something is loading"; concurrent callers ride the same
67+
// element. Re-check the count in case a dismiss already balanced this call while queued.
68+
if (this.#count > 0 && this.#loading === null) {
69+
const loading = await this.#loadingCtrl.create(options);
70+
await loading.present();
71+
this.#loading = loading;
72+
}
73+
});
74+
} catch (error) {
75+
// Roll back the reference this call took: a failed create/present must not leave the counter
76+
// elevated, otherwise a later cycle never reaches N → 0 and the spinner stays stuck on screen.
77+
this.#count--;
78+
throw error;
79+
}
80+
}
81+
82+
/**
83+
* Release one reference; dismiss the indicator once the last reference is gone.
84+
*
85+
* @returns a Promise that resolves once the reference is released (and the indicator dismissed if
86+
* this was the last one). No-ops when the counter is already at zero.
87+
*/
88+
async dismissLoading(): Promise<void> {
89+
if (this.#count === 0) {
90+
return;
91+
}
92+
this.#count--;
93+
await this.#enqueue(async () => {
94+
// Tear down only when the last consumer is gone. Because this runs after any in-flight
95+
// present() has settled (via the queue), there is never an orphaned loading element.
96+
if (this.#count === 0 && this.#loading !== null) {
97+
const loading = this.#loading;
98+
this.#loading = null;
99+
await loading.dismiss();
100+
}
101+
});
102+
}
103+
104+
/**
105+
* Append `task` to the serialization chain and return its completion.
106+
*
107+
* @remarks
108+
* The stored chain swallows rejections so a single failing operation cannot wedge every future
109+
* overlay; the returned promise still rejects so the caller observes the error.
110+
*/
111+
#enqueue(task: () => Promise<void>): Promise<void> {
112+
const run = this.#queue.then(task);
113+
this.#queue = run.then(
114+
() => undefined,
115+
() => undefined,
116+
);
117+
return run;
118+
}
119+
}

0 commit comments

Comments
 (0)