@legendapp/spark 0.0.1-next.6 → 0.0.1-next.8

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 (128) hide show
  1. package/package.json +8 -8
  2. package/schema.json +9 -0
  3. package/skills/spark/SKILL.md +1 -1
  4. package/skills/spark/UPGRADING.md +37 -0
  5. package/vendor/node_modules/@legendapp/spark-ai/package.json +3 -3
  6. package/vendor/node_modules/@legendapp/spark-audio/package.json +2 -2
  7. package/vendor/node_modules/@legendapp/spark-auth-session/package.json +3 -3
  8. package/vendor/node_modules/@legendapp/spark-cli/dist/add-desktop.js +1 -1
  9. package/vendor/node_modules/@legendapp/spark-cli/dist/build.js +16 -4
  10. package/vendor/node_modules/@legendapp/spark-cli/dist/create.js +16 -4
  11. package/vendor/node_modules/@legendapp/spark-cli/dist/credentials.js +2 -2
  12. package/vendor/node_modules/@legendapp/spark-cli/dist/init-template.cjs +2 -1
  13. package/vendor/node_modules/@legendapp/spark-cli/dist/macos-release.js +4 -0
  14. package/vendor/node_modules/@legendapp/spark-cli/dist/project.js +10 -4
  15. package/vendor/node_modules/@legendapp/spark-cli/dist/release-driver.js +35 -0
  16. package/vendor/node_modules/@legendapp/spark-cli/dist/release.json +18 -18
  17. package/vendor/node_modules/@legendapp/spark-cli/dist/updates.js +18 -8
  18. package/vendor/node_modules/@legendapp/spark-cli/dist/windows.js +1 -1
  19. package/vendor/node_modules/@legendapp/spark-cli/package.json +4 -4
  20. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/app.json +5 -1
  21. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/gitignore +2 -1
  22. package/vendor/node_modules/@legendapp/spark-cli/templates/blank-typescript/package.json +7 -7
  23. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/app.json +5 -1
  24. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/gitignore +2 -1
  25. package/vendor/node_modules/@legendapp/spark-cli/templates/universal/package.json +8 -8
  26. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/app.json +5 -1
  27. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/gitignore +2 -1
  28. package/vendor/node_modules/@legendapp/spark-cli/templates/windows/package.json +8 -8
  29. package/vendor/node_modules/@legendapp/spark-clipboard/package.json +2 -2
  30. package/vendor/node_modules/@legendapp/spark-codex/cpp/HybridCodexAppServer.mm +88 -76
  31. package/vendor/node_modules/@legendapp/spark-codex/package.json +2 -2
  32. package/vendor/node_modules/@legendapp/spark-commands/package.json +5 -5
  33. package/vendor/node_modules/@legendapp/spark-context-menu/package.json +2 -2
  34. package/vendor/node_modules/@legendapp/spark-desktop-app/RNDesktopApp.podspec +12 -1
  35. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/RNDesktopApp.mm +8 -1
  36. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/SparkDesktop.h +8 -0
  37. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/SparkDesktop.mm +84 -21
  38. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/SparkInstance.h +27 -0
  39. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/SparkInstance.mm +207 -0
  40. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/SparkTestDriver.h +44 -0
  41. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/SparkTestDriver.mm +349 -0
  42. package/vendor/node_modules/@legendapp/spark-desktop-app/macos/SparkWindow.mm +3 -1
  43. package/vendor/node_modules/@legendapp/spark-desktop-app/package.json +1 -1
  44. package/vendor/node_modules/@legendapp/spark-desktop-app/src/api.ts +39 -6
  45. package/vendor/node_modules/@legendapp/spark-desktop-app/src/contracts/menu.ts +21 -7
  46. package/vendor/node_modules/@legendapp/spark-desktop-config/accessibility-state.cjs +50 -0
  47. package/vendor/node_modules/@legendapp/spark-desktop-config/app.plugin.cjs +9 -1
  48. package/vendor/node_modules/@legendapp/spark-desktop-config/autolinking.cjs +8 -1
  49. package/vendor/node_modules/@legendapp/spark-desktop-config/config.cjs +1 -1
  50. package/vendor/node_modules/@legendapp/spark-desktop-config/config.d.cts +7 -1
  51. package/vendor/node_modules/@legendapp/spark-desktop-config/package.json +4 -4
  52. package/vendor/node_modules/@legendapp/spark-desktop-config/rtl-scroll-view.cjs +144 -0
  53. package/vendor/node_modules/@legendapp/spark-desktop-config/rtl-text-alignment.cjs +60 -0
  54. package/vendor/node_modules/@legendapp/spark-desktop-config/rtl-text-input-alignment.cjs +112 -0
  55. package/vendor/node_modules/@legendapp/spark-desktop-config/schema.json +9 -0
  56. package/vendor/node_modules/@legendapp/spark-desktop-config/test-driver.cjs +11 -0
  57. package/vendor/node_modules/@legendapp/spark-desktop-config/test-driver.d.cts +2 -0
  58. package/vendor/node_modules/@legendapp/spark-desktop-config/text-input-accessibility.cjs +47 -0
  59. package/vendor/node_modules/@legendapp/spark-desktop-config/updates.cjs +4 -2
  60. package/vendor/node_modules/@legendapp/spark-desktop-config/validation.cjs +2 -1
  61. package/vendor/node_modules/@legendapp/spark-desktop-config/windows.plugin.cjs +1 -1
  62. package/vendor/node_modules/@legendapp/spark-desktop-host/AppDelegate.mm +18 -6
  63. package/vendor/node_modules/@legendapp/spark-desktop-host/package.json +2 -2
  64. package/vendor/node_modules/@legendapp/spark-desktop-host/windows/application.inc +61 -15
  65. package/vendor/node_modules/@legendapp/spark-desktop-host/windows/launch.inc +67 -0
  66. package/vendor/node_modules/@legendapp/spark-desktop-links/package.json +2 -2
  67. package/vendor/node_modules/@legendapp/spark-desktop-shortcuts/package.json +2 -2
  68. package/vendor/node_modules/@legendapp/spark-desktop-windows/RNDesktopWindows.podspec +3 -0
  69. package/vendor/node_modules/@legendapp/spark-desktop-windows/macos/RNDesktopWindows.mm +5 -2
  70. package/vendor/node_modules/@legendapp/spark-desktop-windows/macos/window-manager/RNWindowManager.mm +22 -3
  71. package/vendor/node_modules/@legendapp/spark-desktop-windows/package.json +3 -3
  72. package/vendor/node_modules/@legendapp/spark-documents/package.json +7 -7
  73. package/vendor/node_modules/@legendapp/spark-drag-drop/package.json +2 -2
  74. package/vendor/node_modules/@legendapp/spark-file-dialog/RNFileDialog.podspec +1 -0
  75. package/vendor/node_modules/@legendapp/spark-file-dialog/ios/RNFileDialog.mm +153 -64
  76. package/vendor/node_modules/@legendapp/spark-file-dialog/package.json +2 -2
  77. package/vendor/node_modules/@legendapp/spark-file-dialog/src/index.ts +19 -7
  78. package/vendor/node_modules/@legendapp/spark-file-dialog/src/native.ts +5 -1
  79. package/vendor/node_modules/@legendapp/spark-file-dialog/src/options.ts +42 -4
  80. package/vendor/node_modules/@legendapp/spark-file-dialog/src/types.ts +18 -2
  81. package/vendor/node_modules/@legendapp/spark-file-system/package.json +2 -2
  82. package/vendor/node_modules/@legendapp/spark-global-shortcuts/package.json +2 -2
  83. package/vendor/node_modules/@legendapp/spark-html/package.json +2 -2
  84. package/vendor/node_modules/@legendapp/spark-markdown/package.json +2 -2
  85. package/vendor/node_modules/@legendapp/spark-markdown/src/Markdown.tsx +2 -1
  86. package/vendor/node_modules/@legendapp/spark-message-dialog/macos/RNDesktopMessageDialog.mm +113 -12
  87. package/vendor/node_modules/@legendapp/spark-message-dialog/package.json +2 -2
  88. package/vendor/node_modules/@legendapp/spark-message-dialog/src/index.ts +110 -14
  89. package/vendor/node_modules/@legendapp/spark-native-menu/ios/RNNativeMenu.mm +116 -8
  90. package/vendor/node_modules/@legendapp/spark-native-menu/package.json +2 -2
  91. package/vendor/node_modules/@legendapp/spark-native-menu/src/api.ts +63 -18
  92. package/vendor/node_modules/@legendapp/spark-native-menu/src/hooks.ts +9 -3
  93. package/vendor/node_modules/@legendapp/spark-notifications/package.json +2 -2
  94. package/vendor/node_modules/@legendapp/spark-processes/package.json +2 -2
  95. package/vendor/node_modules/@legendapp/spark-rich-text/package.json +2 -2
  96. package/vendor/node_modules/@legendapp/spark-secure-storage/package.json +2 -2
  97. package/vendor/node_modules/@legendapp/spark-settings/package.json +3 -3
  98. package/vendor/node_modules/@legendapp/spark-settings-ui/package.json +4 -4
  99. package/vendor/node_modules/@legendapp/spark-settings-ui/src/index.tsx +5 -2
  100. package/vendor/node_modules/@legendapp/spark-sqlite/package.json +3 -3
  101. package/vendor/node_modules/@legendapp/spark-system/macos/RNDesktopSystem.mm +13 -3
  102. package/vendor/node_modules/@legendapp/spark-system/macos/SparkAppearancePreferences.h +9 -0
  103. package/vendor/node_modules/@legendapp/spark-system/macos/SparkAppearancePreferences.mm +31 -0
  104. package/vendor/node_modules/@legendapp/spark-system/macos/SparkDockTile.h +24 -0
  105. package/vendor/node_modules/@legendapp/spark-system/macos/SparkDockTile.mm +101 -0
  106. package/vendor/node_modules/@legendapp/spark-system/package.json +2 -2
  107. package/vendor/node_modules/@legendapp/spark-system/src/index.ts +73 -7
  108. package/vendor/node_modules/@legendapp/spark-tray/package.json +2 -2
  109. package/vendor/node_modules/@legendapp/spark-ui/macos/RNSparkButton.mm +2 -0
  110. package/vendor/node_modules/@legendapp/spark-ui/macos/RNSparkLayoutDirection.h +17 -0
  111. package/vendor/node_modules/@legendapp/spark-ui/macos/RNSparkTextInput.mm +6 -1
  112. package/vendor/node_modules/@legendapp/spark-ui/macos/appkit-split-view/RNSidebarSplitViewComponent.mm +55 -8
  113. package/vendor/node_modules/@legendapp/spark-ui/macos/glass-effect-view/RNGlassEffectView.mm +11 -7
  114. package/vendor/node_modules/@legendapp/spark-ui/macos/native-select/RNNativeSegmentedControl.mm +4 -0
  115. package/vendor/node_modules/@legendapp/spark-ui/macos/native-select/RNNativeSelect.mm +4 -0
  116. package/vendor/node_modules/@legendapp/spark-ui/macos/sf-symbol/RNSFSymbol.mm +4 -0
  117. package/vendor/node_modules/@legendapp/spark-ui/macos/sidebar/RNSidebar.mm +77 -14
  118. package/vendor/node_modules/@legendapp/spark-ui/macos/swipe-actions/RNSwipeActions.mm +31 -7
  119. package/vendor/node_modules/@legendapp/spark-ui/macos/text-input-search/RNTextInputSearch.mm +25 -1
  120. package/vendor/node_modules/@legendapp/spark-ui/package.json +2 -2
  121. package/vendor/node_modules/@legendapp/spark-ui/src/sidebar/SidebarNativeComponent.ts +5 -0
  122. package/vendor/node_modules/@legendapp/spark-ui/src/sidebar/index.tsx +19 -8
  123. package/vendor/node_modules/@legendapp/spark-updates/macos/RNDesktopUpdates.mm +25 -13
  124. package/vendor/node_modules/@legendapp/spark-updates/macos/SparkUpdateState.h +39 -0
  125. package/vendor/node_modules/@legendapp/spark-updates/package.json +2 -2
  126. package/vendor/node_modules/@legendapp/spark-updates/src/index.ts +45 -9
  127. package/vendor/node_modules/@legendapp/spark-webview/package.json +2 -2
  128. package/vendor/node_modules/@legendapp/spark-window-options/package.json +1 -1
@@ -2,35 +2,136 @@
2
2
  #import <RNDesktopApp/SparkDesktop.h>
3
3
  @interface RNDesktopMessageDialog ()
4
4
  @property NSAlert *alert;
5
+ @property NSPanel *aboutPanel;
6
+ - (NSPanel *)configureAboutPanel:(NSDictionary *)options;
7
+ + (NSAlert *)alertWithArgs:(NSDictionary *)args;
8
+ + (NSDictionary *)aboutPanelOptions:(NSDictionary *)args code:(NSString **)code message:(NSString **)message;
5
9
  @end
6
10
  @implementation RNDesktopMessageDialog
7
11
  RCT_EXPORT_MODULE(NativeDesktopMessageDialog)
12
+ // Configures the alert without presenting it, so native tests can inspect and render it.
13
+ + (NSAlert *)alertWithArgs:(NSDictionary *)args {
14
+ NSAlert *alert = [NSAlert new];
15
+ alert.messageText = args[@"title"]; alert.informativeText = args[@"message"] ?: @"";
16
+ alert.alertStyle = [args[@"kind"] isEqual:@"error"] ? NSAlertStyleCritical : [args[@"kind"] isEqual:@"warning"] ? NSAlertStyleWarning : NSAlertStyleInformational;
17
+ for (NSString *title in args[@"buttons"]) [alert addButtonWithTitle:title];
18
+ for (NSButton *button in alert.buttons) button.keyEquivalent = @"";
19
+ NSUInteger defaultButton = [args[@"defaultButton"] unsignedIntegerValue];
20
+ if (defaultButton < alert.buttons.count) alert.buttons[defaultButton].keyEquivalent = @"\r";
21
+ if (args[@"cancelButton"] && [args[@"cancelButton"] unsignedIntegerValue] < alert.buttons.count) alert.buttons[[args[@"cancelButton"] unsignedIntegerValue]].keyEquivalent = @"\033";
22
+ if (args[@"checkbox"]) { alert.showsSuppressionButton = YES; alert.suppressionButton.title = args[@"checkbox"][@"label"]; alert.suppressionButton.state = [args[@"checkbox"][@"checked"] boolValue] ? NSControlStateValueOn : NSControlStateValueOff; }
23
+ if (NSDictionary *input = args[@"input"]) {
24
+ NSTextField *field = [input[@"secure"] boolValue] ? [[NSSecureTextField alloc] initWithFrame:NSMakeRect(0, 0, 260, 22)] : [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 260, 22)];
25
+ field.stringValue = input[@"defaultValue"] ?: @"";
26
+ if ([input[@"placeholder"] isKindOfClass:NSString.class]) field.placeholderString = input[@"placeholder"];
27
+ field.accessibilityLabel = args[@"title"];
28
+ alert.accessoryView = field;
29
+ alert.window.initialFirstResponder = field;
30
+ }
31
+ return alert;
32
+ }
33
+ // Maps Spark's About options onto AppKit's keys; omitted keys keep the bundle's values.
34
+ + (NSDictionary *)aboutPanelOptions:(NSDictionary *)args code:(NSString **)code message:(NSString **)message {
35
+ NSMutableDictionary *options = [NSMutableDictionary new];
36
+ if (args[@"name"]) options[NSAboutPanelOptionApplicationName] = args[@"name"];
37
+ if (args[@"version"]) options[NSAboutPanelOptionApplicationVersion] = args[@"version"];
38
+ if (args[@"build"]) options[NSAboutPanelOptionVersion] = args[@"build"];
39
+ if (args[@"copyright"]) options[@"Copyright"] = args[@"copyright"];
40
+ if (args[@"credits"]) {
41
+ NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new]; paragraph.alignment = NSTextAlignmentCenter;
42
+ options[NSAboutPanelOptionCredits] = [[NSAttributedString alloc] initWithString:args[@"credits"] attributes:@{ NSFontAttributeName: [NSFont systemFontOfSize:NSFont.smallSystemFontSize], NSForegroundColorAttributeName: NSColor.labelColor, NSParagraphStyleAttributeName: paragraph }];
43
+ }
44
+ if (NSString *path = args[@"iconPath"]) {
45
+ if (![NSFileManager.defaultManager fileExistsAtPath:path]) { *code = @"E_NOT_FOUND"; *message = @"About panel icon does not exist"; return nil; }
46
+ NSImage *icon = [[NSImage alloc] initWithContentsOfFile:path];
47
+ if (!icon) { *code = @"E_INVALID_DATA"; *message = @"About panel icon is not a readable image"; return nil; }
48
+ options[NSAboutPanelOptionApplicationIcon] = icon;
49
+ }
50
+ return options;
51
+ }
52
+ - (NSPanel *)configureAboutPanel:(NSDictionary *)options {
53
+ if (!self.aboutPanel) {
54
+ self.aboutPanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, 360, 280) styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable backing:NSBackingStoreBuffered defer:YES];
55
+ self.aboutPanel.releasedWhenClosed = NO;
56
+ [self.aboutPanel center];
57
+ }
58
+ NSDictionary *bundle = NSBundle.mainBundle.infoDictionary;
59
+ NSString *name = options[NSAboutPanelOptionApplicationName] ?: bundle[@"CFBundleDisplayName"] ?: bundle[@"CFBundleName"] ?: NSProcessInfo.processInfo.processName;
60
+ NSString *version = options[NSAboutPanelOptionApplicationVersion] ?: bundle[@"CFBundleShortVersionString"] ?: @"";
61
+ NSString *build = options[NSAboutPanelOptionVersion] ?: bundle[@"CFBundleVersion"] ?: @"";
62
+ NSString *versionLine = version.length ? [@"Version " stringByAppendingString:version] : @"";
63
+ if (build.length) versionLine = [versionLine stringByAppendingFormat:version.length ? @" (%@)" : @"Version %@", build];
64
+ NSString *copyright = options[@"Copyright"] ?: bundle[@"NSHumanReadableCopyright"] ?: @"";
65
+ NSAttributedString *credits = options[NSAboutPanelOptionCredits];
66
+ if (!credits) for (NSString *extension in @[@"rtf", @"html", @"rtfd"]) {
67
+ NSURL *url = [NSBundle.mainBundle URLForResource:@"Credits" withExtension:extension];
68
+ if (url) { credits = [[NSAttributedString alloc] initWithURL:url options:@{} documentAttributes:nil error:nil]; break; }
69
+ }
70
+ NSImageView *icon = [NSImageView imageViewWithImage:options[NSAboutPanelOptionApplicationIcon] ?: NSApp.applicationIconImage];
71
+ icon.imageScaling = NSImageScaleProportionallyUpOrDown;
72
+ [icon.widthAnchor constraintEqualToConstant:64].active = YES;
73
+ [icon.heightAnchor constraintEqualToConstant:64].active = YES;
74
+ NSTextField *title = [NSTextField wrappingLabelWithString:name]; title.font = [NSFont boldSystemFontOfSize:20];
75
+ NSTextField *detail = [NSTextField wrappingLabelWithString:versionLine];
76
+ NSTextView *credit = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, 312, 120)];
77
+ credit.editable = NO; credit.drawsBackground = NO; credit.verticallyResizable = YES;
78
+ credit.maxSize = NSMakeSize(312, CGFLOAT_MAX);
79
+ credit.textContainer.containerSize = NSMakeSize(312, CGFLOAT_MAX);
80
+ credit.textContainer.widthTracksTextView = YES;
81
+ if (credits) {
82
+ NSMutableAttributedString *text = [credits mutableCopy];
83
+ [credits enumerateAttribute:NSForegroundColorAttributeName inRange:NSMakeRange(0, credits.length) options:0 usingBlock:^(id color, NSRange range, BOOL *) {
84
+ if (!color) [text addAttribute:NSForegroundColorAttributeName value:NSColor.labelColor range:range];
85
+ }];
86
+ [credit.textStorage setAttributedString:text];
87
+ }
88
+ NSScrollView *creditScroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(0, 0, 312, 120)];
89
+ creditScroll.drawsBackground = NO; creditScroll.hasVerticalScroller = YES; creditScroll.documentView = credit;
90
+ [creditScroll.widthAnchor constraintEqualToConstant:312].active = YES;
91
+ [creditScroll.heightAnchor constraintEqualToConstant:120].active = YES;
92
+ creditScroll.hidden = !credits.length;
93
+ NSTextField *legal = [NSTextField wrappingLabelWithString:copyright]; legal.font = [NSFont systemFontOfSize:NSFont.smallSystemFontSize];
94
+ NSStackView *stack = [NSStackView stackViewWithViews:@[icon, title, detail, creditScroll, legal]];
95
+ stack.orientation = NSUserInterfaceLayoutOrientationVertical; stack.alignment = NSLayoutAttributeCenterX; stack.spacing = 12;
96
+ stack.edgeInsets = NSEdgeInsetsMake(24, 24, 24, 24);
97
+ for (NSTextField *label in @[title, detail, legal]) {
98
+ label.alignment = NSTextAlignmentCenter; label.selectable = YES;
99
+ [label.widthAnchor constraintEqualToConstant:312].active = YES;
100
+ label.hidden = !label.stringValue.length;
101
+ }
102
+ self.aboutPanel.title = name;
103
+ self.aboutPanel.contentView = stack;
104
+ [self.aboutPanel setContentSize:NSMakeSize(360, stack.fittingSize.height)];
105
+ return self.aboutPanel;
106
+ }
8
107
  - (void)call:(NSString *)method args:(NSString *)json resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
9
108
  [NSRunLoop.mainRunLoop performBlock:^{
109
+ NSDictionary *args = SparkArgs(json);
110
+ if ([method isEqual:@"about"]) {
111
+ NSString *code = nil, *message = nil;
112
+ NSDictionary *options = [RNDesktopMessageDialog aboutPanelOptions:args code:&code message:&message];
113
+ if (!options) { reject(code, message, nil); return; }
114
+ [[self configureAboutPanel:options] makeKeyAndOrderFront:nil];
115
+ resolve(@"null"); return;
116
+ }
10
117
  if (![method isEqual:@"show"]) { SparkInvalid(reject, @"Unknown dialog operation"); return; }
11
118
  if (self.alert) { reject(@"E_BUSY", @"A message dialog is already open", nil); return; }
12
- NSDictionary *args = SparkArgs(json); NSWindow *parent = nil;
119
+ NSWindow *parent = nil;
13
120
  if (args[@"windowId"]) {
14
121
  for (NSWindow *window in NSApp.windows) if ([window.identifier isEqual:args[@"windowId"]] || [window.identifier isEqual:[@"spark." stringByAppendingString:args[@"windowId"]]]) { parent = window; break; }
15
122
  if (!parent) { reject(@"E_NOT_FOUND", @"Dialog parent does not exist", nil); return; }
16
123
  if (parent.attachedSheet) { reject(@"E_BUSY", @"Parent already has a sheet", nil); return; }
17
124
  }
18
- NSAlert *alert = [NSAlert new]; self.alert = alert;
19
- alert.messageText = args[@"title"]; alert.informativeText = args[@"message"] ?: @"";
20
- alert.alertStyle = [args[@"kind"] isEqual:@"error"] ? NSAlertStyleCritical : [args[@"kind"] isEqual:@"warning"] ? NSAlertStyleWarning : NSAlertStyleInformational;
21
- for (NSString *title in args[@"buttons"]) [alert addButtonWithTitle:title];
22
- for (NSButton *button in alert.buttons) button.keyEquivalent = @"";
23
- NSUInteger defaultButton = [args[@"defaultButton"] unsignedIntegerValue];
24
- if (defaultButton < alert.buttons.count) alert.buttons[defaultButton].keyEquivalent = @"\r";
25
- if (args[@"cancelButton"] && [args[@"cancelButton"] unsignedIntegerValue] < alert.buttons.count) alert.buttons[[args[@"cancelButton"] unsignedIntegerValue]].keyEquivalent = @"\033";
26
- if (args[@"checkbox"]) { alert.showsSuppressionButton = YES; alert.suppressionButton.title = args[@"checkbox"][@"label"]; alert.suppressionButton.state = [args[@"checkbox"][@"checked"] boolValue] ? NSControlStateValueOn : NSControlStateValueOff; }
125
+ NSAlert *alert = [RNDesktopMessageDialog alertWithArgs:args]; self.alert = alert;
27
126
  void (^complete)(NSModalResponse) = ^(NSModalResponse response) {
28
127
  self.alert = nil;
29
- resolve(SparkJSON(@{ @"button": @(response >= NSAlertFirstButtonReturn ? response - NSAlertFirstButtonReturn : -1), @"checked": @(alert.suppressionButton.state == NSControlStateValueOn) }));
128
+ NSMutableDictionary *result = [@{ @"button": @(response >= NSAlertFirstButtonReturn ? response - NSAlertFirstButtonReturn : -1), @"checked": @(alert.suppressionButton.state == NSControlStateValueOn) } mutableCopy];
129
+ if (args[@"input"]) result[@"value"] = ((NSTextField *)alert.accessoryView).stringValue;
130
+ resolve(SparkJSON(result));
30
131
  };
31
132
  if (parent) [alert beginSheetModalForWindow:parent completionHandler:complete]; else complete([alert runModal]);
32
133
  }];
33
134
  }
34
- - (void)invalidate { [NSRunLoop.mainRunLoop performBlock:^{ if (self.alert.window.sheetParent) [self.alert.window.sheetParent endSheet:self.alert.window returnCode:NSModalResponseCancel]; else if (self.alert) [NSApp abortModal]; [self.alert.window orderOut:nil]; self.alert = nil; }]; }
135
+ - (void)invalidate { [NSRunLoop.mainRunLoop performBlock:^{ if (self.alert.window.sheetParent) [self.alert.window.sheetParent endSheet:self.alert.window returnCode:NSModalResponseCancel]; else if (self.alert) [NSApp abortModal]; [self.alert.window orderOut:nil]; self.alert = nil; [self.aboutPanel close]; self.aboutPanel = nil; }]; }
35
136
  - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params { return std::make_shared<facebook::react::NativeDesktopMessageDialogSpecJSI>(params); }
36
137
  @end
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@legendapp/spark-message-dialog",
3
- "version": "0.0.1-next.6",
3
+ "version": "0.0.1-next.8",
4
4
  "license": "MIT",
5
5
  "main": "src/index.ts",
6
6
  "react-native": "src/index.ts",
@@ -40,7 +40,7 @@
40
40
  ]
41
41
  },
42
42
  "dependencies": {
43
- "@legendapp/spark-desktop-app": "0.0.1-next.6"
43
+ "@legendapp/spark-desktop-app": "0.0.1-next.8"
44
44
  },
45
45
  "private": true
46
46
  }
@@ -1,5 +1,6 @@
1
1
  import { Platform } from "react-native";
2
2
  import { SparkError, parseNativeResult, invokeNative, type Availability } from "@legendapp/spark-desktop-app/src/contracts";
3
+ import { nativePath } from "@legendapp/spark-desktop-app/src/contracts/path";
3
4
  import Native from "./NativeDesktopMessageDialog";
4
5
  export interface MessageDialogButton { id: string; label: string }
5
6
  export interface MessageDialogOptions {
@@ -10,6 +11,7 @@ export interface MessageDialogOptions {
10
11
  defaultButtonId?: string;
11
12
  cancelButtonId?: string;
12
13
  windowId?: string;
14
+ /** A "Don't ask again" style checkbox. Its final state returns as `checked`; persisting it is the caller's choice. */
13
15
  checkbox?: { label: string; checked?: boolean };
14
16
  }
15
17
  export interface MessageDialogResult {
@@ -18,33 +20,127 @@ export interface MessageDialogResult {
18
20
  /** The checkbox's final state; present only when options.checkbox was supplied. */
19
21
  checked?: boolean;
20
22
  }
21
- export interface ConfirmOptions { title?: string; windowId?: string }
22
- export function getMessageDialogAvailability(): Availability {
23
+ export interface ConfirmOptions {
24
+ title?: string;
25
+ windowId?: string;
26
+ /** Defaults to "Continue"; pass a localized label for localized apps. */
27
+ confirmLabel?: string;
28
+ /** Defaults to "Cancel"; pass a localized label for localized apps. */
29
+ cancelLabel?: string;
30
+ }
31
+ export interface PromptOptions {
32
+ title: string;
33
+ message?: string;
34
+ placeholder?: string;
35
+ /** Initial text, selected when the dialog opens. */
36
+ defaultValue?: string;
37
+ /** Masks the text and keeps it out of the clipboard (NSSecureTextField). */
38
+ secure?: boolean;
39
+ /** Defaults to "OK"; pass a localized label for localized apps. */
40
+ confirmLabel?: string;
41
+ /** Defaults to "Cancel"; pass a localized label for localized apps. */
42
+ cancelLabel?: string;
43
+ windowId?: string;
44
+ }
45
+ /** Cancel, Escape and host dismissal all resolve `{ canceled: true }`; an empty confirmed value is `""`. */
46
+ export type PromptResult = { canceled: true } | { canceled: false; value: string };
47
+ /** Overrides for the native About panel. Omitted fields use the app bundle's values. */
48
+ export interface AboutPanelOptions {
49
+ name?: string;
50
+ /** The marketing version, shown as "Version <version>". */
51
+ version?: string;
52
+ /** The build, shown in parentheses after the version. */
53
+ build?: string;
54
+ /** Plain text shown in the scrolling credits area. */
55
+ credits?: string;
56
+ copyright?: string;
57
+ /** Absolute path of an image file (PNG, ICNS, …) shown instead of the app icon. */
58
+ iconPath?: string;
59
+ }
60
+ /** Features beyond plain message dialogs, for `getMessageDialogAvailability(feature)`. */
61
+ export type MessageDialogFeature = "checkbox" | "prompt" | "aboutPanel";
62
+ const FEATURES: readonly MessageDialogFeature[] = ["checkbox", "prompt", "aboutPanel"];
63
+
64
+ /** Without a feature, reports message dialogs. Windows supports the checkbox; prompts and the About panel are macOS-only. */
65
+ export function getMessageDialogAvailability(feature?: MessageDialogFeature): Availability {
66
+ if (feature !== undefined && !FEATURES.includes(feature)) throw new SparkError("E_INVALID_ARGUMENT", "Unknown message dialog feature");
23
67
  if (Platform.OS !== "macos" && Platform.OS !== "windows") return { available: false, reason: "unsupported-platform" };
68
+ if (Platform.OS === "windows" && (feature === "prompt" || feature === "aboutPanel")) return { available: false, reason: "unsupported-platform" };
24
69
  return Native ? { available: true } : { available: false, reason: "missing-module" };
25
70
  }
71
+ function requireAvailable(feature?: MessageDialogFeature) {
72
+ const availability = getMessageDialogAvailability(feature);
73
+ if (!availability.available) throw new SparkError(availability.reason === "unsupported-platform" ? "E_UNSUPPORTED_PLATFORM" : "E_MODULE_UNAVAILABLE", `${feature === "aboutPanel" ? "The About panel" : feature === "prompt" ? "Text prompts" : "Message dialogs"} require ${feature ? "macOS" : "a desktop host"} with NativeDesktopMessageDialog installed`);
74
+ }
75
+ const validString = (value: unknown): value is string => typeof value === "string" && !!value.trim() && !value.includes("\0");
76
+ function knownKeys(options: object, allowed: readonly string[], what: string) {
77
+ if (!options || typeof options !== "object" || Array.isArray(options)) throw new SparkError("E_INVALID_ARGUMENT", `Expected ${what} options`);
78
+ for (const key of Object.keys(options)) if (!allowed.includes(key)) throw new SparkError("E_UNSUPPORTED_OPTION", `Unsupported ${what} option: ${key}`);
79
+ }
80
+ function optionalString(options: Record<string, unknown>, keys: readonly string[], allowEmpty = false) {
81
+ for (const key of keys) {
82
+ const value = options[key];
83
+ if (value !== undefined && (typeof value !== "string" || value.includes("\0") || (!allowEmpty && !value.trim()))) throw new SparkError("E_INVALID_ARGUMENT", `${key} must be a ${allowEmpty ? "" : "non-empty "}string without NUL characters`);
84
+ }
85
+ }
86
+ function validWindowId(windowId: unknown) {
87
+ if (windowId !== undefined && (typeof windowId !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(windowId))) throw new SparkError("E_INVALID_ARGUMENT", "Invalid owner window ID");
88
+ }
89
+
90
+ type NativeAlertResult = { button: number; checked: boolean; value?: string };
91
+ async function showAlert(wire: Record<string, unknown>, buttonCount: number, input: boolean): Promise<NativeAlertResult> {
92
+ return parseNativeResult(await invokeNative(() => Native!.call("show", JSON.stringify(wire))), (value): value is NativeAlertResult => {
93
+ if (!value || typeof value !== "object") return false;
94
+ const result = value as Record<string, unknown>;
95
+ return Number.isInteger(result.button) && (result.button as number) >= -1 && (result.button as number) < buttonCount && typeof result.checked === "boolean" && (input ? typeof result.value === "string" : !("value" in result));
96
+ });
97
+ }
98
+
26
99
  export async function showMessage(options: MessageDialogOptions): Promise<MessageDialogResult> {
27
- if (!options || typeof options !== "object") throw new SparkError("E_INVALID_ARGUMENT", "Expected message dialog options");
28
- for (const key of Object.keys(options)) if (!["title", "message", "kind", "buttons", "defaultButtonId", "cancelButtonId", "windowId", "checkbox"].includes(key)) throw new SparkError("E_UNSUPPORTED_OPTION", `Unsupported dialog option: ${key}`);
100
+ knownKeys(options, ["title", "message", "kind", "buttons", "defaultButtonId", "cancelButtonId", "windowId", "checkbox"], "dialog");
29
101
  const buttons = options.buttons ?? [{ id: "ok", label: "OK" }];
30
- const validString = (value: unknown): value is string => typeof value === "string" && !!value && !value.includes("\0");
31
102
  if (!validString(options.title) || !Array.isArray(buttons) || !buttons.length || buttons.length > 4 || buttons.some(value => !value || !validString(value.id) || !validString(value.label))) throw new SparkError("E_INVALID_ARGUMENT", "Dialog needs a title and 1–4 buttons with IDs and labels");
32
103
  const ids = buttons.map(button => button.id);
33
104
  if (new Set(ids).size !== ids.length) throw new SparkError("E_INVALID_ARGUMENT", "Dialog button IDs must be unique");
34
105
  for (const id of [options.defaultButtonId, options.cancelButtonId]) if (id !== undefined && !ids.includes(id)) throw new SparkError("E_INVALID_ARGUMENT", "Dialog button ID must identify a button");
35
106
  if (options.kind !== undefined && !["info", "warning", "error"].includes(options.kind)) throw new SparkError("E_INVALID_ARGUMENT", "Invalid dialog kind");
36
- if (options.windowId !== undefined && (typeof options.windowId !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(options.windowId))) throw new SparkError("E_INVALID_ARGUMENT", "Invalid owner window ID");
107
+ validWindowId(options.windowId);
37
108
  if (options.message !== undefined && typeof options.message !== "string") throw new SparkError("E_INVALID_ARGUMENT", "message must be a string");
38
- if (options.checkbox !== undefined && (!options.checkbox || !validString(options.checkbox.label) || (options.checkbox.checked !== undefined && typeof options.checkbox.checked !== "boolean"))) throw new SparkError("E_INVALID_ARGUMENT", "Invalid checkbox options");
39
- const availability = getMessageDialogAvailability();
40
- if (!availability.available) throw new SparkError(availability.reason === "unsupported-platform" ? "E_UNSUPPORTED_PLATFORM" : "E_MODULE_UNAVAILABLE", "Message dialogs require a desktop host with NativeDesktopMessageDialog installed");
109
+ if (options.checkbox !== undefined && (!options.checkbox || typeof options.checkbox !== "object" || Object.keys(options.checkbox).some(key => key !== "label" && key !== "checked") || !validString(options.checkbox.label) || (options.checkbox.checked !== undefined && typeof options.checkbox.checked !== "boolean"))) throw new SparkError("E_INVALID_ARGUMENT", "Invalid checkbox options");
110
+ requireAvailable(options.checkbox ? "checkbox" : undefined);
41
111
  const { defaultButtonId, cancelButtonId, ...rest } = options;
42
- const result = parseNativeResult(await invokeNative(() => Native!.call("show", JSON.stringify({ ...rest, buttons: buttons.map(button => button.label), defaultButton: defaultButtonId === undefined ? 0 : ids.indexOf(defaultButtonId), cancelButton: cancelButtonId === undefined ? undefined : ids.indexOf(cancelButtonId) }))), (value): value is { button: number; checked: boolean } => !!value && typeof value === "object" && "button" in value && Number.isInteger(value.button) && (value.button as number) >= -1 && (value.button as number) < buttons.length && "checked" in value && typeof value.checked === "boolean");
43
- return { buttonId: result.button === -1 ? null : ids[result.button], ...(options.checkbox ? { checked: result.checked } : {}) };
112
+ const result = await showAlert({ ...rest, buttons: buttons.map(button => button.label), defaultButton: defaultButtonId === undefined ? 0 : ids.indexOf(defaultButtonId), cancelButton: cancelButtonId === undefined ? undefined : ids.indexOf(cancelButtonId) }, buttons.length, false);
113
+ return { buttonId: result.button === -1 ? null : ids[result.button]!, ...(options.checkbox ? { checked: result.checked } : {}) };
44
114
  }
115
+
45
116
  export async function confirm(message: string, options: ConfirmOptions = {}): Promise<boolean> {
46
- if (!options || typeof options !== "object" || Array.isArray(options)) throw new SparkError("E_INVALID_ARGUMENT", "Expected confirmation options");
47
- for (const key of Object.keys(options)) if (!["title", "windowId"].includes(key)) throw new SparkError("E_UNSUPPORTED_OPTION", `Unsupported confirmation option: ${key}`);
48
- const result = await showMessage({ title: options.title ?? "Confirm", message, windowId: options.windowId, buttons: [{ id: "cancel", label: "Cancel" }, { id: "continue", label: "Continue" }], defaultButtonId: "continue", cancelButtonId: "cancel" });
117
+ knownKeys(options, ["title", "windowId", "confirmLabel", "cancelLabel"], "confirmation");
118
+ const result = await showMessage({ title: options.title ?? "Confirm", message, windowId: options.windowId, buttons: [{ id: "cancel", label: options.cancelLabel ?? "Cancel" }, { id: "continue", label: options.confirmLabel ?? "Continue" }], defaultButtonId: "continue", cancelButtonId: "cancel" });
49
119
  return result.buttonId === "continue";
50
120
  }
121
+
122
+ /** A message dialog with one text field. Return confirms; Escape cancels. */
123
+ export async function showPrompt(options: PromptOptions): Promise<PromptResult> {
124
+ knownKeys(options, ["title", "message", "placeholder", "defaultValue", "secure", "confirmLabel", "cancelLabel", "windowId"], "prompt");
125
+ if (!validString(options.title)) throw new SparkError("E_INVALID_ARGUMENT", "Prompt needs a title");
126
+ optionalString(options as unknown as Record<string, unknown>, ["placeholder", "confirmLabel", "cancelLabel"]);
127
+ optionalString(options as unknown as Record<string, unknown>, ["message", "defaultValue"], true);
128
+ if (options.secure !== undefined && typeof options.secure !== "boolean") throw new SparkError("E_INVALID_ARGUMENT", "secure must be boolean");
129
+ validWindowId(options.windowId);
130
+ requireAvailable("prompt");
131
+ const result = await showAlert({
132
+ title: options.title, message: options.message, windowId: options.windowId,
133
+ buttons: [options.confirmLabel ?? "OK", options.cancelLabel ?? "Cancel"], defaultButton: 0, cancelButton: 1,
134
+ input: { placeholder: options.placeholder, defaultValue: options.defaultValue ?? "", secure: options.secure ?? false },
135
+ }, 2, true);
136
+ return result.button === 0 ? { canceled: false, value: result.value! } : { canceled: true };
137
+ }
138
+
139
+ /** Shows a native About panel on macOS. Calls update and reuse one panel, including after it is closed. Omitted fields use bundle values. It is not modal; the promise resolves once it is shown. */
140
+ export async function showAboutPanel(options: AboutPanelOptions = {}): Promise<void> {
141
+ knownKeys(options, ["name", "version", "build", "credits", "copyright", "iconPath"], "About panel");
142
+ optionalString(options as unknown as Record<string, unknown>, ["name", "version", "build", "credits", "copyright", "iconPath"]);
143
+ const wire = { ...options, iconPath: options.iconPath === undefined ? undefined : nativePath(options.iconPath, Platform.OS) };
144
+ requireAvailable("aboutPanel");
145
+ parseNativeResult(await invokeNative(() => Native!.call("about", JSON.stringify(wire))), (value): value is null => value === null);
146
+ }
@@ -30,19 +30,58 @@ static NSMenuItem *Find(NSMenu *menu, NSDictionary *target, BOOL recursive) {
30
30
  return nil;
31
31
  }
32
32
  static void Fail(NSString *code, NSString *message) { @throw [NSException exceptionWithName:code reason:message userInfo:nil]; }
33
+ // AppKit treats an uppercase key equivalent as Shift plus the lowercase key.
34
+ static NSString *KeyIdentity(NSString *key, NSEventModifierFlags modifiers) {
35
+ if (![key.lowercaseString isEqual:key]) modifiers |= NSEventModifierFlagShift;
36
+ return [NSString stringWithFormat:@"%lu:%@", (unsigned long)(modifiers & NSEventModifierFlagDeviceIndependentFlagsMask), key.lowercaseString];
37
+ }
38
+ static NSMenuItem *KeyHolder(NSMenu *menu, NSString *identity, NSMenuItem *except) {
39
+ for (NSMenuItem *item in menu.itemArray) {
40
+ if (item != except && item.keyEquivalent.length && [KeyIdentity(item.keyEquivalent, item.keyEquivalentModifierMask) isEqual:identity]) return item;
41
+ NSMenuItem *found = item.submenu ? KeyHolder(item.submenu, identity, except) : nil;
42
+ if (found) return found;
43
+ }
44
+ return nil;
45
+ }
46
+
47
+ // Wraps a submenu's existing delegate: every NSMenuDelegate call (menuNeedsUpdate:, lazy
48
+ // population, highlighting) still reaches it, and menuWillOpen:/menuDidClose: also report
49
+ // lifecycle. Delegate callbacks fire per submenu; NSMenu tracking notifications fire once per
50
+ // tracking session, so they cannot identify which submenu opened.
51
+ @interface SparkMenuLifecycleDelegate : NSObject <NSMenuDelegate>
52
+ @property (weak) id<NSMenuDelegate> original;
53
+ @property (copy) void (^lifecycle)(NSMenu *, NSString *);
54
+ @end
55
+ @implementation SparkMenuLifecycleDelegate
56
+ - (BOOL)respondsToSelector:(SEL)selector { return [super respondsToSelector:selector] || [self.original respondsToSelector:selector]; }
57
+ - (id)forwardingTargetForSelector:(SEL)selector { return [self.original respondsToSelector:selector] ? self.original : [super forwardingTargetForSelector:selector]; }
58
+ - (void)menuWillOpen:(NSMenu *)menu {
59
+ if ([self.original respondsToSelector:_cmd]) [self.original menuWillOpen:menu];
60
+ if (menu.delegate == self) self.lifecycle(menu, @"open");
61
+ }
62
+ - (void)menuDidClose:(NSMenu *)menu {
63
+ if ([self.original respondsToSelector:_cmd]) [self.original menuDidClose:menu];
64
+ if (menu.delegate == self) self.lifecycle(menu, @"close");
65
+ }
66
+ @end
33
67
 
34
68
  @interface RNNativeMenu ()
35
69
  @property NSMutableArray<void (^)(void)> *undo;
36
70
  @property NSArray *published;
71
+ @property BOOL observing;
72
+ @property NSHashTable<NSMenuItem *> *configured;
73
+ @property NSHashTable<NSMenuItem *> *created;
37
74
  - (void)restore;
38
75
  @end
39
76
  @implementation RNNativeMenu
40
77
  RCT_EXPORT_MODULE(NativeMenu)
41
78
  + (BOOL)requiresMainQueueSetup { return YES; }
42
- - (instancetype)init { if (self = [super init]) { _undo = [NSMutableArray new]; _published = @[]; } return self; }
43
- - (NSArray<NSString *> *)supportedEvents { return @[@"NativeMenuAction"]; }
79
+ - (instancetype)init { if (self = [super init]) { _undo = [NSMutableArray new]; _published = @[]; _configured = [NSHashTable weakObjectsHashTable]; _created = [NSHashTable weakObjectsHashTable]; } return self; }
80
+ - (NSArray<NSString *> *)supportedEvents { return @[@"NativeMenuAction", @"NativeMenuLifecycle"]; }
81
+ - (void)startObserving { self.observing = YES; }
82
+ - (void)stopObserving { self.observing = NO; }
44
83
  - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params { return std::make_shared<facebook::react::NativeMenuSpecJSI>(params); }
45
- - (void)restore { for (void (^undo)(void) in self.undo.reverseObjectEnumerator) undo(); [self.undo removeAllObjects]; }
84
+ - (void)restore { for (void (^undo)(void) in self.undo.reverseObjectEnumerator) undo(); [self.undo removeAllObjects]; [self.configured removeAllObjects]; [self.created removeAllObjects]; }
46
85
  - (void)identifyNativeMenus {
47
86
  NSMenu *main = NSApp.mainMenu;
48
87
  for (NSMenuItem *item in main.itemArray) {
@@ -68,12 +107,12 @@ RCT_EXPORT_MODULE(NativeMenu)
68
107
  NSMenu *menu = item.menu; NSInteger index = [menu indexOfItem:item];
69
108
  NSString *title = item.title, *key = item.keyEquivalent, *identifier = item.identifier;
70
109
  id target = item.target, represented = item.representedObject, role = objc_getAssociatedObject(item, &RoleKey);
71
- SEL action = item.action; BOOL enabled = item.enabled, hidden = item.hidden;
110
+ SEL action = item.action; BOOL enabled = item.enabled, hidden = item.hidden, alternate = item.alternate;
72
111
  NSControlStateValue state = item.state; NSEventModifierFlags modifiers = item.keyEquivalentModifierMask;
73
112
  NSImage *image = item.image;
74
113
  [self.undo addObject:^{
75
114
  item.title = title; item.keyEquivalent = key; item.identifier = identifier; item.target = target; item.action = action;
76
- item.representedObject = represented; item.enabled = enabled; item.hidden = hidden; item.state = state; item.keyEquivalentModifierMask = modifiers; item.image = image;
115
+ item.representedObject = represented; item.enabled = enabled; item.hidden = hidden; item.state = state; item.alternate = alternate; item.keyEquivalentModifierMask = modifiers; item.image = image;
77
116
  objc_setAssociatedObject(item, &RoleKey, role, OBJC_ASSOCIATION_COPY_NONATOMIC);
78
117
  if (item.menu == menu && index >= 0 && [menu indexOfItem:item] != index) { [menu removeItem:item]; [menu insertItem:item atIndex:MIN(index, menu.numberOfItems)]; }
79
118
  }];
@@ -83,14 +122,56 @@ RCT_EXPORT_MODULE(NativeMenu)
83
122
  if (config[@"enabled"]) item.enabled = [config[@"enabled"] boolValue];
84
123
  if (config[@"hidden"]) item.hidden = [config[@"hidden"] boolValue];
85
124
  if (config[@"checked"]) item.state = [config[@"checked"] boolValue] ? NSControlStateValueOn : NSControlStateValueOff;
125
+ if ([config[@"mixed"] boolValue]) item.state = NSControlStateValueMixed;
86
126
  NSDictionary *shortcut = config[@"shortcut"];
87
- if (shortcut) { item.keyEquivalent = shortcut[@"key"]; item.keyEquivalentModifierMask = [shortcut[@"modifiers"] unsignedIntegerValue]; }
127
+ if (shortcut) {
128
+ NSEventModifierFlags modifiers = [shortcut[@"modifiers"] unsignedIntegerValue];
129
+ // Shift+letter uses AppKit's uppercase form: a key event made with +[NSEvent keyEventWithType:...] (the test
130
+ // driver's, automation's) matches a lowercase key equivalent by its characters and ignores Shift (#450).
131
+ NSString *key = shortcut[@"key"], *upper = key.uppercaseString;
132
+ item.keyEquivalent = (modifiers & NSEventModifierFlagShift) && upper.length == 1 ? upper : key;
133
+ item.keyEquivalentModifierMask = modifiers; [self claim:config for:item];
134
+ }
135
+ // A keyed alternate differs from its primary's modifiers; a keyless pair
136
+ // differs by Option, the mask AppKit compares when folding alternates without key equivalents.
137
+ if (config[@"alternate"]) {
138
+ item.alternate = [config[@"alternate"] boolValue];
139
+ if (item.alternate && !item.keyEquivalent.length) item.keyEquivalentModifierMask = NSEventModifierFlagOption;
140
+ }
88
141
  if (config[@"systemImageName"] || config[@"imagePath"]) {
89
142
  NSImage *image = config[@"systemImageName"] ? [NSImage imageWithSystemSymbolName:config[@"systemImageName"] accessibilityDescription:item.title] : [[NSImage alloc] initWithContentsOfFile:config[@"imagePath"]];
90
143
  if (!image) Fail(@"E_INVALID_ARGUMENT", @"Menu image could not be loaded");
91
144
  item.image = image;
92
145
  }
93
146
  }
147
+ // AppKit withholds a key equivalent while another main-menu item with a different action has it
148
+ // (the template's View > Show Sidebar holds Control-Command-S). A host item yields it until the
149
+ // menu is removed; another published item makes the publication reject E_BUSY.
150
+ - (void)claim:(NSDictionary *)config for:(NSMenuItem *)item {
151
+ NSDictionary *shortcut = config[@"shortcut"];
152
+ if (item.keyEquivalent.length || !NSApp.mainMenu) return;
153
+ NSString *name = config[@"id"] ?: config[@"role"];
154
+ while (!item.keyEquivalent.length) {
155
+ NSMenuItem *holder = KeyHolder(NSApp.mainMenu, KeyIdentity(shortcut[@"key"], [shortcut[@"modifiers"] unsignedIntegerValue]), item);
156
+ if (!holder) Fail(@"E_NATIVE", [NSString stringWithFormat:@"AppKit did not apply the shortcut of menu item %@", name]);
157
+ if ([self.configured containsObject:holder]) Fail(@"E_BUSY", [NSString stringWithFormat:@"Menu item %@ cannot use its shortcut: menu item %@ already has it", name, holder.identifier ?: holder.title]);
158
+ [self save:holder]; holder.keyEquivalent = @"";
159
+ }
160
+ }
161
+ - (void)observeMenu:(NSMenu *)menu config:(NSDictionary *)config {
162
+ id<NSMenuDelegate> previous = menu.delegate;
163
+ SparkMenuLifecycleDelegate *delegate = [SparkMenuLifecycleDelegate new];
164
+ delegate.original = [previous isKindOfClass:SparkMenuLifecycleDelegate.class] ? ((SparkMenuLifecycleDelegate *)previous).original : previous;
165
+ __weak RNNativeMenu *weakSelf = self;
166
+ NSString *ownerId = config[@"_sparkOwner"], *itemId = config[@"id"];
167
+ delegate.lifecycle = ^(NSMenu *openedMenu, NSString *type) {
168
+ RNNativeMenu *module = weakSelf;
169
+ if (module.observing) [module sendEventWithName:@"NativeMenuLifecycle" body:@{ @"ownerId": ownerId, @"itemId": itemId, @"type": type }];
170
+ };
171
+ menu.delegate = delegate;
172
+ // NSMenu holds its delegate weakly; the restoration block retains both owners.
173
+ [self.undo addObject:^{ if (menu.delegate == delegate) menu.delegate = previous; }];
174
+ }
94
175
  - (void)install:(NSArray *)configs into:(NSMenu *)menu root:(BOOL)root {
95
176
  for (NSDictionary *config in configs) {
96
177
  if ([config[@"separator"] boolValue]) {
@@ -108,11 +189,23 @@ RCT_EXPORT_MODULE(NativeMenu)
108
189
  if (root && target[@"menu"]) objc_setAssociatedObject(item, &LocationKey, target[@"menu"], OBJC_ASSOCIATION_COPY_NONATOMIC);
109
190
  [menu insertItem:item atIndex:[self index:config[@"placement"] inMenu:menu]];
110
191
  [self.undo addObject:^{ if (item.menu) [item.menu removeItem:item]; }];
192
+ [self.created addObject:item];
111
193
  }
194
+ [self.configured addObject:item];
112
195
  if (config[@"items"]) {
113
196
  if (existing && !item.submenu) Fail(@"E_INVALID_ARGUMENT", @"Submenu target is not a submenu");
114
197
  if (!item.submenu) item.submenu = [[NSMenu alloc] initWithTitle:item.title];
115
- [self apply:config to:item];
198
+ if (root && [target[@"menu"] isEqual:@"help"] && NSApp.helpMenu != item.submenu) {
199
+ NSMenu *previousHelp = NSApp.helpMenu, *helpMenu = item.submenu;
200
+ NSApp.helpMenu = helpMenu;
201
+ [self.undo addObject:^{ if (NSApp.helpMenu == helpMenu) NSApp.helpMenu = previousHelp; }];
202
+ }
203
+ if ([config[@"_sparkLifecycle"] boolValue]) [self observeMenu:item.submenu config:config];
204
+ // A native root located by target keeps its title, which the system localizes (#449);
205
+ // the label names only a root Spark creates.
206
+ NSMutableDictionary *applied = config.mutableCopy;
207
+ if (root && target[@"menu"] && ![self.created containsObject:item]) [applied removeObjectForKey:@"title"];
208
+ [self apply:applied to:item];
116
209
  [self install:config[@"items"] into:item.submenu root:NO];
117
210
  } else {
118
211
  if (item.submenu && ![config[@"role"] isEqual:@"services"]) Fail(@"E_INVALID_ARGUMENT", @"An action cannot replace a submenu; target it with a submenu item");
@@ -140,6 +233,21 @@ RCT_EXPORT_MODULE(NativeMenu)
140
233
  }
141
234
  }
142
235
  }
236
+ - (void)validateAlternates:(NSMenu *)menu {
237
+ NSMenuItem *primary = nil;
238
+ for (NSMenuItem *item in menu.itemArray) {
239
+ if (item.submenu) [self validateAlternates:item.submenu];
240
+ if (item.hidden) continue;
241
+ if (item.alternate && [self.configured containsObject:item]) {
242
+ if (!primary || primary.separatorItem || primary.submenu || primary.alternate)
243
+ Fail(@"E_INVALID_ARGUMENT", @"An alternate must directly follow a visible non-alternate command");
244
+ if (![primary.keyEquivalent.lowercaseString isEqual:item.keyEquivalent.lowercaseString] ||
245
+ (item.keyEquivalent.length && [KeyIdentity(primary.keyEquivalent, primary.keyEquivalentModifierMask) isEqual:KeyIdentity(item.keyEquivalent, item.keyEquivalentModifierMask)]))
246
+ Fail(@"E_INVALID_ARGUMENT", @"An alternate must use its primary's shortcut key with different modifiers");
247
+ }
248
+ primary = item;
249
+ }
250
+ }
143
251
  - (void)publish:(NSString *)json resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
144
252
  RCTExecuteOnMainQueue(^{
145
253
  NSError *error = nil; id value = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
@@ -149,7 +257,7 @@ RCT_EXPORT_MODULE(NativeMenu)
149
257
  [self identifyNativeMenus];
150
258
  NSArray *previous = self.published;
151
259
  [self restore];
152
- @try { [self install:value into:NSApp.mainMenu root:YES]; self.published = value; resolve(nil); }
260
+ @try { [self install:value into:NSApp.mainMenu root:YES]; [self validateAlternates:NSApp.mainMenu]; self.published = value; resolve(nil); }
153
261
  @catch (NSException *failure) {
154
262
  [self restore];
155
263
  @try { [self install:previous into:NSApp.mainMenu root:YES]; }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@legendapp/spark-native-menu",
3
- "version": "0.0.1-next.6",
3
+ "version": "0.0.1-next.8",
4
4
  "main": "src/index",
5
5
  "react-native": "src/index",
6
6
  "codegenConfig": {
@@ -41,6 +41,6 @@
41
41
  },
42
42
  "private": true,
43
43
  "dependencies": {
44
- "@legendapp/spark-desktop-app": "0.0.1-next.6"
44
+ "@legendapp/spark-desktop-app": "0.0.1-next.8"
45
45
  }
46
46
  }