mirror of
https://github.com/darksaid98/new-phone-who-dis.git
synced 2026-12-04 14:38:45 +00:00
Make use of library instead of having code duplicated (#201)
* Use fivem-nui-react-lib
This commit is contained in:
1 parent
0cf5bc2bc7
commit
8e79eb1345
60 files changed
+231
-347
No files matched your search
@@ -1,9 +1,10 @@
|
||||
import { useEffect } from 'react';
|
||||
import Nui from '../../nui-events/utils/Nui';
|
||||
import { useNuiRequest } from 'fivem-nui-react-lib';
|
||||
|
||||
export const AppWithStartup = ({ children, id }) => {
|
||||
const Nui = useNuiRequest();
|
||||
useEffect(() => {
|
||||
Nui.send(`npwd:app:${id}`);
|
||||
}, [id]);
|
||||
}, [Nui, id]);
|
||||
return children;
|
||||
};
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useRecoilState } from 'recoil';
|
||||
import { CallProps } from '../../../../../typings/call';
|
||||
import Nui from '../../nui-events/utils/Nui';
|
||||
import { callerState } from './state';
|
||||
import { CallEvents } from '../../../../../typings/call';
|
||||
import { useNuiRequest } from 'fivem-nui-react-lib';
|
||||
|
||||
interface CallHook {
|
||||
call: CallProps;
|
||||
@@ -13,6 +13,7 @@ interface CallHook {
|
||||
}
|
||||
|
||||
export const useCall = (): CallHook => {
|
||||
const Nui = useNuiRequest();
|
||||
const [call, setCall] = useRecoilState(callerState.currentCall);
|
||||
|
||||
const acceptCall = () => {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNuiEvent } from '../../nui-events/hooks/useNuiEvent';
|
||||
import { useSetRecoilState } from 'recoil';
|
||||
import { useCall } from './useCall';
|
||||
import { CallEvents, CallProps } from '../../../../../typings/call';
|
||||
@@ -8,6 +7,7 @@ import { useCallModal } from './useCallModal';
|
||||
import { useHistory, useLocation } from 'react-router-dom';
|
||||
import { callerState } from './state';
|
||||
import { useCallNotifications } from './useCallNotifications';
|
||||
import { useNuiEvent } from 'fivem-nui-react-lib';
|
||||
|
||||
// InjectDebugData<CallProps | boolean>([
|
||||
// {
|
||||
@@ -55,9 +55,9 @@ export const useCallService = () => {
|
||||
}, [history, modal, pathname, modalHasBeenOpenedThisCall]);
|
||||
|
||||
const _setCall = (_call: CallProps) => {
|
||||
setCall(_call);
|
||||
setCall({ ...call, ..._call });
|
||||
setNotification(_call);
|
||||
};
|
||||
useNuiEvent<CallProps>('CALL', CallEvents.SET_CALLER, _setCall, call);
|
||||
useNuiEvent<boolean>('CALL', CallEvents.SET_CALL_MODAL, setModal);
|
||||
useNuiEvent('CALL', CallEvents.SET_CALLER, _setCall);
|
||||
useNuiEvent('CALL', CallEvents.SET_CALL_MODAL, setModal);
|
||||
};
|
||||
@@ -1,55 +0,0 @@
|
||||
import { MutableRefObject, useEffect, useRef } from 'react';
|
||||
import { eventNameFactory } from '../utils/nuiUtils';
|
||||
import DebugLog from '../../debug/LogDebugEvents';
|
||||
|
||||
interface IOptions {
|
||||
capture?: boolean;
|
||||
passive?: boolean;
|
||||
once?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A hook that manage events listeners for receiving data from the NUI
|
||||
* @param app The app name in which this hoook is used
|
||||
* @param method The specific `method` field that should be listened for.
|
||||
* @param handler The callback function that will handle data relayed by this hook
|
||||
* @param options Any options to pass to the addEventListener
|
||||
**/
|
||||
|
||||
const defaultOptions = {};
|
||||
|
||||
export const useNuiEvent = <S = Record<string, unknown>>(
|
||||
app: string,
|
||||
method: string,
|
||||
handler: Function,
|
||||
currentState?: S,
|
||||
options: IOptions = defaultOptions,
|
||||
) => {
|
||||
const savedHandler: MutableRefObject<any> = useRef();
|
||||
|
||||
// When handler value changes set mutable ref to handler val
|
||||
useEffect(() => {
|
||||
savedHandler.current = handler;
|
||||
}, [handler]);
|
||||
|
||||
// Will run every rerender
|
||||
useEffect(() => {
|
||||
const eventName = eventNameFactory(app, method);
|
||||
const eventListener = (event) => {
|
||||
if (savedHandler.current && savedHandler.current.call) {
|
||||
const { data } = event;
|
||||
DebugLog({
|
||||
action: `NUI Data Received (${eventName})`,
|
||||
data: event.data,
|
||||
level: 1,
|
||||
});
|
||||
const newData = currentState ? { ...currentState, ...data } : data;
|
||||
savedHandler.current(newData);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener(eventName, eventListener, options);
|
||||
// Remove Event Listener on component cleanup
|
||||
return () => window.removeEventListener(eventName, eventListener, options);
|
||||
}, [app, method, currentState, options]);
|
||||
};
|
||||
@@ -1,104 +0,0 @@
|
||||
import { FetchData } from '@sentry/tracing/dist/browser/request';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import Nui, { IAbortableFetch } from '../utils/Nui';
|
||||
import { eventNameFactory } from '../utils/nuiUtils';
|
||||
import { useNuiEvent } from './useNuiEvent';
|
||||
|
||||
type UseNuiEventCallbackResponse<I, R> = [
|
||||
(d?: I) => void,
|
||||
{ loading: boolean; error: any; response: R },
|
||||
];
|
||||
|
||||
export const useNuiEventCallback = <I = FetchData, R = FetchData>(
|
||||
app: string,
|
||||
method: string,
|
||||
handler?: (res: R) => void,
|
||||
errHandler?: Function,
|
||||
): UseNuiEventCallbackResponse<I, R> => {
|
||||
const fetchRef = useRef<IAbortableFetch>();
|
||||
const timeoutRef = useRef<NodeJS.Timeout>();
|
||||
|
||||
// These are Refs to avoid re renders.
|
||||
// We dont care if "app" and "method" arguments change.
|
||||
const eventNameRef = useRef<string>(eventNameFactory(app, method));
|
||||
const methodNameRef = useRef<string>(method);
|
||||
const appNameRef = useRef<string>(app);
|
||||
|
||||
const [timedOut, setTimedOut] = useState<boolean>(false);
|
||||
const [loading, setLoading] = useState<boolean>(false);
|
||||
const [error, setError] = useState<any>(null);
|
||||
const [response, setResponse] = useState<R>(null);
|
||||
|
||||
const onSuccess = useCallback(
|
||||
(data: R) => {
|
||||
if (!loading) {
|
||||
return;
|
||||
}
|
||||
// If we receive eventNameSuccess event, clear timeout
|
||||
timeoutRef.current && clearTimeout(timeoutRef.current);
|
||||
// If already timed out, don't do shit :)
|
||||
if (timedOut) {
|
||||
return;
|
||||
}
|
||||
// Set new state after success event received
|
||||
setResponse(data);
|
||||
setError(null);
|
||||
setLoading(false);
|
||||
handler?.(data);
|
||||
},
|
||||
[handler, timedOut, loading],
|
||||
);
|
||||
|
||||
const onError = useCallback(
|
||||
(err: any) => {
|
||||
if (!loading) {
|
||||
return;
|
||||
}
|
||||
// If we receive eventNameSuccess event, clear timeout
|
||||
timeoutRef.current && clearTimeout(timeoutRef.current);
|
||||
// If already timed out, don't do shit :)
|
||||
if (timedOut) {
|
||||
return;
|
||||
}
|
||||
// Set new state after error event received
|
||||
setError(err);
|
||||
setResponse(null);
|
||||
setLoading(false);
|
||||
errHandler?.(err);
|
||||
},
|
||||
[errHandler, timedOut, loading],
|
||||
);
|
||||
|
||||
// React to loading change and starting timeout timer.
|
||||
useEffect(() => {
|
||||
if (loading && !timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
timeoutRef.current = setTimeout(() => {
|
||||
setTimedOut(true);
|
||||
onError(
|
||||
new Error(`${eventNameRef.current} NUI Event Callback timed out after 10000 seconds`),
|
||||
);
|
||||
fetchRef.current && fetchRef.current.abort();
|
||||
timeoutRef.current = undefined;
|
||||
fetchRef.current = undefined;
|
||||
}, 10000);
|
||||
}
|
||||
}, [loading, onError]);
|
||||
|
||||
// Handle the success and error events for this method
|
||||
useNuiEvent(appNameRef.current, `${methodNameRef.current}Success`, onSuccess);
|
||||
useNuiEvent(appNameRef.current, `${methodNameRef.current}Error`, onError);
|
||||
|
||||
// Only fetch if we are not loading/waiting the events.
|
||||
const fetch = useCallback((data?: I) => {
|
||||
setLoading((curr) => {
|
||||
if (!curr) {
|
||||
fetchRef.current = Nui.sendAbortable(methodNameRef.current, data);
|
||||
return true;
|
||||
}
|
||||
return curr;
|
||||
});
|
||||
}, []);
|
||||
|
||||
return [fetch, { loading, response, error }];
|
||||
};
|
||||
@@ -1,27 +0,0 @@
|
||||
import { useEffect } from 'react';
|
||||
import { eventNameFactory } from '../utils/nuiUtils';
|
||||
|
||||
interface IOptions {
|
||||
capture?: boolean;
|
||||
passive?: boolean;
|
||||
once?: boolean;
|
||||
}
|
||||
|
||||
export const useNuiService = (options: IOptions = {}) => {
|
||||
const { capture, passive, once } = options;
|
||||
const eventListener = (event: any) => {
|
||||
const { app, method, data } = event.data;
|
||||
if (app && method && data !== undefined) {
|
||||
window.dispatchEvent(
|
||||
new MessageEvent(eventNameFactory(app, method), {
|
||||
data,
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
const opts = { capture, passive, once };
|
||||
window.addEventListener('message', eventListener, opts);
|
||||
return () => window.removeEventListener('message', eventListener, opts);
|
||||
}, [capture, passive, once]);
|
||||
};
|
||||
@@ -1,36 +0,0 @@
|
||||
export interface IAbortableFetch {
|
||||
abort: () => void;
|
||||
promise: Promise<Response>;
|
||||
}
|
||||
|
||||
function abortableFetch(request, opts): IAbortableFetch {
|
||||
const controller = new AbortController();
|
||||
const signal = controller.signal;
|
||||
|
||||
return {
|
||||
abort: () => controller.abort(),
|
||||
promise: fetch(request, { ...opts, signal }),
|
||||
};
|
||||
}
|
||||
|
||||
function getParams(event, data): [RequestInfo, RequestInit] {
|
||||
return [
|
||||
`https://new-phone-who-dis/${event}`,
|
||||
{
|
||||
method: 'post',
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=UTF-8',
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export default {
|
||||
async send(event: any, data = {}) {
|
||||
return fetch(...getParams(event, data));
|
||||
},
|
||||
sendAbortable(event: any, data = {}): IAbortableFetch {
|
||||
return abortableFetch(...getParams(event, data));
|
||||
},
|
||||
};
|
||||
@@ -1,3 +0,0 @@
|
||||
export const eventNameFactory = (app: string, method: string) => `${app}:${method}`;
|
||||
|
||||
export const eventNameMethod = (name: string) => name.split(':')[1] || null;
|
||||
@@ -2,7 +2,7 @@ import { useRecoilValue } from 'recoil';
|
||||
import { IServerConfig } from '../../../../../typings/config';
|
||||
import ServerConfig from '../../../config.autogen.json';
|
||||
import { useNotifications } from '../../notifications/hooks/useNotifications';
|
||||
import Nui from '../../nui-events/utils/Nui';
|
||||
import { useNuiRequest } from 'fivem-nui-react-lib';
|
||||
import { phoneState } from './state';
|
||||
import { PhoneEvents } from '../../../../../typings/phone';
|
||||
|
||||
@@ -15,6 +15,7 @@ interface IUsePhone {
|
||||
}
|
||||
|
||||
export const usePhone = (): IUsePhone => {
|
||||
const Nui = useNuiRequest();
|
||||
const isPhoneOpen = useRecoilValue(phoneState.visibility);
|
||||
const isPhoneReady = useRecoilValue(phoneState.phoneReady);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useNuiEvent } from 'fivem-nui-react-lib';
|
||||
import { useSetRecoilState } from 'recoil';
|
||||
import { phoneState } from './state';
|
||||
import { useNuiEvent } from '../../nui-events/hooks/useNuiEvent';
|
||||
|
||||
export const usePhoneService = () => {
|
||||
const setVisibility = useSetRecoilState(phoneState.visibility);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useNuiEvent } from '../../nui-events/hooks/useNuiEvent';
|
||||
import { useSetRecoilState } from 'recoil';
|
||||
import { simcardState } from './state';
|
||||
import { useSimcard } from './useSimcard';
|
||||
import InjectDebugData from '../../debug/InjectDebugData';
|
||||
import { useNuiEvent } from 'fivem-nui-react-lib';
|
||||
|
||||
InjectDebugData([
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user