DevSettings.js 1.8 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. * @format
  8. */
  9. import NativeDevSettings from '../NativeModules/specs/NativeDevSettings';
  10. import NativeEventEmitter from '../EventEmitter/NativeEventEmitter';
  11. class DevSettings extends NativeEventEmitter {
  12. _menuItems: Map<string, () => mixed>;
  13. constructor() {
  14. super(NativeDevSettings);
  15. this._menuItems = new Map();
  16. }
  17. addMenuItem(title: string, handler: () => mixed) {
  18. // Make sure items are not added multiple times. This can
  19. // happen when hot reloading the module that registers the
  20. // menu items. The title is used as the id which means we
  21. // don't support multiple items with the same name.
  22. const oldHandler = this._menuItems.get(title);
  23. if (oldHandler != null) {
  24. this.removeListener('didPressMenuItem', oldHandler);
  25. } else {
  26. NativeDevSettings.addMenuItem(title);
  27. }
  28. this._menuItems.set(title, handler);
  29. this.addListener('didPressMenuItem', event => {
  30. if (event.title === title) {
  31. handler();
  32. }
  33. });
  34. }
  35. reload(reason: string) {
  36. if (typeof NativeDevSettings.reloadWithReason === 'function') {
  37. NativeDevSettings.reloadWithReason(reason || 'Uncategorized from JS');
  38. } else {
  39. NativeDevSettings.reload();
  40. }
  41. }
  42. onFastRefresh() {
  43. if (typeof NativeDevSettings.onFastRefresh === 'function') {
  44. NativeDevSettings.onFastRefresh();
  45. }
  46. }
  47. // TODO: Add other dev setting methods exposed by the native module.
  48. }
  49. // Avoid including the full `NativeDevSettings` class in prod.
  50. class NoopDevSettings {
  51. addMenuItem(title: string, handler: () => mixed) {}
  52. reload() {}
  53. }
  54. module.exports = __DEV__ ? new DevSettings() : new NoopDevSettings();