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

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.
Files changed (52) hide show
  1. package/dist/app-state.d.ts +34 -0
  2. package/dist/app-state.d.ts.map +1 -0
  3. package/dist/app-state.js +57 -0
  4. package/dist/apple-sign-in.d.ts +116 -0
  5. package/dist/apple-sign-in.d.ts.map +1 -0
  6. package/dist/apple-sign-in.js +179 -0
  7. package/dist/back-button.d.ts +43 -0
  8. package/dist/back-button.d.ts.map +1 -0
  9. package/dist/back-button.js +77 -0
  10. package/dist/barcode-scanner.d.ts +59 -0
  11. package/dist/barcode-scanner.d.ts.map +1 -0
  12. package/dist/barcode-scanner.js +100 -0
  13. package/dist/biometrics.d.ts +79 -0
  14. package/dist/biometrics.d.ts.map +1 -0
  15. package/dist/biometrics.js +151 -0
  16. package/dist/bluetooth.d.ts +121 -0
  17. package/dist/bluetooth.d.ts.map +1 -0
  18. package/dist/bluetooth.js +369 -0
  19. package/dist/calendar.d.ts +68 -0
  20. package/dist/calendar.d.ts.map +1 -0
  21. package/dist/calendar.js +120 -0
  22. package/dist/file-picker.d.ts +76 -0
  23. package/dist/file-picker.d.ts.map +1 -0
  24. package/dist/file-picker.js +125 -0
  25. package/dist/index.d.ts +28 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +15 -0
  28. package/dist/motion.d.ts +90 -0
  29. package/dist/motion.d.ts.map +1 -0
  30. package/dist/motion.js +169 -0
  31. package/dist/nfc.d.ts +85 -0
  32. package/dist/nfc.d.ts.map +1 -0
  33. package/dist/nfc.js +253 -0
  34. package/dist/photo-library.d.ts +58 -0
  35. package/dist/photo-library.d.ts.map +1 -0
  36. package/dist/photo-library.js +91 -0
  37. package/dist/render.d.ts.map +1 -1
  38. package/dist/render.js +19 -1
  39. package/dist/setup.js +59 -0
  40. package/dist/share-target.d.ts +56 -0
  41. package/dist/share-target.d.ts.map +1 -0
  42. package/dist/share-target.js +92 -0
  43. package/dist/store-review.d.ts +30 -0
  44. package/dist/store-review.d.ts.map +1 -0
  45. package/dist/store-review.js +49 -0
  46. package/dist/tracking.d.ts +60 -0
  47. package/dist/tracking.d.ts.map +1 -0
  48. package/dist/tracking.js +94 -0
  49. package/dist/wifi.d.ts +77 -0
  50. package/dist/wifi.d.ts.map +1 -0
  51. package/dist/wifi.js +148 -0
  52. package/package.json +3 -3
@@ -0,0 +1,369 @@
1
+ /** What `LynxBluetooth` calls and hears, named as the shells name them. */
2
+ const MODULE = 'AngularLynxBluetooth';
3
+ const EVENT = 'angularLynxBluetooth';
4
+ const DEFAULT_PROPERTIES = [
5
+ 'read',
6
+ 'write',
7
+ 'notify',
8
+ ];
9
+ /** A device's write-without-response limit when the spec gives none. */
10
+ const DEFAULT_MAX_WRITE_LENGTH = 182;
11
+ /** The longest attribute value, and so write with a response, ATT allows. */
12
+ const MAX_ATTRIBUTE_LENGTH = 512;
13
+ const BASE_UUID_TAIL = '-0000-1000-8000-00805f9b34fb';
14
+ /**
15
+ * A UUID as the runtime sends and expects them, so a spec can name a
16
+ * service either way.
17
+ */
18
+ const canonical = (uuid) => {
19
+ const text = uuid.toLowerCase();
20
+ if (text.length === 4)
21
+ return `0000${text}${BASE_UUID_TAIL}`;
22
+ if (text.length === 8)
23
+ return `${text}${BASE_UUID_TAIL}`;
24
+ return text;
25
+ };
26
+ const toBase64 = (bytes) => {
27
+ let binary = '';
28
+ for (const byte of bytes)
29
+ binary += String.fromCharCode(byte);
30
+ return btoa(binary);
31
+ };
32
+ const fromBase64 = (base64) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0));
33
+ const failure = (error, message) => ({ error, message });
34
+ /**
35
+ * Why the radio can't be used in `state`, as the error the shells give, or
36
+ * undefined when it's on.
37
+ */
38
+ const unusable = (state) => {
39
+ if (state === 'poweredOn')
40
+ return undefined;
41
+ const code = state === 'unsupported' ||
42
+ state === 'unauthorized' ||
43
+ state === 'poweredOff'
44
+ ? state
45
+ : 'failed';
46
+ return failure(code, `Bluetooth is ${state}.`);
47
+ };
48
+ const environment = () => globalThis.lynxTestingEnv;
49
+ /**
50
+ * Sends one of the shells' global events. They arrive on the background
51
+ * thread, whose listener calls the app's on the main thread, so the event is
52
+ * sent from it. A fake method the runtime called is on that thread already;
53
+ * a spec is on the main thread, which comes back afterwards.
54
+ */
55
+ const emit = (payload) => {
56
+ const env = environment();
57
+ const background = env.backgroundThread.globalThis;
58
+ const onMainThread = globalThis.lynx !== background.lynx;
59
+ if (onMainThread)
60
+ env.switchToBackgroundThread();
61
+ try {
62
+ background.lynx.getJSModule('GlobalEventEmitter').emit(EVENT, [payload]);
63
+ }
64
+ finally {
65
+ if (onMainThread)
66
+ env.switchToMainThread();
67
+ }
68
+ };
69
+ /**
70
+ * The most bytes a write without response to `device` carries: never more
71
+ * than an attribute holds, as the shells cap it however large the MTU.
72
+ */
73
+ const maxWriteLength = (device) => Math.min(device.maxWriteLength ?? DEFAULT_MAX_WRITE_LENGTH, MAX_ATTRIBUTE_LENGTH);
74
+ const sighting = (device, scan) => ({
75
+ type: 'device',
76
+ scan,
77
+ device: {
78
+ id: device.id,
79
+ name: device.name ?? null,
80
+ rssi: device.rssi ?? -50,
81
+ services: advertised(device),
82
+ serviceData: Object.fromEntries(Object.entries(device.serviceData ?? {}).map(([uuid, data]) => [
83
+ canonical(uuid),
84
+ toBase64(data),
85
+ ])),
86
+ manufacturerData: Object.fromEntries(Object.entries(device.manufacturerData ?? {}).map(([company, data]) => [
87
+ company,
88
+ toBase64(data),
89
+ ])),
90
+ },
91
+ });
92
+ const advertised = (device) => (device.advertisedServices ?? Object.keys(device.services ?? {})).map(canonical);
93
+ const matches = (device, services) => services.length === 0 ||
94
+ advertised(device).some((uuid) => services.includes(uuid));
95
+ /**
96
+ * The characteristic a call names, by the runtime's canonical UUIDs.
97
+ */
98
+ const characteristicOf = (device, service, characteristic) => {
99
+ const services = Object.entries(device.services ?? {});
100
+ const characteristics = services.find(([uuid]) => canonical(uuid) === service)?.[1];
101
+ return Object.entries(characteristics ?? {}).find(([uuid]) => canonical(uuid) === characteristic)?.[1];
102
+ };
103
+ /**
104
+ * Gives the environment's background thread an `AngularLynxBluetooth`
105
+ * module, as the apps `ng build --platform` makes have when angular.json's
106
+ * `permissions` list `bluetooth`. The devices in range are the ones
107
+ * {@link addBluetoothDevice} adds, and the radio is on and allowed until
108
+ * {@link setBluetoothState} says otherwise. `LynxBluetooth` reaches it
109
+ * through the background thread, as it reaches the shells' module, so specs
110
+ * see the runtime's own behavior.
111
+ *
112
+ * It runs each time the environment injects the background thread's
113
+ * globals: when it's created, and on the reset after each test, so each test
114
+ * starts with no devices and the radio on.
115
+ */
116
+ export const installBluetoothModule = (threadGlobals) => {
117
+ const devices = new Map();
118
+ const connectedDevice = (id, done) => {
119
+ const device = devices.get(id);
120
+ if (device?.connected)
121
+ return device;
122
+ done(failure('notConnected', `${id} isn't connected.`));
123
+ return undefined;
124
+ };
125
+ /**
126
+ * The characteristic of a connected device a call names, if it can do
127
+ * `property`; otherwise calls back with why not.
128
+ */
129
+ const usable = (id, service, characteristic, properties, done) => {
130
+ const device = connectedDevice(id, done);
131
+ if (!device)
132
+ return undefined;
133
+ const found = characteristicOf(device.spec, service, characteristic);
134
+ if (!found) {
135
+ done(failure('notFound', `${id} has no characteristic ${characteristic}.`));
136
+ return undefined;
137
+ }
138
+ const allowed = found.properties ?? DEFAULT_PROPERTIES;
139
+ if (!properties.some((property) => allowed.includes(property))) {
140
+ done(failure('failed', `${characteristic} can't ${properties.join(' or ')}.`));
141
+ return undefined;
142
+ }
143
+ return { device, characteristic: found };
144
+ };
145
+ /**
146
+ * Asks the person for permission when they haven't been asked, as the
147
+ * shells do before the first scan or connection: they allow it, unless a
148
+ * spec said otherwise.
149
+ */
150
+ const ask = () => {
151
+ if (module.state !== 'unknown')
152
+ return;
153
+ module.state = 'poweredOn';
154
+ emit({ type: 'state', state: module.state });
155
+ };
156
+ const module = {
157
+ state: 'poweredOn',
158
+ devices,
159
+ scanning: null,
160
+ getState: (done) => done({ state: module.state }),
161
+ requestPermission: (done) => {
162
+ ask();
163
+ done({ state: module.state });
164
+ },
165
+ startScan: ({ services, scan }, done) => {
166
+ ask();
167
+ const error = unusable(module.state);
168
+ if (error)
169
+ return done(error);
170
+ module.scanning = { id: scan, services };
171
+ done({});
172
+ for (const { spec } of devices.values()) {
173
+ if (matches(spec, services))
174
+ emit(sighting(spec, scan));
175
+ }
176
+ },
177
+ stopScan: (done) => {
178
+ module.scanning = null;
179
+ done({});
180
+ },
181
+ connect: (id, _options, done) => {
182
+ ask();
183
+ const error = unusable(module.state);
184
+ if (error)
185
+ return done(error);
186
+ const device = devices.get(id);
187
+ if (!device)
188
+ return done(failure('notFound', `No device is ${id}.`));
189
+ device.connected = true;
190
+ const { spec } = device;
191
+ done({
192
+ id,
193
+ name: spec.name ?? null,
194
+ maxWriteLength: maxWriteLength(spec),
195
+ services: Object.entries(spec.services ?? {}).map(([uuid, characteristics]) => ({
196
+ uuid: canonical(uuid),
197
+ characteristics: Object.entries(characteristics).map(([characteristic, { properties }]) => ({
198
+ uuid: canonical(characteristic),
199
+ properties: properties ?? DEFAULT_PROPERTIES,
200
+ })),
201
+ })),
202
+ });
203
+ },
204
+ disconnect: (id, done) => {
205
+ const device = devices.get(id);
206
+ if (device) {
207
+ device.connected = false;
208
+ device.subscribed.clear();
209
+ }
210
+ done({});
211
+ },
212
+ read: (id, service, characteristic, done) => {
213
+ const found = usable(id, service, characteristic, ['read'], done);
214
+ if (!found)
215
+ return;
216
+ done({ value: toBase64(found.characteristic.value ?? new Uint8Array()) });
217
+ },
218
+ write: (id, service, characteristic, value, withResponse, done) => {
219
+ const found = usable(id, service, characteristic, [withResponse ? 'write' : 'writeWithoutResponse'], done);
220
+ if (!found)
221
+ return;
222
+ const bytes = fromBase64(value);
223
+ const limit = withResponse
224
+ ? MAX_ATTRIBUTE_LENGTH
225
+ : maxWriteLength(found.device.spec);
226
+ if (bytes.length > limit) {
227
+ return done(failure('failed', `The value is ${bytes.length} bytes, and this write takes at most ${limit}.`));
228
+ }
229
+ found.device.writes.push({
230
+ service,
231
+ characteristic,
232
+ value: bytes,
233
+ withResponse,
234
+ });
235
+ done({});
236
+ found.characteristic.onWrite?.(bytes, found.device.ref);
237
+ },
238
+ setNotifications: (id, service, characteristic, enabled, done) => {
239
+ const found = usable(id, service, characteristic, ['notify', 'indicate'], done);
240
+ if (!found)
241
+ return;
242
+ const key = `${service} ${characteristic}`;
243
+ if (enabled)
244
+ found.device.subscribed.add(key);
245
+ else
246
+ found.device.subscribed.delete(key);
247
+ done({});
248
+ },
249
+ };
250
+ threadGlobals.NativeModules = {
251
+ ...threadGlobals.NativeModules,
252
+ [MODULE]: module,
253
+ };
254
+ };
255
+ /**
256
+ * The fake module of this test's environment. Read through the environment
257
+ * rather than kept here: under `ng test`, the setup file and the specs can
258
+ * load different copies of this module.
259
+ */
260
+ const fakeModule = (caller) => {
261
+ const module = environment()?.backgroundThread.globalThis.NativeModules?.[MODULE];
262
+ if (!module) {
263
+ throw new Error(`${caller}() needs the testing library's environment, which its setup file installs.`);
264
+ }
265
+ return module;
266
+ };
267
+ /**
268
+ * Puts a Bluetooth LE device in range of the app, for `LynxBluetooth` to
269
+ * find, connect to and talk to as it would a real one. A scan that's running
270
+ * sees it at once, and one that starts later sees it as it starts. Each test
271
+ * starts with none, and adding an id a second time throws.
272
+ *
273
+ * @example
274
+ * ```ts
275
+ * const frame = addBluetoothDevice({
276
+ * id: 'frame',
277
+ * name: 'Blotch - XyZ1',
278
+ * services: {
279
+ * [SETUP_SERVICE]: {
280
+ * [CREDENTIALS]: {
281
+ * properties: ['write'],
282
+ * onWrite: (_value, device) =>
283
+ * device.notify(SETUP_SERVICE, STATUS, encode('connected')),
284
+ * },
285
+ * [STATUS]: { properties: ['notify'] },
286
+ * },
287
+ * },
288
+ * });
289
+ * await render(SetUpFrame);
290
+ * fireEvent.tap(await screen.findByText('Blotch - XyZ1'));
291
+ * // …
292
+ * expect(frame.writes).toHaveLength(1);
293
+ * ```
294
+ */
295
+ export const addBluetoothDevice = (device) => {
296
+ const module = fakeModule('addBluetoothDevice');
297
+ // Replacing it would leave the app's connection to it looking open while
298
+ // its calls fail.
299
+ if (module.devices.has(device.id)) {
300
+ throw new Error(`addBluetoothDevice() already added a device with the id ${device.id}.`);
301
+ }
302
+ const writes = [];
303
+ const subscribed = new Set();
304
+ const entry = {
305
+ spec: device,
306
+ writes,
307
+ subscribed,
308
+ connected: false,
309
+ ref: {
310
+ get connected() {
311
+ return entry.connected;
312
+ },
313
+ writes,
314
+ notify: (service, characteristic, value) => {
315
+ const key = `${canonical(service)} ${canonical(characteristic)}`;
316
+ if (!entry.connected || !subscribed.has(key))
317
+ return;
318
+ emit({
319
+ type: 'value',
320
+ id: device.id,
321
+ service: canonical(service),
322
+ characteristic: canonical(characteristic),
323
+ value: toBase64(value),
324
+ });
325
+ },
326
+ disconnect: () => {
327
+ if (!entry.connected)
328
+ return;
329
+ entry.connected = false;
330
+ subscribed.clear();
331
+ emit({ type: 'disconnected', id: device.id });
332
+ },
333
+ },
334
+ };
335
+ module.devices.set(device.id, entry);
336
+ if (module.scanning && matches(device, module.scanning.services)) {
337
+ emit(sighting(device, module.scanning.id));
338
+ }
339
+ return entry.ref;
340
+ };
341
+ /**
342
+ * Sets the state of the phone's Bluetooth, as the person turning it off or
343
+ * refusing permission does, so a spec can check what the app shows then.
344
+ * Anything but `poweredOn` ends a running scan and every connection, as it
345
+ * does on a phone. `unknown` stands for not asked yet: the person allows it
346
+ * when `LynxBluetooth` asks, as `requestPermission()`, `scan()` and
347
+ * `connect()` do.
348
+ *
349
+ * @example
350
+ * ```ts
351
+ * setBluetoothState('poweredOff');
352
+ * await render(SetUpFrame);
353
+ * expect(await screen.findByText('Turn on Bluetooth')).toBeInTheDocument();
354
+ * ```
355
+ */
356
+ export const setBluetoothState = (state) => {
357
+ const module = fakeModule('setBluetoothState');
358
+ module.state = state;
359
+ emit({ type: 'state', state });
360
+ const error = unusable(state);
361
+ if (!error)
362
+ return;
363
+ if (module.scanning) {
364
+ emit({ type: 'scanStopped', scan: module.scanning.id, ...error });
365
+ module.scanning = null;
366
+ }
367
+ for (const { ref } of module.devices.values())
368
+ ref.disconnect();
369
+ };
@@ -0,0 +1,68 @@
1
+ /** An event the app opened the editor with, as `LynxCalendar` was given it. */
2
+ export type CalendarSheetEvent = {
3
+ readonly title: string;
4
+ readonly start: Date;
5
+ readonly end: Date;
6
+ readonly allDay: boolean;
7
+ readonly location?: string;
8
+ readonly notes?: string;
9
+ };
10
+ /** How the editor closes, as `LynxCalendar.addEvent()` resolves. */
11
+ export type CalendarSheetAnswer = 'saved' | 'canceled' | 'unknown';
12
+ /** Why the editor didn't open, as `CalendarError`'s `code` names it. */
13
+ export type CalendarSheetFailure = 'unavailable' | 'failed';
14
+ /**
15
+ * Gives the environment's background thread an `AngularLynxCalendar` module,
16
+ * as the apps `ng build --platform` makes with angular.json's `calendar`
17
+ * have. It keeps each event the app opens the editor with, for
18
+ * {@link calendarEvents}, and leaves the editor open until
19
+ * {@link answerCalendarSheet} or {@link failCalendarSheet} closes it, or
20
+ * closes it at once with what one of them queued before it opened.
21
+ * `LynxCalendar` reaches it through the background thread, as it reaches the
22
+ * shells' module, so specs see the runtime's own behavior.
23
+ *
24
+ * It runs each time the environment injects the background thread's
25
+ * globals: when it's created, and on the reset after each test, so each test
26
+ * starts with no events, no editor open and nothing queued.
27
+ */
28
+ export declare const installCalendarModule: (threadGlobals: {
29
+ NativeModules?: Record<string, unknown>;
30
+ }) => void;
31
+ /**
32
+ * The events the app has opened the system's event editor with, through
33
+ * `LynxCalendar.addEvent()`, in this test, oldest first. Each test starts
34
+ * with none.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * fireEvent.tap(screen.getByText('Add to calendar'));
39
+ * await waitForUpdate();
40
+ * expect(calendarEvents()).toEqual([
41
+ * expect.objectContaining({ title: 'Table for 2' }),
42
+ * ]);
43
+ * ```
44
+ */
45
+ export declare const calendarEvents: () => readonly CalendarSheetEvent[];
46
+ /**
47
+ * Closes the event editor as the person would: the open
48
+ * `LynxCalendar.addEvent()` resolves with `result` (`saved` by default), or,
49
+ * when none is open, the next one does as soon as it's called. Each call
50
+ * answers one editor, in order. The answer reaches the app through the
51
+ * background thread, as on a phone: wait for it with `waitForUpdate()`.
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * fireEvent.tap(screen.getByText('Add to calendar'));
56
+ * answerCalendarSheet('saved');
57
+ * await waitForUpdate();
58
+ * expect(screen.getByText('Added to your calendar')).toBeInTheDocument();
59
+ * ```
60
+ */
61
+ export declare const answerCalendarSheet: (result?: CalendarSheetAnswer) => void;
62
+ /**
63
+ * Ends the open `LynxCalendar.addEvent()`, or the next one, with a
64
+ * `CalendarError` of `code`: `unavailable` for a phone without an editor
65
+ * (before iOS 17, or Android without a calendar app), or `failed`.
66
+ */
67
+ export declare const failCalendarSheet: (code: CalendarSheetFailure, message?: string) => void;
68
+ //# sourceMappingURL=calendar.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calendar.d.ts","sourceRoot":"","sources":["../src/calendar.ts"],"names":[],"mappings":"AAGA,+EAA+E;AAC/E,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC;IACrB,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC;IACnB,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,oEAAoE;AACpE,MAAM,MAAM,mBAAmB,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,CAAC;AAEnE,wEAAwE;AACxE,MAAM,MAAM,oBAAoB,GAAG,aAAa,GAAG,QAAQ,CAAC;AAsC5D;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,qBAAqB,GAAI,eAAe;IACnD,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACzC,KAAG,IA8BH,CAAC;AA0CF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,cAAc,QAAO,SAAS,kBAAkB,EAE5D,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,mBAAmB,GAC9B,SAAQ,mBAA6B,KACpC,IAAiD,CAAC;AAErD;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,GAC5B,MAAM,oBAAoB,EAC1B,UAAU,MAAM,KACf,IAIC,CAAC"}
@@ -0,0 +1,120 @@
1
+ /** What `LynxCalendar` calls, named as the shells name their module. */
2
+ const MODULE = 'AngularLynxCalendar';
3
+ /**
4
+ * Gives the environment's background thread an `AngularLynxCalendar` module,
5
+ * as the apps `ng build --platform` makes with angular.json's `calendar`
6
+ * have. It keeps each event the app opens the editor with, for
7
+ * {@link calendarEvents}, and leaves the editor open until
8
+ * {@link answerCalendarSheet} or {@link failCalendarSheet} closes it, or
9
+ * closes it at once with what one of them queued before it opened.
10
+ * `LynxCalendar` reaches it through the background thread, as it reaches the
11
+ * shells' module, so specs see the runtime's own behavior.
12
+ *
13
+ * It runs each time the environment injects the background thread's
14
+ * globals: when it's created, and on the reset after each test, so each test
15
+ * starts with no events, no editor open and nothing queued.
16
+ */
17
+ export const installCalendarModule = (threadGlobals) => {
18
+ const module = {
19
+ events: [],
20
+ queued: [],
21
+ open: undefined,
22
+ addEvent(event, done) {
23
+ if (this.open) {
24
+ done({ error: 'failed', message: 'The event editor is already open.' });
25
+ return;
26
+ }
27
+ this.events.push({
28
+ title: event.title,
29
+ start: new Date(event.start),
30
+ end: new Date(event.end),
31
+ allDay: event.allDay,
32
+ ...(event.location !== undefined && { location: event.location }),
33
+ ...(event.notes !== undefined && { notes: event.notes }),
34
+ });
35
+ const answer = this.queued.shift();
36
+ if (answer) {
37
+ done(answer);
38
+ return;
39
+ }
40
+ this.open = done;
41
+ },
42
+ };
43
+ threadGlobals.NativeModules = {
44
+ ...threadGlobals.NativeModules,
45
+ [MODULE]: module,
46
+ };
47
+ };
48
+ /**
49
+ * The fake module, read through the environment rather than kept here:
50
+ * under `ng test`, the setup file and the specs can load different copies of
51
+ * this file.
52
+ */
53
+ const fakeModule = (name) => {
54
+ const env = globalThis.lynxTestingEnv;
55
+ const module = env?.backgroundThread.globalThis.NativeModules?.[MODULE];
56
+ if (!env || !module) {
57
+ throw new Error(`${name}() needs the testing library's environment, which its setup file installs.`);
58
+ }
59
+ return { env, module };
60
+ };
61
+ const answer = (name, result) => {
62
+ const { env, module } = fakeModule(name);
63
+ const open = module.open;
64
+ if (!open) {
65
+ module.queued.push(result);
66
+ return;
67
+ }
68
+ module.open = undefined;
69
+ // The shells call back on the background thread, which relays the answer
70
+ // to the main thread, where specs run: it comes back afterwards.
71
+ env.switchToBackgroundThread();
72
+ try {
73
+ open(result);
74
+ }
75
+ finally {
76
+ env.switchToMainThread();
77
+ }
78
+ };
79
+ /**
80
+ * The events the app has opened the system's event editor with, through
81
+ * `LynxCalendar.addEvent()`, in this test, oldest first. Each test starts
82
+ * with none.
83
+ *
84
+ * @example
85
+ * ```ts
86
+ * fireEvent.tap(screen.getByText('Add to calendar'));
87
+ * await waitForUpdate();
88
+ * expect(calendarEvents()).toEqual([
89
+ * expect.objectContaining({ title: 'Table for 2' }),
90
+ * ]);
91
+ * ```
92
+ */
93
+ export const calendarEvents = () => [
94
+ ...fakeModule('calendarEvents').module.events,
95
+ ];
96
+ /**
97
+ * Closes the event editor as the person would: the open
98
+ * `LynxCalendar.addEvent()` resolves with `result` (`saved` by default), or,
99
+ * when none is open, the next one does as soon as it's called. Each call
100
+ * answers one editor, in order. The answer reaches the app through the
101
+ * background thread, as on a phone: wait for it with `waitForUpdate()`.
102
+ *
103
+ * @example
104
+ * ```ts
105
+ * fireEvent.tap(screen.getByText('Add to calendar'));
106
+ * answerCalendarSheet('saved');
107
+ * await waitForUpdate();
108
+ * expect(screen.getByText('Added to your calendar')).toBeInTheDocument();
109
+ * ```
110
+ */
111
+ export const answerCalendarSheet = (result = 'saved') => answer('answerCalendarSheet', { result });
112
+ /**
113
+ * Ends the open `LynxCalendar.addEvent()`, or the next one, with a
114
+ * `CalendarError` of `code`: `unavailable` for a phone without an editor
115
+ * (before iOS 17, or Android without a calendar app), or `failed`.
116
+ */
117
+ export const failCalendarSheet = (code, message) => answer('failCalendarSheet', {
118
+ error: code,
119
+ ...(message !== undefined && { message }),
120
+ });
@@ -0,0 +1,76 @@
1
+ /** A file {@link setPickedFiles} has the person pick. */
2
+ export type FakePickedFile = {
3
+ /** Its name, such as `receipt.pdf`. */
4
+ readonly name: string;
5
+ /**
6
+ * Its MIME type, such as `application/pdf`. `application/octet-stream`
7
+ * when it's left out, as a phone answers for a type it doesn't know.
8
+ */
9
+ readonly type?: string;
10
+ /** Its bytes, or text, which is stored as UTF-8. */
11
+ readonly content: string | Uint8Array;
12
+ };
13
+ /** A file the app saved, as {@link savedFiles} lists it. */
14
+ export type SavedFile = {
15
+ /** The name it was offered under. */
16
+ readonly name: string;
17
+ /** Its MIME type: the Blob's `type`, or `application/octet-stream`. */
18
+ readonly type: string;
19
+ /** Its bytes. */
20
+ readonly bytes: Uint8Array;
21
+ /** Its bytes read as UTF-8, for a text file such as a CSV. */
22
+ readonly text: string;
23
+ };
24
+ /**
25
+ * Gives the environment's background thread an `AngularLynxFilePicker`
26
+ * module, as the apps `ng build --platform` makes with angular.json's
27
+ * `filePicker` have. It stands for a person who closes the picker until a
28
+ * spec says what they pick ({@link setPickedFiles}), and who saves every
29
+ * file the app offers ({@link savedFiles}) unless a spec has them close the
30
+ * screen ({@link setFilePickerCanceled}). The runtime reaches it through the
31
+ * background thread, as it reaches the shells' module, so specs see the
32
+ * runtime's own behavior, its size limit included.
33
+ *
34
+ * It runs each time the environment injects the background thread's
35
+ * globals: when it's created, and on the reset after each test, so each test
36
+ * starts with nothing to pick and nothing saved.
37
+ */
38
+ export declare const installFilePickerModule: (threadGlobals: {
39
+ NativeModules?: Record<string, unknown>;
40
+ }) => void;
41
+ /**
42
+ * Has the person pick `files` each time the app opens `LynxFilePicker`'s
43
+ * picker in this test, so `pick()` resolves with them. Until a spec calls
44
+ * it, the person closes the picker, and `pick()` resolves with `[]`. Files
45
+ * over the runtime's 20 MiB limit, together, reject with `too-large`, as on
46
+ * a phone.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * setPickedFiles([{ name: 'receipt.pdf', type: 'application/pdf', content: pdfBytes }]);
51
+ * fireEvent.tap(screen.getByText('Attach receipt'));
52
+ * await waitForUpdate();
53
+ * expect(screen.getByText('receipt.pdf')).toBeInTheDocument();
54
+ * ```
55
+ */
56
+ export declare const setPickedFiles: (files: readonly FakePickedFile[]) => void;
57
+ /**
58
+ * Has the person close `LynxFilePicker`'s picker and save screen for the
59
+ * rest of this test: `pick()` resolves with `[]`, and `save()` with false.
60
+ * {@link setPickedFiles} undoes it.
61
+ */
62
+ export declare const setFilePickerCanceled: () => void;
63
+ /**
64
+ * The files the app saved with `LynxFilePicker.save()` in this test, oldest
65
+ * first. Each test starts with none.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * fireEvent.tap(screen.getByText('Export'));
70
+ * await waitForUpdate();
71
+ * expect(savedFiles()).toMatchObject([{ name: 'report.csv', type: 'text/csv' }]);
72
+ * expect(savedFiles()[0]!.text).toContain('Total,42');
73
+ * ```
74
+ */
75
+ export declare const savedFiles: () => readonly SavedFile[];
76
+ //# sourceMappingURL=file-picker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-picker.d.ts","sourceRoot":"","sources":["../src/file-picker.ts"],"names":[],"mappings":"AAGA,yDAAyD;AACzD,MAAM,MAAM,cAAc,GAAG;IAC3B,uCAAuC;IACvC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,oDAAoD;IACpD,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,UAAU,CAAC;CACvC,CAAC;AAEF,4DAA4D;AAC5D,MAAM,MAAM,SAAS,GAAG;IACtB,qCAAqC;IACrC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,uEAAuE;IACvE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,iBAAiB;IACjB,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAC3B,8DAA8D;IAC9D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB,CAAC;AAyBF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,uBAAuB,GAAI,eAAe;IACrD,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACzC,KAAG,IA2CH,CAAC;AAkBF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,SAAS,cAAc,EAAE,KAAG,IAIjE,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,QAAO,IAExC,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,UAAU,QAAO,SAAS,SAAS,EAE/C,CAAC"}