@blotch/angular-lynx-testing-library 22.3.2 → 22.3.3

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 +1 @@
1
- {"version":3,"file":"app-state.d.ts","sourceRoot":"","sources":["../src/app-state.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,QAAQ,GAAG,QAAQ,GAAG,UAAU,GAAG,YAAY,CAAC;AAkB5D;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,WAAW,GAAI,OAAO,QAAQ,KAAG,IA+B7C,CAAC"}
1
+ {"version":3,"file":"app-state.d.ts","sourceRoot":"","sources":["../src/app-state.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,MAAM,MAAM,QAAQ,GAAG,QAAQ,GAAG,UAAU,GAAG,YAAY,CAAC;AAQ5D;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,WAAW,GAAI,OAAO,QAAQ,KAAG,IACO,CAAC"}
package/dist/app-state.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { setGlobalProp } from './global-props.js';
1
2
  /**
2
3
  * The global prop the shells send the state in (see the runtime's
3
4
  * app-state.ts).
@@ -29,29 +30,4 @@ const APP_STATE_PROP = 'appState';
29
30
  * while it's on screen but not taking touches (Control Center pulled over
30
31
  * it, or a call coming in), and `'active'` when it's back.
31
32
  */
32
- export const setAppState = (state) => {
33
- // Read through the environment rather than kept here: under `ng test`, the
34
- // setup file and the specs can load different copies of this module.
35
- const env = globalThis.lynxTestingEnv;
36
- // The runtime's callback for the engine, which it puts on the global as it
37
- // loads: specs run on the main thread, whose globals the environment copies
38
- // there.
39
- const update = globalThis.updateGlobalProps;
40
- if (!env || typeof update !== 'function') {
41
- throw new Error("setAppState() needs the testing library's environment, which its setup file installs, and the runtime, which render() loads.");
42
- }
43
- // The background thread's props, as the engine keeps both threads'. The
44
- // environment gives each thread a `lynx`.
45
- const background = env.backgroundThread.globalThis.lynx;
46
- background.__globalProps = {
47
- ...background.__globalProps,
48
- [APP_STATE_PROP]: state,
49
- };
50
- // What the engine calls on the main thread, where the app runs, when the
51
- // host sends new global props: the runtime merges them and LynxGlobalData
52
- // hears them.
53
- update({
54
- ...env.mainThread.globalThis.lynx.__globalProps,
55
- [APP_STATE_PROP]: state,
56
- });
57
- };
33
+ export const setAppState = (state) => setGlobalProp(APP_STATE_PROP, state, 'setAppState');
@@ -0,0 +1,95 @@
1
+ import type { MicrophonePermission } from '@blotch/angular-lynx';
2
+ /**
3
+ * Whether the fake phone lets the app use its microphone, as
4
+ * `@blotch/angular-lynx`'s `MicrophonePermission` names it.
5
+ */
6
+ export type FakeMicrophonePermission = MicrophonePermission;
7
+ /** What the fake phone's recordings hold, which {@link setRecordedAudio} sets. */
8
+ export type FakeRecordedAudio = {
9
+ /** The clip's bytes, which its `blob()` resolves with. */
10
+ readonly bytes?: Uint8Array;
11
+ /** Its type. `audio/mp4` when left out, as the shells record. */
12
+ readonly mimeType?: string;
13
+ /**
14
+ * How long it plays, in milliseconds. When left out, how long it recorded
15
+ * by the clock, which `vi.useFakeTimers()` moves.
16
+ */
17
+ readonly durationMs?: number;
18
+ };
19
+ /** The recording the app has open, as {@link audioRecording} reports it. */
20
+ export type FakeAudioRecordingInfo = {
21
+ /** `paused` after the app's `pause()` or {@link interruptAudioRecording}. */
22
+ readonly state: 'recording' | 'paused';
23
+ /** The `maxDuration` the app started it with, in milliseconds. */
24
+ readonly maxDuration?: number;
25
+ };
26
+ /**
27
+ * Gives the environment's background thread an `AngularLynxAudioRecorder`
28
+ * module, as the apps `ng build --platform` makes with
29
+ * `permissions.microphone` have. Its person hasn't been asked yet: the first
30
+ * start asks, and they allow it, unless {@link setMicrophonePermission} says
31
+ * otherwise. Each recording holds a few bytes, or what
32
+ * {@link setRecordedAudio} says. `LynxAudioRecorder` reaches it through the
33
+ * background thread, as it reaches the shells' module, so specs see the
34
+ * runtime's own behavior.
35
+ *
36
+ * It runs each time the environment injects the background thread's globals:
37
+ * when it's created, and on the reset after each test, so each test starts
38
+ * afresh. Only `NativeModules.AngularLynxAudioRecorder` is added.
39
+ */
40
+ export declare const installAudioRecorderModule: (threadGlobals: {
41
+ NativeModules?: Record<string, unknown>;
42
+ }) => void;
43
+ /**
44
+ * Sets whether the fake phone lets the app use its microphone: what
45
+ * `LynxAudioRecorder.permission` reads, and what `start()` finds. `denied`
46
+ * has `start()` reject with `denied`, and `unsupported` with `unavailable`,
47
+ * as on a phone without the module. `undetermined`, where each test starts,
48
+ * has the next start ask and the person allow it.
49
+ *
50
+ * Set it before the component that injects `LynxAudioRecorder` renders: the
51
+ * service reads the permission when it's created, and each time the app
52
+ * comes back to the foreground.
53
+ */
54
+ export declare const setMicrophonePermission: (permission: FakeMicrophonePermission) => void;
55
+ /**
56
+ * Sets what the fake phone's recordings hold from now on: the bytes a
57
+ * clip's `blob()` resolves with, its type and its length.
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * setRecordedAudio({ bytes: voiceNote, durationMs: 4200 });
62
+ * await render(VoiceNote);
63
+ * fireEvent.tap(screen.getByText('Record'));
64
+ * await waitForUpdate();
65
+ * fireEvent.tap(screen.getByText('Stop'));
66
+ * expect(await screen.findByText('0:04')).toBeInTheDocument();
67
+ * ```
68
+ */
69
+ export declare const setRecordedAudio: (audio: FakeRecordedAudio) => void;
70
+ /**
71
+ * The recording the app has open, or undefined while none is, such as
72
+ * before `start()` and after `stop()`.
73
+ */
74
+ export declare const audioRecording: () => FakeAudioRecordingInfo | undefined;
75
+ /**
76
+ * Sends the open recording's level (0..1) and its length so far by the
77
+ * clock, as the shells do about ten times a second. Once it's as long as its
78
+ * `maxDuration`, it ends instead, as the shells end it, and the app's
79
+ * `stop()` resolves with the clip. Does nothing while none records.
80
+ */
81
+ export declare const emitAudioLevel: (level: number) => void;
82
+ /**
83
+ * Pauses the open recording as the system does for a phone call or the app
84
+ * going to the background: the app's recording turns `paused`, and its
85
+ * `resume()` carries on. Does nothing while none records.
86
+ */
87
+ export declare const interruptAudioRecording: () => void;
88
+ /**
89
+ * Ends the open recording with an error, as the shells do when the
90
+ * microphone fails: the app's recording turns `stopped`, its `error` holds
91
+ * an `AudioRecorderError` with code `failed` and `message`, and its `stop()`
92
+ * rejects with it. Does nothing while none is open.
93
+ */
94
+ export declare const failAudioRecording: (message?: string) => void;
95
+ //# sourceMappingURL=audio-recorder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audio-recorder.d.ts","sourceRoot":"","sources":["../src/audio-recorder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAMjE;;;GAGG;AACH,MAAM,MAAM,wBAAwB,GAAG,oBAAoB,CAAC;AAE5D,kFAAkF;AAClF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,0DAA0D;IAC1D,QAAQ,CAAC,KAAK,CAAC,EAAE,UAAU,CAAC;IAC5B,iEAAiE;IACjE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B,CAAC;AAEF,4EAA4E;AAC5E,MAAM,MAAM,sBAAsB,GAAG;IACnC,6EAA6E;IAC7E,QAAQ,CAAC,KAAK,EAAE,WAAW,GAAG,QAAQ,CAAC;IACvC,kEAAkE;IAClE,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;CAC/B,CAAC;AA8EF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,0BAA0B,GAAI,eAAe;IACxD,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACzC,KAAG,IA6FH,CAAC;AAgBF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,uBAAuB,GAClC,YAAY,wBAAwB,KACnC,IAEF,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,gBAAgB,GAAI,OAAO,iBAAiB,KAAG,IAE3D,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,cAAc,QAAO,sBAAsB,GAAG,SAO1D,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,MAAM,KAAG,IAW9C,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,QAAO,IAO1C,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,GAC7B,gBAAkC,KACjC,IAMF,CAAC"}
@@ -0,0 +1,250 @@
1
+ /** What `LynxAudioRecorder` calls and hears, named as the shells name them. */
2
+ const MODULE = 'AngularLynxAudioRecorder';
3
+ const EVENT = 'angularLynxAudioRecorder';
4
+ /**
5
+ * What a recording holds when a spec doesn't say: a few bytes, which is all
6
+ * an app's code sees of a clip it uploads or shares.
7
+ */
8
+ const DEFAULT_BYTES = new Uint8Array([0, 0, 0, 24, 102, 116, 121, 112]);
9
+ const toBase64 = (bytes) => {
10
+ let binary = '';
11
+ for (const byte of bytes)
12
+ binary += String.fromCharCode(byte);
13
+ return btoa(binary);
14
+ };
15
+ const failure = (error, message) => ({ error, message });
16
+ const environment = () => globalThis.lynxTestingEnv;
17
+ /**
18
+ * Sends one of the shells' global events from the background thread, where
19
+ * they arrive, and comes back to the main thread, where specs run.
20
+ */
21
+ const emit = (payload) => {
22
+ const env = environment();
23
+ env.switchToBackgroundThread();
24
+ try {
25
+ env.backgroundThread.globalThis
26
+ .lynx.getJSModule('GlobalEventEmitter')
27
+ .emit(EVENT, [payload]);
28
+ }
29
+ finally {
30
+ env.switchToMainThread();
31
+ }
32
+ };
33
+ const elapsed = (open) => open.recorded + (open.since === undefined ? 0 : Date.now() - open.since);
34
+ /**
35
+ * Gives the environment's background thread an `AngularLynxAudioRecorder`
36
+ * module, as the apps `ng build --platform` makes with
37
+ * `permissions.microphone` have. Its person hasn't been asked yet: the first
38
+ * start asks, and they allow it, unless {@link setMicrophonePermission} says
39
+ * otherwise. Each recording holds a few bytes, or what
40
+ * {@link setRecordedAudio} says. `LynxAudioRecorder` reaches it through the
41
+ * background thread, as it reaches the shells' module, so specs see the
42
+ * runtime's own behavior.
43
+ *
44
+ * It runs each time the environment injects the background thread's globals:
45
+ * when it's created, and on the reset after each test, so each test starts
46
+ * afresh. Only `NativeModules.AngularLynxAudioRecorder` is added.
47
+ */
48
+ export const installAudioRecorderModule = (threadGlobals) => {
49
+ /**
50
+ * Stops the open recording, and describes the clip it made.
51
+ */
52
+ const finish = () => {
53
+ const open = module.open;
54
+ if (!open)
55
+ return undefined;
56
+ module.open = undefined;
57
+ const bytes = module.audio.bytes ?? DEFAULT_BYTES;
58
+ const mimeType = module.audio.mimeType ?? 'audio/mp4';
59
+ const name = `recording-${++module.clips}.${mimeType === 'audio/mp4' ? 'm4a' : 'audio'}`;
60
+ const uri = `file:///fake/recordings/${name}`;
61
+ // A copy, so a spec changing its array afterwards can't change this clip.
62
+ // Not slice(): a Buffer's slice() shares its memory.
63
+ module.files.set(uri, new Uint8Array(bytes));
64
+ return {
65
+ uri,
66
+ name,
67
+ durationMs: module.audio.durationMs ?? Math.round(elapsed(open)),
68
+ mimeType,
69
+ size: bytes.length,
70
+ };
71
+ };
72
+ const module = {
73
+ permissionState: 'undetermined',
74
+ audio: {},
75
+ open: undefined,
76
+ ended: undefined,
77
+ clips: 0,
78
+ files: new Map(),
79
+ permission: (done) => done({ permission: module.permissionState }),
80
+ requestPermission: (done) => {
81
+ // The person allows it when asked, as most do.
82
+ if (module.permissionState === 'undetermined') {
83
+ module.permissionState = 'granted';
84
+ }
85
+ done({ permission: module.permissionState });
86
+ },
87
+ start: (options, done) => {
88
+ module.requestPermission(() => { });
89
+ if (module.permissionState === 'unsupported') {
90
+ done(failure('unavailable', "The fake phone can't record."));
91
+ return;
92
+ }
93
+ if (module.permissionState === 'denied') {
94
+ done(failure('denied', "The person didn't allow the microphone."));
95
+ return;
96
+ }
97
+ module.open = {
98
+ id: options.recording,
99
+ ...(options.maxDuration !== undefined && {
100
+ maxDuration: options.maxDuration,
101
+ }),
102
+ recorded: 0,
103
+ since: Date.now(),
104
+ };
105
+ module.ended = undefined;
106
+ done({});
107
+ },
108
+ // The runtime pauses only a recording that records, and resumes only
109
+ // one that's paused, and refuses a second start itself.
110
+ pause: (done) => {
111
+ const open = module.open;
112
+ open.recorded = elapsed(open);
113
+ open.since = undefined;
114
+ done({});
115
+ },
116
+ resume: (done) => {
117
+ module.open.since = Date.now();
118
+ done({});
119
+ },
120
+ stop: (done) => {
121
+ const clip = finish() ?? module.ended;
122
+ done(clip ? { clip } : failure('failed', 'Nothing is recording.'));
123
+ },
124
+ cancel: (done) => {
125
+ module.open = undefined;
126
+ module.ended = undefined;
127
+ done({});
128
+ },
129
+ read: ({ uri }, done) => {
130
+ const bytes = module.files.get(uri);
131
+ done(bytes
132
+ ? { base64: toBase64(bytes) }
133
+ : failure('failed', "The recording couldn't be read."));
134
+ },
135
+ };
136
+ threadGlobals.NativeModules = {
137
+ ...threadGlobals.NativeModules,
138
+ [MODULE]: module,
139
+ };
140
+ };
141
+ const fakeModule = (caller) => {
142
+ // Read through the environment rather than kept here: under `ng test`, the
143
+ // setup file and the specs can load different copies of this module.
144
+ const module = environment()?.backgroundThread.globalThis.NativeModules?.[MODULE];
145
+ if (!module) {
146
+ throw new Error(`${caller}() needs the testing library's environment, which its setup file installs.`);
147
+ }
148
+ return module;
149
+ };
150
+ /**
151
+ * Sets whether the fake phone lets the app use its microphone: what
152
+ * `LynxAudioRecorder.permission` reads, and what `start()` finds. `denied`
153
+ * has `start()` reject with `denied`, and `unsupported` with `unavailable`,
154
+ * as on a phone without the module. `undetermined`, where each test starts,
155
+ * has the next start ask and the person allow it.
156
+ *
157
+ * Set it before the component that injects `LynxAudioRecorder` renders: the
158
+ * service reads the permission when it's created, and each time the app
159
+ * comes back to the foreground.
160
+ */
161
+ export const setMicrophonePermission = (permission) => {
162
+ fakeModule('setMicrophonePermission').permissionState = permission;
163
+ };
164
+ /**
165
+ * Sets what the fake phone's recordings hold from now on: the bytes a
166
+ * clip's `blob()` resolves with, its type and its length.
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * setRecordedAudio({ bytes: voiceNote, durationMs: 4200 });
171
+ * await render(VoiceNote);
172
+ * fireEvent.tap(screen.getByText('Record'));
173
+ * await waitForUpdate();
174
+ * fireEvent.tap(screen.getByText('Stop'));
175
+ * expect(await screen.findByText('0:04')).toBeInTheDocument();
176
+ * ```
177
+ */
178
+ export const setRecordedAudio = (audio) => {
179
+ fakeModule('setRecordedAudio').audio = audio;
180
+ };
181
+ /**
182
+ * The recording the app has open, or undefined while none is, such as
183
+ * before `start()` and after `stop()`.
184
+ */
185
+ export const audioRecording = () => {
186
+ const open = fakeModule('audioRecording').open;
187
+ if (!open)
188
+ return undefined;
189
+ return {
190
+ state: open.since === undefined ? 'paused' : 'recording',
191
+ ...(open.maxDuration !== undefined && { maxDuration: open.maxDuration }),
192
+ };
193
+ };
194
+ /**
195
+ * Sends the open recording's level (0..1) and its length so far by the
196
+ * clock, as the shells do about ten times a second. Once it's as long as its
197
+ * `maxDuration`, it ends instead, as the shells end it, and the app's
198
+ * `stop()` resolves with the clip. Does nothing while none records.
199
+ */
200
+ export const emitAudioLevel = (level) => {
201
+ const module = fakeModule('emitAudioLevel');
202
+ const open = module.open;
203
+ if (!open || open.since === undefined)
204
+ return;
205
+ const durationMs = Math.round(elapsed(open));
206
+ if (open.maxDuration !== undefined && durationMs >= open.maxDuration) {
207
+ module.ended = finishOpen(module);
208
+ emit({ type: 'ended', recording: open.id, clip: module.ended });
209
+ return;
210
+ }
211
+ emit({ type: 'level', recording: open.id, level, durationMs });
212
+ };
213
+ /**
214
+ * Pauses the open recording as the system does for a phone call or the app
215
+ * going to the background: the app's recording turns `paused`, and its
216
+ * `resume()` carries on. Does nothing while none records.
217
+ */
218
+ export const interruptAudioRecording = () => {
219
+ const module = fakeModule('interruptAudioRecording');
220
+ const open = module.open;
221
+ if (!open || open.since === undefined)
222
+ return;
223
+ open.recorded = elapsed(open);
224
+ open.since = undefined;
225
+ emit({ type: 'paused', recording: open.id });
226
+ };
227
+ /**
228
+ * Ends the open recording with an error, as the shells do when the
229
+ * microphone fails: the app's recording turns `stopped`, its `error` holds
230
+ * an `AudioRecorderError` with code `failed` and `message`, and its `stop()`
231
+ * rejects with it. Does nothing while none is open.
232
+ */
233
+ export const failAudioRecording = (message = 'The microphone failed.') => {
234
+ const module = fakeModule('failAudioRecording');
235
+ const open = module.open;
236
+ if (!open)
237
+ return;
238
+ module.open = undefined;
239
+ emit({ type: 'ended', recording: open.id, error: 'failed', message });
240
+ };
241
+ /**
242
+ * The open recording's clip, through the module's own stop.
243
+ */
244
+ const finishOpen = (module) => {
245
+ let clip;
246
+ module.stop((answer) => {
247
+ clip = answer.clip;
248
+ });
249
+ return clip;
250
+ };
@@ -1 +1 @@
1
- {"version":3,"file":"fire-event.d.ts","sourceRoot":"","sources":["../src/fire-event.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAoBH;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmEpB,CAAC;AAEF,KAAK,SAAS,GAAG,MAAM,OAAO,QAAQ,CAAC;AACvC,KAAK,YAAY,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC;AAC/E,KAAK,SAAS,GAAG,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,KAAK,OAAO,CAAC,GAAG;KAC3D,CAAC,IAAI,SAAS,GAAG,YAAY;CAC/B,CAAC;AAsLF,eAAO,MAAM,SAAS,EAAE,SAET,CAAC"}
1
+ {"version":3,"file":"fire-event.d.ts","sourceRoot":"","sources":["../src/fire-event.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAoBH;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmEpB,CAAC;AAEF,KAAK,SAAS,GAAG,MAAM,OAAO,QAAQ,CAAC;AACvC,KAAK,YAAY,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC;AAC/E,KAAK,SAAS,GAAG,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,KAAK,OAAO,CAAC,GAAG;KAC3D,CAAC,IAAI,SAAS,GAAG,YAAY;CAC/B,CAAC;AA8OF,eAAO,MAAM,SAAS,EAAE,SAET,CAAC"}
@@ -143,6 +143,46 @@ const createLynxEvent = (elem, type, name, init) => {
143
143
  });
144
144
  return event;
145
145
  };
146
+ /** Each reader runHandler puts in runWorklet's place, to the one it calls. */
147
+ const readers = new WeakMap();
148
+ /** Lynx's `EventResult::kStopPropagationBit`. */
149
+ const STOP_PROPAGATION = 1;
150
+ /** Lynx's `EventResult::kStopImmediatePropagationBit`. */
151
+ const STOP_IMMEDIATE_PROPAGATION = 2;
152
+ /**
153
+ * Runs `handler` with `event`, and returns the bits of Lynx's `EventResult`
154
+ * its worklet returned, which a device reads to stop the event
155
+ * (`TouchEventHandler::HandleEventOperations`): a listener's
156
+ * `$event.stopPropagation()` sets them. The testing environment's handler
157
+ * drops what its worklet returns, so it's read from runWorklet as it
158
+ * returns.
159
+ */
160
+ const runHandler = (handler, event) => {
161
+ const store = globalThis;
162
+ const run = store.runWorklet;
163
+ // The testing environment's own runWorklet, under any reader an enclosing
164
+ // fireEvent put there: a fireEvent inside a listener reads its own event's
165
+ // bits, which the enclosing one's mustn't take for its listener's.
166
+ const base = run && (readers.get(run) ?? run);
167
+ let bits = 0;
168
+ const reader = (...args) => {
169
+ const result = base?.(...args);
170
+ const returned = result
171
+ ?.eventReturnResult;
172
+ if (typeof returned === 'number')
173
+ bits |= returned;
174
+ return result;
175
+ };
176
+ readers.set(reader, base);
177
+ store.runWorklet = reader;
178
+ try {
179
+ handler(event);
180
+ }
181
+ finally {
182
+ store.runWorklet = run;
183
+ }
184
+ return bits;
185
+ };
146
186
  /**
147
187
  * Every element in `target`'s tree with a `global-bind` handler for `name`:
148
188
  * Lynx runs one for an event on any element of the page.
@@ -161,8 +201,11 @@ const globalHandlersOf = (target, name) => {
161
201
  * `window:` listener runs. An event that
162
202
  * bubbles goes down from the page to the target, running `capture-bind` and
163
203
  * `capture-catch` handlers, then back up, running `bind` and `catch` ones. A
164
- * `catch` handler of either phase runs and stops the event there. Any other
165
- * event runs the target's own `bind` or `catch` handler and nothing more.
204
+ * `catch` handler of either phase runs and stops the event there, and so
205
+ * does a handler whose listener called `stopPropagation()`, as Lynx reads
206
+ * the bits it returns; after `stopImmediatePropagation()` no other handler
207
+ * runs. Any other event runs the target's own `bind` or `catch` handler and
208
+ * nothing more.
166
209
  *
167
210
  * It calls the handlers rather than dispatching one DOM event, because the
168
211
  * testing environment listens for a separate DOM event per kind
@@ -186,7 +229,7 @@ const deliver = (target, name, init) => {
186
229
  let notCanceled = true;
187
230
  /**
188
231
  * Runs each element's handlers of `types` in turn. Returns true once a
189
- * catch handler stops the event.
232
+ * catch handler, or a listener's stopPropagation(), stops the event.
190
233
  */
191
234
  const runPhase = (elements, types) => {
192
235
  for (const element of elements) {
@@ -196,20 +239,27 @@ const deliver = (target, name, init) => {
196
239
  if (!handler)
197
240
  continue;
198
241
  const event = createLynxEvent(target, type, name, init);
199
- handler(event);
242
+ const bits = runHandler(handler, event);
200
243
  notCanceled &&= !event.defaultPrevented;
201
- caught ||= type.endsWith('catchEvent');
244
+ if (bits & STOP_IMMEDIATE_PROPAGATION)
245
+ return true;
246
+ caught ||= type.endsWith('catchEvent') || !!(bits & STOP_PROPAGATION);
202
247
  }
203
248
  if (caught)
204
249
  return true;
205
250
  }
206
251
  return false;
207
252
  };
208
- for (const element of globalHandlersOf(target, name)) {
253
+ // Lynx runs them first, so one that stops the event stops it for every
254
+ // element (see native-source.ts in the runtime).
255
+ const stoppedGlobally = globalHandlersOf(target, name).some((element) => {
209
256
  const event = createLynxEvent(target, 'global-bindEvent', name, init);
210
- handlerOf(element, 'global-bindEvent', name)(event);
257
+ const bits = runHandler(handlerOf(element, 'global-bindEvent', name), event);
211
258
  notCanceled &&= !event.defaultPrevented;
212
- }
259
+ return bits !== 0;
260
+ });
261
+ if (stoppedGlobally)
262
+ return notCanceled;
213
263
  // Lynx has no capture phase for the events that stay on their target.
214
264
  const captured = !!init['bubbles'] && runPhase([...chain].reverse(), CAPTURE_PHASE);
215
265
  if (!captured)
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Where {@link setLocation} puts the phone. Only the coordinates are needed;
3
+ * the rest is what the platform would know, null when left out.
4
+ */
5
+ export type FakeLocation = {
6
+ readonly latitude: number;
7
+ readonly longitude: number;
8
+ /** In meters. 5 by default, a good GPS fix. */
9
+ readonly accuracy?: number;
10
+ readonly altitude?: number | null;
11
+ readonly altitudeAccuracy?: number | null;
12
+ readonly heading?: number | null;
13
+ readonly speed?: number | null;
14
+ /** When it was found, in milliseconds since 1970. Now, by default. */
15
+ readonly timestamp?: number;
16
+ };
17
+ /**
18
+ * What the app is allowed, as `LynxGeolocation.state()` reports it (with
19
+ * `off` coming from {@link setLocationEnabled} instead).
20
+ */
21
+ export type FakeLocationPermission = 'unknown' | 'denied' | 'approximate' | 'precise';
22
+ /**
23
+ * Gives the environment's background thread an `AngularLynxGeolocation`
24
+ * module, as the apps `ng build --platform` makes have when angular.json's
25
+ * `permissions` list `location`. It starts where a fresh install does: the
26
+ * person hasn't been asked, allows precise location when the app asks, and
27
+ * the phone has no position until {@link setLocation} gives it one.
28
+ * `LynxGeolocation` reaches it through the background thread, as it reaches
29
+ * the shells' module, so specs see the runtime's own behavior.
30
+ *
31
+ * It runs each time the environment injects the background thread's
32
+ * globals: when it's created, and on the reset after each test, so each test
33
+ * starts from a fresh install.
34
+ */
35
+ export declare const installGeolocationModule: (threadGlobals: {
36
+ NativeModules?: Record<string, unknown>;
37
+ }) => void;
38
+ /**
39
+ * Puts the phone at `location`, or nowhere it can find with `null`: what
40
+ * `LynxGeolocation.getCurrentPosition()` resolves with, and the next
41
+ * position each running watch gets, unless it's nearer the last one than
42
+ * the watch's `distanceFilter`. Until a spec sets one, the phone can't find
43
+ * itself, and `getCurrentPosition()` rejects with `timeout`.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * setLocationPermission('precise');
48
+ * setLocation({ latitude: 51.5007, longitude: -0.1246 });
49
+ * await render(NearbyShops);
50
+ * expect(await screen.findByText('2 shops near you')).toBeInTheDocument();
51
+ * ```
52
+ */
53
+ export declare const setLocation: (location: FakeLocation | null) => void;
54
+ /**
55
+ * Sets what the app is allowed, as if the person had answered the prompt or
56
+ * changed it in Settings: what `LynxGeolocation.state()` reports, without a
57
+ * prompt unless it's `unknown` (each test starts there). `denied` ends every
58
+ * running watch, as it does on a phone.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * setLocationPermission('denied');
63
+ * await render(NearbyShops);
64
+ * expect(screen.getByText('Allow location in Settings')).toBeInTheDocument();
65
+ * ```
66
+ */
67
+ export declare const setLocationPermission: (permission: FakeLocationPermission) => void;
68
+ /**
69
+ * Sets what the person answers when `LynxGeolocation` shows the prompt:
70
+ * `precise` (the default), `approximate` (Android 12's and iOS's choice of
71
+ * an approximate location), or `denied`. The prompt shows only while the
72
+ * permission is `unknown`.
73
+ *
74
+ * @example
75
+ * ```ts
76
+ * setLocationAnswer('approximate');
77
+ * fireEvent.tap(screen.getByText('Find shops near me'));
78
+ * await waitForUpdate();
79
+ * expect(locationPrompts()).toBe(1);
80
+ * ```
81
+ */
82
+ export declare const setLocationAnswer: (answer: Exclude<FakeLocationPermission, "unknown">) => void;
83
+ /**
84
+ * Turns Location on or off for the whole phone. Off, the state is `off`,
85
+ * whatever the app is allowed, every call rejects with `off`, and every
86
+ * running watch ends with it.
87
+ */
88
+ export declare const setLocationEnabled: (enabled: boolean) => void;
89
+ /**
90
+ * How many times the location prompt has shown in this test, so a spec can
91
+ * check the app asks at the right moment, and only once.
92
+ */
93
+ export declare const locationPrompts: () => number;
94
+ //# sourceMappingURL=geolocation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"geolocation.d.ts","sourceRoot":"","sources":["../src/geolocation.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,+CAA+C;IAC/C,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1C,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACjC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,sEAAsE;IACtE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC7B,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,sBAAsB,GAC9B,SAAS,GACT,QAAQ,GACR,aAAa,GACb,SAAS,CAAC;AAiId;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,wBAAwB,GAAI,eAAe;IACtD,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACzC,KAAG,IAwEH,CAAC;AAmBF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,WAAW,GAAI,UAAU,YAAY,GAAG,IAAI,KAAG,IAQ3D,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,qBAAqB,GAChC,YAAY,sBAAsB,KACjC,IAUF,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,iBAAiB,GAC5B,QAAQ,OAAO,CAAC,sBAAsB,EAAE,SAAS,CAAC,KACjD,IAEF,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,GAAI,SAAS,OAAO,KAAG,IAOrD,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,eAAe,QAAO,MACG,CAAC"}