This commit is contained in:
Shusui MOYATANI
2023-03-09 00:55:05 +09:00
parent adbee3e174
commit 75e2244220
9 changed files with 45 additions and 33 deletions

View File

@@ -1,4 +1,3 @@
import { onMount } from 'solid-js';
import { useRequestMessage, useHandleMessage } from '@/hooks/useMessageBus';
type UseHandleCommandProps = {

View File

@@ -14,11 +14,9 @@ export type MessageChannelRequest<T> = {
request: T;
};
export type MessageChannelResponse<T> = {
requestId: string;
response?: T;
error?: any;
};
export type MessageChannelResponse<T> =
| { requestId: string; ok: true; response: T }
| { requestId: string; ok: false; error: any };
const [channels, setChannels]: Signal<Record<string, MessageChannel>> = createSignal({});
@@ -42,22 +40,26 @@ export const useRequestMessage = <Req, Res>(propsProvider: () => UseRequestMessa
const waitResponse = (requestId: string, timeoutMs = 1000): Promise<Res> =>
new Promise((resolve, reject) => {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const listener = (event: MessageEvent) => {
const data = event.data as MessageChannelResponse<Res>;
if (data.requestId !== requestId) return;
channel().port1.removeEventListener('message', listener);
if (data.response != null) {
if (data.ok) {
resolve(data.response);
} else {
reject(data.error);
}
if (timeoutId != null) {
clearTimeout(timeoutId);
}
};
setTimeout(() => {
timeoutId = setTimeout(() => {
channel().port1.removeEventListener('message', listener);
reject(new Error('TimeoutError'));
reject(new Error(`TimeoutError: ${requestId}`));
}, timeoutMs);
channel().port1.addEventListener('message', listener, false);
@@ -84,6 +86,9 @@ export const useHandleMessage = <Req, Res>(
const channel = () => channels()[props().id];
onMount(() => {
const { id } = props();
registerChannelIfNotExist(id);
const port = channel().port2;
const messageHandler = (event: MessageEvent) => {
const { requestId, request } = event.data as MessageChannelRequest<Req>;
@@ -92,12 +97,12 @@ export const useHandleMessage = <Req, Res>(
resultPromise
.then((res) => {
const response: MessageChannelResponse<Res> = { requestId, response: res };
const response: MessageChannelResponse<Res> = { requestId, ok: true, response: res };
port.postMessage(response);
})
.catch((err) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const response: MessageChannelResponse<Res> = { requestId, error: err };
const response: MessageChannelResponse<Res> = { requestId, ok: false, error: err };
port.postMessage(response);
});
};

View File

@@ -68,7 +68,7 @@ export const useMountShortcutKeys = () => {
useShortcutKeys({
onShortcut: (shortcut) => {
request(shortcut.command).then(
() => console.debug(`${shortcut.key} was processed successfully`),
() => console.debug(`shortcut key '${shortcut.key}' was processed successfully`),
(err) => console.error(err),
);
},