2019-10-19 15:48:39 +00:00
|
|
|
/*
|
|
|
|
Copyright 2019 The Matrix.org Foundation C.I.C.
|
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
limitations under the License.
|
|
|
|
*/
|
|
|
|
|
2021-07-28 16:39:56 +00:00
|
|
|
import { useRef, useEffect, useState, useCallback } from "react";
|
2021-06-29 12:11:58 +00:00
|
|
|
import type { EventEmitter } from "events";
|
2020-08-04 21:00:05 +00:00
|
|
|
|
|
|
|
type Handler = (...args: any[]) => void;
|
2019-10-19 15:39:06 +00:00
|
|
|
|
|
|
|
// Hook to wrap event emitter on and removeListener in hook lifecycle
|
2020-08-04 21:00:05 +00:00
|
|
|
export const useEventEmitter = (emitter: EventEmitter, eventName: string | symbol, handler: Handler) => {
|
2019-10-19 15:39:06 +00:00
|
|
|
// Create a ref that stores handler
|
2020-08-04 21:00:05 +00:00
|
|
|
const savedHandler = useRef(handler);
|
2019-10-19 15:39:06 +00:00
|
|
|
|
|
|
|
// Update ref.current value if handler changes.
|
|
|
|
useEffect(() => {
|
|
|
|
savedHandler.current = handler;
|
|
|
|
}, [handler]);
|
|
|
|
|
|
|
|
useEffect(
|
|
|
|
() => {
|
2019-12-17 14:05:51 +00:00
|
|
|
// allow disabling this hook by passing a falsy emitter
|
|
|
|
if (!emitter) return;
|
|
|
|
|
2019-10-19 15:39:06 +00:00
|
|
|
// Create event listener that calls handler function stored in ref
|
2020-05-24 13:11:25 +00:00
|
|
|
const eventListener = (...args) => savedHandler.current(...args);
|
2019-10-19 15:39:06 +00:00
|
|
|
|
|
|
|
// Add event listener
|
|
|
|
emitter.on(eventName, eventListener);
|
|
|
|
|
|
|
|
// Remove event listener on cleanup
|
|
|
|
return () => {
|
|
|
|
emitter.removeListener(eventName, eventListener);
|
|
|
|
};
|
|
|
|
},
|
|
|
|
[eventName, emitter], // Re-run if eventName or emitter changes
|
|
|
|
);
|
|
|
|
};
|
2021-07-28 16:39:56 +00:00
|
|
|
|
|
|
|
type Mapper<T> = (...args: any[]) => T;
|
|
|
|
|
|
|
|
export const useEventEmitterState = <T>(emitter: EventEmitter, eventName: string | symbol, fn: Mapper<T>): T => {
|
|
|
|
const [value, setValue] = useState<T>(fn());
|
|
|
|
const handler = useCallback((...args: any[]) => {
|
|
|
|
setValue(fn(...args));
|
|
|
|
}, [fn]);
|
|
|
|
useEventEmitter(emitter, eventName, handler);
|
|
|
|
return value;
|
|
|
|
};
|