@ng-native/desktop 0.24.0 → 0.25.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.
package/bin/package.mjs CHANGED
@@ -29,6 +29,7 @@ export const MINIMUM_MACOS = '14.0';
29
29
  export const DEFAULT_OUTPUT = 'dist/macos';
30
30
 
31
31
  const FORMATS = ['app', 'dmg', 'mas'];
32
+ const HERMES_FRAMEWORK = 'hermesvm.framework';
32
33
 
33
34
  export const PACKAGE_USAGE = `Usage: ng-native-desktop package [--format app|dmg|mas] [--output <dir>] [--feed-url <url> [--sparkle-key <key>]] [--skip-notarize]
34
35
 
@@ -439,16 +440,18 @@ function signsInWithApple(sys, expo, format) {
439
440
  * network, the files the user picks, and the app's identity on the team. `appleSignIn` adds Sign
440
441
  * in with Apple and `push` remote notifications (production APNs, which both distribution formats
441
442
  * use), and either adds to a `dmg` the app's identity on the team, which its profile is for.
443
+ * `loadsAdHocFramework` turns off library validation in an ad hoc signed `dmg`, which loads its
444
+ * embedded Hermes framework with no team to check it against.
442
445
  *
443
446
  * @param {DesktopAppConfig} config
444
447
  * @param {'app' | 'dmg' | 'mas'} format
445
- * @param {{ bundleIdentifier: string, team?: string, appleSignIn?: boolean, push?: boolean }} identity
448
+ * @param {{ bundleIdentifier: string, team?: string, appleSignIn?: boolean, push?: boolean, loadsAdHocFramework?: boolean }} identity
446
449
  * @returns {string | null}
447
450
  */
448
451
  export function entitlements(
449
452
  config,
450
453
  format,
451
- { bundleIdentifier, team, appleSignIn = false, push = false },
454
+ { bundleIdentifier, team, appleSignIn = false, push = false, loadsAdHocFramework = false },
452
455
  ) {
453
456
  if (format === 'app') return null;
454
457
  /** @type {import('./plist.mjs').PlistDict} */
@@ -458,6 +461,7 @@ export function entitlements(
458
461
  if (appleSignIn) granted['com.apple.developer.applesignin'] = ['Default'];
459
462
  if (push) granted['com.apple.developer.aps-environment'] = 'production';
460
463
  if (format === 'dmg') {
464
+ if (loadsAdHocFramework) granted['com.apple.security.cs.disable-library-validation'] = true;
461
465
  if (!appleSignIn && !push) return plist(granted);
462
466
  return plist({
463
467
  ...granted,
@@ -716,11 +720,16 @@ export async function packageApp(options, sys) {
716
720
  ]),
717
721
  'expo export:embed did not bundle the app for macos; the output above says why.',
718
722
  );
719
- compileBytecode(sys, hermesc, javascript, path.join(resources, 'main.jsbundle'));
723
+ // Compiled beside the bundle, then copied in: hermesc makes no folder, and an app with no assets
724
+ // has no Resources yet.
725
+ const bytecode = path.join(staging, 'main.jsbundle');
726
+ compileBytecode(sys, hermesc, javascript, bytecode);
727
+ sys.copy(bytecode, path.join(resources, 'main.jsbundle'));
720
728
  const executable = path.join(contents, 'MacOS', config.name);
721
729
  sys.copy(path.join(buildDir, 'appkit', 'ngn-macos'), executable);
722
730
  // Local symbols only, which nothing resolves at run time; the exported ones stay.
723
731
  expectSuccess(sys.run('strip', ['-x', executable]), `strip could not strip ${executable}.`);
732
+ const hermes = embedHermes(sys, buildDir, contents);
724
733
  const iconName = config.icon
725
734
  ? compileIcon(sys, path.resolve(cwd, config.icon), resources, staging)
726
735
  : null;
@@ -742,7 +751,7 @@ export async function packageApp(options, sys) {
742
751
 
743
752
  const made = [app];
744
753
  if (options.format === 'app') {
745
- expectSuccess(sys.run('codesign', ['--force', '--sign', '-', app]), 'codesign failed.');
754
+ signAdHoc(sys, app, hermes);
746
755
  } else if (options.format === 'dmg' && keys) {
747
756
  made.push(
748
757
  ...shipDmg(sys, {
@@ -755,10 +764,13 @@ export async function packageApp(options, sys) {
755
764
  options,
756
765
  signIn,
757
766
  push,
767
+ hermes,
758
768
  }),
759
769
  );
760
770
  } else if (keys) {
761
- made.push(shipMas(sys, { config, app, output, staging, bundleIdentifier, keys, signIn, push }));
771
+ made.push(
772
+ shipMas(sys, { config, app, output, staging, bundleIdentifier, keys, signIn, push, hermes }),
773
+ );
762
774
  }
763
775
  for (const file of made) console.log(path.relative(cwd, file));
764
776
  return 0;
@@ -782,6 +794,36 @@ function fallbackIdentifier(format, expo) {
782
794
  return `dev.ngnative.${slug || 'app'}`;
783
795
  }
784
796
 
797
+ /**
798
+ * An `app` build's ad hoc signature, for this Mac: the embedded Hermes framework first, then the app.
799
+ *
800
+ * @param {System} sys
801
+ * @param {string} app
802
+ * @param {string | null} hermes
803
+ */
804
+ function signAdHoc(sys, app, hermes) {
805
+ for (const target of hermes ? [hermes, app] : [app]) {
806
+ expectSuccess(sys.run('codesign', ['--force', '--sign', '-', target]), 'codesign failed.');
807
+ }
808
+ }
809
+
810
+ /**
811
+ * React Native's Hermes framework, which a host built against it links, from the host build into
812
+ * the app's Frameworks, where the binary's rpath finds it. Null for a host with Hermes linked in.
813
+ *
814
+ * @param {System} sys
815
+ * @param {string} buildDir
816
+ * @param {string} contents
817
+ * @returns {string | null} the embedded framework
818
+ */
819
+ function embedHermes(sys, buildDir, contents) {
820
+ const hermes = path.join(buildDir, 'appkit', HERMES_FRAMEWORK);
821
+ if (!sys.exists(hermes)) return null;
822
+ const embedded = path.join(contents, 'Frameworks', HERMES_FRAMEWORK);
823
+ sys.copy(hermes, embedded);
824
+ return embedded;
825
+ }
826
+
785
827
  /**
786
828
  * Sparkle, from the host build, into the app's Frameworks.
787
829
  *
@@ -807,12 +849,12 @@ function embedSparkle(sys, buildDir, contents) {
807
849
  * only a real identity can get.
808
850
  *
809
851
  * @param {System} sys
810
- * @param {{ config: DesktopAppConfig, app: string, output: string, staging: string, bundleIdentifier: string, keys: NonNullable<ReturnType<typeof credentials>>, options: PackageCommand, signIn: boolean, push: boolean }} build
852
+ * @param {{ config: DesktopAppConfig, app: string, output: string, staging: string, bundleIdentifier: string, keys: NonNullable<ReturnType<typeof credentials>>, options: PackageCommand, signIn: boolean, push: boolean, hermes: string | null }} build
811
853
  * @returns {string[]} the files made beside the app
812
854
  */
813
855
  function shipDmg(
814
856
  sys,
815
- { config, app, output, staging, bundleIdentifier, keys, options, signIn, push },
857
+ { config, app, output, staging, bundleIdentifier, keys, options, signIn, push, hermes },
816
858
  ) {
817
859
  if (signIn || push) embedProfile(sys, keys, app);
818
860
  const file = path.join(staging, 'entitlements.plist');
@@ -821,6 +863,8 @@ function shipDmg(
821
863
  team: keys.team,
822
864
  appleSignIn: signIn,
823
865
  push,
866
+ // An ad hoc signature has no team for library validation to match the framework against.
867
+ loadsAdHocFramework: Boolean(hermes) && keys.identity === '-',
824
868
  });
825
869
  sys.writeFile(file, /** @type {string} */ (granted));
826
870
  const timestamp = keys.identity === '-' ? '--timestamp=none' : '--timestamp';
@@ -839,6 +883,9 @@ function shipDmg(
839
883
  ]),
840
884
  `codesign could not sign ${path.basename(target)}.`,
841
885
  );
886
+ // Nested code before the app, with the app's identity: the hardened runtime loads a framework
887
+ // only from the app's own team.
888
+ if (hermes) sign(hermes);
842
889
  if (options.feedUrl) signSparkle(path.join(app, 'Contents', 'Frameworks', 'Sparkle.framework'));
843
890
  sign(app, ['--entitlements', file]);
844
891
 
@@ -931,9 +978,12 @@ function embedProfile(sys, keys, app) {
931
978
  * Embeds the provisioning profile, signs inside the App Sandbox and makes the installer package.
932
979
  *
933
980
  * @param {System} sys
934
- * @param {{ config: DesktopAppConfig, app: string, output: string, staging: string, bundleIdentifier: string, keys: NonNullable<ReturnType<typeof credentials>>, signIn: boolean, push: boolean }} build
981
+ * @param {{ config: DesktopAppConfig, app: string, output: string, staging: string, bundleIdentifier: string, keys: NonNullable<ReturnType<typeof credentials>>, signIn: boolean, push: boolean, hermes: string | null }} build
935
982
  */
936
- function shipMas(sys, { config, app, output, staging, bundleIdentifier, keys, signIn, push }) {
983
+ function shipMas(
984
+ sys,
985
+ { config, app, output, staging, bundleIdentifier, keys, signIn, push, hermes },
986
+ ) {
937
987
  embedProfile(sys, keys, app);
938
988
  const file = path.join(staging, 'entitlements.plist');
939
989
  const granted = entitlements(config, 'mas', {
@@ -943,6 +993,12 @@ function shipMas(sys, { config, app, output, staging, bundleIdentifier, keys, si
943
993
  push,
944
994
  });
945
995
  sys.writeFile(file, /** @type {string} */ (granted));
996
+ if (hermes) {
997
+ expectSuccess(
998
+ sys.run('codesign', ['--force', '--timestamp', '--sign', keys.identity, hermes]),
999
+ `codesign could not sign ${HERMES_FRAMEWORK}.`,
1000
+ );
1001
+ }
946
1002
  expectSuccess(
947
1003
  sys.run('codesign', [
948
1004
  '--force',
package/bin/prebuilt.mjs CHANGED
@@ -7,8 +7,8 @@
7
7
  * `prebuilt.json` beside this package lists them, one entry per version and flavour; an entry
8
8
  * that names no flavour is a release host. The release workflow writes each entry before
9
9
  * the package is packed (`docs/desktop-host.md` has the steps), so the SHA-256 of each archive
10
- * travels inside the npm package, not beside the archive it vouches for. An archive holds `appkit/ngn-macos`, `appkit/hermesc` and
11
- * `appkit/Sparkle.framework`, the files a host build's `appkit` folder has, and unpacks into the
10
+ * travels inside the npm package, not beside the archive it vouches for. An archive holds `appkit/ngn-macos`, `appkit/hermesc`,
11
+ * `appkit/hermesvm.framework` and `appkit/Sparkle.framework`, the files a host build's `appkit` folder has, and unpacks into the
12
12
  * per-user cache under its own hash, so a new archive never reuses an old one's files.
13
13
  *
14
14
  * `native/scripts/make-prebuilt.mjs` builds and packs one. The host is signed ad hoc unless
@@ -291,21 +291,41 @@ export function fetchPrebuilt(sys, host, cache) {
291
291
  return dir;
292
292
  }
293
293
 
294
+ /**
295
+ * The entitlements of an ad hoc signed host with the hardened runtime. Library validation loads
296
+ * only libraries from the process's own team, and an ad hoc signature has none, so it would refuse
297
+ * React Native's Hermes framework beside the binary. A real identity signs the framework too and
298
+ * keeps validation.
299
+ */
300
+ export const AD_HOC_HOST_ENTITLEMENTS = `<?xml version="1.0" encoding="UTF-8"?>
301
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
302
+ <plist version="1.0">
303
+ <dict>
304
+ <key>com.apple.security.cs.disable-library-validation</key>
305
+ <true/>
306
+ </dict>
307
+ </plist>
308
+ `;
309
+
294
310
  /**
295
311
  * Strips each file's local symbols, then signs it with the hardened runtime: with
296
312
  * `NGN_SIGN_IDENTITY` when that is set and not empty, ad hoc (`--sign -`, no timestamp) otherwise.
313
+ * `adHocEntitlements` go with an ad hoc signature only. A framework is signed as it is, unstripped.
297
314
  * Throws when a command fails.
298
315
  *
299
316
  * @param {(command: string, args: string[]) => { status: number | null }} run
300
317
  * @param {string[]} files
301
318
  * @param {Record<string, string | undefined>} env
319
+ * @param {string} [adHocEntitlements]
302
320
  */
303
- export function signPrebuiltFiles(run, files, env) {
321
+ export function signPrebuiltFiles(run, files, env, adHocEntitlements) {
304
322
  const identity = env['NGN_SIGN_IDENTITY'] || '-';
323
+ const entitlements =
324
+ identity === '-' && adHocEntitlements ? ['--entitlements', adHocEntitlements] : [];
305
325
  for (const file of files) {
306
326
  // Before signing, which stripping would break.
307
327
  for (const [command, args] of /** @type {[string, string[]][]} */ ([
308
- ['strip', ['-x', file]],
328
+ ...(file.endsWith('.framework') ? [] : [['strip', ['-x', file]]]),
309
329
  [
310
330
  'codesign',
311
331
  [
@@ -313,6 +333,7 @@ export function signPrebuiltFiles(run, files, env) {
313
333
  '--options',
314
334
  'runtime',
315
335
  identity === '-' ? '--timestamp=none' : '--timestamp',
336
+ ...entitlements,
316
337
  '--sign',
317
338
  identity,
318
339
  file,
@@ -22,6 +22,7 @@ option(NGN_TESTS "Build the core tests" ON)
22
22
  set(RN_DIR "" CACHE PATH "The installed react-native package")
23
23
  set(NGN_SOURCES "" CACHE PATH "Sources fetched by scripts/fetch.sh (<cache>/src)")
24
24
  set(NGN_HERMES_BUILD "" CACHE PATH "Hermes built by scripts/build-hermes.sh")
25
+ set(NGN_HERMES_PREBUILT "" CACHE PATH "React Native's prebuilt Hermes, from scripts/fetch-hermes.sh")
25
26
  foreach(var RN_DIR NGN_SOURCES)
26
27
  if(NOT IS_DIRECTORY "${${var}}")
27
28
  message(FATAL_ERROR "${var} is not set to a directory; build through scripts/build.sh")
@@ -238,6 +239,9 @@ if(NGN_TESTS)
238
239
  target_link_libraries(ngn_core_tests PRIVATE "-framework Foundation" "-framework Security" "-framework IOKit" "-framework SystemConfiguration" "-framework Network" "-framework AppKit" "-framework CoreText" "-framework ImageIO" "-framework Vision" "-framework UniformTypeIdentifiers" "-framework EventKit" "-framework AVFoundation" "-framework CoreMedia" "-framework Photos" "-framework PhotosUI" "-framework AppTrackingTransparency" "-framework AdSupport" "-framework CoreLocation" "-framework MapKit" "-framework WebKit" "-framework PDFKit" "-framework CoreImage" "-framework AuthenticationServices" "-framework AVKit" "-framework UserNotifications")
239
240
  endif()
240
241
  enable_testing()
242
+ if(NGN_HERMES_TEST_RPATH)
243
+ target_link_options(ngn_core_tests PRIVATE ${NGN_HERMES_TEST_RPATH})
244
+ endif()
241
245
  add_test(NAME core COMMAND ngn_core_tests)
242
246
  endif()
243
247
 
@@ -105,8 +105,16 @@ target_compile_definitions(ngn-macos PRIVATE NGN_REACT_NATIVE_VERSION="${_rn_ver
105
105
  # The hermesc built with the Hermes the binary links, beside it, where `package` takes it from to
106
106
  # compile the bundle to bytecode of the version this Hermes runs.
107
107
  add_custom_command(TARGET ngn-macos POST_BUILD
108
- COMMAND ${CMAKE_COMMAND} -E copy_if_different ${NGN_HERMES_BUILD}/bin/hermesc $<TARGET_FILE_DIR:ngn-macos>/hermesc
108
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different ${NGN_HERMESC} $<TARGET_FILE_DIR:ngn-macos>/hermesc
109
109
  VERBATIM)
110
+ # React Native's prebuilt Hermes beside the binary, which loads it from there in a build and
111
+ # `package` embeds in Contents/Frameworks.
112
+ if(NGN_HERMES_FRAMEWORK)
113
+ add_custom_command(TARGET ngn-macos POST_BUILD
114
+ COMMAND rm -rf $<TARGET_FILE_DIR:ngn-macos>/hermesvm.framework
115
+ COMMAND ditto ${NGN_HERMES_FRAMEWORK} $<TARGET_FILE_DIR:ngn-macos>/hermesvm.framework
116
+ VERBATIM)
117
+ endif()
110
118
 
111
119
  # Sparkle's framework beside the binary, where `package --format dmg` takes it from to embed it.
112
120
  # The binary never links it: it loads it at runtime in a dmg build only (app-updater.mm).
@@ -122,9 +130,14 @@ endif()
122
130
  # backend the binary uses. Built with the core tests, and run beside them.
123
131
  if(NGN_TESTS)
124
132
  add_executable(ngn_appkit_tests ../core/tests/main.cpp tests/views/accessibility.test.mm tests/views/svg-foreign-object.test.mm
125
- tests/views/tab-walk.test.mm tests/views/camera-view.test.mm tests/views/text-input-alignment.test.mm)
133
+ tests/views/tab-walk.test.mm tests/views/camera-view.test.mm tests/views/text-input-alignment.test.mm
134
+ tests/views/image-view.test.mm tests/views/modal-beside-split.test.mm
135
+ tests/views/split-under-pushed-screen.test.mm)
126
136
  target_include_directories(ngn_appkit_tests PRIVATE ../core/tests)
127
137
  target_link_libraries(ngn_appkit_tests PRIVATE ngn_appkit doctest ${NGN_APPKIT_FRAMEWORKS})
138
+ if(NGN_HERMES_TEST_RPATH)
139
+ target_link_options(ngn_appkit_tests PRIVATE ${NGN_HERMES_TEST_RPATH})
140
+ endif()
128
141
  ngn_link_swift(ngn_appkit_tests)
129
142
  add_test(NAME appkit COMMAND ngn_appkit_tests)
130
143
  endif()
@@ -78,7 +78,7 @@ void AppKitBackend::deleteView(SurfaceId, Tag tag) {
78
78
  [sourceLists_ removeObjectForKey:@(tag)];
79
79
  }
80
80
 
81
- void AppKitBackend::insertChild(SurfaceId, Tag parent, Tag child, int index) {
81
+ void AppKitBackend::insertChild(SurfaceId surfaceId, Tag parent, Tag child, int index) {
82
82
  NGNView *parentView = views_[@(parent)];
83
83
  NGNView *childView = views_[@(child)];
84
84
  if (parentView == nil || childView == nil) {
@@ -86,7 +86,16 @@ void AppKitBackend::insertChild(SurfaceId, Tag parent, Tag child, int index) {
86
86
  }
87
87
  // The index counts Fabric children only: a TextInput holds an NSTextField of its own.
88
88
  if ([childView isKindOfClass:NGNModalHostView.class] && ![childView isKindOfClass:NGNPresentedScreenView.class]) {
89
- [(NGNModalHostView *)childView presentOver:parentView];
89
+ // A view beside a split view at the root has no window: the split view's controller took the
90
+ // window's content, surface and all. The modal goes over the surface's window all the same.
91
+ NSView *over = parentView;
92
+ if (over.window == nil) {
93
+ // A surface already removed (a mount queued before it went) has no window to give.
94
+ NGNSurfaceView *surface = surfaces_[@(surfaceId)];
95
+ NSView *content = surface != nil ? NGNWindowOfSplit(surface).contentView : nil;
96
+ over = content != nil ? content : parentView;
97
+ }
98
+ [(NGNModalHostView *)childView presentOver:over];
90
99
  return;
91
100
  }
92
101
  if ([parentView conformsToProtocol:@protocol(NGNMountsChildren)]) {
@@ -155,7 +164,23 @@ void AppKitBackend::dispatchCommand(Tag tag, const std::string &name, const foll
155
164
  }
156
165
 
157
166
  void AppKitBackend::setCovered(SurfaceId, Tag tag, bool covered) {
158
- views_[@(tag)].covered = covered;
167
+ NGNView *screen = views_[@(tag)];
168
+ if (screen == nil) {
169
+ return;
170
+ }
171
+ screen.covered = covered;
172
+ // A window's split view on the covered screen gives the window back to the screen in front.
173
+ // ponytail: walks the screen's views on each push and pop; keep a registry if that shows up.
174
+ NSMutableArray<NSView *> *queue = [NSMutableArray arrayWithObject:screen];
175
+ while (queue.count > 0) {
176
+ NSView *view = queue.firstObject;
177
+ [queue removeObjectAtIndex:0];
178
+ if ([view isKindOfClass:NGNSplitView.class]) {
179
+ [(NGNSplitView *)view setScreenCovered:covered];
180
+ continue;
181
+ }
182
+ [queue addObjectsFromArray:view.subviews];
183
+ }
159
184
  }
160
185
 
161
186
  NGNHeaderToolbar *AppKitBackend::toolbarFor(SurfaceId surfaceId) {
@@ -1,6 +1,8 @@
1
1
  #import "image-view.h"
2
2
  #import "image-request.h"
3
3
 
4
+ #import <QuartzCore/QuartzCore.h>
5
+
4
6
  #include "ngn/file-system.h"
5
7
 
6
8
  #include <react/renderer/components/image/ImageEventEmitter.h>
@@ -14,6 +16,10 @@ using namespace facebook::react;
14
16
  std::optional<ImageSource> _source;
15
17
  NSURLSessionDataTask *_task;
16
18
  NSImage *_image;
19
+ // Holds the image under the view's children. The view's own layer is no place for it: NGNView
20
+ // draws its box in drawRect:, and each redraw (every layout asks for one) replaces the layer's
21
+ // contents, so an image that loaded before the redraw was wiped.
22
+ CALayer *_imageLayer;
17
23
  // Moved on by each load: a completion already queued for an earlier one, even of the same uri,
18
24
  // is ignored.
19
25
  uint64_t _load;
@@ -23,6 +29,24 @@ using namespace facebook::react;
23
29
  [_task cancel];
24
30
  }
25
31
 
32
+ - (CALayer *)imageLayer {
33
+ if (_imageLayer == nil) {
34
+ _imageLayer = [CALayer layer];
35
+ _imageLayer.contentsGravity = self.layer.contentsGravity;
36
+ _imageLayer.frame = self.layer.bounds;
37
+ [self.layer insertSublayer:_imageLayer atIndex:0];
38
+ }
39
+ return _imageLayer;
40
+ }
41
+
42
+ - (void)updateLayout:(const LayoutMetrics &)metrics {
43
+ [super updateLayout:metrics];
44
+ [CATransaction begin];
45
+ [CATransaction setDisableActions:YES];
46
+ _imageLayer.frame = self.layer.bounds;
47
+ [CATransaction commit];
48
+ }
49
+
26
50
  - (std::shared_ptr<const ImageEventEmitter>)imageEmitter {
27
51
  return std::dynamic_pointer_cast<const ImageEventEmitter>(self.eventEmitter);
28
52
  }
@@ -48,6 +72,7 @@ using namespace facebook::react;
48
72
  break;
49
73
  }
50
74
  self.layer.masksToBounds = YES;
75
+ _imageLayer.contentsGravity = self.layer.contentsGravity;
51
76
  // The source whose scale is nearest the screen's, as React Native iOS picks.
52
77
  double screenScale = self.window ? self.window.backingScaleFactor : NSScreen.mainScreen.backingScaleFactor;
53
78
  auto source = ngn::appkit::pickImageSource(p->sources, screenScale);
@@ -63,7 +88,7 @@ using namespace facebook::react;
63
88
  [_task cancel];
64
89
  _task = nil;
65
90
  _load++;
66
- self.layer.contents = nil;
91
+ _imageLayer.contents = nil;
67
92
  // A file is drawn only inside the file boundary, and exactly the file checked.
68
93
  std::shared_ptr<ngn::FileAccess::Use> use;
69
94
  NSString *load = _uri;
@@ -118,11 +143,15 @@ using namespace facebook::react;
118
143
 
119
144
  - (void)loaded:(NSImage *)image {
120
145
  _image = image;
121
- self.layer.contents = image;
146
+ CALayer *layer = [self imageLayer];
147
+ layer.contentsGravity = self.layer.contentsGravity;
148
+ layer.contents = image;
122
149
  if (auto e = [self imageEmitter]) {
123
150
  NSImageRep *rep = image.representations.firstObject;
124
151
  ImageSource source;
125
152
  source.uri = std::string(_uri.UTF8String);
153
+ // In pixels, at a scale of 1: ImageSource's default scale of 3 would report three times the size.
154
+ source.scale = 1;
126
155
  source.size = {static_cast<Float>(rep ? rep.pixelsWide : image.size.width),
127
156
  static_cast<Float>(rep ? rep.pixelsHigh : image.size.height)};
128
157
  e->onLoad(source);
@@ -65,6 +65,9 @@ std::function<void(NSInteger, CGPoint)> gOffsetChanged;
65
65
  object:_scrollView.contentView];
66
66
  [self addSubview:_scrollView];
67
67
  __weak NGNScrollView *weakSelf = self;
68
+ _scrollView.phaseChanged = ^(NGNScrollPhase phase, NSPoint velocity) {
69
+ [weakSelf report:phase velocity:velocity];
70
+ };
68
71
  _styleObserver = [[NGNScrollerStyleObserver alloc] initWithChanged:^{
69
72
  [weakSelf updateScrollers];
70
73
  }];
@@ -94,6 +97,7 @@ std::function<void(NSInteger, CGPoint)> gOffsetChanged;
94
97
  _scrollView.horizontalScrollElasticity = _scrollView.verticalScrollElasticity;
95
98
  // The inner scroll view takes the wheel before this view does.
96
99
  _scrollView.scrollingDisabled = !p->scrollEnabled;
100
+ _scrollView.pagingEnabled = p->pagingEnabled;
97
101
  if (_offsetProp != p->contentOffset) {
98
102
  bool first = !_offsetProp;
99
103
  _offsetProp = p->contentOffset;
@@ -198,15 +202,6 @@ std::function<void(NSInteger, CGPoint)> gOffsetChanged;
198
202
  [self applyPendingOffsetAfterMount];
199
203
  }
200
204
 
201
- - (void)scrollWheel:(NSEvent *)event {
202
- auto p = std::dynamic_pointer_cast<const ScrollViewProps>(self.props);
203
- if (p && !p->scrollEnabled) {
204
- [self.nextResponder scrollWheel:event];
205
- return;
206
- }
207
- [_scrollView scrollWheel:event];
208
- }
209
-
210
205
  - (void)boundsDidChange:(NSNotification *)note {
211
206
  NSPoint origin = _scrollView.contentView.bounds.origin;
212
207
  if (gOffsetChanged) {
@@ -220,13 +215,45 @@ std::function<void(NSInteger, CGPoint)> gOffsetChanged;
220
215
  }
221
216
  auto emitter = std::dynamic_pointer_cast<const ScrollViewEventEmitter>(self.eventEmitter);
222
217
  if (emitter) {
223
- ScrollEvent event;
224
- event.contentOffset = {static_cast<Float>(origin.x), static_cast<Float>(origin.y)};
225
- event.contentSize = {static_cast<Float>(_document.frame.size.width), static_cast<Float>(_document.frame.size.height)};
226
- event.containerSize = {static_cast<Float>(self.bounds.size.width), static_cast<Float>(self.bounds.size.height)};
227
- event.zoomScale = 1;
228
- event.timestamp = NSProcessInfo.processInfo.systemUptime;
229
- emitter->onScroll(event);
218
+ emitter->onScroll([self scrollEvent]);
219
+ }
220
+ }
221
+
222
+ - (ScrollEvent)scrollEvent {
223
+ NSPoint origin = _scrollView.contentView.bounds.origin;
224
+ ScrollEvent event;
225
+ event.contentOffset = {static_cast<Float>(origin.x), static_cast<Float>(origin.y)};
226
+ event.contentSize = {static_cast<Float>(_document.frame.size.width), static_cast<Float>(_document.frame.size.height)};
227
+ event.containerSize = {static_cast<Float>(self.bounds.size.width), static_cast<Float>(self.bounds.size.height)};
228
+ event.zoomScale = 1;
229
+ event.timestamp = NSProcessInfo.processInfo.systemUptime;
230
+ return event;
231
+ }
232
+
233
+ // A trackpad gesture's drag and momentum, as onScrollBeginDrag, onScrollEndDrag,
234
+ // onMomentumScrollBegin and onMomentumScrollEnd report a touch's on iOS.
235
+ - (void)report:(NGNScrollPhase)phase velocity:(NSPoint)velocity {
236
+ auto emitter = std::dynamic_pointer_cast<const ScrollViewEventEmitter>(self.eventEmitter);
237
+ if (!emitter) {
238
+ return;
239
+ }
240
+ switch (phase) {
241
+ case NGNScrollPhaseDragBegan:
242
+ emitter->onScrollBeginDrag([self scrollEvent]);
243
+ break;
244
+ case NGNScrollPhaseDragEnded: {
245
+ ScrollEndDragEvent event([self scrollEvent]);
246
+ event.velocity = {static_cast<Float>(velocity.x), static_cast<Float>(velocity.y)};
247
+ event.targetContentOffset = event.contentOffset;
248
+ emitter->onScrollEndDrag(event);
249
+ break;
250
+ }
251
+ case NGNScrollPhaseMomentumBegan:
252
+ emitter->onMomentumScrollBegin([self scrollEvent]);
253
+ break;
254
+ case NGNScrollPhaseMomentumEnded:
255
+ emitter->onMomentumScrollEnd([self scrollEvent]);
256
+ break;
230
257
  }
231
258
  }
232
259
 
@@ -244,6 +271,20 @@ std::function<void(NSInteger, CGPoint)> gOffsetChanged;
244
271
  } else {
245
272
  return;
246
273
  }
274
+ // scrollTo's third argument, and scrollToEnd's only one, is whether it animates.
275
+ const auto &animated = name == "scrollTo" ? (args.size() >= 3 ? args[2] : folly::dynamic()) : (args.isArray() && !args.empty() ? args[0] : folly::dynamic());
276
+ if (animated.isBool() && animated.asBool()) {
277
+ NGNWheelScrollView *scroll = _scrollView;
278
+ [NSAnimationContext
279
+ runAnimationGroup:^(NSAnimationContext *context) {
280
+ context.duration = 0.3;
281
+ clip.animator.boundsOrigin = target;
282
+ }
283
+ completionHandler:^{
284
+ [scroll reflectScrolledClipView:clip];
285
+ }];
286
+ return;
287
+ }
247
288
  [clip scrollToPoint:target];
248
289
  [_scrollView reflectScrolledClipView:clip];
249
290
  }
@@ -18,8 +18,28 @@ float NGNLegacyScrollerWidth(BOOL thin);
18
18
  - (instancetype)initWithChanged:(void (^)(void))changed;
19
19
  @end
20
20
 
21
- // A scroll view's NSScrollView, which takes a wheel turn before the view holding it: with
22
- // `scrollingDisabled` (`scrollEnabled={false}`) the turn goes past it, up the responder chain.
21
+ // Where a trackpad scroll is, as a scroll view's drag and momentum events report it.
22
+ typedef NS_ENUM(NSInteger, NGNScrollPhase) {
23
+ NGNScrollPhaseDragBegan,
24
+ NGNScrollPhaseDragEnded,
25
+ NGNScrollPhaseMomentumBegan,
26
+ NGNScrollPhaseMomentumEnded,
27
+ };
28
+
29
+ // A scroll view's NSScrollView, which takes a wheel turn before the view holding it. A turn goes
30
+ // past it, up the responder chain, with `scrollingDisabled` (`scrollEnabled={false}`), or when the
31
+ // content cannot scroll along the turn's axis: a vertical turn over a horizontal scroll view
32
+ // scrolls the one around it. A trackpad gesture is routed once, as it begins, and its momentum
33
+ // follows it. A view drawn mirrored (an inverted list's scale of -1) scrolls by mirrored deltas, so
34
+ // the content follows the fingers, and the user's scroll direction, as drawn.
23
35
  @interface NGNWheelScrollView : NSScrollView
24
36
  @property (nonatomic) BOOL scrollingDisabled;
37
+ // `pagingEnabled`: a gesture's end settles on a page, the view's size along the axis.
38
+ @property (nonatomic) BOOL pagingEnabled;
39
+ // Called as a trackpad gesture this view scrolls with begins and ends, and as its momentum, or a
40
+ // page settling, begins and ends. `velocity` is the drag's at its end, in points a millisecond.
41
+ @property (nonatomic, copy) void (^phaseChanged)(NGNScrollPhase phase, NSPoint velocity);
25
42
  @end
43
+
44
+ // `event` with its deltas along the axes given turned round.
45
+ NSEvent *NGNMirroredScroll(NSEvent *event, BOOL x, BOOL y);