@ng-native/device 0.22.2 → 0.24.0

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 (132) hide show
  1. package/dist/accessibility.d.ts +7 -0
  2. package/dist/accessibility.js +14 -2
  3. package/dist/accessibility.js.map +1 -1
  4. package/dist/app-lifecycle.d.ts +49 -0
  5. package/dist/app-lifecycle.js +67 -0
  6. package/dist/app-lifecycle.js.map +1 -0
  7. package/dist/app-state.d.ts +2 -0
  8. package/dist/app-state.js +2 -0
  9. package/dist/app-state.js.map +1 -1
  10. package/dist/app-windows.d.ts +321 -0
  11. package/dist/app-windows.js +526 -0
  12. package/dist/app-windows.js.map +1 -0
  13. package/dist/color-scheme.d.ts +5 -0
  14. package/dist/color-scheme.js +16 -0
  15. package/dist/color-scheme.js.map +1 -1
  16. package/dist/conditions.d.ts +11 -3
  17. package/dist/conditions.js +42 -9
  18. package/dist/conditions.js.map +1 -1
  19. package/dist/control-size.d.ts +6 -0
  20. package/dist/control-size.js +2 -0
  21. package/dist/control-size.js.map +1 -0
  22. package/dist/deep-links.d.ts +3 -1
  23. package/dist/deep-links.js +3 -1
  24. package/dist/deep-links.js.map +1 -1
  25. package/dist/desktop-options.d.ts +73 -0
  26. package/dist/desktop-options.js +182 -0
  27. package/dist/desktop-options.js.map +1 -0
  28. package/dist/desktop-permissions.d.ts +30 -0
  29. package/dist/desktop-permissions.js +169 -0
  30. package/dist/desktop-permissions.js.map +1 -0
  31. package/dist/dev-menu.d.ts +2 -2
  32. package/dist/dev-menu.js +3 -5
  33. package/dist/dev-menu.js.map +1 -1
  34. package/dist/dialogs.d.ts +9 -7
  35. package/dist/dialogs.js +15 -10
  36. package/dist/dialogs.js.map +1 -1
  37. package/dist/direction.d.ts +2 -0
  38. package/dist/direction.js +2 -0
  39. package/dist/direction.js.map +1 -1
  40. package/dist/dock.d.ts +48 -0
  41. package/dist/dock.js +70 -0
  42. package/dist/dock.js.map +1 -0
  43. package/dist/drag-and-drop.d.ts +67 -0
  44. package/dist/drag-and-drop.js +74 -0
  45. package/dist/drag-and-drop.js.map +1 -0
  46. package/dist/expo-view-name.d.ts +16 -0
  47. package/dist/expo-view-name.js +22 -0
  48. package/dist/expo-view-name.js.map +1 -0
  49. package/dist/hardware-back.d.ts +3 -10
  50. package/dist/hardware-back.js +4 -1
  51. package/dist/hardware-back.js.map +1 -1
  52. package/dist/index.d.ts +26 -2
  53. package/dist/index.js +26 -2
  54. package/dist/index.js.map +1 -1
  55. package/dist/interaction-observer.d.ts +117 -0
  56. package/dist/interaction-observer.js +241 -0
  57. package/dist/interaction-observer.js.map +1 -0
  58. package/dist/keyboard.d.ts +2 -8
  59. package/dist/keyboard.js +3 -0
  60. package/dist/keyboard.js.map +1 -1
  61. package/dist/layout-animation.d.ts +3 -1
  62. package/dist/layout-animation.js +3 -1
  63. package/dist/layout-animation.js.map +1 -1
  64. package/dist/menu-model.d.ts +108 -0
  65. package/dist/menu-model.js +259 -0
  66. package/dist/menu-model.js.map +1 -0
  67. package/dist/menu-template.d.ts +19 -0
  68. package/dist/menu-template.js +31 -0
  69. package/dist/menu-template.js.map +1 -0
  70. package/dist/menus.d.ts +225 -0
  71. package/dist/menus.js +341 -0
  72. package/dist/menus.js.map +1 -0
  73. package/dist/navigation-bar.d.ts +2 -12
  74. package/dist/navigation-bar.js +4 -1
  75. package/dist/navigation-bar.js.map +1 -1
  76. package/dist/os-support.d.ts +42 -0
  77. package/dist/os-support.js +207 -0
  78. package/dist/os-support.js.map +1 -0
  79. package/dist/os.d.ts +26 -5
  80. package/dist/os.js +35 -7
  81. package/dist/os.js.map +1 -1
  82. package/dist/own-host.d.ts +27 -0
  83. package/dist/own-host.js +79 -0
  84. package/dist/own-host.js.map +1 -0
  85. package/dist/processes.d.ts +116 -0
  86. package/dist/processes.js +177 -0
  87. package/dist/processes.js.map +1 -0
  88. package/dist/react-native.d.ts +19 -0
  89. package/dist/react-native.js.map +1 -1
  90. package/dist/safe-area.d.ts +12 -1
  91. package/dist/safe-area.js +16 -2
  92. package/dist/safe-area.js.map +1 -1
  93. package/dist/screen.d.ts +2 -0
  94. package/dist/screen.js +2 -0
  95. package/dist/screen.js.map +1 -1
  96. package/dist/sharing.d.ts +3 -1
  97. package/dist/sharing.js +8 -1
  98. package/dist/sharing.js.map +1 -1
  99. package/dist/shell.d.ts +33 -0
  100. package/dist/shell.js +73 -0
  101. package/dist/shell.js.map +1 -0
  102. package/dist/shortcut.d.ts +49 -0
  103. package/dist/shortcut.js +92 -0
  104. package/dist/shortcut.js.map +1 -0
  105. package/dist/sidebar-selection.d.ts +8 -0
  106. package/dist/sidebar-selection.js +9 -0
  107. package/dist/sidebar-selection.js.map +1 -0
  108. package/dist/spawn-rules.d.ts +108 -0
  109. package/dist/spawn-rules.js +313 -0
  110. package/dist/spawn-rules.js.map +1 -0
  111. package/dist/split-views.d.ts +7 -0
  112. package/dist/split-views.js +21 -0
  113. package/dist/split-views.js.map +1 -0
  114. package/dist/status-bar.d.ts +2 -12
  115. package/dist/status-bar.js +3 -0
  116. package/dist/status-bar.js.map +1 -1
  117. package/dist/tray.d.ts +63 -0
  118. package/dist/tray.js +76 -0
  119. package/dist/tray.js.map +1 -0
  120. package/dist/undo-stack.d.ts +64 -0
  121. package/dist/undo-stack.js +110 -0
  122. package/dist/undo-stack.js.map +1 -0
  123. package/dist/vibration.d.ts +3 -14
  124. package/dist/vibration.js +4 -1
  125. package/dist/vibration.js.map +1 -1
  126. package/dist/window-navigator.d.ts +25 -0
  127. package/dist/window-navigator.js +7 -0
  128. package/dist/window-navigator.js.map +1 -0
  129. package/dist/window-restore.d.ts +45 -0
  130. package/dist/window-restore.js +66 -0
  131. package/dist/window-restore.js.map +1 -0
  132. package/package.json +10 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"own-host.js","sourceRoot":"","sources":["../src/own-host.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,gB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C,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE;QACjF,CAAC,CAAC,IAAI,CAAC;IACT,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACxB,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,OAAO,CAAI,IAAO,EAAE,IAAc;IAChD,SAAS,CAAC,IAAkB,CAAC,CAAC;IAC9B,MAAM,KAAK,GAAI,IAA4C,CAAC,KAAK,CAAC;IAClE,IAAI,CAAC,KAAK;QAAE,OAAO,IAAI,CAAC;IACxB,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC3C,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IAC3B,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QACtC,IAAI,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC;YAAE,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC;IAC1C,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * Claiming a host node, and taking off the attributes its inputs consumed.\n *\n * Internal: it lives here because `@ng-native/components` and `@ng-native/router` both own host\n * nodes and cannot import each other.\n */\nimport { isDevMode, reflectComponentType, ɵgetDirectiveDef, type Type } from '@angular/core';\nimport { claimHost, type EngineNode } from '@ng-native/fabric';\n\n/** A class's inputs, by the names a template writes. */\ninterface HostInputs {\n readonly names: ReadonlySet<string>;\n /**\n * Whether a static attribute by one of those names was consumed by them. Not for a directive\n * with no selector: it is only ever a `hostDirectives` entry, which exposes the inputs its host\n * lists and no others, so an attribute named after the rest was not consumed.\n */\n readonly consumes: boolean;\n}\n\nconst NONE: HostInputs = { names: new Set(), consumes: false };\n\n/** Per class, as the inputs of a class do not change, except under a hot reload (see below). */\nconst cache = new WeakMap<object, HostInputs>();\n\n/**\n * The inputs of a component or a directive, by the names a template writes (an alias where there\n * is one), inherited ones included. Empty for a class that is neither.\n *\n * A component's come from the public `reflectComponentType`. Angular has no public mirror of a\n * directive, which is what most host primitives are, so a directive's are read from its exported\n * `ɵgetDirectiveDef`.\n */\nexport function hostInputNames(type: unknown): ReadonlySet<string> {\n return inputsOf(type).names;\n}\n\nfunction inputsOf(type: unknown): HostInputs {\n if (typeof type !== 'function') return NONE;\n const cached = cache.get(type);\n if (cached) return cached;\n const mirror = reflectComponentType(type as Type<unknown>);\n if (mirror) {\n const inputs = {\n names: new Set(mirror.inputs.map((input) => input.templateName)),\n consumes: true,\n };\n // A hot reload replaces a component's definition in place, under the same class, so in\n // development a component's inputs are read again for each host.\n if (!isDevMode()) cache.set(type, inputs);\n return inputs;\n }\n const def = ɵgetDirectiveDef(type);\n const inputs = def\n ? { names: new Set(Object.keys(def.inputs)), consumes: def.selectors.length > 0 }\n : NONE;\n cache.set(type, inputs);\n return inputs;\n}\n\n/**\n * Mark `node` as owned, and take off any prop Angular wrote there from a static attribute that\n * one of `type`'s inputs already consumed. Angular writes a static attribute to the element as\n * well as feeding it to the input of the same name, so `<switch thumbColor=\"#fff\">` leaves a\n * stray `thumbColor` prop next to the `thumbTintColor` the input produces, and\n * `<native-header title=\"Settings\">` a `title` prop. A host binding puts back any that native\n * does read.\n *\n * Walking the *node's* props rather than the inputs is not a detail. This runs for every element\n * on screen, a primitive declares some forty-five inputs, and at this point the node usually has\n * no props at all: bindings have not run yet, so only static attributes are there. The other way\n * round it was forty-five `delete`s per element on an object that had none of them, which is both\n * wasted work and the way to push an object into dictionary mode.\n *\n * Never throws: a node with no props bag yet (a host that has not put one there) and a class that\n * is neither a component nor a directive are claimed and otherwise left alone.\n */\nexport function ownHost<T>(node: T, type?: unknown): T {\n claimHost(node as EngineNode);\n const props = (node as { props?: Record<string, unknown> }).props;\n if (!props) return node;\n const { names, consumes } = inputsOf(type);\n if (!consumes) return node;\n for (const name of Object.keys(props)) {\n if (names.has(name)) delete props[name];\n }\n return node;\n}\n"]}
@@ -0,0 +1,116 @@
1
+ /**
2
+ * `Processes`: the app's environment on a desktop OS, and the programs it declares, run with
3
+ * `spawn`. Absent on iOS, Android and the web, which give an app neither.
4
+ *
5
+ * The host contract, on the `NgNativeProcesses` module:
6
+ *
7
+ * - `getConstants()` answers `env` (the environment, already filtered to `capabilities.env`),
8
+ * `envNames` (`capabilities.env` itself), `spawn` (the declared spawn capabilities) and `resolved` (where each declared bare name was
9
+ * pinned at startup, or null where it is absent).
10
+ * - `spawn(program, args, cwd, env)` runs the program, never through a shell, after checking the
11
+ * call against the declaration again, and answers a handle; it rejects an undeclared call.
12
+ * - `write(handle, data)`, `closeStdin(handle)` and `kill(handle, signal)`.
13
+ * - `{ type: 'stdout' | 'stderr', handle, data }` and `{ type: 'exit', handle, code, signal }`
14
+ * arrive on `ngNativeProcesses`.
15
+ */
16
+ import { InjectionToken, type Signal } from '@angular/core';
17
+ import { type SpawnCapability } from './spawn-rules.ts';
18
+ import * as i0 from "@angular/core";
19
+ /** How a spawned program ended: its exit code, or the signal that stopped it. */
20
+ export interface ProcessExit {
21
+ readonly code: number | null;
22
+ readonly signal: string | null;
23
+ }
24
+ /** What the host reports about a spawned program. */
25
+ export type ProcessEvent = {
26
+ readonly type: 'stdout' | 'stderr';
27
+ readonly handle: number;
28
+ readonly data: string;
29
+ } | {
30
+ readonly type: 'exit';
31
+ readonly handle: number;
32
+ readonly code: number | null;
33
+ readonly signal: string | null;
34
+ };
35
+ /** What the desktop host's module reports, and what a test fakes. */
36
+ export interface NativeProcesses {
37
+ /** The environment variables the app was started with, filtered to those it declares. */
38
+ readonly env: Readonly<Record<string, string>>;
39
+ /** The variables `capabilities.env` declares: all a spawned program may be given. */
40
+ readonly envNames?: readonly string[];
41
+ /** The declared spawn capabilities. None declared, nothing may be spawned. */
42
+ readonly spawnCapabilities?: readonly SpawnCapability[];
43
+ /** Where each declared bare program name was pinned at startup, or null where it is absent. */
44
+ readonly resolved?: Readonly<Record<string, string | null>>;
45
+ spawn?(program: string, args: readonly string[], cwd: string | null, env: Readonly<Record<string, string>>): Promise<number>;
46
+ write?(handle: number, data: string): void;
47
+ closeStdin?(handle: number): void;
48
+ kill?(handle: number, signal: string): void;
49
+ subscribe?(listener: (event: ProcessEvent) => void): () => void;
50
+ }
51
+ /** A program `spawn` started. */
52
+ export interface ChildProcess {
53
+ /** Settles once the program has ended. */
54
+ readonly exit: Promise<ProcessExit>;
55
+ /** Hear what the program writes to standard output. Answers the function that stops it. */
56
+ onStdout(listener: (chunk: string) => void): () => void;
57
+ /** Hear what the program writes to standard error. */
58
+ onStderr(listener: (chunk: string) => void): () => void;
59
+ /** Write to the program's standard input. */
60
+ write(data: string): void;
61
+ /** Close the program's standard input. */
62
+ end(): void;
63
+ /** Stop the program. `SIGTERM` unless it says. */
64
+ kill(signal?: 'SIGTERM' | 'SIGINT' | 'SIGKILL' | 'SIGHUP'): void;
65
+ }
66
+ /** What `spawn` takes beside the program and its arguments. */
67
+ export interface SpawnOptions {
68
+ /** The working directory. The app's own when unset. */
69
+ readonly cwd?: string;
70
+ /**
71
+ * The program's environment. Only the variables the app declares in `capabilities.env` are
72
+ * passed; the rest are left out. Unset, it gets `Processes.env`.
73
+ */
74
+ readonly env?: Readonly<Record<string, string>>;
75
+ }
76
+ /** A spawn the app did not declare: a misconfiguration, so it throws rather than doing nothing. */
77
+ export declare class UndeclaredCapabilityError extends Error {
78
+ readonly name = "UndeclaredCapabilityError";
79
+ }
80
+ export declare class Processes {
81
+ /** Overridden in a test to start the app with an environment, and to fake programs. */
82
+ static readonly SOURCE: InjectionToken<NativeProcesses | null>;
83
+ private readonly native;
84
+ private readonly capabilities;
85
+ private readonly running;
86
+ /**
87
+ * What the host said of a program before its spawn resolved with the handle: its reader threads
88
+ * can queue a short program's output and exit ahead of that answer.
89
+ */
90
+ private readonly early;
91
+ /** Spawns waiting on the host, while which an unknown handle's events are kept. */
92
+ private spawning;
93
+ /** Held events not yet replayed, by handle: live ones queue behind them, in order. */
94
+ private readonly replaying;
95
+ private readonly unsubscribe;
96
+ /** Whether the OS gives the app processes: a desktop OS with the desktop host's module. */
97
+ readonly available: Signal<boolean>;
98
+ /** The environment variables, as the app was started with them. Empty where absent. */
99
+ readonly env: Readonly<Record<string, string>>;
100
+ /**
101
+ * Run `program` with `args`, never through a shell. The call has to match a capability the app
102
+ * declares in app.json; one that does not throws `UndeclaredCapabilityError`. Resolves to null
103
+ * where processes are absent.
104
+ *
105
+ * const git = await processes.spawn('git', ['status', '--porcelain'], { cwd: repo });
106
+ * git?.onStdout((chunk) => output.update((text) => text + chunk));
107
+ * const { code } = (await git?.exit) ?? { code: null };
108
+ */
109
+ spawn(program: string, args?: readonly string[], options?: SpawnOptions): Promise<ChildProcess | null>;
110
+ private child;
111
+ private heard;
112
+ /** Stop hearing the host, as the app goes. */
113
+ ngOnDestroy(): void;
114
+ static ɵfac: i0.ɵɵFactoryDeclaration<Processes, never>;
115
+ static ɵprov: i0.ɵɵInjectableDeclaration<any>;
116
+ }
@@ -0,0 +1,177 @@
1
+ /**
2
+ * `Processes`: the app's environment on a desktop OS, and the programs it declares, run with
3
+ * `spawn`. Absent on iOS, Android and the web, which give an app neither.
4
+ *
5
+ * The host contract, on the `NgNativeProcesses` module:
6
+ *
7
+ * - `getConstants()` answers `env` (the environment, already filtered to `capabilities.env`),
8
+ * `envNames` (`capabilities.env` itself), `spawn` (the declared spawn capabilities) and `resolved` (where each declared bare name was
9
+ * pinned at startup, or null where it is absent).
10
+ * - `spawn(program, args, cwd, env)` runs the program, never through a shell, after checking the
11
+ * call against the declaration again, and answers a handle; it rejects an undeclared call.
12
+ * - `write(handle, data)`, `closeStdin(handle)` and `kill(handle, signal)`.
13
+ * - `{ type: 'stdout' | 'stderr', handle, data }` and `{ type: 'exit', handle, code, signal }`
14
+ * arrive on `ngNativeProcesses`.
15
+ */
16
+ import { InjectionToken, Service, inject, signal } from '@angular/core';
17
+ import { reactNative } from "./react-native.js";
18
+ import { compileCapability, filterEnvironment, matchSpawn, } from "./spawn-rules.js";
19
+ import * as i0 from "@angular/core";
20
+ /** A spawn the app did not declare: a misconfiguration, so it throws rather than doing nothing. */
21
+ export class UndeclaredCapabilityError extends Error {
22
+ name = 'UndeclaredCapabilityError';
23
+ }
24
+ /** The desktop host's module, or null where there is none: every OS but a desktop one. */
25
+ function processesSource() {
26
+ const native = reactNative();
27
+ const module = native?.TurboModuleRegistry?.get?.('NgNativeProcesses');
28
+ const constants = module?.getConstants?.();
29
+ if (!module || !constants?.env)
30
+ return null;
31
+ return {
32
+ ...declared(constants.env, constants),
33
+ ...processMethods(module, native?.DeviceEventEmitter),
34
+ };
35
+ }
36
+ /** What the host's constants declare, with what an older host leaves out filled in. */
37
+ function declared(env, constants) {
38
+ return {
39
+ env,
40
+ envNames: constants.envNames ?? Object.keys(env),
41
+ spawnCapabilities: constants.spawn ?? [],
42
+ resolved: constants.resolved ?? {},
43
+ };
44
+ }
45
+ /** The module's methods, as the service calls them. */
46
+ function processMethods(module, emitter) {
47
+ return {
48
+ spawn: module.spawn &&
49
+ ((...call) => module.spawn(call[0], [...call[1]], call[2], call[3])),
50
+ write: (handle, data) => module.write?.(handle, data),
51
+ closeStdin: (handle) => module.closeStdin?.(handle),
52
+ kill: (handle, signal) => module.kill?.(handle, signal),
53
+ subscribe: (listener) => {
54
+ const subscription = emitter?.addListener('ngNativeProcesses', (event) => listener(event));
55
+ return () => subscription?.remove();
56
+ },
57
+ };
58
+ }
59
+ export class Processes {
60
+ /** Overridden in a test to start the app with an environment, and to fake programs. */
61
+ static SOURCE = new InjectionToken('angular-native.processesSource', { factory: processesSource });
62
+ native = inject(Processes.SOURCE);
63
+ capabilities = (this.native?.spawnCapabilities ?? []).map(compileCapability);
64
+ running = new Map();
65
+ /**
66
+ * What the host said of a program before its spawn resolved with the handle: its reader threads
67
+ * can queue a short program's output and exit ahead of that answer.
68
+ */
69
+ early = new Map();
70
+ /** Spawns waiting on the host, while which an unknown handle's events are kept. */
71
+ spawning = 0;
72
+ /** Held events not yet replayed, by handle: live ones queue behind them, in order. */
73
+ replaying = new Map();
74
+ unsubscribe = this.native?.subscribe?.((event) => this.heard(event)) ?? null;
75
+ /** Whether the OS gives the app processes: a desktop OS with the desktop host's module. */
76
+ available = signal(this.native !== null).asReadonly();
77
+ /** The environment variables, as the app was started with them. Empty where absent. */
78
+ env = Object.freeze({ ...this.native?.env });
79
+ /**
80
+ * Run `program` with `args`, never through a shell. The call has to match a capability the app
81
+ * declares in app.json; one that does not throws `UndeclaredCapabilityError`. Resolves to null
82
+ * where processes are absent.
83
+ *
84
+ * const git = await processes.spawn('git', ['status', '--porcelain'], { cwd: repo });
85
+ * git?.onStdout((chunk) => output.update((text) => text + chunk));
86
+ * const { code } = (await git?.exit) ?? { code: null };
87
+ */
88
+ async spawn(program, args = [], options = {}) {
89
+ const native = this.native;
90
+ if (!native?.spawn)
91
+ return null;
92
+ const match = matchSpawn(this.capabilities, program, args, native.resolved ?? {});
93
+ if (!match) {
94
+ throw new UndeclaredCapabilityError(`[angular-native] ${program} ${JSON.stringify(args)} matches no spawn capability. ` +
95
+ 'Declare the program and its arguments in capabilities.spawn of the @ng-native/desktop ' +
96
+ 'plugin options in app.json, then rebuild with npm run macos.');
97
+ }
98
+ const env = filterEnvironment(options.env ?? this.env, native.envNames ?? Object.keys(this.env));
99
+ this.spawning++;
100
+ let handle;
101
+ try {
102
+ handle = await native.spawn(match.path, args, options.cwd ?? null, env);
103
+ }
104
+ finally {
105
+ this.spawning--;
106
+ }
107
+ const child = this.child(native, handle);
108
+ // Nothing is waiting for the rest: they were another program's, gone before the app heard it.
109
+ if (!this.spawning)
110
+ this.early.clear();
111
+ return child;
112
+ }
113
+ child(native, handle) {
114
+ const stdout = new Set();
115
+ const stderr = new Set();
116
+ let exited;
117
+ const exit = new Promise((resolve) => (exited = resolve));
118
+ this.running.set(handle, { stdout, stderr, exited });
119
+ const early = this.early.get(handle);
120
+ if (early) {
121
+ this.early.delete(handle);
122
+ this.replaying.set(handle, early);
123
+ // A turn later, as the host's events arrive, so the caller has listened by then.
124
+ setTimeout(() => {
125
+ this.replaying.delete(handle);
126
+ early.forEach((event) => this.heard(event));
127
+ }, 0);
128
+ }
129
+ const listen = (set, listener) => {
130
+ set.add(listener);
131
+ return () => void set.delete(listener);
132
+ };
133
+ return {
134
+ exit,
135
+ onStdout: (listener) => listen(stdout, listener),
136
+ onStderr: (listener) => listen(stderr, listener),
137
+ write: (data) => native.write?.(handle, data),
138
+ end: () => native.closeStdin?.(handle),
139
+ kill: (signal = 'SIGTERM') => native.kill?.(handle, signal),
140
+ };
141
+ }
142
+ heard(event) {
143
+ const queued = this.replaying.get(event.handle);
144
+ if (queued) {
145
+ queued.push(event);
146
+ return;
147
+ }
148
+ const running = this.running.get(event.handle);
149
+ if (!running) {
150
+ if (!this.spawning)
151
+ return;
152
+ const early = this.early.get(event.handle);
153
+ if (early)
154
+ early.push(event);
155
+ else
156
+ this.early.set(event.handle, [event]);
157
+ return;
158
+ }
159
+ if (event.type === 'exit') {
160
+ this.running.delete(event.handle);
161
+ running.exited({ code: event.code, signal: event.signal });
162
+ return;
163
+ }
164
+ for (const listener of running[event.type])
165
+ listener(event.data);
166
+ }
167
+ /** Stop hearing the host, as the app goes. */
168
+ ngOnDestroy() {
169
+ this.unsubscribe?.();
170
+ }
171
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: Processes, deps: [], target: i0.ɵɵFactoryTarget.Service });
172
+ static ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "22.2.0", ngImport: i0, type: Processes });
173
+ }
174
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: Processes, decorators: [{
175
+ type: Service
176
+ }] });
177
+ //# sourceMappingURL=processes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"processes.js","sourceRoot":"","sources":["../src/processes.ts"],"names":[],"mappings":"AAA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AC,KAAK,CAAC,MAAM,CAAC,CAAC;YAC3C,IAAI,KAAK;gBAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;;gBACxB,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;YAC3C,OAAO;QACT,CAAC;QACD,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC1B,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YAClC,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;YAC3D,OAAO;QACT,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC;YAAE,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACnE,CAAC;IAED,8CAA8C;IAC9C,WAAW;QACT,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;IACvB,CAAC;uGA7HU,SAAS;wGAAT,SAAS;;2FAAT,SAAS;kBADrB,OAAO","sourcesContent":["/**\n * `Processes`: the app's environment on a desktop OS, and the programs it declares, run with\n * `spawn`. Absent on iOS, Android and the web, which give an app neither.\n *\n * The host contract, on the `NgNativeProcesses` module:\n *\n * - `getConstants()` answers `env` (the environment, already filtered to `capabilities.env`),\n * `envNames` (`capabilities.env` itself), `spawn` (the declared spawn capabilities) and `resolved` (where each declared bare name was\n * pinned at startup, or null where it is absent).\n * - `spawn(program, args, cwd, env)` runs the program, never through a shell, after checking the\n * call against the declaration again, and answers a handle; it rejects an undeclared call.\n * - `write(handle, data)`, `closeStdin(handle)` and `kill(handle, signal)`.\n * - `{ type: 'stdout' | 'stderr', handle, data }` and `{ type: 'exit', handle, code, signal }`\n * arrive on `ngNativeProcesses`.\n */\nimport { InjectionToken, Service, inject, signal, type Signal } from '@angular/core';\nimport { reactNative } from './react-native.ts';\nimport {\n compileCapability,\n filterEnvironment,\n matchSpawn,\n type CompiledCapability,\n type SpawnCapability,\n} from './spawn-rules.ts';\n\n/** How a spawned program ended: its exit code, or the signal that stopped it. */\nexport interface ProcessExit {\n readonly code: number | null;\n readonly signal: string | null;\n}\n\n/** What the host reports about a spawned program. */\nexport type ProcessEvent =\n | { readonly type: 'stdout' | 'stderr'; readonly handle: number; readonly data: string }\n | {\n readonly type: 'exit';\n readonly handle: number;\n readonly code: number | null;\n readonly signal: string | null;\n };\n\n/** What the desktop host's module reports, and what a test fakes. */\nexport interface NativeProcesses {\n /** The environment variables the app was started with, filtered to those it declares. */\n readonly env: Readonly<Record<string, string>>;\n /** The variables `capabilities.env` declares: all a spawned program may be given. */\n readonly envNames?: readonly string[];\n /** The declared spawn capabilities. None declared, nothing may be spawned. */\n readonly spawnCapabilities?: readonly SpawnCapability[];\n /** Where each declared bare program name was pinned at startup, or null where it is absent. */\n readonly resolved?: Readonly<Record<string, string | null>>;\n spawn?(\n program: string,\n args: readonly string[],\n cwd: string | null,\n env: Readonly<Record<string, string>>,\n ): Promise<number>;\n write?(handle: number, data: string): void;\n closeStdin?(handle: number): void;\n kill?(handle: number, signal: string): void;\n subscribe?(listener: (event: ProcessEvent) => void): () => void;\n}\n\n/** A program `spawn` started. */\nexport interface ChildProcess {\n /** Settles once the program has ended. */\n readonly exit: Promise<ProcessExit>;\n /** Hear what the program writes to standard output. Answers the function that stops it. */\n onStdout(listener: (chunk: string) => void): () => void;\n /** Hear what the program writes to standard error. */\n onStderr(listener: (chunk: string) => void): () => void;\n /** Write to the program's standard input. */\n write(data: string): void;\n /** Close the program's standard input. */\n end(): void;\n /** Stop the program. `SIGTERM` unless it says. */\n kill(signal?: 'SIGTERM' | 'SIGINT' | 'SIGKILL' | 'SIGHUP'): void;\n}\n\n/** What `spawn` takes beside the program and its arguments. */\nexport interface SpawnOptions {\n /** The working directory. The app's own when unset. */\n readonly cwd?: string;\n /**\n * The program's environment. Only the variables the app declares in `capabilities.env` are\n * passed; the rest are left out. Unset, it gets `Processes.env`.\n */\n readonly env?: Readonly<Record<string, string>>;\n}\n\n/** A spawn the app did not declare: a misconfiguration, so it throws rather than doing nothing. */\nexport class UndeclaredCapabilityError extends Error {\n override readonly name = 'UndeclaredCapabilityError';\n}\n\n/** The desktop host's TurboModule. */\ninterface ProcessesTurboModule {\n getConstants?(): {\n env?: Record<string, string>;\n envNames?: string[];\n spawn?: SpawnCapability[];\n resolved?: Record<string, string | null>;\n };\n spawn?(program: string, args: string[], cwd: string | null, env: object): Promise<number>;\n write?(handle: number, data: string): void;\n closeStdin?(handle: number): void;\n kill?(handle: number, signal: string): void;\n}\n\n/** React Native's event emitter, which the host's process events arrive on. */\ntype Emitter = {\n addListener(event: string, listener: (event: unknown) => void): { remove(): void };\n};\n\n/** The desktop host's module, or null where there is none: every OS but a desktop one. */\nfunction processesSource(): NativeProcesses | null {\n const native = reactNative() as {\n TurboModuleRegistry?: { get?(name: string): unknown };\n DeviceEventEmitter?: Emitter;\n } | null;\n const module = native?.TurboModuleRegistry?.get?.('NgNativeProcesses') as\n ProcessesTurboModule | null | undefined;\n const constants = module?.getConstants?.();\n if (!module || !constants?.env) return null;\n return {\n ...declared(constants.env, constants),\n ...processMethods(module, native?.DeviceEventEmitter),\n };\n}\n\n/** What the host's constants declare, with what an older host leaves out filled in. */\nfunction declared(\n env: Record<string, string>,\n constants: ReturnType<NonNullable<ProcessesTurboModule['getConstants']>>,\n) {\n return {\n env,\n envNames: constants.envNames ?? Object.keys(env),\n spawnCapabilities: constants.spawn ?? [],\n resolved: constants.resolved ?? {},\n };\n}\n\n/** The module's methods, as the service calls them. */\nfunction processMethods(module: ProcessesTurboModule, emitter: Emitter | undefined) {\n return {\n spawn:\n module.spawn &&\n ((...call: Parameters<NonNullable<NativeProcesses['spawn']>>) =>\n module.spawn!(call[0], [...call[1]], call[2], call[3])),\n write: (handle: number, data: string) => module.write?.(handle, data),\n closeStdin: (handle: number) => module.closeStdin?.(handle),\n kill: (handle: number, signal: string) => module.kill?.(handle, signal),\n subscribe: (listener: (event: ProcessEvent) => void) => {\n const subscription = emitter?.addListener('ngNativeProcesses', (event) =>\n listener(event as ProcessEvent),\n );\n return () => subscription?.remove();\n },\n };\n}\n\n/** One spawned program's listeners, until it exits. */\ninterface Running {\n readonly stdout: Set<(chunk: string) => void>;\n readonly stderr: Set<(chunk: string) => void>;\n exited(exit: ProcessExit): void;\n}\n\n@Service()\nexport class Processes {\n /** Overridden in a test to start the app with an environment, and to fake programs. */\n static readonly SOURCE = new InjectionToken<NativeProcesses | null>(\n 'angular-native.processesSource',\n { factory: processesSource },\n );\n\n private readonly native = inject(Processes.SOURCE);\n private readonly capabilities: readonly CompiledCapability[] = (\n this.native?.spawnCapabilities ?? []\n ).map(compileCapability);\n private readonly running = new Map<number, Running>();\n /**\n * What the host said of a program before its spawn resolved with the handle: its reader threads\n * can queue a short program's output and exit ahead of that answer.\n */\n private readonly early = new Map<number, ProcessEvent[]>();\n /** Spawns waiting on the host, while which an unknown handle's events are kept. */\n private spawning = 0;\n /** Held events not yet replayed, by handle: live ones queue behind them, in order. */\n private readonly replaying = new Map<number, ProcessEvent[]>();\n private readonly unsubscribe = this.native?.subscribe?.((event) => this.heard(event)) ?? null;\n\n /** Whether the OS gives the app processes: a desktop OS with the desktop host's module. */\n readonly available: Signal<boolean> = signal(this.native !== null).asReadonly();\n\n /** The environment variables, as the app was started with them. Empty where absent. */\n readonly env: Readonly<Record<string, string>> = Object.freeze({ ...this.native?.env });\n\n /**\n * Run `program` with `args`, never through a shell. The call has to match a capability the app\n * declares in app.json; one that does not throws `UndeclaredCapabilityError`. Resolves to null\n * where processes are absent.\n *\n * const git = await processes.spawn('git', ['status', '--porcelain'], { cwd: repo });\n * git?.onStdout((chunk) => output.update((text) => text + chunk));\n * const { code } = (await git?.exit) ?? { code: null };\n */\n async spawn(\n program: string,\n args: readonly string[] = [],\n options: SpawnOptions = {},\n ): Promise<ChildProcess | null> {\n const native = this.native;\n if (!native?.spawn) return null;\n const match = matchSpawn(this.capabilities, program, args, native.resolved ?? {});\n if (!match) {\n throw new UndeclaredCapabilityError(\n `[angular-native] ${program} ${JSON.stringify(args)} matches no spawn capability. ` +\n 'Declare the program and its arguments in capabilities.spawn of the @ng-native/desktop ' +\n 'plugin options in app.json, then rebuild with npm run macos.',\n );\n }\n const env = filterEnvironment(\n options.env ?? this.env,\n native.envNames ?? Object.keys(this.env),\n );\n this.spawning++;\n let handle: number;\n try {\n handle = await native.spawn(match.path, args, options.cwd ?? null, env);\n } finally {\n this.spawning--;\n }\n const child = this.child(native, handle);\n // Nothing is waiting for the rest: they were another program's, gone before the app heard it.\n if (!this.spawning) this.early.clear();\n return child;\n }\n\n private child(native: NativeProcesses, handle: number): ChildProcess {\n const stdout = new Set<(chunk: string) => void>();\n const stderr = new Set<(chunk: string) => void>();\n let exited!: (exit: ProcessExit) => void;\n const exit = new Promise<ProcessExit>((resolve) => (exited = resolve));\n this.running.set(handle, { stdout, stderr, exited });\n const early = this.early.get(handle);\n if (early) {\n this.early.delete(handle);\n this.replaying.set(handle, early);\n // A turn later, as the host's events arrive, so the caller has listened by then.\n setTimeout(() => {\n this.replaying.delete(handle);\n early.forEach((event) => this.heard(event));\n }, 0);\n }\n const listen = (set: Set<(chunk: string) => void>, listener: (chunk: string) => void) => {\n set.add(listener);\n return () => void set.delete(listener);\n };\n return {\n exit,\n onStdout: (listener) => listen(stdout, listener),\n onStderr: (listener) => listen(stderr, listener),\n write: (data) => native.write?.(handle, data),\n end: () => native.closeStdin?.(handle),\n kill: (signal = 'SIGTERM') => native.kill?.(handle, signal),\n };\n }\n\n private heard(event: ProcessEvent): void {\n const queued = this.replaying.get(event.handle);\n if (queued) {\n queued.push(event);\n return;\n }\n const running = this.running.get(event.handle);\n if (!running) {\n if (!this.spawning) return;\n const early = this.early.get(event.handle);\n if (early) early.push(event);\n else this.early.set(event.handle, [event]);\n return;\n }\n if (event.type === 'exit') {\n this.running.delete(event.handle);\n running.exited({ code: event.code, signal: event.signal });\n return;\n }\n for (const listener of running[event.type]) listener(event.data);\n }\n\n /** Stop hearing the host, as the app goes. */\n ngOnDestroy(): void {\n this.unsubscribe?.();\n }\n}\n"]}
@@ -25,6 +25,12 @@ export interface ReactNative {
25
25
  remove(): void;
26
26
  };
27
27
  };
28
+ /** Optional: a host without it (the web host's stand-in) has no surfaces it starts itself. */
29
+ AppRegistry?: {
30
+ registerRunnable(name: string, run: (parameters: {
31
+ rootTag: number;
32
+ }) => void): void;
33
+ };
28
34
  AppState: {
29
35
  currentState: string | null;
30
36
  addEventListener(event: 'change', handler: (state: string) => void): {
@@ -113,11 +119,19 @@ export interface ReactNative {
113
119
  Platform: {
114
120
  OS: string;
115
121
  Version?: string | number;
122
+ /** iOS: whether the device is an iPad. */
123
+ isPad?: boolean;
116
124
  };
117
125
  /** Optional: the status bar and keyboard read it, for `DeviceInfo`'s `isEdgeToEdge` on Android. */
118
126
  TurboModuleRegistry?: {
119
127
  get(name: string): unknown;
120
128
  };
129
+ /** Where a native module without its own emitter sends events. */
130
+ DeviceEventEmitter?: {
131
+ addListener(event: string, handler: (payload: unknown) => void): {
132
+ remove(): void;
133
+ };
134
+ };
121
135
  Share: {
122
136
  share(content: {
123
137
  message?: string;
@@ -137,6 +151,11 @@ export interface ReactNative {
137
151
  vibrate(pattern?: number | number[], repeat?: boolean): void;
138
152
  cancel(): void;
139
153
  };
154
+ /** iOS's and macOS's user defaults, read once as the runtime starts. Absent on Android. */
155
+ Settings?: {
156
+ get(key: string): unknown;
157
+ set(values: Record<string, unknown>): void;
158
+ };
140
159
  DevSettings?: {
141
160
  addMenuItem(title: string, handler: () => unknown): void;
142
161
  reload(reason?: string): void;
@@ -1 +1 @@
1
- {"version":3,"file":"react-native.js","sourceRoot":"","sources":["../src/react-native.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAuJH;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,MAAmB;IAChD,MAAM,IAAI,GAAG,MAAM,CAAC,mBAAmB,EAAE,GAAG,CAAC,YAAY,CACW,CAAC;IACrE,OAAO,IAAI,EAAE,YAAY,EAAE,EAAE,CAAC,YAAY,KAAK,IAAI,CAAC;AACtD,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,WAAW;IACzB,IAAK,UAAkD,CAAC,qBAAqB,KAAK,SAAS,EAAE,CAAC;QAC5F,OAAO,IAAI,CAAC;IACd,CAAC;IACD,+FAA+F;IAC/F,8EAA8E;IAC9E,aAAa;IACb,IAAI,OAAO,OAAO,KAAK,UAAU;QAAE,OAAO,OAAO,CAAC,cAAc,CAAgB,CAAC;IACjF,OAAO,CAAC,KAAK,CACX,uFAAuF;QACrF,+DAA+D,CAClE,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * React Native's own modules, fetched when a service is first constructed rather than when this\n * file is loaded.\n *\n * The distinction matters more than it looks. React Native ships its JavaScript as Flow, which\n * Node cannot parse, so a static `import ... from 'react-native'` anywhere in this package would\n * make the package unimportable by the test suite - and by `@ng-native/components`, which\n * the suite imports constantly. A call inside a factory is only ever executed on a device, where\n * `react-native` is the most ordinary import there is.\n *\n * ponytail: a `require` in a codebase that otherwise has none. The alternative is the shape\n * `@ng-native/expo` uses - a file per service outside `src`, importing the module and\n * declaring the service - which is right there because Expo's packages are optional peer\n * dependencies an app may not have installed. React Native is not optional, so the seam buys\n * nothing but files.\n */\n\n/** The subset of React Native this package reaches for, described so `require` has a type. */\nexport interface ReactNative {\n AccessibilityInfo: {\n isScreenReaderEnabled(): Promise<boolean>;\n isReduceMotionEnabled(): Promise<boolean>;\n isBoldTextEnabled(): Promise<boolean>;\n announceForAccessibility(announcement: string): void;\n addEventListener(\n event: 'screenReaderChanged' | 'reduceMotionChanged' | 'boldTextChanged',\n handler: (value: boolean) => void,\n ): { remove(): void };\n };\n AppState: {\n currentState: string | null;\n addEventListener(event: 'change', handler: (state: string) => void): { remove(): void };\n };\n Appearance: {\n getColorScheme(): 'light' | 'dark' | null | undefined;\n addChangeListener(handler: (preferences: { colorScheme?: string | null }) => void): {\n remove(): void;\n };\n setColorScheme?(scheme: 'light' | 'dark' | 'unspecified'): void;\n };\n BackHandler: {\n addEventListener(event: 'hardwareBackPress', handler: () => boolean): { remove(): void };\n };\n Dimensions: {\n get(dimension: 'window' | 'screen'): { width: number; height: number };\n addEventListener(\n event: 'change',\n handler: (sizes: {\n window: { width: number; height: number };\n screen: { width: number; height: number };\n }) => void,\n ): { remove(): void };\n };\n I18nManager: {\n /** Whether the app is laid out right to left. Fixed for the lifetime of the process. */\n isRTL: boolean;\n };\n Keyboard: {\n dismiss(): void;\n /** Where the last show `Keyboard.js` heard put the keyboard, or nothing once it hid. */\n metrics?(): { height: number; screenY: number } | null | undefined;\n addListener(\n event:\n | 'keyboardDidShow'\n | 'keyboardDidHide'\n | 'keyboardWillShow'\n | 'keyboardWillHide'\n | 'keyboardWillChangeFrame',\n handler: (event: NativeKeyboardEvent) => void,\n ): { remove(): void };\n };\n StyleSheet: {\n /** The thinnest line the screen can draw, in points. `1 / PixelRatio.get()`, near enough. */\n hairlineWidth: number;\n };\n ActionSheetIOS?: {\n showActionSheetWithOptions(\n options: {\n title?: string;\n message?: string;\n options: string[];\n cancelButtonIndex: number;\n destructiveButtonIndex?: number;\n },\n callback: (index: number) => void,\n ): void;\n };\n Alert: {\n alert(\n title: string,\n message?: string,\n buttons?: { text?: string; style?: string; onPress?: () => void }[],\n options?: object,\n ): void;\n /** iOS only. Absent on Android, where there is no such dialog. */\n prompt?(\n title: string,\n message?: string,\n callbackOrButtons?:\n | ((value: string) => void)\n | { text?: string; style?: string; onPress?: (value?: string) => void }[],\n type?: string,\n defaultValue?: string,\n ): void;\n };\n PixelRatio: {\n get(): number;\n /** The user's text size setting, as a multiplier. One is the default. */\n getFontScale(): number;\n };\n /** `Version` is a string on iOS, `'26.5'`, and the API level, a number, on Android. */\n Platform: { OS: string; Version?: string | number };\n /** Optional: the status bar and keyboard read it, for `DeviceInfo`'s `isEdgeToEdge` on Android. */\n TurboModuleRegistry?: { get(name: string): unknown };\n Share: {\n share(\n content: { message?: string; url?: string; title?: string },\n options?: object,\n ): Promise<{ action: string; activityType?: string | null }>;\n };\n ToastAndroid?: {\n show(message: string, duration: number): void;\n SHORT: number;\n LONG: number;\n };\n Vibration: {\n vibrate(pattern?: number | number[], repeat?: boolean): void;\n cancel(): void;\n };\n DevSettings?: {\n addMenuItem(title: string, handler: () => unknown): void;\n reload(reason?: string): void;\n };\n LayoutAnimation: {\n configureNext(config: object, onDone?: () => void, onFail?: () => void): void;\n };\n PermissionsAndroid?: {\n check(permission: string): Promise<boolean>;\n request(permission: string, rationale?: object): Promise<string>;\n };\n StatusBar: {\n /** Android reports the bar's height in dp; iOS leaves it undefined. */\n currentHeight?: number;\n setBarStyle(style: string, animated?: boolean): void;\n setHidden(hidden: boolean, animation?: string): void;\n /** Removed in React Native 0.88, with edge-to-edge on every Android app. */\n setBackgroundColor?(color: string, animated?: boolean): void;\n /** Removed in React Native 0.88, with `setBackgroundColor`. */\n setTranslucent?(translucent: boolean): void;\n };\n Linking: {\n getInitialURL(): Promise<string | null>;\n openURL(url: string): Promise<unknown>;\n openSettings(): Promise<void>;\n addEventListener(event: 'url', handler: (event: { url: string }) => void): { remove(): void };\n };\n}\n\n/** What RN hands a keyboard listener. */\nexport interface NativeKeyboardEvent {\n readonly endCoordinates: { readonly height: number; readonly screenY: number };\n readonly duration?: number;\n /** One of `LayoutEasing`'s names; usually `'keyboard'` on iOS, and always on Android, with a zero duration. */\n readonly easing?: string;\n}\n\n/**\n * React Native's edge-to-edge flag on Android, which its `DeviceInfo` module reports: whether it\n * treats the app as drawn under the system bars, for its status bar and for where it measures from.\n */\nexport function edgeToEdgeFlag(native: ReactNative): boolean {\n const info = native.TurboModuleRegistry?.get('DeviceInfo') as\n { getConstants?(): { isEdgeToEdge?: boolean } } | null | undefined;\n return info?.getConstants?.().isEdgeToEdge === true;\n}\n\n/**\n * `null` off a device, where each capability falls back to doing nothing - the same as an\n * optional injection token nobody provided.\n *\n * The engine's presence is what tells the two apart. In Node and in a browser there is no\n * `nativeFabricUIManager`; on a device there is one, and a missing `require` would mean the bundler\n * stopped emitting CommonJS under us. That is worth saying out loud rather than quietly rendering\n * an app whose keyboard never moves.\n *\n * `require` alone cannot tell them apart: a browser bundle can have one. Rolldown gives a `vite\n * build` its own `require` for an external module, which passes `typeof require === 'function'`\n * and throws when called.\n */\nexport function reactNative(): ReactNative | null {\n if ((globalThis as { nativeFabricUIManager?: unknown }).nativeFabricUIManager === undefined) {\n return null;\n }\n // `require` has a type only where the app's tsconfig loads Node's or React Native's types, and\n // a browser app's loads neither. `@ts-expect-error` would fail where it does.\n // @ts-ignore\n if (typeof require === 'function') return require('react-native') as ReactNative;\n console.error(\n '[angular-native] react-native could not be required, so every platform capability is ' +\n 'inert. The bundle is not CommonJS; check the Metro transform.',\n );\n return null;\n}\n"]}
1
+ {"version":3,"file":"react-native.js","sourceRoot":"","sources":["../src/react-native.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAyKH;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,MAAmB;IAChD,MAAM,IAAI,GAAG,MAAM,CAAC,mBAAmB,EAAE,GAAG,CAAC,YAAY,CACW,CAAC;IACrE,OAAO,IAAI,EAAE,YAAY,EAAE,EAAE,CAAC,YAAY,KAAK,IAAI,CAAC;AACtD,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,WAAW;IACzB,IAAK,UAAkD,CAAC,qBAAqB,KAAK,SAAS,EAAE,CAAC;QAC5F,OAAO,IAAI,CAAC;IACd,CAAC;IACD,+FAA+F;IAC/F,8EAA8E;IAC9E,aAAa;IACb,IAAI,OAAO,OAAO,KAAK,UAAU;QAAE,OAAO,OAAO,CAAC,cAAc,CAAgB,CAAC;IACjF,OAAO,CAAC,KAAK,CACX,uFAAuF;QACrF,+DAA+D,CAClE,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * React Native's own modules, fetched when a service is first constructed rather than when this\n * file is loaded.\n *\n * The distinction matters more than it looks. React Native ships its JavaScript as Flow, which\n * Node cannot parse, so a static `import ... from 'react-native'` anywhere in this package would\n * make the package unimportable by the test suite - and by `@ng-native/components`, which\n * the suite imports constantly. A call inside a factory is only ever executed on a device, where\n * `react-native` is the most ordinary import there is.\n *\n * ponytail: a `require` in a codebase that otherwise has none. The alternative is the shape\n * `@ng-native/expo` uses - a file per service outside `src`, importing the module and\n * declaring the service - which is right there because Expo's packages are optional peer\n * dependencies an app may not have installed. React Native is not optional, so the seam buys\n * nothing but files.\n */\n\n/** The subset of React Native this package reaches for, described so `require` has a type. */\nexport interface ReactNative {\n AccessibilityInfo: {\n isScreenReaderEnabled(): Promise<boolean>;\n isReduceMotionEnabled(): Promise<boolean>;\n isBoldTextEnabled(): Promise<boolean>;\n announceForAccessibility(announcement: string): void;\n addEventListener(\n event: 'screenReaderChanged' | 'reduceMotionChanged' | 'boldTextChanged',\n handler: (value: boolean) => void,\n ): { remove(): void };\n };\n /** Optional: a host without it (the web host's stand-in) has no surfaces it starts itself. */\n AppRegistry?: {\n registerRunnable(name: string, run: (parameters: { rootTag: number }) => void): void;\n };\n AppState: {\n currentState: string | null;\n addEventListener(event: 'change', handler: (state: string) => void): { remove(): void };\n };\n Appearance: {\n getColorScheme(): 'light' | 'dark' | null | undefined;\n addChangeListener(handler: (preferences: { colorScheme?: string | null }) => void): {\n remove(): void;\n };\n setColorScheme?(scheme: 'light' | 'dark' | 'unspecified'): void;\n };\n BackHandler: {\n addEventListener(event: 'hardwareBackPress', handler: () => boolean): { remove(): void };\n };\n Dimensions: {\n get(dimension: 'window' | 'screen'): { width: number; height: number };\n addEventListener(\n event: 'change',\n handler: (sizes: {\n window: { width: number; height: number };\n screen: { width: number; height: number };\n }) => void,\n ): { remove(): void };\n };\n I18nManager: {\n /** Whether the app is laid out right to left. Fixed for the lifetime of the process. */\n isRTL: boolean;\n };\n Keyboard: {\n dismiss(): void;\n /** Where the last show `Keyboard.js` heard put the keyboard, or nothing once it hid. */\n metrics?(): { height: number; screenY: number } | null | undefined;\n addListener(\n event:\n | 'keyboardDidShow'\n | 'keyboardDidHide'\n | 'keyboardWillShow'\n | 'keyboardWillHide'\n | 'keyboardWillChangeFrame',\n handler: (event: NativeKeyboardEvent) => void,\n ): { remove(): void };\n };\n StyleSheet: {\n /** The thinnest line the screen can draw, in points. `1 / PixelRatio.get()`, near enough. */\n hairlineWidth: number;\n };\n ActionSheetIOS?: {\n showActionSheetWithOptions(\n options: {\n title?: string;\n message?: string;\n options: string[];\n cancelButtonIndex: number;\n destructiveButtonIndex?: number;\n },\n callback: (index: number) => void,\n ): void;\n };\n Alert: {\n alert(\n title: string,\n message?: string,\n buttons?: { text?: string; style?: string; onPress?: () => void }[],\n options?: object,\n ): void;\n /** iOS only. Absent on Android, where there is no such dialog. */\n prompt?(\n title: string,\n message?: string,\n callbackOrButtons?:\n | ((value: string) => void)\n | { text?: string; style?: string; onPress?: (value?: string) => void }[],\n type?: string,\n defaultValue?: string,\n ): void;\n };\n PixelRatio: {\n get(): number;\n /** The user's text size setting, as a multiplier. One is the default. */\n getFontScale(): number;\n };\n /** `Version` is a string on iOS, `'26.5'`, and the API level, a number, on Android. */\n Platform: {\n OS: string;\n Version?: string | number;\n /** iOS: whether the device is an iPad. */\n isPad?: boolean;\n };\n /** Optional: the status bar and keyboard read it, for `DeviceInfo`'s `isEdgeToEdge` on Android. */\n TurboModuleRegistry?: { get(name: string): unknown };\n /** Where a native module without its own emitter sends events. */\n DeviceEventEmitter?: {\n addListener(event: string, handler: (payload: unknown) => void): { remove(): void };\n };\n Share: {\n share(\n content: { message?: string; url?: string; title?: string },\n options?: object,\n ): Promise<{ action: string; activityType?: string | null }>;\n };\n ToastAndroid?: {\n show(message: string, duration: number): void;\n SHORT: number;\n LONG: number;\n };\n Vibration: {\n vibrate(pattern?: number | number[], repeat?: boolean): void;\n cancel(): void;\n };\n /** iOS's and macOS's user defaults, read once as the runtime starts. Absent on Android. */\n Settings?: {\n get(key: string): unknown;\n set(values: Record<string, unknown>): void;\n };\n DevSettings?: {\n addMenuItem(title: string, handler: () => unknown): void;\n reload(reason?: string): void;\n };\n LayoutAnimation: {\n configureNext(config: object, onDone?: () => void, onFail?: () => void): void;\n };\n PermissionsAndroid?: {\n check(permission: string): Promise<boolean>;\n request(permission: string, rationale?: object): Promise<string>;\n };\n StatusBar: {\n /** Android reports the bar's height in dp; iOS leaves it undefined. */\n currentHeight?: number;\n setBarStyle(style: string, animated?: boolean): void;\n setHidden(hidden: boolean, animation?: string): void;\n /** Removed in React Native 0.88, with edge-to-edge on every Android app. */\n setBackgroundColor?(color: string, animated?: boolean): void;\n /** Removed in React Native 0.88, with `setBackgroundColor`. */\n setTranslucent?(translucent: boolean): void;\n };\n Linking: {\n getInitialURL(): Promise<string | null>;\n openURL(url: string): Promise<unknown>;\n openSettings(): Promise<void>;\n addEventListener(event: 'url', handler: (event: { url: string }) => void): { remove(): void };\n };\n}\n\n/** What RN hands a keyboard listener. */\nexport interface NativeKeyboardEvent {\n readonly endCoordinates: { readonly height: number; readonly screenY: number };\n readonly duration?: number;\n /** One of `LayoutEasing`'s names; usually `'keyboard'` on iOS, and always on Android, with a zero duration. */\n readonly easing?: string;\n}\n\n/**\n * React Native's edge-to-edge flag on Android, which its `DeviceInfo` module reports: whether it\n * treats the app as drawn under the system bars, for its status bar and for where it measures from.\n */\nexport function edgeToEdgeFlag(native: ReactNative): boolean {\n const info = native.TurboModuleRegistry?.get('DeviceInfo') as\n { getConstants?(): { isEdgeToEdge?: boolean } } | null | undefined;\n return info?.getConstants?.().isEdgeToEdge === true;\n}\n\n/**\n * `null` off a device, where each capability falls back to doing nothing - the same as an\n * optional injection token nobody provided.\n *\n * The engine's presence is what tells the two apart. In Node and in a browser there is no\n * `nativeFabricUIManager`; on a device there is one, and a missing `require` would mean the bundler\n * stopped emitting CommonJS under us. That is worth saying out loud rather than quietly rendering\n * an app whose keyboard never moves.\n *\n * `require` alone cannot tell them apart: a browser bundle can have one. Rolldown gives a `vite\n * build` its own `require` for an external module, which passes `typeof require === 'function'`\n * and throws when called.\n */\nexport function reactNative(): ReactNative | null {\n if ((globalThis as { nativeFabricUIManager?: unknown }).nativeFabricUIManager === undefined) {\n return null;\n }\n // `require` has a type only where the app's tsconfig loads Node's or React Native's types, and\n // a browser app's loads neither. `@ts-expect-error` would fail where it does.\n // @ts-ignore\n if (typeof require === 'function') return require('react-native') as ReactNative;\n console.error(\n '[angular-native] react-native could not be required, so every platform capability is ' +\n 'inert. The bundle is not CommonJS; check the Metro transform.',\n );\n return null;\n}\n"]}
@@ -28,8 +28,11 @@ export interface Frame {
28
28
  readonly height: number;
29
29
  }
30
30
  export declare class SafeArea {
31
+ /** Whether the service is here: on every OS, where it answers what the OS reports. */
32
+ readonly available: Signal<boolean>;
31
33
  private readonly current;
32
34
  private readonly measured;
35
+ private readonly controls;
33
36
  /** What each provider still up last reported, the latest last. */
34
37
  private readonly reports;
35
38
  private reporter;
@@ -43,13 +46,21 @@ export declare class SafeArea {
43
46
  * one frame after the app mounts, and again once every provider that reported is destroyed.
44
47
  */
45
48
  readonly frame: Signal<Frame | null>;
49
+ /**
50
+ * On macOS, how far the window's close, minimise and zoom buttons reach into the reporting
51
+ * pane from its leading edge: what `--safe-area-inset-titlebar-leading` holds. Their width in a
52
+ * window with no sidebar and in the sidebar pane under them; zero in the content pane beside a
53
+ * sidebar, which they do not reach, and on every other OS. One value for the app: the latest
54
+ * report's, not one per pane.
55
+ */
56
+ readonly titlebarLeading: Signal<number>;
46
57
  /** Whether anything has reported yet, for a layout that would rather wait than jump. */
47
58
  readonly known: Signal<boolean>;
48
59
  /**
49
60
  * Called by `<safe-area-provider>` when native reports. Not for apps: an inset written from
50
61
  * anywhere else is a number that stops matching the screen the moment the device rotates.
51
62
  */
52
- report(insets: Insets, frame: Frame, from?: object): void;
63
+ report(insets: Insets, frame: Frame, from?: object, titlebarLeading?: number): void;
53
64
  /**
54
65
  * Called by `<safe-area-provider>` as it goes: forgets its report. When that report was the
55
66
  * latest, what a provider still up last reported takes its place, or nothing when none is.
package/dist/safe-area.js CHANGED
@@ -17,10 +17,14 @@ import { Service, computed, signal } from '@angular/core';
17
17
  import * as i0 from "@angular/core";
18
18
  const NOTHING = { top: 0, right: 0, bottom: 0, left: 0 };
19
19
  export class SafeArea {
20
+ /** Whether the service is here: on every OS, where it answers what the OS reports. */
21
+ available = signal(true).asReadonly();
20
22
  current = signal(NOTHING, /* @ts-ignore */
21
23
  ...(ngDevMode ? [{ debugName: "current" }] : /* istanbul ignore next */ []));
22
24
  measured = signal(null, /* @ts-ignore */
23
25
  ...(ngDevMode ? [{ debugName: "measured" }] : /* istanbul ignore next */ []));
26
+ controls = signal(0, /* @ts-ignore */
27
+ ...(ngDevMode ? [{ debugName: "controls" }] : /* istanbul ignore next */ []));
24
28
  /** What each provider still up last reported, the latest last. */
25
29
  reports = new Map();
26
30
  reporter = null;
@@ -34,6 +38,14 @@ export class SafeArea {
34
38
  * one frame after the app mounts, and again once every provider that reported is destroyed.
35
39
  */
36
40
  frame = this.measured.asReadonly();
41
+ /**
42
+ * On macOS, how far the window's close, minimise and zoom buttons reach into the reporting
43
+ * pane from its leading edge: what `--safe-area-inset-titlebar-leading` holds. Their width in a
44
+ * window with no sidebar and in the sidebar pane under them; zero in the content pane beside a
45
+ * sidebar, which they do not reach, and on every other OS. One value for the app: the latest
46
+ * report's, not one per pane.
47
+ */
48
+ titlebarLeading = this.controls.asReadonly();
37
49
  /** Whether anything has reported yet, for a layout that would rather wait than jump. */
38
50
  known = computed(() => this.measured() !== null, /* @ts-ignore */
39
51
  ...(ngDevMode ? [{ debugName: "known" }] : /* istanbul ignore next */ []));
@@ -41,14 +53,15 @@ export class SafeArea {
41
53
  * Called by `<safe-area-provider>` when native reports. Not for apps: an inset written from
42
54
  * anywhere else is a number that stops matching the screen the moment the device rotates.
43
55
  */
44
- report(insets, frame, from) {
56
+ report(insets, frame, from, titlebarLeading = 0) {
45
57
  this.current.set(insets);
46
58
  this.measured.set(frame);
59
+ this.controls.set(titlebarLeading);
47
60
  this.reporter = from ?? null;
48
61
  if (!from)
49
62
  return;
50
63
  this.reports.delete(from);
51
- this.reports.set(from, { insets, frame });
64
+ this.reports.set(from, { insets, frame, titlebarLeading });
52
65
  }
53
66
  /**
54
67
  * Called by `<safe-area-provider>` as it goes: forgets its report. When that report was the
@@ -63,6 +76,7 @@ export class SafeArea {
63
76
  this.reporter = previous?.[0] ?? null;
64
77
  this.current.set(previous?.[1].insets ?? NOTHING);
65
78
  this.measured.set(previous?.[1].frame ?? null);
79
+ this.controls.set(previous?.[1].titlebarLeading ?? 0);
66
80
  return true;
67
81
  }
68
82
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: SafeArea, deps: [], target: i0.ɵɵFactoryTarget.Service });
@@ -1 +1 @@
1
- {"version":3,"file":"safe-area.js","sourceRoot":"","sources":["../src/safe-area.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAe,MAAM,eAAe,CAAC;;AAgBvE,MAAM,OAAO,GAAW,EAAE,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;AAGjE,MAAM,OAAO,QAAQ;IACF,OAAO,GAAG,MAAM,CAAS,OAAO;gFAAC,CAAC;IAClC,QAAQ,GAAG,MAAM,CAAe,IAAI;iFAAC,CAAC;IACvD,kEAAkE;IACjD,OAAO,GAAG,IAAI,GAAG,EAA4C,CAAC;IACvE,QAAQ,GAAkB,IAAI,CAAC;IAEvC,wDAAwD;IAC/C,MAAM,GAAmB,IAAI,CAAC,OAAO,CAAC,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I,CAAC,CAAC;QAC/C,OAAO,IAAI,CAAC;IACd,CAAC;uGAhDU,QAAQ;wGAAR,QAAQ;;2FAAR,QAAQ;kBADpB,OAAO","sourcesContent":["/**\n * How much of the screen belongs to the system: the notch, the status bar, the home indicator,\n * a rounded corner, and on Android the display cutout and the navigation bar.\n *\n * Unlike everything else here, this has no React Native module behind it. Insets are a property\n * of a *view*, not of the device, and the only thing that can report them is a native view inside\n * the window - `<safe-area-provider>` in `@ng-native/components`, which pushes what it\n * measures in here. That is also why the values start at zero: nothing is known until a view has\n * been laid out, which is one frame after the app mounts.\n *\n * Most layouts should not read this at all. A `<safe-area-view>` applies the insets natively,\n * without a round trip through JavaScript, and a screen in a native stack has its header do it.\n * This is for the cases neither covers: a floating button that must clear the home indicator, a\n * scroll view whose content inset is computed, a sheet drawing its own chrome.\n */\nimport { Service, computed, signal, type Signal } from '@angular/core';\n\nexport interface Insets {\n readonly top: number;\n readonly right: number;\n readonly bottom: number;\n readonly left: number;\n}\n\nexport interface Frame {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\nconst NOTHING: Insets = { top: 0, right: 0, bottom: 0, left: 0 };\n\n@Service()\nexport class SafeArea {\n private readonly current = signal<Insets>(NOTHING);\n private readonly measured = signal<Frame | null>(null);\n /** What each provider still up last reported, the latest last. */\n private readonly reports = new Map<object, { insets: Insets; frame: Frame }>();\n private reporter: object | null = null;\n\n /** What the system occupies on each edge, in points. */\n readonly insets: Signal<Insets> = this.current.asReadonly();\n\n /**\n * The provider's own frame: the area it was handed to lay out in.\n *\n * On Android 15 that includes the system bars, because the app draws behind them - which is why\n * `Screen.window` reads this rather than `Dimensions`. Null until the provider has laid out,\n * one frame after the app mounts, and again once every provider that reported is destroyed.\n */\n readonly frame: Signal<Frame | null> = this.measured.asReadonly();\n\n /** Whether anything has reported yet, for a layout that would rather wait than jump. */\n readonly known = computed(() => this.measured() !== null);\n\n /**\n * Called by `<safe-area-provider>` when native reports. Not for apps: an inset written from\n * anywhere else is a number that stops matching the screen the moment the device rotates.\n */\n report(insets: Insets, frame: Frame, from?: object): void {\n this.current.set(insets);\n this.measured.set(frame);\n this.reporter = from ?? null;\n if (!from) return;\n this.reports.delete(from);\n this.reports.set(from, { insets, frame });\n }\n\n /**\n * Called by `<safe-area-provider>` as it goes: forgets its report. When that report was the\n * latest, what a provider still up last reported takes its place, or nothing when none is.\n * True when the values changed.\n */\n withdraw(from: object): boolean {\n this.reports.delete(from);\n if (this.reporter !== from) return false;\n const [previous] = [...this.reports].slice(-1);\n this.reporter = previous?.[0] ?? null;\n this.current.set(previous?.[1].insets ?? NOTHING);\n this.measured.set(previous?.[1].frame ?? null);\n return true;\n }\n}\n"]}
1
+ {"version":3,"file":"safe-area.js","sourceRoot":"","sources":["../src/safe-area.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAe,MAAM,eAAe,CAAC;;AAgBvE,MAAM,OAAO,GAAW,EAAE,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;AAGjE,MAAM,OAAO,QAAQ;IACnB,sFAAsF;IAC7E,SAAS,GAAoB,MAAM,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,CAAC;IAE/C,OAAO,GAAG,MAAM,CAAS,OAAO;gFAAC,CAAC;IAClC,QAAQ,GAAG,MAAM,CAAe,IAAI;iFAAC,CAAC;IACtC,QAAQ,GAAG,MAAM,CAAC,CAAC;iFAAC,CAAC;IACtC,kEAAkE;IACjD,OAAO,GAAG,IAAI,GAAG,EAG/B,CAAC;IACI,QAAQ,GAAkB,IAAI,CAAC;IAEvC,wDAAwD;IAC/C,MAAM,GAAmB,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;IAE5D;;;;;;OAMG;IACM,KAAK,GAAyB,IAAI,CAAC,QAAQ,CA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AAC;QAClD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,eAAe,IAAI,CAAC,CAAC,CAAC;QACtD,OAAO,IAAI,CAAC;IACd,CAAC;uGAlEU,QAAQ;wGAAR,QAAQ;;2FAAR,QAAQ;kBADpB,OAAO","sourcesContent":["/**\n * How much of the screen belongs to the system: the notch, the status bar, the home indicator,\n * a rounded corner, and on Android the display cutout and the navigation bar.\n *\n * Unlike everything else here, this has no React Native module behind it. Insets are a property\n * of a *view*, not of the device, and the only thing that can report them is a native view inside\n * the window - `<safe-area-provider>` in `@ng-native/components`, which pushes what it\n * measures in here. That is also why the values start at zero: nothing is known until a view has\n * been laid out, which is one frame after the app mounts.\n *\n * Most layouts should not read this at all. A `<safe-area-view>` applies the insets natively,\n * without a round trip through JavaScript, and a screen in a native stack has its header do it.\n * This is for the cases neither covers: a floating button that must clear the home indicator, a\n * scroll view whose content inset is computed, a sheet drawing its own chrome.\n */\nimport { Service, computed, signal, type Signal } from '@angular/core';\n\nexport interface Insets {\n readonly top: number;\n readonly right: number;\n readonly bottom: number;\n readonly left: number;\n}\n\nexport interface Frame {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\nconst NOTHING: Insets = { top: 0, right: 0, bottom: 0, left: 0 };\n\n@Service()\nexport class SafeArea {\n /** Whether the service is here: on every OS, where it answers what the OS reports. */\n readonly available: Signal<boolean> = signal(true).asReadonly();\n\n private readonly current = signal<Insets>(NOTHING);\n private readonly measured = signal<Frame | null>(null);\n private readonly controls = signal(0);\n /** What each provider still up last reported, the latest last. */\n private readonly reports = new Map<\n object,\n { insets: Insets; frame: Frame; titlebarLeading: number }\n >();\n private reporter: object | null = null;\n\n /** What the system occupies on each edge, in points. */\n readonly insets: Signal<Insets> = this.current.asReadonly();\n\n /**\n * The provider's own frame: the area it was handed to lay out in.\n *\n * On Android 15 that includes the system bars, because the app draws behind them - which is why\n * `Screen.window` reads this rather than `Dimensions`. Null until the provider has laid out,\n * one frame after the app mounts, and again once every provider that reported is destroyed.\n */\n readonly frame: Signal<Frame | null> = this.measured.asReadonly();\n\n /**\n * On macOS, how far the window's close, minimise and zoom buttons reach into the reporting\n * pane from its leading edge: what `--safe-area-inset-titlebar-leading` holds. Their width in a\n * window with no sidebar and in the sidebar pane under them; zero in the content pane beside a\n * sidebar, which they do not reach, and on every other OS. One value for the app: the latest\n * report's, not one per pane.\n */\n readonly titlebarLeading: Signal<number> = this.controls.asReadonly();\n\n /** Whether anything has reported yet, for a layout that would rather wait than jump. */\n readonly known = computed(() => this.measured() !== null);\n\n /**\n * Called by `<safe-area-provider>` when native reports. Not for apps: an inset written from\n * anywhere else is a number that stops matching the screen the moment the device rotates.\n */\n report(insets: Insets, frame: Frame, from?: object, titlebarLeading = 0): void {\n this.current.set(insets);\n this.measured.set(frame);\n this.controls.set(titlebarLeading);\n this.reporter = from ?? null;\n if (!from) return;\n this.reports.delete(from);\n this.reports.set(from, { insets, frame, titlebarLeading });\n }\n\n /**\n * Called by `<safe-area-provider>` as it goes: forgets its report. When that report was the\n * latest, what a provider still up last reported takes its place, or nothing when none is.\n * True when the values changed.\n */\n withdraw(from: object): boolean {\n this.reports.delete(from);\n if (this.reporter !== from) return false;\n const [previous] = [...this.reports].slice(-1);\n this.reporter = previous?.[0] ?? null;\n this.current.set(previous?.[1].insets ?? NOTHING);\n this.measured.set(previous?.[1].frame ?? null);\n this.controls.set(previous?.[1].titlebarLeading ?? 0);\n return true;\n }\n}\n"]}
package/dist/screen.d.ts CHANGED
@@ -36,6 +36,8 @@ export declare class Screen {
36
36
  /** Overridden in a test to resize the screen, or rotate it. */
37
37
  static readonly SOURCE: InjectionToken<ScreenSource>;
38
38
  private readonly source;
39
+ /** Whether the service is here: on every OS, where it answers what the OS reports. */
40
+ readonly available: Signal<boolean>;
39
41
  private readonly safeArea;
40
42
  private readonly sizes;
41
43
  /**
package/dist/screen.js CHANGED
@@ -50,6 +50,8 @@ export class Screen {
50
50
  factory: () => (reactNative() ? screenSource() : (engineScreenSource() ?? screenSource())),
51
51
  });
52
52
  source = inject(Screen.SOURCE);
53
+ /** Whether the service is here: on every OS, where it answers what the OS reports. */
54
+ available = signal(true).asReadonly();
53
55
  safeArea = inject(SafeArea);
54
56
  sizes = signal(this.source.current(), /* @ts-ignore */
55
57
  ...(ngDevMode ? [{ debugName: "sizes" }] : /* istanbul ignore next */ []));
@@ -1 +1 @@
1
- {"version":3,"file":"screen.js","sourceRoot":"","sources":["../src/screen.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EACL,UAAU,EACV,cAAc,EACd,OAAO,EACP,QAAQ,EACR,MAAM,EACN,MAAM,GAEP,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,UAAU,EAAe,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;;AA0B1C,MAAM,OAAO,GAAU,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;AAE5F,6EAA6E;AAC7E,MAAM,CAAC,MAAM,aAAa,GAAG,GAAG,CAAC;AAEjC,MAAM,UAAU,YAAY;IAC1B,MAAM,MAAM,GAAG,WAAW,EAAE,CAAC;IAC7B,IAAI,CAAC,MAAM;QAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,GAAE,CAAC,EAAE,CAAC;IAE1E,OAAO;QACL,OAAO,EAAE,GA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AG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACxF,CAAC;uGArDU,MAAM;wGAAN,MAAM;;2FAAN,MAAM;kBADlB,OAAO","sourcesContent":["/**\n * How big the screen is, and which way up.\n *\n * The engine already tracks this for media queries, but only for the cascade: it resolves `@media`\n * and viewport units and tells nobody. Component logic that has to branch on size - a two-column\n * layout above a breakpoint, a different image for a tall screen - has no way to ask, and reaching\n * for `Dimensions.get` directly gets a value that never updates on rotation.\n */\nimport {\n DestroyRef,\n InjectionToken,\n Service,\n computed,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\nimport { HostEngine, type Engine } from '@ng-native/fabric';\nimport { reactNative } from './react-native.ts';\nimport { SafeArea } from './safe-area.ts';\n\nexport interface Size {\n readonly width: number;\n readonly height: number;\n}\n\nexport interface Sizes {\n /**\n * What `Dimensions` calls the window, which is not always what the app can draw in.\n *\n * On Android 15 an app draws edge to edge, painting behind the status and navigation bars, and\n * this reports the area *between* them - short by their height. `Screen.window` prefers the\n * safe-area provider's measured frame for that reason; this is the fallback for the frame before\n * the provider has laid out.\n */\n readonly window: Size;\n /** The physical display. */\n readonly screen: Size;\n}\n\nexport interface ScreenSource {\n current(): Sizes;\n subscribe(listener: (sizes: Sizes) => void): () => void;\n}\n\nconst NOTHING: Sizes = { window: { width: 0, height: 0 }, screen: { width: 0, height: 0 } };\n\n/** Tailwind's `md`. Below it a phone layout, at or above it a tablet one. */\nexport const COMPACT_WIDTH = 768;\n\nexport function screenSource(): ScreenSource {\n const native = reactNative();\n if (!native) return { current: () => NOTHING, subscribe: () => () => {} };\n\n return {\n current: () => ({\n window: native.Dimensions.get('window'),\n screen: native.Dimensions.get('screen'),\n }),\n subscribe: (listener) => {\n const subscription = native.Dimensions.addEventListener('change', (sizes) =>\n listener({ window: sizes.window, screen: sizes.screen }),\n );\n return () => subscription.remove();\n },\n };\n}\n\n/**\n * The screen as the engine was told it, where there is no React Native to ask: a test, whose\n * `conditions` size what `@media` sees, so the two views of the screen agree. Null on a host whose\n * engine keeps no viewport.\n */\nfunction engineScreenSource(): ScreenSource | null {\n const engine = inject(HostEngine, { optional: true }) as Partial<\n Pick<Engine, 'viewport' | 'watchViewport'>\n > | null;\n if (!engine?.viewport) return null;\n const current = (): Sizes => ({ window: engine.viewport!, screen: engine.viewport! });\n return {\n current,\n subscribe: (listener) => engine.watchViewport?.(() => listener(current())) ?? (() => {}),\n };\n}\n\n@Service()\nexport class Screen {\n /** Overridden in a test to resize the screen, or rotate it. */\n static readonly SOURCE = new InjectionToken<ScreenSource>('angular-native.screenSource', {\n factory: () => (reactNative() ? screenSource() : (engineScreenSource() ?? screenSource())),\n });\n\n private readonly source = inject(Screen.SOURCE);\n private readonly safeArea = inject(SafeArea);\n private readonly sizes = signal<Sizes>(this.source.current());\n\n /**\n * What the app can draw in: the one almost everything wants.\n *\n * Measured by the safe-area provider rather than read from `Dimensions`, because on Android 15\n * an app draws edge to edge - behind the status and navigation bars - and `Dimensions` reports\n * the area between them instead. On a 1080x2400 phone that was 838.5pt against a real drawable\n * height of 914.3, so viewport units, height media queries and anything sizing itself from this\n * were all short by the bars. The provider measures the frame it was actually handed, which is\n * the drawable area by definition and on both platforms.\n *\n * `Dimensions` is the fallback for the one frame between mounting and the provider laying out,\n * because a window of zero for that frame would be worse than a slightly wrong one. An app with\n * no `<safe-area-provider>` never gets past the fallback, which is the behaviour it had before.\n */\n readonly window: Signal<Size> = computed(() => {\n const frame = this.safeArea.frame();\n return frame ? { width: frame.width, height: frame.height } : this.sizes().window;\n });\n /** The physical display, which on Android is larger than the window. */\n readonly display: Signal<Size> = computed(() => this.sizes().screen);\n readonly orientation: Signal<'portrait' | 'landscape'> = computed(() =>\n this.window().width > this.window().height ? 'landscape' : 'portrait',\n );\n\n /**\n * Whether the window is narrow enough to want the phone layout.\n *\n * The one branch a component library actually needs, and the reason it is a signal rather than\n * a media query: a sidebar that is a rail on an iPad and a sheet on a phone is not two sets of\n * classes on one tree, it is two different trees. shadcn's own sidebar branches in JavaScript\n * for exactly this reason, and `@media` in the stylesheet cannot decide which components to\n * build. Where the difference *is* only classes, write `md:` and let the cascade do it - the\n * compiler answers width, height and orientation queries, so Tailwind's breakpoints work.\n *\n * `COMPACT_WIDTH` is Tailwind's `md`, which is also the number `useIsMobile` uses upstream.\n * It is close to, but not the same as, iOS's own compact/regular width class: an iPad mini in\n * portrait is 744pt, which Apple calls regular and this calls compact. Close enough to be the\n * right default and named so an app that disagrees can say so.\n */\n readonly compact: Signal<boolean> = computed(() => this.window().width < COMPACT_WIDTH);\n\n constructor() {\n inject(DestroyRef).onDestroy(this.source.subscribe((sizes) => this.sizes.set(sizes)));\n }\n}\n"]}
1
+ {"version":3,"file":"screen.js","sourceRoot":"","sources":["../src/screen.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EACL,UAAU,EACV,cAAc,EACd,OAAO,EACP,QAAQ,EACR,MAAM,EACN,MAAM,GAEP,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,UAAU,EAAe,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;;AA0B1C,MAAM,OAAO,GAAU,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;AAE5F,6EAA6E;AAC7E,MAAM,CAAC,MAAM,aAAa,GAAG,GAAG,CAAC;AAEjC,MAAM,UAAU,YAAY;IAC1B,MAAM,MAAM,GAAG,WAAW,EAAE,CAAC;IAC7B,IAAI,CAAC,MAAM;QAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,GAAE,CAAC,EAAE,CAAC;IAE1E,OAAO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SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACxF,CAAC;uGAxDU,MAAM;wGAAN,MAAM;;2FAAN,MAAM;kBADlB,OAAO","sourcesContent":["/**\n * How big the screen is, and which way up.\n *\n * The engine already tracks this for media queries, but only for the cascade: it resolves `@media`\n * and viewport units and tells nobody. Component logic that has to branch on size - a two-column\n * layout above a breakpoint, a different image for a tall screen - has no way to ask, and reaching\n * for `Dimensions.get` directly gets a value that never updates on rotation.\n */\nimport {\n DestroyRef,\n InjectionToken,\n Service,\n computed,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\nimport { HostEngine, type Engine } from '@ng-native/fabric';\nimport { reactNative } from './react-native.ts';\nimport { SafeArea } from './safe-area.ts';\n\nexport interface Size {\n readonly width: number;\n readonly height: number;\n}\n\nexport interface Sizes {\n /**\n * What `Dimensions` calls the window, which is not always what the app can draw in.\n *\n * On Android 15 an app draws edge to edge, painting behind the status and navigation bars, and\n * this reports the area *between* them - short by their height. `Screen.window` prefers the\n * safe-area provider's measured frame for that reason; this is the fallback for the frame before\n * the provider has laid out.\n */\n readonly window: Size;\n /** The physical display. */\n readonly screen: Size;\n}\n\nexport interface ScreenSource {\n current(): Sizes;\n subscribe(listener: (sizes: Sizes) => void): () => void;\n}\n\nconst NOTHING: Sizes = { window: { width: 0, height: 0 }, screen: { width: 0, height: 0 } };\n\n/** Tailwind's `md`. Below it a phone layout, at or above it a tablet one. */\nexport const COMPACT_WIDTH = 768;\n\nexport function screenSource(): ScreenSource {\n const native = reactNative();\n if (!native) return { current: () => NOTHING, subscribe: () => () => {} };\n\n return {\n current: () => ({\n window: native.Dimensions.get('window'),\n screen: native.Dimensions.get('screen'),\n }),\n subscribe: (listener) => {\n const subscription = native.Dimensions.addEventListener('change', (sizes) =>\n listener({ window: sizes.window, screen: sizes.screen }),\n );\n return () => subscription.remove();\n },\n };\n}\n\n/**\n * The screen as the engine was told it, where there is no React Native to ask: a test, whose\n * `conditions` size what `@media` sees, so the two views of the screen agree. Null on a host whose\n * engine keeps no viewport.\n */\nfunction engineScreenSource(): ScreenSource | null {\n const engine = inject(HostEngine, { optional: true }) as Partial<\n Pick<Engine, 'viewport' | 'watchViewport'>\n > | null;\n if (!engine?.viewport) return null;\n const current = (): Sizes => ({ window: engine.viewport!, screen: engine.viewport! });\n return {\n current,\n subscribe: (listener) => engine.watchViewport?.(() => listener(current())) ?? (() => {}),\n };\n}\n\n@Service()\nexport class Screen {\n /** Overridden in a test to resize the screen, or rotate it. */\n static readonly SOURCE = new InjectionToken<ScreenSource>('angular-native.screenSource', {\n factory: () => (reactNative() ? screenSource() : (engineScreenSource() ?? screenSource())),\n });\n\n private readonly source = inject(Screen.SOURCE);\n\n /** Whether the service is here: on every OS, where it answers what the OS reports. */\n readonly available: Signal<boolean> = signal(true).asReadonly();\n private readonly safeArea = inject(SafeArea);\n private readonly sizes = signal<Sizes>(this.source.current());\n\n /**\n * What the app can draw in: the one almost everything wants.\n *\n * Measured by the safe-area provider rather than read from `Dimensions`, because on Android 15\n * an app draws edge to edge - behind the status and navigation bars - and `Dimensions` reports\n * the area between them instead. On a 1080x2400 phone that was 838.5pt against a real drawable\n * height of 914.3, so viewport units, height media queries and anything sizing itself from this\n * were all short by the bars. The provider measures the frame it was actually handed, which is\n * the drawable area by definition and on both platforms.\n *\n * `Dimensions` is the fallback for the one frame between mounting and the provider laying out,\n * because a window of zero for that frame would be worse than a slightly wrong one. An app with\n * no `<safe-area-provider>` never gets past the fallback, which is the behaviour it had before.\n */\n readonly window: Signal<Size> = computed(() => {\n const frame = this.safeArea.frame();\n return frame ? { width: frame.width, height: frame.height } : this.sizes().window;\n });\n /** The physical display, which on Android is larger than the window. */\n readonly display: Signal<Size> = computed(() => this.sizes().screen);\n readonly orientation: Signal<'portrait' | 'landscape'> = computed(() =>\n this.window().width > this.window().height ? 'landscape' : 'portrait',\n );\n\n /**\n * Whether the window is narrow enough to want the phone layout.\n *\n * The one branch a component library actually needs, and the reason it is a signal rather than\n * a media query: a sidebar that is a rail on an iPad and a sheet on a phone is not two sets of\n * classes on one tree, it is two different trees. shadcn's own sidebar branches in JavaScript\n * for exactly this reason, and `@media` in the stylesheet cannot decide which components to\n * build. Where the difference *is* only classes, write `md:` and let the cascade do it - the\n * compiler answers width, height and orientation queries, so Tailwind's breakpoints work.\n *\n * `COMPACT_WIDTH` is Tailwind's `md`, which is also the number `useIsMobile` uses upstream.\n * It is close to, but not the same as, iOS's own compact/regular width class: an iPad mini in\n * portrait is 744pt, which Apple calls regular and this calls compact. Close enough to be the\n * right default and named so an app that disagrees can say so.\n */\n readonly compact: Signal<boolean> = computed(() => this.window().width < COMPACT_WIDTH);\n\n constructor() {\n inject(DestroyRef).onDestroy(this.source.subscribe((sizes) => this.sizes.set(sizes)));\n }\n}\n"]}