@ng-native/device 0.26.0 → 0.27.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 (44) hide show
  1. package/dist/accessibility.d.ts +5 -3
  2. package/dist/accessibility.js +5 -0
  3. package/dist/accessibility.js.map +1 -1
  4. package/dist/desktop-options.d.ts +5 -0
  5. package/dist/desktop-options.js +6 -1
  6. package/dist/desktop-options.js.map +1 -1
  7. package/dist/dialogs.js +4 -2
  8. package/dist/dialogs.js.map +1 -1
  9. package/dist/dock.d.ts +2 -0
  10. package/dist/dock.js +4 -1
  11. package/dist/dock.js.map +1 -1
  12. package/dist/menu-model.d.ts +11 -9
  13. package/dist/menu-model.js +72 -9
  14. package/dist/menu-model.js.map +1 -1
  15. package/dist/menus.js +2 -2
  16. package/dist/menus.js.map +1 -1
  17. package/dist/os-support.d.ts +1 -1
  18. package/dist/os-support.js +188 -62
  19. package/dist/os-support.js.map +1 -1
  20. package/dist/os-version.d.ts +3 -1
  21. package/dist/os-version.js +3 -1
  22. package/dist/os-version.js.map +1 -1
  23. package/dist/os.d.ts +5 -3
  24. package/dist/os.js +5 -3
  25. package/dist/os.js.map +1 -1
  26. package/dist/processes.d.ts +2 -0
  27. package/dist/processes.js +4 -1
  28. package/dist/processes.js.map +1 -1
  29. package/dist/safe-area.d.ts +12 -3
  30. package/dist/safe-area.js +16 -4
  31. package/dist/safe-area.js.map +1 -1
  32. package/dist/sharing.js +4 -3
  33. package/dist/sharing.js.map +1 -1
  34. package/dist/spawn-rules.js +8 -0
  35. package/dist/spawn-rules.js.map +1 -1
  36. package/dist/tray.d.ts +6 -3
  37. package/dist/tray.js +8 -4
  38. package/dist/tray.js.map +1 -1
  39. package/dist/vibration.d.ts +1 -1
  40. package/dist/vibration.js +3 -3
  41. package/dist/vibration.js.map +1 -1
  42. package/dist/window-restore.js +1 -1
  43. package/dist/window-restore.js.map +1 -1
  44. package/package.json +2 -2
@@ -18,9 +18,11 @@ export interface AccessibilitySettings {
18
18
  /**
19
19
  * The user's text size, as a multiplier of the default.
20
20
  *
21
- * Not an event: it is read at startup and again when the app comes back, because changing it
22
- * means leaving for Settings. Text scales natively without anything here, so this is for the
23
- * layouts that have to give way to it - a row height, a line clamp, an icon beside a label.
21
+ * Read at startup and again when the app comes back to the foreground, because changing it on
22
+ * iOS and Android means leaving for Settings. On Linux the GTK host reports a change in the
23
+ * desktop's text scaling while the app runs, and this follows it. Text scales natively without
24
+ * anything here, so this is for the layouts that have to give way to it - a row height, a line
25
+ * clamp, an icon beside a label.
24
26
  */
25
27
  readonly fontScale: number;
26
28
  }
@@ -67,6 +67,11 @@ export function accessibilitySource() {
67
67
  listener({ fontScale: systemFontScale(native) });
68
68
  }),
69
69
  ];
70
+ // The GTK host never reports the app becoming active, but it passes a change in the
71
+ // desktop's text scaling on as a `Dimensions` change.
72
+ if (platformOs() === 'linux') {
73
+ subscriptions.push(native.Dimensions.addEventListener('change', () => listener({ fontScale: systemFontScale(native) })));
74
+ }
70
75
  return () => subscriptions.forEach((subscription) => subscription.remove());
71
76
  },
72
77
  announce: (message) => info.announceForAccessibility(message),
@@ -1 +1 @@
1
- {"version":3,"file":"accessibility.js","sourceRoot":"","sources":["../src/accessibility.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EACL,UAAU,EACV,cAAc,EACd,OAAO,EACP,QAAQ,EACR,MAAM,EACN,MAAM,GAEP,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;;AAsBhD;;;GAGG;AACH,MAAM,UAAU,eAAe,CAAC,MAAM,GAAG,WAAW,EAAE;IACpD,IAAI,UAAU,EAAE,KAAK,OAAO;QAAE,OAAO,CAAC,CAAC;IACvC,OAAO,MAAM,EAAE,UAAU,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;AAChD,CAAC;AAED,MAAM,UA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,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAChC,CAAC;uGArDU,aAAa;wGAAb,aAAa;;2FAAb,aAAa;kBADzB,OAAO","sourcesContent":["/**\n * What the user has turned on in the system's accessibility settings.\n *\n * The components apply the defaults React Native's wrappers do - roles, labels, whether a view is\n * an element at all - without anything being injected. This is for the decisions those defaults\n * cannot make: not animating when the user asked for less motion, announcing something that\n * changed off screen, giving a screen reader a different affordance than a finger gets.\n *\n * Every value starts at its neutral setting and is corrected once the platform answers, because\n * React Native reports all three asynchronously. A first paint therefore assumes nothing is on.\n */\nimport {\n DestroyRef,\n InjectionToken,\n Service,\n computed,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\nimport { platformOs } from './os.ts';\nimport { reactNative } from './react-native.ts';\n\nexport interface AccessibilitySettings {\n readonly screenReader: boolean;\n readonly reduceMotion: boolean;\n readonly boldText: boolean;\n /**\n * The user's text size, as a multiplier of the default.\n *\n * Not an event: it is read at startup and again when the app comes back, because changing it\n * means leaving for Settings. Text scales natively without anything here, so this is for the\n * layouts that have to give way to it - a row height, a line clamp, an icon beside a label.\n */\n readonly fontScale: number;\n}\n\nexport interface AccessibilitySource {\n current(): Promise<AccessibilitySettings>;\n subscribe(listener: (settings: Partial<AccessibilitySettings>) => void): () => void;\n announce(message: string): void;\n}\n\n/**\n * The system text size, as a multiplier: `PixelRatio.getFontScale()`. One off a device, and on a\n * Mac, where nothing resizes an app: it reaches Mac sizes with `macos:` variants instead.\n */\nexport function systemFontScale(native = reactNative()): number {\n if (platformOs() === 'macos') return 1;\n return native?.PixelRatio.getFontScale() ?? 1;\n}\n\nexport function accessibilitySource(): AccessibilitySource {\n const native = reactNative();\n if (!native) {\n return {\n current: () =>\n Promise.resolve({\n screenReader: false,\n reduceMotion: false,\n boldText: false,\n fontScale: 1,\n }),\n subscribe: () => () => {},\n announce: () => {},\n };\n }\n\n const info = native.AccessibilityInfo;\n // A read that fails is the neutral setting, so the other three still arrive.\n const read = async (ask: () => Promise<boolean>) => {\n try {\n return await ask();\n } catch {\n return false;\n }\n };\n return {\n current: async () => {\n const [screenReader, reduceMotion, boldText] = await Promise.all([\n read(() => info.isScreenReaderEnabled()),\n read(() => info.isReduceMotionEnabled()),\n read(() => info.isBoldTextEnabled()),\n ]);\n return { screenReader, reduceMotion, boldText, fontScale: systemFontScale(native) };\n },\n subscribe: (listener) => {\n const subscriptions = [\n info.addEventListener('screenReaderChanged', (screenReader) => listener({ screenReader })),\n info.addEventListener('reduceMotionChanged', (reduceMotion) => listener({ reduceMotion })),\n info.addEventListener('boldTextChanged', (boldText) => listener({ boldText })),\n // `fontScale` has no change event of its own - changing it means leaving for Settings -\n // so the app coming back to the foreground is what stands in for one.\n native.AppState.addEventListener('change', (state) => {\n if (state === 'active') listener({ fontScale: systemFontScale(native) });\n }),\n ];\n return () => subscriptions.forEach((subscription) => subscription.remove());\n },\n announce: (message) => info.announceForAccessibility(message),\n };\n}\n\n@Service()\nexport class Accessibility {\n /** Overridden in a test to turn a setting on. */\n static readonly SOURCE = new InjectionToken<AccessibilitySource>(\n 'angular-native.accessibilitySource',\n { factory: accessibilitySource },\n );\n\n private readonly source = inject(Accessibility.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 settings = signal<AccessibilitySettings>({\n screenReader: false,\n reduceMotion: false,\n boldText: false,\n fontScale: 1,\n });\n\n /** VoiceOver or TalkBack is running. */\n readonly screenReader: Signal<boolean> = computed(() => this.settings().screenReader);\n /**\n * The user asked for less animation. `@media (prefers-reduced-motion: reduce)` reads the same\n * setting and is the better answer wherever the motion is styling rather than logic.\n */\n readonly reduceMotion: Signal<boolean> = computed(() => this.settings().reduceMotion);\n /** The system font is heavier, so hand-tuned weights may need to give way. */\n readonly boldText: Signal<boolean> = computed(() => this.settings().boldText);\n /**\n * How much larger the user has asked text to be. One is the default; the largest accessibility\n * sizes are past three, which is where a row built for one line stops working.\n */\n readonly fontScale: Signal<number> = computed(() => this.settings().fontScale);\n\n constructor() {\n let heard: Partial<AccessibilitySettings> = {};\n // A read that fails leaves the neutral settings, which the change events still correct.\n this.source.current().then(\n (settings) => this.settings.set({ ...settings, ...heard }),\n () => {},\n );\n const stop = this.source.subscribe((change) => {\n heard = { ...heard, ...change };\n this.settings.update((current) => ({ ...current, ...change }));\n });\n inject(DestroyRef).onDestroy(stop);\n }\n\n /**\n * Say something to a screen reader that no focus change would have said. A list that reordered,\n * a search that returned nothing: changes a sighted user sees and a screen reader would miss.\n */\n announce(message: string): void {\n this.source.announce(message);\n }\n}\n"]}
1
+ {"version":3,"file":"accessibility.js","sourceRoot":"","sources":["../src/accessibility.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EACL,UAAU,EACV,cAAc,EACd,OAAO,EACP,QAAQ,EACR,MAAM,EACN,MAAM,GAEP,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;;AAwBhD;;;GAGG;AACH,MAAM,UAAU,eAAe,CAAC,MAAM,GAAG,WAAW,EAAE;IACpD,IAAI,UAAU,EAAE,KAAK,OAAO;QAAE,OAAO,CAAC,CAAC;IACvC,OAAO,MAAM,EAAE,UAAU,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;AAChD,CAAC;AAED,MAAM,UAAU,mBAAmB;IACjC,MAAM,MAAM,GAAG,WAAW,EAAE,CAAC;IAC7B,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO;YACL,OAAO,EAAE,GAAG,EAAE,CACZ,OAAO,CAAC,OAAO,CAAC;gBACd,YAAY,EAAE,KAAK;gBACnB,YAAY,EAAE,KAAK;gBACnB,QAAQ,EAAE,KAAK;gBACf,SAAS,EAAE,CAAC;aACb,CAAC;YACJ,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,GAAE,CAAC;Y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C;uGArDU,aAAa;wGAAb,aAAa;;2FAAb,aAAa;kBADzB,OAAO","sourcesContent":["/**\n * What the user has turned on in the system's accessibility settings.\n *\n * The components apply the defaults React Native's wrappers do - roles, labels, whether a view is\n * an element at all - without anything being injected. This is for the decisions those defaults\n * cannot make: not animating when the user asked for less motion, announcing something that\n * changed off screen, giving a screen reader a different affordance than a finger gets.\n *\n * Every value starts at its neutral setting and is corrected once the platform answers, because\n * React Native reports all three asynchronously. A first paint therefore assumes nothing is on.\n */\nimport {\n DestroyRef,\n InjectionToken,\n Service,\n computed,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\nimport { platformOs } from './os.ts';\nimport { reactNative } from './react-native.ts';\n\nexport interface AccessibilitySettings {\n readonly screenReader: boolean;\n readonly reduceMotion: boolean;\n readonly boldText: boolean;\n /**\n * The user's text size, as a multiplier of the default.\n *\n * Read at startup and again when the app comes back to the foreground, because changing it on\n * iOS and Android means leaving for Settings. On Linux the GTK host reports a change in the\n * desktop's text scaling while the app runs, and this follows it. Text scales natively without\n * anything here, so this is for the layouts that have to give way to it - a row height, a line\n * clamp, an icon beside a label.\n */\n readonly fontScale: number;\n}\n\nexport interface AccessibilitySource {\n current(): Promise<AccessibilitySettings>;\n subscribe(listener: (settings: Partial<AccessibilitySettings>) => void): () => void;\n announce(message: string): void;\n}\n\n/**\n * The system text size, as a multiplier: `PixelRatio.getFontScale()`. One off a device, and on a\n * Mac, where nothing resizes an app: it reaches Mac sizes with `macos:` variants instead.\n */\nexport function systemFontScale(native = reactNative()): number {\n if (platformOs() === 'macos') return 1;\n return native?.PixelRatio.getFontScale() ?? 1;\n}\n\nexport function accessibilitySource(): AccessibilitySource {\n const native = reactNative();\n if (!native) {\n return {\n current: () =>\n Promise.resolve({\n screenReader: false,\n reduceMotion: false,\n boldText: false,\n fontScale: 1,\n }),\n subscribe: () => () => {},\n announce: () => {},\n };\n }\n\n const info = native.AccessibilityInfo;\n // A read that fails is the neutral setting, so the other three still arrive.\n const read = async (ask: () => Promise<boolean>) => {\n try {\n return await ask();\n } catch {\n return false;\n }\n };\n return {\n current: async () => {\n const [screenReader, reduceMotion, boldText] = await Promise.all([\n read(() => info.isScreenReaderEnabled()),\n read(() => info.isReduceMotionEnabled()),\n read(() => info.isBoldTextEnabled()),\n ]);\n return { screenReader, reduceMotion, boldText, fontScale: systemFontScale(native) };\n },\n subscribe: (listener) => {\n const subscriptions = [\n info.addEventListener('screenReaderChanged', (screenReader) => listener({ screenReader })),\n info.addEventListener('reduceMotionChanged', (reduceMotion) => listener({ reduceMotion })),\n info.addEventListener('boldTextChanged', (boldText) => listener({ boldText })),\n // `fontScale` has no change event of its own - changing it means leaving for Settings -\n // so the app coming back to the foreground is what stands in for one.\n native.AppState.addEventListener('change', (state) => {\n if (state === 'active') listener({ fontScale: systemFontScale(native) });\n }),\n ];\n // The GTK host never reports the app becoming active, but it passes a change in the\n // desktop's text scaling on as a `Dimensions` change.\n if (platformOs() === 'linux') {\n subscriptions.push(\n native.Dimensions.addEventListener('change', () =>\n listener({ fontScale: systemFontScale(native) }),\n ),\n );\n }\n return () => subscriptions.forEach((subscription) => subscription.remove());\n },\n announce: (message) => info.announceForAccessibility(message),\n };\n}\n\n@Service()\nexport class Accessibility {\n /** Overridden in a test to turn a setting on. */\n static readonly SOURCE = new InjectionToken<AccessibilitySource>(\n 'angular-native.accessibilitySource',\n { factory: accessibilitySource },\n );\n\n private readonly source = inject(Accessibility.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 settings = signal<AccessibilitySettings>({\n screenReader: false,\n reduceMotion: false,\n boldText: false,\n fontScale: 1,\n });\n\n /** VoiceOver or TalkBack is running. */\n readonly screenReader: Signal<boolean> = computed(() => this.settings().screenReader);\n /**\n * The user asked for less animation. `@media (prefers-reduced-motion: reduce)` reads the same\n * setting and is the better answer wherever the motion is styling rather than logic.\n */\n readonly reduceMotion: Signal<boolean> = computed(() => this.settings().reduceMotion);\n /** The system font is heavier, so hand-tuned weights may need to give way. */\n readonly boldText: Signal<boolean> = computed(() => this.settings().boldText);\n /**\n * How much larger the user has asked text to be. One is the default; the largest accessibility\n * sizes are past three, which is where a row built for one line stops working.\n */\n readonly fontScale: Signal<number> = computed(() => this.settings().fontScale);\n\n constructor() {\n let heard: Partial<AccessibilitySettings> = {};\n // A read that fails leaves the neutral settings, which the change events still correct.\n this.source.current().then(\n (settings) => this.settings.set({ ...settings, ...heard }),\n () => {},\n );\n const stop = this.source.subscribe((change) => {\n heard = { ...heard, ...change };\n this.settings.update((current) => ({ ...current, ...change }));\n });\n inject(DestroyRef).onDestroy(stop);\n }\n\n /**\n * Say something to a screen reader that no focus change would have said. A list that reordered,\n * a search that returned nothing: changes a sighted user sees and a screen reader would miss.\n */\n announce(message: string): void {\n this.source.announce(message);\n }\n}\n"]}
@@ -29,6 +29,11 @@ export interface DocumentType {
29
29
  readonly role?: 'editor' | 'viewer';
30
30
  /** Uniform type identifiers, where the kind has them, e.g. `net.daringfireball.markdown`. */
31
31
  readonly utis?: readonly string[];
32
+ /**
33
+ * MIME types, e.g. `text/markdown`: what a Linux desktop opens with the app, since its desktop
34
+ * entry lists types by MIME type and not by extension.
35
+ */
36
+ readonly mimeTypes?: readonly string[];
32
37
  /** An icon in the app's assets for documents of this kind. */
33
38
  readonly icon?: string;
34
39
  }
@@ -22,6 +22,7 @@ import { SpawnRuleError, compileCapability } from "./spawn-rules.js";
22
22
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
23
23
  const EXTENSION = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
24
24
  const UTI = /^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/;
25
+ const MIME_TYPE = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*$/;
25
26
  const PACKAGE = /^(@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/;
26
27
  const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
27
28
  /** Why a declared path cannot be used, or null when it can. */
@@ -63,7 +64,7 @@ export function desktopOptionProblems(options) {
63
64
  report(where, 'must be an object');
64
65
  return;
65
66
  }
66
- unknownKeys(type, ['name', 'extensions', 'role', 'utis', 'icon'], where, report);
67
+ unknownKeys(type, ['name', 'extensions', 'role', 'utis', 'mimeTypes', 'icon'], where, report);
67
68
  if (typeof type['name'] !== 'string' || type['name'] === '') {
68
69
  report(`${where}.name`, 'a name is required');
69
70
  }
@@ -83,6 +84,10 @@ export function desktopOptionProblems(options) {
83
84
  if (typeof uti !== 'string' || !UTI.test(uti))
84
85
  report(at, 'is not a type identifier');
85
86
  });
87
+ list(type['mimeTypes'], `${where}.mimeTypes`, report, (mime, at) => {
88
+ if (typeof mime !== 'string' || !MIME_TYPE.test(mime))
89
+ report(at, 'is not a MIME type');
90
+ });
86
91
  if (type['icon'] !== undefined && typeof type['icon'] !== 'string') {
87
92
  report(`${where}.icon`, 'must be a string');
88
93
  }
@@ -1 +1 @@
1
- {"version":3,"file":"desktop-options.js","sourceRoot":"","sources":["../src/desktop-options.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAwB,MAAM,kBAAkB,CAAC;AAwC3F,MAAM,QAAQ,GAAG,0BAA0B,CAAC;AAC5C,MAAM,SAAS,GAAG,8BAA8B,CAAC;AACjD,MAAM,GAAG,GAAG,mCAAmC,CAAC;AAChD,MAAM,OAAO,GAAG,oDAAoD,CAAC;AAErE,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAoC,EAAE,CACpE,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAEvE,+DAA+D;AAC/D,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,IAAI,OAAO,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;IAE5C,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO;IAChC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1B,MAAM,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAC;QAChC,OAAO;IACT,CAAC;IACD,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,KAAK,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC;AACnE,CAAC;AAED,cAAc,kBAAkB,CAAC;AACjC,cAAc,0BAA0B,CAAC","sourcesContent":["/**\n * The `@ng-native/desktop` plugin's options in `app.json`, and their validation. They hold only\n * what has to exist before JavaScript runs: the document types the app opens, its declared\n * capabilities (programs it spawns, environment variables it reads and paths outside its own\n * folders), and the libraries kept out of the desktop build.\n *\n * [\"@ng-native/desktop\", {\n * \"documentTypes\": [{ \"name\": \"Markdown\", \"extensions\": [\"md\"], \"role\": \"editor\" }],\n * \"capabilities\": {\n * \"spawn\": [{ \"program\": \"git\", \"args\": [\"status\", \"--porcelain\"] }],\n * \"env\": [\"HOME\", \"LANG\"],\n * \"paths\": [{ \"path\": \"~/Projects\", \"access\": \"readwrite\" }]\n * },\n * \"deny\": [\"react-native-some-library\"]\n * }]\n *\n * Permissions are not here: the Expo keys (`ios.infoPlist`'s usage strings and each `expo-*`\n * plugin's permission option) declare them for every OS. Plain TypeScript with no Angular, so the\n * config plugin can run it in Node.\n */\nimport { SpawnRuleError, compileCapability, type SpawnCapability } from './spawn-rules.ts';\n\n/** A kind of document the app opens from Finder, by its file extensions. */\nexport interface DocumentType {\n /** What Finder calls the kind, e.g. `Markdown`. */\n readonly name: string;\n /** File extensions without the dot, e.g. `md`. */\n readonly extensions: readonly string[];\n /** Whether the app edits these files or only views them. `editor` when unset. */\n readonly role?: 'editor' | 'viewer';\n /** Uniform type identifiers, where the kind has them, e.g. `net.daringfireball.markdown`. */\n readonly utis?: readonly string[];\n /** An icon in the app's assets for documents of this kind. */\n readonly icon?: string;\n}\n\n/** A path outside the app's own folders that it may use. */\nexport interface PathCapability {\n /** An absolute path, or one under the home folder written `~/...`. */\n readonly path: string;\n /** `read` unless it says `readwrite`. */\n readonly access?: 'read' | 'readwrite';\n}\n\n/** What the app may do beyond its own folders, the user's picks and the Expo-keyed permissions. */\nexport interface DesktopCapabilities {\n readonly spawn?: readonly SpawnCapability[];\n /** The environment variables `Processes.env` holds and a spawned program is given. */\n readonly env?: readonly string[];\n readonly paths?: readonly PathCapability[];\n}\n\n/** The plugin's options. */\nexport interface DesktopOptions {\n readonly documentTypes?: readonly DocumentType[];\n readonly capabilities?: DesktopCapabilities;\n /** npm packages whose native code stays out of the desktop build, even where they ship some. */\n readonly deny?: readonly string[];\n}\n\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst EXTENSION = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\nconst UTI = /^[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)+$/;\nconst PACKAGE = /^(@[a-z0-9][a-z0-9._~-]*\\/)?[a-z0-9][a-z0-9._~-]*$/;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** Why a declared path cannot be used, or null when it can. */\nexport function pathProblem(path: string): string | null {\n if (typeof path !== 'string' || path.length === 0) return 'a path is required';\n if (path.includes('\\0')) return 'a path cannot hold a NUL character';\n const rooted = path.startsWith('/')\n ? path.slice(1)\n : path.startsWith('~/')\n ? path.slice(2)\n : null;\n if (rooted === null) return `${path} must be absolute, or start with ~/`;\n if (rooted === '') return `${path} would give the whole ${path === '/' ? 'disk' : 'home folder'}`;\n const segments = rooted.replace(/\\/$/, '').split('/');\n if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) {\n return `${path} is not a normalized path`;\n }\n return null;\n}\n\n/**\n * The problems with a set of options, each naming where it is, e.g.\n * `capabilities.spawn[0].program: /bin/sh runs its arguments as a command`. Empty when there are\n * none. Unknown keys are problems too, so a misspelt key is not silently a capability missing.\n */\nexport function desktopOptionProblems(options: unknown): string[] {\n const problems: string[] = [];\n const report = (where: string, problem: string) => problems.push(`${where}: ${problem}`);\n if (options === undefined) return problems;\n if (!isRecord(options)) return ['options must be an object'];\n unknownKeys(options, ['documentTypes', 'capabilities', 'deny'], '', report);\n\n list(options['documentTypes'], 'documentTypes', report, (type, where) => {\n if (!isRecord(type)) {\n report(where, 'must be an object');\n return;\n }\n unknownKeys(type, ['name', 'extensions', 'role', 'utis', 'icon'], where, report);\n if (typeof type['name'] !== 'string' || type['name'] === '') {\n report(`${where}.name`, 'a name is required');\n }\n const extensions = type['extensions'];\n if (!Array.isArray(extensions) || extensions.length === 0) {\n report(`${where}.extensions`, 'at least one extension is required');\n }\n list(extensions, `${where}.extensions`, report, (extension, at) => {\n if (typeof extension !== 'string' || !EXTENSION.test(extension)) {\n report(at, `${JSON.stringify(extension)} is not an extension: write it without the dot`);\n }\n });\n if (type['role'] !== undefined && type['role'] !== 'editor' && type['role'] !== 'viewer') {\n report(`${where}.role`, \"must be 'editor' or 'viewer'\");\n }\n list(type['utis'], `${where}.utis`, report, (uti, at) => {\n if (typeof uti !== 'string' || !UTI.test(uti)) report(at, 'is not a type identifier');\n });\n if (type['icon'] !== undefined && typeof type['icon'] !== 'string') {\n report(`${where}.icon`, 'must be a string');\n }\n });\n\n const capabilities = options['capabilities'];\n if (capabilities !== undefined && !isRecord(capabilities)) {\n report('capabilities', 'must be an object');\n } else if (capabilities) {\n unknownKeys(capabilities, ['spawn', 'env', 'paths'], 'capabilities', report);\n list(capabilities['spawn'], 'capabilities.spawn', report, (entry, where) => {\n if (!isRecord(entry)) {\n report(where, 'must be an object');\n return;\n }\n unknownKeys(entry, ['program', 'args'], where, report);\n try {\n compileCapability(entry as unknown as SpawnCapability);\n } catch (error) {\n if (!(error instanceof SpawnRuleError)) throw error;\n report(where, error.message);\n }\n });\n list(capabilities['env'], 'capabilities.env', report, (name, where) => {\n if (typeof name !== 'string' || !ENV_NAME.test(name)) {\n report(where, `${JSON.stringify(name)} is not an environment variable name`);\n }\n });\n list(capabilities['paths'], 'capabilities.paths', report, (entry, where) => {\n if (!isRecord(entry)) {\n report(where, 'must be an object');\n return;\n }\n unknownKeys(entry, ['path', 'access'], where, report);\n const problem = pathProblem(entry['path'] as string);\n if (problem) report(`${where}.path`, problem);\n const access = entry['access'];\n if (access !== undefined && access !== 'read' && access !== 'readwrite') {\n report(`${where}.access`, \"must be 'read' or 'readwrite'\");\n }\n });\n }\n\n list(options['deny'], 'deny', report, (name, where) => {\n if (typeof name !== 'string' || !PACKAGE.test(name))\n report(where, 'is not an npm package name');\n });\n return problems;\n}\n\n/** Check a set of options, throwing one error that lists every problem. */\nexport function validateDesktopOptions(options: unknown): DesktopOptions {\n const problems = desktopOptionProblems(options);\n if (problems.length > 0) {\n throw new Error(\n `[@ng-native/desktop] The plugin options in app.json are not valid:\\n` +\n problems.map((problem) => ` - ${problem}`).join('\\n'),\n );\n }\n return (options ?? {}) as DesktopOptions;\n}\n\n/**\n * Whether `path` is inside one of the declared paths, with the access asked for. `home` is the\n * user's home folder, which `~/` stands for. A path with a `.` or `..` segment is refused rather\n * than resolved: the host resolves links and normalizes before it asks.\n */\nexport function pathAllowed(\n declared: readonly PathCapability[],\n path: string,\n home: string,\n access: 'read' | 'readwrite' = 'read',\n): boolean {\n if (pathProblem(path) !== null || !path.startsWith('/')) return false;\n const target = path.replace(/\\/$/, '');\n return declared.some((entry) => {\n if (pathProblem(entry.path) !== null) return false;\n if (access === 'readwrite' && entry.access !== 'readwrite') return false;\n const root = (\n entry.path.startsWith('~/') ? `${home}/${entry.path.slice(2)}` : entry.path\n ).replace(/\\/$/, '');\n return target === root || target.startsWith(`${root}/`);\n });\n}\n\nfunction unknownKeys(\n value: Record<string, unknown>,\n known: readonly string[],\n where: string,\n report: (where: string, problem: string) => void,\n): void {\n for (const key of Object.keys(value)) {\n if (!known.includes(key)) {\n report(\n where ? `${where}.${key}` : key,\n `is not an option (expected one of ${known.join(', ')})`,\n );\n }\n }\n}\n\nfunction list(\n value: unknown,\n where: string,\n report: (where: string, problem: string) => void,\n each: (item: unknown, where: string) => void,\n): void {\n if (value === undefined) return;\n if (!Array.isArray(value)) {\n report(where, 'must be a list');\n return;\n }\n value.forEach((item, index) => each(item, `${where}[${index}]`));\n}\n\nexport * from './spawn-rules.ts';\nexport * from './desktop-permissions.ts';\n"]}
1
+ {"version":3,"file":"desktop-options.js","sourceRoot":"","sources":["../src/desktop-options.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAwB,MAAM,kBAAkB,CAAC;AA6C3F,MAAM,QAAQ,GAAG,0BAA0B,CAAC;AAC5C,MAAM,SAAS,GAAG,8BAA8B,CAAC;AACjD,MAAM,GAAG,GAAG,mCAAmC,CAAC;AAChD,MAAM,SAAS,GAAG,sEAAsE,CAAC;AACzF,MAAM,OAAO,GAAG,oDAAoD,CAAC;AAErE,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAoC,EAAE,CACpE,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAEvE,+DAA+D;AAC/D,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,oBAAoB,CAAC;IAC/E,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;QAAE,OAAO,oCAAoC,CAAC;IACrE,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;QACjC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;QACf,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;YACrB,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,OAAO;IAChC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1B,MAAM,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAC;QAChC,OAAO;IACT,CAAC;IACD,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,KAAK,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC;AACnE,CAAC;AAED,cAAc,kBAAkB,CAAC;AACjC,cAAc,0BAA0B,CAAC","sourcesContent":["/**\n * The `@ng-native/desktop` plugin's options in `app.json`, and their validation. They hold only\n * what has to exist before JavaScript runs: the document types the app opens, its declared\n * capabilities (programs it spawns, environment variables it reads and paths outside its own\n * folders), and the libraries kept out of the desktop build.\n *\n * [\"@ng-native/desktop\", {\n * \"documentTypes\": [{ \"name\": \"Markdown\", \"extensions\": [\"md\"], \"role\": \"editor\" }],\n * \"capabilities\": {\n * \"spawn\": [{ \"program\": \"git\", \"args\": [\"status\", \"--porcelain\"] }],\n * \"env\": [\"HOME\", \"LANG\"],\n * \"paths\": [{ \"path\": \"~/Projects\", \"access\": \"readwrite\" }]\n * },\n * \"deny\": [\"react-native-some-library\"]\n * }]\n *\n * Permissions are not here: the Expo keys (`ios.infoPlist`'s usage strings and each `expo-*`\n * plugin's permission option) declare them for every OS. Plain TypeScript with no Angular, so the\n * config plugin can run it in Node.\n */\nimport { SpawnRuleError, compileCapability, type SpawnCapability } from './spawn-rules.ts';\n\n/** A kind of document the app opens from Finder, by its file extensions. */\nexport interface DocumentType {\n /** What Finder calls the kind, e.g. `Markdown`. */\n readonly name: string;\n /** File extensions without the dot, e.g. `md`. */\n readonly extensions: readonly string[];\n /** Whether the app edits these files or only views them. `editor` when unset. */\n readonly role?: 'editor' | 'viewer';\n /** Uniform type identifiers, where the kind has them, e.g. `net.daringfireball.markdown`. */\n readonly utis?: readonly string[];\n /**\n * MIME types, e.g. `text/markdown`: what a Linux desktop opens with the app, since its desktop\n * entry lists types by MIME type and not by extension.\n */\n readonly mimeTypes?: readonly string[];\n /** An icon in the app's assets for documents of this kind. */\n readonly icon?: string;\n}\n\n/** A path outside the app's own folders that it may use. */\nexport interface PathCapability {\n /** An absolute path, or one under the home folder written `~/...`. */\n readonly path: string;\n /** `read` unless it says `readwrite`. */\n readonly access?: 'read' | 'readwrite';\n}\n\n/** What the app may do beyond its own folders, the user's picks and the Expo-keyed permissions. */\nexport interface DesktopCapabilities {\n readonly spawn?: readonly SpawnCapability[];\n /** The environment variables `Processes.env` holds and a spawned program is given. */\n readonly env?: readonly string[];\n readonly paths?: readonly PathCapability[];\n}\n\n/** The plugin's options. */\nexport interface DesktopOptions {\n readonly documentTypes?: readonly DocumentType[];\n readonly capabilities?: DesktopCapabilities;\n /** npm packages whose native code stays out of the desktop build, even where they ship some. */\n readonly deny?: readonly string[];\n}\n\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst EXTENSION = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\nconst UTI = /^[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)+$/;\nconst MIME_TYPE = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*\\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*$/;\nconst PACKAGE = /^(@[a-z0-9][a-z0-9._~-]*\\/)?[a-z0-9][a-z0-9._~-]*$/;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** Why a declared path cannot be used, or null when it can. */\nexport function pathProblem(path: string): string | null {\n if (typeof path !== 'string' || path.length === 0) return 'a path is required';\n if (path.includes('\\0')) return 'a path cannot hold a NUL character';\n const rooted = path.startsWith('/')\n ? path.slice(1)\n : path.startsWith('~/')\n ? path.slice(2)\n : null;\n if (rooted === null) return `${path} must be absolute, or start with ~/`;\n if (rooted === '') return `${path} would give the whole ${path === '/' ? 'disk' : 'home folder'}`;\n const segments = rooted.replace(/\\/$/, '').split('/');\n if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) {\n return `${path} is not a normalized path`;\n }\n return null;\n}\n\n/**\n * The problems with a set of options, each naming where it is, e.g.\n * `capabilities.spawn[0].program: /bin/sh runs its arguments as a command`. Empty when there are\n * none. Unknown keys are problems too, so a misspelt key is not silently a capability missing.\n */\nexport function desktopOptionProblems(options: unknown): string[] {\n const problems: string[] = [];\n const report = (where: string, problem: string) => problems.push(`${where}: ${problem}`);\n if (options === undefined) return problems;\n if (!isRecord(options)) return ['options must be an object'];\n unknownKeys(options, ['documentTypes', 'capabilities', 'deny'], '', report);\n\n list(options['documentTypes'], 'documentTypes', report, (type, where) => {\n if (!isRecord(type)) {\n report(where, 'must be an object');\n return;\n }\n unknownKeys(type, ['name', 'extensions', 'role', 'utis', 'mimeTypes', 'icon'], where, report);\n if (typeof type['name'] !== 'string' || type['name'] === '') {\n report(`${where}.name`, 'a name is required');\n }\n const extensions = type['extensions'];\n if (!Array.isArray(extensions) || extensions.length === 0) {\n report(`${where}.extensions`, 'at least one extension is required');\n }\n list(extensions, `${where}.extensions`, report, (extension, at) => {\n if (typeof extension !== 'string' || !EXTENSION.test(extension)) {\n report(at, `${JSON.stringify(extension)} is not an extension: write it without the dot`);\n }\n });\n if (type['role'] !== undefined && type['role'] !== 'editor' && type['role'] !== 'viewer') {\n report(`${where}.role`, \"must be 'editor' or 'viewer'\");\n }\n list(type['utis'], `${where}.utis`, report, (uti, at) => {\n if (typeof uti !== 'string' || !UTI.test(uti)) report(at, 'is not a type identifier');\n });\n list(type['mimeTypes'], `${where}.mimeTypes`, report, (mime, at) => {\n if (typeof mime !== 'string' || !MIME_TYPE.test(mime)) report(at, 'is not a MIME type');\n });\n if (type['icon'] !== undefined && typeof type['icon'] !== 'string') {\n report(`${where}.icon`, 'must be a string');\n }\n });\n\n const capabilities = options['capabilities'];\n if (capabilities !== undefined && !isRecord(capabilities)) {\n report('capabilities', 'must be an object');\n } else if (capabilities) {\n unknownKeys(capabilities, ['spawn', 'env', 'paths'], 'capabilities', report);\n list(capabilities['spawn'], 'capabilities.spawn', report, (entry, where) => {\n if (!isRecord(entry)) {\n report(where, 'must be an object');\n return;\n }\n unknownKeys(entry, ['program', 'args'], where, report);\n try {\n compileCapability(entry as unknown as SpawnCapability);\n } catch (error) {\n if (!(error instanceof SpawnRuleError)) throw error;\n report(where, error.message);\n }\n });\n list(capabilities['env'], 'capabilities.env', report, (name, where) => {\n if (typeof name !== 'string' || !ENV_NAME.test(name)) {\n report(where, `${JSON.stringify(name)} is not an environment variable name`);\n }\n });\n list(capabilities['paths'], 'capabilities.paths', report, (entry, where) => {\n if (!isRecord(entry)) {\n report(where, 'must be an object');\n return;\n }\n unknownKeys(entry, ['path', 'access'], where, report);\n const problem = pathProblem(entry['path'] as string);\n if (problem) report(`${where}.path`, problem);\n const access = entry['access'];\n if (access !== undefined && access !== 'read' && access !== 'readwrite') {\n report(`${where}.access`, \"must be 'read' or 'readwrite'\");\n }\n });\n }\n\n list(options['deny'], 'deny', report, (name, where) => {\n if (typeof name !== 'string' || !PACKAGE.test(name))\n report(where, 'is not an npm package name');\n });\n return problems;\n}\n\n/** Check a set of options, throwing one error that lists every problem. */\nexport function validateDesktopOptions(options: unknown): DesktopOptions {\n const problems = desktopOptionProblems(options);\n if (problems.length > 0) {\n throw new Error(\n `[@ng-native/desktop] The plugin options in app.json are not valid:\\n` +\n problems.map((problem) => ` - ${problem}`).join('\\n'),\n );\n }\n return (options ?? {}) as DesktopOptions;\n}\n\n/**\n * Whether `path` is inside one of the declared paths, with the access asked for. `home` is the\n * user's home folder, which `~/` stands for. A path with a `.` or `..` segment is refused rather\n * than resolved: the host resolves links and normalizes before it asks.\n */\nexport function pathAllowed(\n declared: readonly PathCapability[],\n path: string,\n home: string,\n access: 'read' | 'readwrite' = 'read',\n): boolean {\n if (pathProblem(path) !== null || !path.startsWith('/')) return false;\n const target = path.replace(/\\/$/, '');\n return declared.some((entry) => {\n if (pathProblem(entry.path) !== null) return false;\n if (access === 'readwrite' && entry.access !== 'readwrite') return false;\n const root = (\n entry.path.startsWith('~/') ? `${home}/${entry.path.slice(2)}` : entry.path\n ).replace(/\\/$/, '');\n return target === root || target.startsWith(`${root}/`);\n });\n}\n\nfunction unknownKeys(\n value: Record<string, unknown>,\n known: readonly string[],\n where: string,\n report: (where: string, problem: string) => void,\n): void {\n for (const key of Object.keys(value)) {\n if (!known.includes(key)) {\n report(\n where ? `${where}.${key}` : key,\n `is not an option (expected one of ${known.join(', ')})`,\n );\n }\n }\n}\n\nfunction list(\n value: unknown,\n where: string,\n report: (where: string, problem: string) => void,\n each: (item: unknown, where: string) => void,\n): void {\n if (value === undefined) return;\n if (!Array.isArray(value)) {\n report(where, 'must be a list');\n return;\n }\n value.forEach((item, index) => each(item, `${where}[${index}]`));\n}\n\nexport * from './spawn-rules.ts';\nexport * from './desktop-permissions.ts';\n"]}
package/dist/dialogs.js CHANGED
@@ -12,6 +12,7 @@
12
12
  * platform - and the one thing neither can do is fail silently on the platform it is not for.
13
13
  */
14
14
  import { InjectionToken, Service, inject, signal } from '@angular/core';
15
+ import { isDesktopOs } from "./os.js";
15
16
  import { reactNative } from "./react-native.js";
16
17
  import * as i0 from "@angular/core";
17
18
  /**
@@ -165,8 +166,9 @@ export function dialogSource(native) {
165
166
  if (!native)
166
167
  return null;
167
168
  const ios = native.Platform.OS === 'ios';
168
- // A Mac's alert module is iOS's, and React Native's `Alert.prompt` takes its iOS body there.
169
- const apple = ios || native.Platform.OS === 'macos';
169
+ // The desktop host's alert module is iOS's, and React Native's `Alert.prompt` takes its iOS body
170
+ // on macOS and Linux, whose bundles take React Native's iOS files.
171
+ const apple = ios || isDesktopOs(native.Platform.OS);
170
172
  const android = native.Platform.OS === 'android';
171
173
  return {
172
174
  platform: native.Platform.OS,
@@ -1 +1 @@
1
- {"version":3,"file":"dialogs.js","sourceRoot":"","sources":["../src/dialogs.ts"],"names":[],"mappings":"AAAA;;;;;;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C9D;aACJ;YACH,CAAC,CAAC,EAAE,CAAC;KACR,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The platform's own dialogs: an alert, a confirmation, a prompt, an action sheet, a toast.\n *\n * All of these are callback APIs, and the reason to wrap them is that **a dialog is a question**.\n * `Alert.alert` hands its answer to one of several `onPress` callbacks, so asking something and\n * acting on the answer means splitting one thought across three functions. A promise puts it back\n * together, and `await` at the call site reads like what it is.\n *\n * The platform split is the other half. An action sheet is iOS's way of offering a short list of\n * choices and Android's is a dialog; a toast is Android's way of saying something small and iOS\n * has none. `choose` and `notify` pick per platform, so an app writes the intent rather than the\n * platform - and the one thing neither can do is fail silently on the platform it is not for.\n */\n\nimport { InjectionToken, Service, inject, signal, type Signal } from '@angular/core';\nimport { reactNative, type ReactNative } from './react-native.ts';\n\n/** One choice in a dialog or an action sheet. */\nexport interface Choice {\n readonly label: string;\n /** `cancel` is dismissal; `destructive` is the one the platform paints red. */\n readonly style?: 'default' | 'cancel' | 'destructive';\n}\n\nexport interface NativeDialogs {\n readonly platform: 'ios' | 'android' | string;\n alert(\n title: string,\n message: string | undefined,\n buttons: readonly { text: string; style?: string; onPress?: () => void }[],\n ): void;\n prompt?(\n title: string,\n message: string | undefined,\n onResult: (value: string | null) => void,\n defaultValue?: string,\n ): void;\n actionSheet?(\n options: {\n title?: string;\n message?: string;\n options: string[];\n cancelButtonIndex: number;\n destructiveButtonIndex?: number;\n },\n onSelect: (index: number) => void,\n ): void;\n toast?(message: string, long: boolean): void;\n}\n\n/**\n * `inject(Dialogs).confirm('Delete this?', { destructive: true })`.\n *\n * A dialog is a question, so every method here resolves to the answer rather than handing it to\n * one of several callbacks.\n */\n@Service()\nexport class Dialogs {\n /** Overridden in a test to answer a dialog without one being shown. */\n static readonly SOURCE = new InjectionToken<NativeDialogs | null>('angular-native.dialogSource', {\n factory: () => dialogSource(reactNative()),\n });\n\n private readonly native = inject(Dialogs.SOURCE);\n\n /** Whether React Native's module is here. Where it is not, every call is inert. */\n readonly available: Signal<boolean> = signal(this.native !== null).asReadonly();\n\n /** Say something, and wait until it has been read. Resolves when the dialog is dismissed. */\n tell(title: string, message?: string, dismiss = 'OK'): Promise<void> {\n return new Promise((resolve) => {\n if (!this.native) return resolve();\n this.native.alert(title, message, [{ text: dismiss, onPress: () => resolve() }]);\n });\n }\n\n /**\n * Ask something with two answers. Resolves to whether they agreed.\n *\n * `destructive` paints the confirm button as the platform paints a delete, and puts cancel where\n * the platform puts it - which on iOS is the *right*, so a confirmation dialog does not train\n * people to tap the wrong thing.\n */\n confirm(\n title: string,\n options: { message?: string; confirm?: string; cancel?: string; destructive?: boolean } = {},\n ): Promise<boolean> {\n const { message, confirm = 'OK', cancel = 'Cancel', destructive = false } = options;\n return new Promise((resolve) => {\n if (!this.native) return resolve(false);\n this.native.alert(title, message, [\n { text: cancel, style: 'cancel', onPress: () => resolve(false) },\n {\n text: confirm,\n style: destructive ? 'destructive' : 'default',\n onPress: () => resolve(true),\n },\n ]);\n });\n }\n\n /**\n * Ask for a line of text. Resolves to null if they cancelled.\n *\n * iOS and macOS only: `Alert.prompt` has no Android equivalent, and inventing one out of a modal\n * and a text input would be a dialog that looks nothing like the platform's. On Android this\n * resolves to null so a caller can fall back to a screen of its own.\n */\n ask(title: string, options: { message?: string; value?: string } = {}): Promise<string | null> {\n return new Promise((resolve) => {\n if (!this.native?.prompt) return resolve(null);\n this.native.prompt(title, options.message, resolve, options.value);\n });\n }\n\n /**\n * Offer a short list of choices. Resolves to the index chosen, or null if dismissed.\n *\n * An action sheet on iOS and a dialog on Android, because that is what each platform means by\n * this. A `cancel` choice is where the platform puts cancel rather than in the list.\n *\n * `message` is the smaller line under the title, the one that says what a destructive choice\n * does: the action sheet's message on iOS and the dialog's message on Android.\n */\n choose(\n title: string,\n choices: readonly Choice[],\n options: { message?: string } = {},\n ): Promise<number | null> {\n const { message } = options;\n const cancelAt = choices.findIndex((choice) => choice.style === 'cancel');\n const destructiveAt = choices.findIndex((choice) => choice.style === 'destructive');\n\n return new Promise((resolve) => {\n if (!this.native) return resolve(null);\n\n if (this.native.actionSheet) {\n // iOS wants cancel last and named by index; a list with none gets one, because an action\n // sheet with no way out is one the user has to guess at.\n const labels = choices.map((choice) => choice.label);\n const cancelIndex = cancelAt >= 0 ? cancelAt : labels.push('Cancel') - 1;\n this.native.actionSheet(\n {\n title,\n ...(message !== undefined ? { message } : {}),\n options: labels,\n cancelButtonIndex: cancelIndex,\n ...(destructiveAt >= 0 ? { destructiveButtonIndex: destructiveAt } : {}),\n },\n (index) => resolve(index === cancelIndex ? null : index),\n );\n return;\n }\n\n /*\n * Android's alert is put up `cancelable: false` by React Native, so a press outside does\n * nothing and neither does the back button. Without a cancel among the choices there is no\n * way at all to decline - the user has to pick something - so one is appended, exactly as\n * the iOS branch above does for the same reason.\n *\n * Android's dialog holds three buttons: a negative, a neutral and a positive. Anything past\n * that is dropped by the platform without a word, and a choice the user cannot see is worse\n * than a list that refused to open, so it says so. A Mac's alert, the same call, has a\n * button for every choice, with Cancel bound to Escape.\n */\n const buttons = choices.map((choice, index) => ({\n text: choice.label,\n style: choice.style,\n onPress: () => resolve(choice.style === 'cancel' ? null : index),\n }));\n if (cancelAt < 0) {\n buttons.push({ text: 'Cancel', style: 'cancel', onPress: () => resolve(null) });\n }\n if (this.native.platform === 'android' && buttons.length > 3) {\n console.error(\n `[angular-native] Dialogs.choose was given ${choices.length} choices and Android shows ` +\n 'at most three buttons, counting the cancel. The rest will not appear. Use a ' +\n '`ui-select` or an `action-sheet`-shaped list for anything longer.',\n );\n }\n this.native.alert(title, message, buttons);\n });\n }\n\n /**\n * Say something small and transient.\n *\n * A toast on Android. iOS has no such thing and never has, so this does nothing there rather\n * than putting up a modal alert for something that did not warrant interrupting anyone - and an\n * app that must be seen should use `tell`.\n */\n notify(message: string, options: { long?: boolean } = {}): void {\n this.native?.toast?.(message, options.long ?? false);\n }\n}\n\n/**\n * The platform's dialogs, from React Native's own modules.\n *\n * `Alert.prompt` is iOS and macOS only, `ActionSheetIOS` iOS only and `ToastAndroid` Android\n * only; each is left absent rather than shimmed, which is what lets `ask`, `choose` and `notify`\n * above decide what to do about it.\n *\n * Which platform it is has to be asked outright, because React Native's own modules do not answer\n * it. `react-native` exports `ActionSheetIOS` on Android too - the object is there and so is\n * `showActionSheetWithOptions`; only the TurboModule underneath is null, and the invariant that\n * catches that throws out of the promise `choose` returns, so a press did nothing at all and said\n * nothing about it. `Alert.prompt` is worse: it exists on Android and its body is one\n * `Platform.OS === 'ios'` check, so it returns having called no callback and the promise `ask`\n * returns never settles. `ToastAndroid` is the mirror image on iOS. Presence is not capability\n * here; only the platform name is.\n */\nexport function dialogSource(\n native: Pick<ReactNative, 'Platform' | 'Alert' | 'ActionSheetIOS' | 'ToastAndroid'> | null,\n): NativeDialogs | null {\n if (!native) return null;\n\n const ios = native.Platform.OS === 'ios';\n // A Mac's alert module is iOS's, and React Native's `Alert.prompt` takes its iOS body there.\n const apple = ios || native.Platform.OS === 'macos';\n const android = native.Platform.OS === 'android';\n\n return {\n platform: native.Platform.OS,\n alert: (title, message, buttons) => native.Alert.alert(title, message, [...buttons]),\n // Buttons rather than a callback: given a callback, `Alert.prompt` answers OK alone, and the\n // Cancel the native alert adds calls nothing, so a cancelled `ask` never settled.\n ...(apple && native.Alert.prompt\n ? {\n prompt: (title, message, onResult, defaultValue) =>\n native.Alert.prompt!(\n title,\n message,\n [\n { text: 'Cancel', style: 'cancel', onPress: () => onResult(null) },\n { text: 'OK', onPress: (value) => onResult(value ?? '') },\n ],\n undefined,\n defaultValue,\n ),\n }\n : {}),\n ...(ios && native.ActionSheetIOS\n ? {\n actionSheet: (options, onSelect) =>\n native.ActionSheetIOS!.showActionSheetWithOptions(options, onSelect),\n }\n : {}),\n ...(android && native.ToastAndroid\n ? {\n toast: (message, long) =>\n native.ToastAndroid!.show(\n message,\n long ? native.ToastAndroid!.LONG : native.ToastAndroid!.SHORT,\n ),\n }\n : {}),\n };\n}\n"]}
1
+ {"version":3,"file":"dialogs.js","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,CACvB,OAAO,EACP,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,YAAa,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,YAAa,CAAC,KAAK,CAC9D;aACJ;YACH,CAAC,CAAC,EAAE,CAAC;KACR,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The platform's own dialogs: an alert, a confirmation, a prompt, an action sheet, a toast.\n *\n * All of these are callback APIs, and the reason to wrap them is that **a dialog is a question**.\n * `Alert.alert` hands its answer to one of several `onPress` callbacks, so asking something and\n * acting on the answer means splitting one thought across three functions. A promise puts it back\n * together, and `await` at the call site reads like what it is.\n *\n * The platform split is the other half. An action sheet is iOS's way of offering a short list of\n * choices and Android's is a dialog; a toast is Android's way of saying something small and iOS\n * has none. `choose` and `notify` pick per platform, so an app writes the intent rather than the\n * platform - and the one thing neither can do is fail silently on the platform it is not for.\n */\n\nimport { InjectionToken, Service, inject, signal, type Signal } from '@angular/core';\nimport { isDesktopOs } from './os.ts';\nimport { reactNative, type ReactNative } from './react-native.ts';\n\n/** One choice in a dialog or an action sheet. */\nexport interface Choice {\n readonly label: string;\n /** `cancel` is dismissal; `destructive` is the one the platform paints red. */\n readonly style?: 'default' | 'cancel' | 'destructive';\n}\n\nexport interface NativeDialogs {\n readonly platform: 'ios' | 'android' | string;\n alert(\n title: string,\n message: string | undefined,\n buttons: readonly { text: string; style?: string; onPress?: () => void }[],\n ): void;\n prompt?(\n title: string,\n message: string | undefined,\n onResult: (value: string | null) => void,\n defaultValue?: string,\n ): void;\n actionSheet?(\n options: {\n title?: string;\n message?: string;\n options: string[];\n cancelButtonIndex: number;\n destructiveButtonIndex?: number;\n },\n onSelect: (index: number) => void,\n ): void;\n toast?(message: string, long: boolean): void;\n}\n\n/**\n * `inject(Dialogs).confirm('Delete this?', { destructive: true })`.\n *\n * A dialog is a question, so every method here resolves to the answer rather than handing it to\n * one of several callbacks.\n */\n@Service()\nexport class Dialogs {\n /** Overridden in a test to answer a dialog without one being shown. */\n static readonly SOURCE = new InjectionToken<NativeDialogs | null>('angular-native.dialogSource', {\n factory: () => dialogSource(reactNative()),\n });\n\n private readonly native = inject(Dialogs.SOURCE);\n\n /** Whether React Native's module is here. Where it is not, every call is inert. */\n readonly available: Signal<boolean> = signal(this.native !== null).asReadonly();\n\n /** Say something, and wait until it has been read. Resolves when the dialog is dismissed. */\n tell(title: string, message?: string, dismiss = 'OK'): Promise<void> {\n return new Promise((resolve) => {\n if (!this.native) return resolve();\n this.native.alert(title, message, [{ text: dismiss, onPress: () => resolve() }]);\n });\n }\n\n /**\n * Ask something with two answers. Resolves to whether they agreed.\n *\n * `destructive` paints the confirm button as the platform paints a delete, and puts cancel where\n * the platform puts it - which on iOS is the *right*, so a confirmation dialog does not train\n * people to tap the wrong thing.\n */\n confirm(\n title: string,\n options: { message?: string; confirm?: string; cancel?: string; destructive?: boolean } = {},\n ): Promise<boolean> {\n const { message, confirm = 'OK', cancel = 'Cancel', destructive = false } = options;\n return new Promise((resolve) => {\n if (!this.native) return resolve(false);\n this.native.alert(title, message, [\n { text: cancel, style: 'cancel', onPress: () => resolve(false) },\n {\n text: confirm,\n style: destructive ? 'destructive' : 'default',\n onPress: () => resolve(true),\n },\n ]);\n });\n }\n\n /**\n * Ask for a line of text. Resolves to null if they cancelled.\n *\n * iOS and macOS only: `Alert.prompt` has no Android equivalent, and inventing one out of a modal\n * and a text input would be a dialog that looks nothing like the platform's. On Android this\n * resolves to null so a caller can fall back to a screen of its own.\n */\n ask(title: string, options: { message?: string; value?: string } = {}): Promise<string | null> {\n return new Promise((resolve) => {\n if (!this.native?.prompt) return resolve(null);\n this.native.prompt(title, options.message, resolve, options.value);\n });\n }\n\n /**\n * Offer a short list of choices. Resolves to the index chosen, or null if dismissed.\n *\n * An action sheet on iOS and a dialog on Android, because that is what each platform means by\n * this. A `cancel` choice is where the platform puts cancel rather than in the list.\n *\n * `message` is the smaller line under the title, the one that says what a destructive choice\n * does: the action sheet's message on iOS and the dialog's message on Android.\n */\n choose(\n title: string,\n choices: readonly Choice[],\n options: { message?: string } = {},\n ): Promise<number | null> {\n const { message } = options;\n const cancelAt = choices.findIndex((choice) => choice.style === 'cancel');\n const destructiveAt = choices.findIndex((choice) => choice.style === 'destructive');\n\n return new Promise((resolve) => {\n if (!this.native) return resolve(null);\n\n if (this.native.actionSheet) {\n // iOS wants cancel last and named by index; a list with none gets one, because an action\n // sheet with no way out is one the user has to guess at.\n const labels = choices.map((choice) => choice.label);\n const cancelIndex = cancelAt >= 0 ? cancelAt : labels.push('Cancel') - 1;\n this.native.actionSheet(\n {\n title,\n ...(message !== undefined ? { message } : {}),\n options: labels,\n cancelButtonIndex: cancelIndex,\n ...(destructiveAt >= 0 ? { destructiveButtonIndex: destructiveAt } : {}),\n },\n (index) => resolve(index === cancelIndex ? null : index),\n );\n return;\n }\n\n /*\n * Android's alert is put up `cancelable: false` by React Native, so a press outside does\n * nothing and neither does the back button. Without a cancel among the choices there is no\n * way at all to decline - the user has to pick something - so one is appended, exactly as\n * the iOS branch above does for the same reason.\n *\n * Android's dialog holds three buttons: a negative, a neutral and a positive. Anything past\n * that is dropped by the platform without a word, and a choice the user cannot see is worse\n * than a list that refused to open, so it says so. A Mac's alert, the same call, has a\n * button for every choice, with Cancel bound to Escape.\n */\n const buttons = choices.map((choice, index) => ({\n text: choice.label,\n style: choice.style,\n onPress: () => resolve(choice.style === 'cancel' ? null : index),\n }));\n if (cancelAt < 0) {\n buttons.push({ text: 'Cancel', style: 'cancel', onPress: () => resolve(null) });\n }\n if (this.native.platform === 'android' && buttons.length > 3) {\n console.error(\n `[angular-native] Dialogs.choose was given ${choices.length} choices and Android shows ` +\n 'at most three buttons, counting the cancel. The rest will not appear. Use a ' +\n '`ui-select` or an `action-sheet`-shaped list for anything longer.',\n );\n }\n this.native.alert(title, message, buttons);\n });\n }\n\n /**\n * Say something small and transient.\n *\n * A toast on Android. iOS has no such thing and never has, so this does nothing there rather\n * than putting up a modal alert for something that did not warrant interrupting anyone - and an\n * app that must be seen should use `tell`.\n */\n notify(message: string, options: { long?: boolean } = {}): void {\n this.native?.toast?.(message, options.long ?? false);\n }\n}\n\n/**\n * The platform's dialogs, from React Native's own modules.\n *\n * `Alert.prompt` is iOS and macOS only, `ActionSheetIOS` iOS only and `ToastAndroid` Android\n * only; each is left absent rather than shimmed, which is what lets `ask`, `choose` and `notify`\n * above decide what to do about it.\n *\n * Which platform it is has to be asked outright, because React Native's own modules do not answer\n * it. `react-native` exports `ActionSheetIOS` on Android too - the object is there and so is\n * `showActionSheetWithOptions`; only the TurboModule underneath is null, and the invariant that\n * catches that throws out of the promise `choose` returns, so a press did nothing at all and said\n * nothing about it. `Alert.prompt` is worse: it exists on Android and its body is one\n * `Platform.OS === 'ios'` check, so it returns having called no callback and the promise `ask`\n * returns never settles. `ToastAndroid` is the mirror image on iOS. Presence is not capability\n * here; only the platform name is.\n */\nexport function dialogSource(\n native: Pick<ReactNative, 'Platform' | 'Alert' | 'ActionSheetIOS' | 'ToastAndroid'> | null,\n): NativeDialogs | null {\n if (!native) return null;\n\n const ios = native.Platform.OS === 'ios';\n // The desktop host's alert module is iOS's, and React Native's `Alert.prompt` takes its iOS body\n // on macOS and Linux, whose bundles take React Native's iOS files.\n const apple = ios || isDesktopOs(native.Platform.OS);\n const android = native.Platform.OS === 'android';\n\n return {\n platform: native.Platform.OS,\n alert: (title, message, buttons) => native.Alert.alert(title, message, [...buttons]),\n // Buttons rather than a callback: given a callback, `Alert.prompt` answers OK alone, and the\n // Cancel the native alert adds calls nothing, so a cancelled `ask` never settled.\n ...(apple && native.Alert.prompt\n ? {\n prompt: (title, message, onResult, defaultValue) =>\n native.Alert.prompt!(\n title,\n message,\n [\n { text: 'Cancel', style: 'cancel', onPress: () => onResult(null) },\n { text: 'OK', onPress: (value) => onResult(value ?? '') },\n ],\n undefined,\n defaultValue,\n ),\n }\n : {}),\n ...(ios && native.ActionSheetIOS\n ? {\n actionSheet: (options, onSelect) =>\n native.ActionSheetIOS!.showActionSheetWithOptions(options, onSelect),\n }\n : {}),\n ...(android && native.ToastAndroid\n ? {\n toast: (message, long) =>\n native.ToastAndroid!.show(\n message,\n long ? native.ToastAndroid!.LONG : native.ToastAndroid!.SHORT,\n ),\n }\n : {}),\n };\n}\n"]}
package/dist/dock.d.ts CHANGED
@@ -25,6 +25,8 @@ export declare class Dock {
25
25
  /** Overridden in a test with a fake host. */
26
26
  static readonly SOURCE: InjectionToken<NativeDock | null>;
27
27
  private readonly native;
28
+ /** The desktop OS whose shortcuts the menu shows: Linux's own, else a Mac's. */
29
+ private readonly menuOs;
28
30
  private actions;
29
31
  private readonly unsubscribe;
30
32
  /** Whether the app has a Dock icon: macOS. */
package/dist/dock.js CHANGED
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import { InjectionToken, Service, inject, signal } from '@angular/core';
12
12
  import { serializeMenu } from "./menus.js";
13
+ import { injectOs } from "./os.js";
13
14
  import { reactNative } from "./react-native.js";
14
15
  import * as i0 from "@angular/core";
15
16
  function dockSource() {
@@ -33,6 +34,8 @@ export class Dock {
33
34
  factory: dockSource,
34
35
  });
35
36
  native = inject(Dock.SOURCE);
37
+ /** The desktop OS whose shortcuts the menu shows: Linux's own, else a Mac's. */
38
+ menuOs = injectOs() === 'linux' ? 'linux' : 'macos';
36
39
  actions = new Map();
37
40
  unsubscribe = this.native?.subscribe((event) => this.actions.get(event.id)?.()) ?? null;
38
41
  /** Whether the app has a Dock icon: macOS. */
@@ -43,7 +46,7 @@ export class Dock {
43
46
  * `<menu-item>` registers them.
44
47
  */
45
48
  setMenu(entries) {
46
- const menu = serializeMenu(entries ?? [], 'macos');
49
+ const menu = serializeMenu(entries ?? [], this.menuOs);
47
50
  this.actions = menu.actions;
48
51
  this.native?.setMenu(menu.entries.length ? menu.entries : null);
49
52
  }
package/dist/dock.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"dock.js","sourceRoot":"","sources":["../src/dock.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EA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C,MAAM,EAAE,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC;IAE5E,8CAA8C;IACrC,SAAS,GAAoB,MAAM,CAAC,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,UAAU,EAAE,CAAC;IAEhF;;;;OAIG;IACH,OAAO,CAAC,OAAoC;QAC1C,MAAM,IAAI,GAAG,aAAa,CAAC,OAAO,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC;QACnD,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC5B,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAClE,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,UAAkC,EAAE;QACzC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3B,IAAI,CAAC,MAAM;YAAE,OAAO,GAAG,EAAE,GAAE,CAAC,CAAC;QAC7B,MAAM,EAAE,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,KAAK,IAAI,CAAC,CAAC;QACpD,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC;IACvC,CAAC;IAED,WAAW;QACT,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;IACvB,CAAC;uGAtCU,IAAI;wGAAJ,IAAI;;2FAAJ,IAAI;kBADhB,OAAO","sourcesContent":["/**\n * The app's Dock icon on macOS: a menu of the app's own above the standard one, and a bounce that\n * asks for attention. Its badge is the Notifications badge count, from `@ng-native/expo`'s\n * `Notifications.setBadge`, as an app icon's badge is on iOS. Absent on every other OS, where each\n * call does nothing.\n *\n * The host contract, on the `NgNativeDock` module: `setMenu(entries)` takes the menu as\n * `serializeMenu` makes it, or null for none; `bounce(critical)` answers an id that\n * `cancelBounce(id)` takes; `{ type: 'menuSelect', id }` arrives on `ngNativeDock`.\n */\nimport { InjectionToken, Service, inject, signal, type Signal } from '@angular/core';\nimport type { MenuEntry } from './menu-model.ts';\nimport { serializeMenu, type NativeMenuEntry } from './menus.ts';\nimport { reactNative } from './react-native.ts';\n\nexport interface NativeDock {\n setMenu(entries: readonly NativeMenuEntry[] | null): void;\n bounce(critical: boolean): number;\n cancelBounce(id: number): void;\n subscribe(listener: (event: { type: 'menuSelect'; id: string }) => void): () => void;\n}\n\ninterface DockTurboModule {\n setMenu?(entries: readonly NativeMenuEntry[] | null): void;\n bounce?(critical: boolean): number;\n cancelBounce?(id: number): void;\n}\n\nfunction dockSource(): NativeDock | null {\n const native = reactNative();\n const module = native?.TurboModuleRegistry?.get?.('NgNativeDock') as\n DockTurboModule | null | undefined;\n if (!module) return null;\n return {\n setMenu: (entries) => module.setMenu?.(entries),\n bounce: (critical) => module.bounce?.(critical) ?? -1,\n cancelBounce: (id) => module.cancelBounce?.(id),\n subscribe: (listener) => {\n const subscription = native?.DeviceEventEmitter?.addListener('ngNativeDock', (event) =>\n listener(event as { type: 'menuSelect'; id: string }),\n );\n return () => subscription?.remove();\n },\n };\n}\n\n@Service()\nexport class Dock {\n /** Overridden in a test with a fake host. */\n static readonly SOURCE = new InjectionToken<NativeDock | null>('angular-native.dockSource', {\n factory: dockSource,\n });\n\n private readonly native = inject(Dock.SOURCE);\n private actions: ReadonlyMap<string, () => void> = new Map();\n private readonly unsubscribe =\n this.native?.subscribe((event) => this.actions.get(event.id)?.()) ?? null;\n\n /** Whether the app has a Dock icon: macOS. */\n readonly available: Signal<boolean> = signal(this.native !== null).asReadonly();\n\n /**\n * Show `entries` in the Dock icon's menu, above the items macOS adds (Options, Show All Windows,\n * Hide, Quit); an empty list or null takes them away. Items are `MenuItemModel`s, as a\n * `<menu-item>` registers them.\n */\n setMenu(entries: readonly MenuEntry[] | null): void {\n const menu = serializeMenu(entries ?? [], 'macos');\n this.actions = menu.actions;\n this.native?.setMenu(menu.entries.length ? menu.entries : null);\n }\n\n /**\n * Bounce the Dock icon until the app comes to the front: once, or with `critical` until then.\n * Nothing while the app is in front. Answers the function that stops it.\n */\n bounce(options: { critical?: boolean } = {}): () => void {\n const native = this.native;\n if (!native) return () => {};\n const id = native.bounce(options.critical === true);\n return () => native.cancelBounce(id);\n }\n\n ngOnDestroy(): void {\n this.unsubscribe?.();\n }\n}\n"]}
1
+ {"version":3,"file":"dock.js","sourceRoot":"","sources":["../src/dock.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAe,MAAM,eAAe,CAAC;AAErF,OAAO,EAAE,aAAa,EAAwB,MAAM,YAAY,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;;AAehD,SAAS,UAAU;IACjB,MAAM,MAAM,GAAG,WAAW,EAAE,CAAC;IAC7B,MAAM,MAAM,GAAG,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,CAAC,cAAc,CAC5B,CAAC;IACrC,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,OAAO;QACL,OAAO,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC;QAC/C,MAAM,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACrD,YAAY,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,MAAM,CAAC,YAAY,EAAE,CAAC,EAAE,CAAC;QAC/C,SAAS,EAAE,CAAC,QAAQ,EAAE,EAAE;YACtB,MAAM,YAAY,GAAG,MAAM,EA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,UAAkC,EAAE;QACzC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3B,IAAI,CAAC,MAAM;YAAE,OAAO,GAAG,EAAE,GAAE,CAAC,CAAC;QAC7B,MAAM,EAAE,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,KAAK,IAAI,CAAC,CAAC;QACpD,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC;IACvC,CAAC;IAED,WAAW;QACT,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;IACvB,CAAC;uGAxCU,IAAI;wGAAJ,IAAI;;2FAAJ,IAAI;kBADhB,OAAO","sourcesContent":["/**\n * The app's Dock icon on macOS: a menu of the app's own above the standard one, and a bounce that\n * asks for attention. Its badge is the Notifications badge count, from `@ng-native/expo`'s\n * `Notifications.setBadge`, as an app icon's badge is on iOS. Absent on every other OS, where each\n * call does nothing.\n *\n * The host contract, on the `NgNativeDock` module: `setMenu(entries)` takes the menu as\n * `serializeMenu` makes it, or null for none; `bounce(critical)` answers an id that\n * `cancelBounce(id)` takes; `{ type: 'menuSelect', id }` arrives on `ngNativeDock`.\n */\nimport { InjectionToken, Service, inject, signal, type Signal } from '@angular/core';\nimport type { MenuEntry } from './menu-model.ts';\nimport { serializeMenu, type NativeMenuEntry } from './menus.ts';\nimport { injectOs } from './os.ts';\nimport { reactNative } from './react-native.ts';\n\nexport interface NativeDock {\n setMenu(entries: readonly NativeMenuEntry[] | null): void;\n bounce(critical: boolean): number;\n cancelBounce(id: number): void;\n subscribe(listener: (event: { type: 'menuSelect'; id: string }) => void): () => void;\n}\n\ninterface DockTurboModule {\n setMenu?(entries: readonly NativeMenuEntry[] | null): void;\n bounce?(critical: boolean): number;\n cancelBounce?(id: number): void;\n}\n\nfunction dockSource(): NativeDock | null {\n const native = reactNative();\n const module = native?.TurboModuleRegistry?.get?.('NgNativeDock') as\n DockTurboModule | null | undefined;\n if (!module) return null;\n return {\n setMenu: (entries) => module.setMenu?.(entries),\n bounce: (critical) => module.bounce?.(critical) ?? -1,\n cancelBounce: (id) => module.cancelBounce?.(id),\n subscribe: (listener) => {\n const subscription = native?.DeviceEventEmitter?.addListener('ngNativeDock', (event) =>\n listener(event as { type: 'menuSelect'; id: string }),\n );\n return () => subscription?.remove();\n },\n };\n}\n\n@Service()\nexport class Dock {\n /** Overridden in a test with a fake host. */\n static readonly SOURCE = new InjectionToken<NativeDock | null>('angular-native.dockSource', {\n factory: dockSource,\n });\n\n private readonly native = inject(Dock.SOURCE);\n /** The desktop OS whose shortcuts the menu shows: Linux's own, else a Mac's. */\n private readonly menuOs = injectOs() === 'linux' ? 'linux' : 'macos';\n private actions: ReadonlyMap<string, () => void> = new Map();\n private readonly unsubscribe =\n this.native?.subscribe((event) => this.actions.get(event.id)?.()) ?? null;\n\n /** Whether the app has a Dock icon: macOS. */\n readonly available: Signal<boolean> = signal(this.native !== null).asReadonly();\n\n /**\n * Show `entries` in the Dock icon's menu, above the items macOS adds (Options, Show All Windows,\n * Hide, Quit); an empty list or null takes them away. Items are `MenuItemModel`s, as a\n * `<menu-item>` registers them.\n */\n setMenu(entries: readonly MenuEntry[] | null): void {\n const menu = serializeMenu(entries ?? [], this.menuOs);\n this.actions = menu.actions;\n this.native?.setMenu(menu.entries.length ? menu.entries : null);\n }\n\n /**\n * Bounce the Dock icon until the app comes to the front: once, or with `critical` until then.\n * Nothing while the app is in front. Answers the function that stops it.\n */\n bounce(options: { critical?: boolean } = {}): () => void {\n const native = this.native;\n if (!native) return () => {};\n const id = native.bounce(options.critical === true);\n return () => native.cancelBounce(id);\n }\n\n ngOnDestroy(): void {\n this.unsubscribe?.();\n }\n}\n"]}
@@ -9,13 +9,14 @@
9
9
  * Emoji) is left to the desktop host.
10
10
  */
11
11
  import { InjectionToken, type Signal } from '@angular/core';
12
+ import type { OsName } from './os.ts';
12
13
  /** A standard menu a `<menu-group menuRole>` adds its items to. */
13
14
  export type MenuGroupRole = 'app' | 'file' | 'edit' | 'view' | 'window' | 'help';
14
15
  /**
15
16
  * What an item is for, where the OS has a standard one: an item with a `menuRole` replaces that
16
17
  * role's default item, and without a handler does what the OS does for it.
17
18
  */
18
- export type MenuRole = 'about' | 'settings' | 'services' | 'hide' | 'hideOthers' | 'showAll' | 'quit' | 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'selectAll' | 'find' | 'toggleSidebar' | 'toggleFullScreen' | 'back' | 'forward' | 'minimize' | 'zoom' | 'bringAllToFront' | 'close' | 'print';
19
+ export type MenuRole = 'about' | 'settings' | 'services' | 'hide' | 'hideOthers' | 'showAll' | 'quit' | 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'selectAll' | 'find' | 'toggleSidebar' | 'toggleFullScreen' | 'back' | 'forward' | 'minimize' | 'zoom' | 'bringAllToFront' | 'close' | 'print' | 'keyboardShortcuts' | 'help';
19
20
  /** One item in a menu. */
20
21
  export interface MenuItemModel {
21
22
  readonly label: string;
@@ -54,25 +55,26 @@ export interface MenuGroupModel {
54
55
  readonly items: readonly MenuEntry[];
55
56
  }
56
57
  export declare const isSeparator: (entry: MenuEntry) => entry is MenuSeparator;
57
- /**
58
- * The menu bar every desktop app gets: App, File, Edit, View, Window and Help, each item with its
59
- * role and standard shortcut. `Settings...` is in it until the merge, which keeps it only when the
60
- * app gives it a handler. File holds Print... (`mod+p`), which prints the key window unless the app
61
- * gives a `print` item a handler.
62
- */
63
58
  /**
64
59
  * The groups of a merged menu bar (`mergeMenuBar`) that have no `menuRole` and are named as one
65
60
  * of the default menus is: each is drawn as a second menu of that name beside the default one,
66
61
  * since only a role merges a group into its menu.
67
62
  */
68
63
  export declare function unmergedGroups(defaults: readonly MenuGroupModel[], merged: readonly MenuGroupModel[]): string[];
69
- export declare function defaultMenuBar(appName: string): MenuGroupModel[];
64
+ /**
65
+ * The menu bar every desktop app gets on `os`. On macOS: App, File, Edit, View, Window and Help,
66
+ * each item with its role and standard shortcut. `Settings...` is in it until the merge, which
67
+ * keeps it only when the app gives it a handler. File holds Print... (`mod+p`), which prints the
68
+ * key window unless the app gives a `print` item a handler. On Linux: linuxMenuBar's.
69
+ */
70
+ export declare function defaultMenuBar(appName: string, os?: OsName): MenuGroupModel[];
70
71
  /**
71
72
  * The menu bar an app ends up with, from the defaults and its `<menu-bar>`:
72
73
  *
73
74
  * - An app item with a `menuRole` replaces the default item with that role, where the default is,
74
75
  * and leaves the group it was written in.
75
- * - `Settings...` shows only when the app gives a `settings` item a handler.
76
+ * - `Settings...` (Preferences on Linux) and Linux's Help show only when the app gives a `settings`
77
+ * or `help` item a handler.
76
78
  * - A group whose `menuRole` names a default menu adds its items to the end of that menu; a `file`
77
79
  * group's go before Print..., which stays last, as on a Mac.
78
80
  * - A `file` group with no default File menu goes after the App menu, and any other group after
@@ -11,12 +11,66 @@
11
11
  import { InjectionToken, computed, signal } from '@angular/core';
12
12
  const SEPARATOR = { separator: true };
13
13
  export const isSeparator = (entry) => 'separator' in entry;
14
+ const item = (label, menuRole, shortcut) => shortcut ? { label, menuRole, shortcut } : { label, menuRole };
14
15
  /**
15
- * The menu bar every desktop app gets: App, File, Edit, View, Window and Help, each item with its
16
- * role and standard shortcut. `Settings...` is in it until the merge, which keeps it only when the
17
- * app gives it a handler. File holds Print... (`mod+p`), which prints the key window unless the app
18
- * gives a `print` item a handler.
16
+ * Linux's bar, as GNOME's and KDE's apps have theirs: File (Close Window, Print...), Edit, View
17
+ * (Back, Forward, Show Sidebar on F9, Full Screen on F11), the app's own groups after View, and a
18
+ * menu named for the app last, with Preferences and Help on F1 (each kept only with the app's
19
+ * handler), Keyboard Shortcuts (a window the host draws, unless the app handles it), About and
20
+ * Quit. None of macOS's Services, Hide, Minimize, Zoom or window list.
19
21
  */
22
+ function linuxMenuBar(appName) {
23
+ return [
24
+ {
25
+ label: 'File',
26
+ menuRole: 'file',
27
+ items: [
28
+ item('Close Window', 'close', 'mod+w'),
29
+ SEPARATOR,
30
+ item('Print...', 'print', 'mod+p'),
31
+ ],
32
+ },
33
+ {
34
+ label: 'Edit',
35
+ menuRole: 'edit',
36
+ items: [
37
+ item('Undo', 'undo', 'mod+z'),
38
+ item('Redo', 'redo', 'mod+shift+z'),
39
+ SEPARATOR,
40
+ item('Cut', 'cut', 'mod+x'),
41
+ item('Copy', 'copy', 'mod+c'),
42
+ item('Paste', 'paste', 'mod+v'),
43
+ item('Select All', 'selectAll', 'mod+a'),
44
+ SEPARATOR,
45
+ item('Find', 'find', 'mod+f'),
46
+ ],
47
+ },
48
+ {
49
+ label: 'View',
50
+ menuRole: 'view',
51
+ items: [
52
+ item('Back', 'back'),
53
+ item('Forward', 'forward'),
54
+ SEPARATOR,
55
+ item('Show Sidebar', 'toggleSidebar', 'F9'),
56
+ item('Full Screen', 'toggleFullScreen', 'F11'),
57
+ ],
58
+ },
59
+ {
60
+ label: appName,
61
+ menuRole: 'app',
62
+ items: [
63
+ item('Preferences', 'settings', 'mod+,'),
64
+ item('Keyboard Shortcuts', 'keyboardShortcuts', 'mod+shift+?'),
65
+ item('Help', 'help', 'F1'),
66
+ SEPARATOR,
67
+ item(`About ${appName}`, 'about'),
68
+ SEPARATOR,
69
+ item('Quit', 'quit', 'mod+q'),
70
+ ],
71
+ },
72
+ ];
73
+ }
20
74
  /**
21
75
  * The groups of a merged menu bar (`mergeMenuBar`) that have no `menuRole` and are named as one
22
76
  * of the default menus is: each is drawn as a second menu of that name beside the default one,
@@ -28,8 +82,15 @@ export function unmergedGroups(defaults, merged) {
28
82
  .filter((group) => !group.menuRole && named.has(group.label.toLowerCase()))
29
83
  .map((group) => group.label);
30
84
  }
31
- export function defaultMenuBar(appName) {
32
- const item = (label, menuRole, shortcut) => shortcut ? { label, menuRole, shortcut } : { label, menuRole };
85
+ /**
86
+ * The menu bar every desktop app gets on `os`. On macOS: App, File, Edit, View, Window and Help,
87
+ * each item with its role and standard shortcut. `Settings...` is in it until the merge, which
88
+ * keeps it only when the app gives it a handler. File holds Print... (`mod+p`), which prints the
89
+ * key window unless the app gives a `print` item a handler. On Linux: linuxMenuBar's.
90
+ */
91
+ export function defaultMenuBar(appName, os = 'macos') {
92
+ if (os === 'linux')
93
+ return linuxMenuBar(appName);
33
94
  return [
34
95
  {
35
96
  label: appName,
@@ -174,7 +235,8 @@ function takeClose(groups) {
174
235
  *
175
236
  * - An app item with a `menuRole` replaces the default item with that role, where the default is,
176
237
  * and leaves the group it was written in.
177
- * - `Settings...` shows only when the app gives a `settings` item a handler.
238
+ * - `Settings...` (Preferences on Linux) and Linux's Help show only when the app gives a `settings`
239
+ * or `help` item a handler.
178
240
  * - A group whose `menuRole` names a default menu adds its items to the end of that menu; a `file`
179
241
  * group's go before Print..., which stays last, as on a Mac.
180
242
  * - A `file` group with no default File menu goes after the App menu, and any other group after
@@ -185,7 +247,8 @@ function takeClose(groups) {
185
247
  export function mergeMenuBar(defaults, app) {
186
248
  const replacing = byRole(app);
187
249
  const defaultRoles = byRole(defaults);
188
- const settings = replacing.get('settings');
250
+ // Preferences (Settings... on macOS) and Help show only with the app's handler: the OS has none.
251
+ const handled = (role) => Boolean(replacing.get(role)?.select);
189
252
  const replace = (entries) => entries.map((entry) => {
190
253
  if (isSeparator(entry))
191
254
  return entry;
@@ -196,7 +259,7 @@ export function mergeMenuBar(defaults, app) {
196
259
  });
197
260
  const merged = defaults.map((group) => ({
198
261
  ...group,
199
- items: tidy(replace(group.items), (item) => item.menuRole === 'settings' && !settings?.select),
262
+ items: tidy(replace(group.items), (item) => (item.menuRole === 'settings' || item.menuRole === 'help') && !handled(item.menuRole)),
200
263
  }));
201
264
  const moved = (item) => Boolean(item.menuRole && defaultRoles.has(item.menuRole));
202
265
  const defaultFile = merged.find((group) => group.menuRole === 'file');