Factored out ipcRenderer.on

Summary:
Delegate receiving events from the Electron host process to the RenderHost interface.

Typed them as well while at it.

Reviewed By: timur-valiev

Differential Revision: D31828130

fbshipit-source-id: 920055de6f48512b91a433b229dbacd611c6f139
This commit is contained in:
Michel Weststrate
2021-10-22 09:20:14 -07:00
committed by Facebook GitHub Bot
parent cc946d12ec
commit ecf2e32722
6 changed files with 70 additions and 37 deletions

View File

@@ -7,6 +7,22 @@
* @format * @format
*/ */
import {NotificationEvents} from './dispatcher/notifications';
import {PluginNotification} from './reducers/notifications';
// Events that are emitted from the main.ts ovr the IPC process bridge in Electron
type MainProcessEvents = {
'flipper-protocol-handler': [query: string];
'open-flipper-file': [url: string];
notificationEvent: [
eventName: NotificationEvents,
pluginNotification: PluginNotification,
arg: null | string | number,
];
trackUsage: any[];
getLaunchTime: [launchStartTime: number];
};
/** /**
* Utilities provided by the render host, e.g. Electron, the Browser, etc * Utilities provided by the render host, e.g. Electron, the Browser, etc
*/ */
@@ -16,6 +32,10 @@ export interface RenderHost {
selectDirectory?(defaultPath?: string): Promise<string | undefined>; selectDirectory?(defaultPath?: string): Promise<string | undefined>;
registerShortcut(shortCut: string, callback: () => void): void; registerShortcut(shortCut: string, callback: () => void): void;
hasFocus(): boolean; hasFocus(): boolean;
onIpcEvent<Event extends keyof MainProcessEvents>(
event: Event,
callback: (...arg: MainProcessEvents[Event]) => void,
): void;
} }
let renderHostInstance: RenderHost | undefined; let renderHostInstance: RenderHost | undefined;
@@ -41,5 +61,6 @@ if (process.env.NODE_ENV === 'test') {
hasFocus() { hasFocus() {
return true; return true;
}, },
onIpcEvent() {},
}); });
} }

View File

@@ -9,7 +9,7 @@
// Fine for app startup. // Fine for app startup.
// eslint-disable-next-line flipper/no-electron-remote-imports // eslint-disable-next-line flipper/no-electron-remote-imports
import {remote, ipcRenderer, IpcRendererEvent} from 'electron'; import {remote} from 'electron';
import {Store} from '../reducers/index'; import {Store} from '../reducers/index';
import {Logger} from 'flipper-common'; import {Logger} from 'flipper-common';
import { import {
@@ -19,9 +19,12 @@ import {
import {tryCatchReportPlatformFailures} from 'flipper-common'; import {tryCatchReportPlatformFailures} from 'flipper-common';
import {handleDeeplink} from '../deeplink'; import {handleDeeplink} from '../deeplink';
import {Dialog} from 'flipper-plugin'; import {Dialog} from 'flipper-plugin';
import {getRenderHostInstance} from '../RenderHost';
export default (store: Store, logger: Logger) => { export default (store: Store, logger: Logger) => {
const currentWindow = remote.getCurrentWindow(); const currentWindow = remote.getCurrentWindow();
const renderHost = getRenderHostInstance();
const onFocus = () => { const onFocus = () => {
setImmediate(() => { setImmediate(() => {
store.dispatch({ store.dispatch({
@@ -55,28 +58,22 @@ export default (store: Store, logger: Logger) => {
}); });
}); });
ipcRenderer.on( renderHost.onIpcEvent('flipper-protocol-handler', (query: string) => {
'flipper-protocol-handler', handleDeeplink(store, logger, query).catch((e) => {
(_event: IpcRendererEvent, query: string) => { console.warn('Failed to handle deeplink', query, e);
handleDeeplink(store, logger, query).catch((e) => { Dialog.alert({
console.warn('Failed to handle deeplink', query, e); title: 'Failed to open deeplink',
Dialog.alert({ type: 'error',
title: 'Failed to open deeplink', message: `Failed to handle deeplink '${query}': ${
type: 'error', e.message ?? e.toString()
message: `Failed to handle deeplink '${query}': ${ }`,
e.message ?? e.toString()
}`,
});
}); });
}, });
); });
ipcRenderer.on( renderHost.onIpcEvent('open-flipper-file', (url: string) => {
'open-flipper-file', tryCatchReportPlatformFailures(() => {
(_event: IpcRendererEvent, url: string) => { return importFileToStore(url, store);
tryCatchReportPlatformFailures(() => { }, `${IMPORT_FLIPPER_TRACE_EVENT}:Deeplink`);
return importFileToStore(url, store); });
}, `${IMPORT_FLIPPER_TRACE_EVENT}:Deeplink`);
},
);
}; };

View File

@@ -10,7 +10,7 @@
import {Store} from '../reducers/index'; import {Store} from '../reducers/index';
import {Logger} from 'flipper-common'; import {Logger} from 'flipper-common';
import {PluginNotification} from '../reducers/notifications'; import {PluginNotification} from '../reducers/notifications';
import {ipcRenderer, IpcRendererEvent} from 'electron'; import {ipcRenderer} from 'electron';
import { import {
updatePluginBlocklist, updatePluginBlocklist,
updateCategoryBlocklist, updateCategoryBlocklist,
@@ -19,18 +19,24 @@ import {textContent} from 'flipper-plugin';
import {getPluginTitle} from '../utils/pluginUtils'; import {getPluginTitle} from '../utils/pluginUtils';
import {sideEffect} from '../utils/sideEffect'; import {sideEffect} from '../utils/sideEffect';
import {openNotification} from '../sandy-chrome/notification/Notification'; import {openNotification} from '../sandy-chrome/notification/Notification';
import {getRenderHostInstance} from '../RenderHost';
export type NotificationEvents =
| 'show'
| 'click'
| 'close'
| 'reply'
| 'action';
type NotificationEvents = 'show' | 'click' | 'close' | 'reply' | 'action';
const NOTIFICATION_THROTTLE = 5 * 1000; // in milliseconds const NOTIFICATION_THROTTLE = 5 * 1000; // in milliseconds
export default (store: Store, logger: Logger) => { export default (store: Store, logger: Logger) => {
const knownNotifications: Set<string> = new Set(); const knownNotifications: Set<string> = new Set();
const lastNotificationTime: Map<string, number> = new Map(); const lastNotificationTime: Map<string, number> = new Map();
ipcRenderer.on( getRenderHostInstance().onIpcEvent(
'notificationEvent', 'notificationEvent',
( (
_event: IpcRendererEvent,
eventName: NotificationEvents, eventName: NotificationEvents,
pluginNotification: PluginNotification, pluginNotification: PluginNotification,
arg: null | string | number, arg: null | string | number,

View File

@@ -7,9 +7,6 @@
* @format * @format
*/ */
// Used for PID tracking.
// eslint-disable-next-line flipper/no-electron-remote-imports
import {ipcRenderer} from 'electron';
import {performance} from 'perf_hooks'; import {performance} from 'perf_hooks';
import {EventEmitter} from 'events'; import {EventEmitter} from 'events';
@@ -146,16 +143,15 @@ export default (store: Store, logger: Logger) => {
); );
} }
ipcRenderer.on('trackUsage', (event, ...args: any[]) => { renderHost.onIpcEvent('trackUsage', (...args: any[]) => {
let state: State; let state: State;
try { try {
state = store.getState(); state = store.getState();
} catch (e) { } catch (e) {
// if trackUsage is called (indirectly) through a reducer, this will utterly die Flipper. Let's prevent that and log an error instead // if trackUsage is called (indirectly) through a reducer, this will utterly die Flipper. Let's prevent that and log an error instead
console.error( console.error(
'trackUsage triggered indirectly as side effect of a reducer. Event: ', 'trackUsage triggered indirectly as side effect of a reducer',
event.type, e,
event,
); );
return; return;
} }

View File

@@ -297,5 +297,10 @@ function initializeFlipperForElectron() {
hasFocus() { hasFocus() {
return remote.getCurrentWindow().isFocused(); return remote.getCurrentWindow().isFocused();
}, },
onIpcEvent(event, callback) {
ipcRenderer.on(event, (_ev, ...args: any[]) => {
callback(...(args as any));
});
},
}); });
} }

View File

@@ -38,6 +38,7 @@ import fbConfig from '../fb-stubs/config';
import {isFBEmployee} from '../utils/fbEmployee'; import {isFBEmployee} from '../utils/fbEmployee';
import {notification} from 'antd'; import {notification} from 'antd';
import isProduction from '../utils/isProduction'; import isProduction from '../utils/isProduction';
import {getRenderHostInstance} from '../RenderHost';
export type ToplevelNavItem = export type ToplevelNavItem =
| 'appinspect' | 'appinspect'
@@ -214,9 +215,16 @@ function registerStartupTime(logger: Logger) {
// track time since launch // track time since launch
const [s, ns] = process.hrtime(); const [s, ns] = process.hrtime();
const launchEndTime = s * 1e3 + ns / 1e6; const launchEndTime = s * 1e3 + ns / 1e6;
ipcRenderer.on('getLaunchTime', (_: any, launchStartTime: number) => { getRenderHostInstance().onIpcEvent(
logger.track('performance', 'launchTime', launchEndTime - launchStartTime); 'getLaunchTime',
}); (launchStartTime: number) => {
logger.track(
'performance',
'launchTime',
launchEndTime - launchStartTime,
);
},
);
ipcRenderer.send('getLaunchTime'); ipcRenderer.send('getLaunchTime');
ipcRenderer.send('componentDidMount'); ipcRenderer.send('componentDidMount');