mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-02-11 20:08:37 +00:00
feat: init window.affine (#2682)
This commit is contained in:
59
packages/hooks/src/use-affine-ipc-renderer.ts
Normal file
59
packages/hooks/src/use-affine-ipc-renderer.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
|
||||
declare global {
|
||||
interface IPCRenderer {
|
||||
send(channel: string, ...args: any[]): void;
|
||||
invoke(channel: string, ...args: any[]): Promise<any>;
|
||||
on(
|
||||
channel: string,
|
||||
listener: (event: unknown, ...args: any[]) => void
|
||||
): this;
|
||||
once(
|
||||
channel: string,
|
||||
listener: (event: unknown, ...args: any[]) => void
|
||||
): this;
|
||||
removeListener(channel: string, listener: (...args: any[]) => void): this;
|
||||
}
|
||||
|
||||
interface Window {
|
||||
affine: {
|
||||
ipcRenderer: IPCRenderer;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsafe
|
||||
*/
|
||||
export function useAffineAsyncCallback(channel: string) {
|
||||
return useCallback(
|
||||
(...args: any[]): Promise<any> => {
|
||||
return window.affine.ipcRenderer.invoke(channel, ...args);
|
||||
},
|
||||
[channel]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsafe
|
||||
*/
|
||||
export function useAffineListener(
|
||||
channel: string,
|
||||
listener: (event: unknown, ...args: any[]) => void,
|
||||
once?: boolean
|
||||
): void {
|
||||
const fnRef = useRef<((event: unknown, ...args: any[]) => void) | null>(null);
|
||||
if (!fnRef.current) {
|
||||
fnRef.current = listener;
|
||||
}
|
||||
useEffect(() => {
|
||||
if (once) {
|
||||
window.affine.ipcRenderer.once(channel, fnRef.current!);
|
||||
} else {
|
||||
window.affine.ipcRenderer.on(channel, fnRef.current!);
|
||||
}
|
||||
return () => {
|
||||
window.affine.ipcRenderer.removeListener(channel, fnRef.current!);
|
||||
};
|
||||
}, [channel, once]);
|
||||
}
|
||||
Reference in New Issue
Block a user