RCTReloadCommand.m 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #import "RCTReloadCommand.h"
  8. #import "RCTAssert.h"
  9. #import "RCTKeyCommands.h"
  10. #import "RCTUtils.h"
  11. static NSHashTable<id<RCTReloadListener>> *listeners;
  12. static NSLock *listenersLock;
  13. static NSURL *bundleURL;
  14. NSString *const RCTTriggerReloadCommandNotification = @"RCTTriggerReloadCommandNotification";
  15. NSString *const RCTTriggerReloadCommandReasonKey = @"reason";
  16. NSString *const RCTTriggerReloadCommandBundleURLKey = @"bundleURL";
  17. void RCTRegisterReloadCommandListener(id<RCTReloadListener> listener)
  18. {
  19. if (!listenersLock) {
  20. listenersLock = [NSLock new];
  21. }
  22. [listenersLock lock];
  23. if (!listeners) {
  24. listeners = [NSHashTable weakObjectsHashTable];
  25. }
  26. #if RCT_DEV
  27. RCTAssertMainQueue(); // because registerKeyCommandWithInput: must be called on the main thread
  28. static dispatch_once_t onceToken;
  29. dispatch_once(&onceToken, ^{
  30. [[RCTKeyCommands sharedInstance] registerKeyCommandWithInput:@"r"
  31. modifierFlags:UIKeyModifierCommand
  32. action:^(__unused UIKeyCommand *command) {
  33. RCTTriggerReloadCommandListeners(@"Command + R");
  34. }];
  35. });
  36. #endif
  37. [listeners addObject:listener];
  38. [listenersLock unlock];
  39. }
  40. void RCTTriggerReloadCommandListeners(NSString *reason)
  41. {
  42. [listenersLock lock];
  43. [[NSNotificationCenter defaultCenter] postNotificationName:RCTTriggerReloadCommandNotification
  44. object:nil
  45. userInfo:@{
  46. RCTTriggerReloadCommandReasonKey : RCTNullIfNil(reason),
  47. RCTTriggerReloadCommandBundleURLKey : RCTNullIfNil(bundleURL)
  48. }];
  49. for (id<RCTReloadListener> l in [listeners allObjects]) {
  50. [l didReceiveReloadCommand];
  51. }
  52. [listenersLock unlock];
  53. }
  54. void RCTReloadCommandSetBundleURL(NSURL *URL)
  55. {
  56. bundleURL = URL;
  57. }