mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-08-01 09:30:01 +08:00
feat: improve electron sandbox (#14156)
This commit is contained in:
@@ -10,6 +10,7 @@ import { z } from 'zod';
|
||||
import {
|
||||
AFFINE_API_CHANNEL_NAME,
|
||||
AFFINE_EVENT_CHANNEL_NAME,
|
||||
AFFINE_EVENT_SUBSCRIBE_CHANNEL_NAME,
|
||||
type ExposedMeta,
|
||||
type HelperToRenderer,
|
||||
type RendererToHelper,
|
||||
@@ -83,6 +84,33 @@ function getMainAPIs() {
|
||||
|
||||
// channel -> callback[]
|
||||
const listenersMap = new Map<string, ((...args: any[]) => void)[]>();
|
||||
const subscribeCounts = new Map<string, number>();
|
||||
|
||||
const subscribe = (channel: string) => {
|
||||
const count = (subscribeCounts.get(channel) ?? 0) + 1;
|
||||
subscribeCounts.set(channel, count);
|
||||
if (count === 1) {
|
||||
ipcRenderer.send(
|
||||
AFFINE_EVENT_SUBSCRIBE_CHANNEL_NAME,
|
||||
'subscribe',
|
||||
channel
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const unsubscribe = (channel: string) => {
|
||||
const count = (subscribeCounts.get(channel) ?? 0) - 1;
|
||||
if (count <= 0) {
|
||||
subscribeCounts.delete(channel);
|
||||
ipcRenderer.send(
|
||||
AFFINE_EVENT_SUBSCRIBE_CHANNEL_NAME,
|
||||
'unsubscribe',
|
||||
channel
|
||||
);
|
||||
} else {
|
||||
subscribeCounts.set(channel, count);
|
||||
}
|
||||
};
|
||||
|
||||
ipcRenderer.on(AFFINE_EVENT_CHANNEL_NAME, (_event, channel, ...args) => {
|
||||
if (typeof channel !== 'string') {
|
||||
@@ -108,12 +136,20 @@ function getMainAPIs() {
|
||||
...(listenersMap.get(channel) ?? []),
|
||||
callback,
|
||||
]);
|
||||
subscribe(channel);
|
||||
|
||||
return () => {
|
||||
const listeners = listenersMap.get(channel) ?? [];
|
||||
const index = listeners.indexOf(callback);
|
||||
if (index !== -1) {
|
||||
listeners.splice(index, 1);
|
||||
if (index === -1) {
|
||||
return;
|
||||
}
|
||||
listeners.splice(index, 1);
|
||||
unsubscribe(channel);
|
||||
if (listeners.length === 0) {
|
||||
listenersMap.delete(channel);
|
||||
} else {
|
||||
listenersMap.set(channel, listeners);
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user