Merge branch 'refactor' into main

This commit is contained in:
Linden committed 2022-02-14 22:23:28 +11:00
commit 2ea78f1b1b
58 files changed
+14613 -521

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+24
View File
@@ -0,0 +1,24 @@
const path = require('path');
module.exports = {
webpack: {
configure: (webpackConfig) => {
// Because CEF has issues with loading source maps properly atm,
// lets use the best we can get in line with `eval-source-map`
if (webpackConfig.mode === 'development' && process.env.IN_GAME_DEV) {
webpackConfig.devtool = 'eval-source-map';
webpackConfig.output.path = path.join(__dirname, 'build');
}
return webpackConfig;
},
},
devServer: (devServerConfig) => {
if (process.env.IN_GAME_DEV) {
// Used for in-game dev mode
devServerConfig.devMiddleware.writeToDisk = true;
}
return devServerConfig;
},
};
+55
View File
@@ -0,0 +1,55 @@
{
"name": "ui",
"version": "1.0.0",
"homepage": "ui/build",
"private": true,
"dependencies": {
"@chakra-ui/icons": "^1.1.1",
"@chakra-ui/react": "^1.7.3",
"@emotion/react": "^11",
"@emotion/styled": "^11",
"@types/jest": "^26.0.24",
"@types/node": "^16.11.18",
"@types/react": "^17.0.38",
"@types/react-dom": "^17.0.11",
"@types/react-table": "^7.7.9",
"framer-motion": "4.1.17",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "6",
"react-scripts": "5.0.0",
"react-table": "^7.7.0",
"typescript": "^4.5.4",
"victory": "^36.2.0"
},
"scripts": {
"start": "cross-env PUBLIC_URL=/ craco start",
"start:game": "cross-env IN_GAME_DEV=1 craco start",
"build": "rimraf build && craco build",
"test": "craco test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@craco/craco": "^6.4.3",
"cross-env": "^7.0.3",
"rimraf": "^3.0.2"
}
}
+23
View File
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<title>NUI React Boilerplate</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
+58
View File
@@ -0,0 +1,58 @@
import { Center, Box } from '@chakra-ui/react';
import { debugData } from '../utils/debugData';
import TopBar from './NavBars/TopBar';
import LeftBar from './NavBars/LeftBar';
import { Routes, Route, useNavigate } from 'react-router-dom';
import Resource from './Resource';
import RightBar from './NavBars/RightBar';
import MainContent from './MainContent';
import { useNuiEvent } from '../hooks/useNuiEvent';
debugData([
{
action: 'openUI',
data: {
resources: ['ox_inventory', 'luke_garages', 'es_extended'],
totalQueries: 732,
totalTime: 258,
slowQueries: 6,
chartData: [
{ x: 13, y: 350, z: 'ox_inventory' },
{ x: 27, y: 752, z: 'es_extended' },
{ x: 41, y: 52, z: 'luke_garages' },
],
},
},
]);
const App: React.FC = () => {
const navigate = useNavigate();
useNuiEvent('openUI', () => navigate('/'));
return (
<Center w="100%" h="100%">
<Box
width="60%"
height="50%"
backgroundColor="#191E26"
borderRadius="1vh"
color="white"
fontFamily="Poppins"
userSelect="none"
>
<TopBar />
<LeftBar />
<RightBar />
<MainContent>
<Routes>
<Route path="/:resource" element={<Resource />} />
<Route path="/" element={<></>} />
</Routes>
</MainContent>
</Box>
</Center>
);
};
export default App;
+16
View File
@@ -0,0 +1,16 @@
import React from 'react';
import { Box, Center } from '@chakra-ui/react';
const MainContent: React.FC = ({ children }) => {
return (
<>
<Center h="95%" alignItems="stretch">
<Box h="100%" w="50%" backgroundColor="#1B2129" flex="1" overflowY="scroll">
{children}
</Box>
</Center>
</>
);
};
export default MainContent;
+40
View File
@@ -0,0 +1,40 @@
import { Box, VStack } from '@chakra-ui/react';
import { useState } from 'react';
import { NavLink } from 'react-router-dom';
import { useNuiEvent } from '../../hooks/useNuiEvent';
import type { InitData } from '../../types';
const LeftBar: React.FC = () => {
const [initData, setInitData] = useState<InitData>({
resources: [''],
totalQueries: 0,
totalTime: 0,
slowQueries: 0,
chartData: [{ x: 0, y: 0, z: '' }],
});
useNuiEvent<InitData>('openUI', (data) => {
setInitData(data);
});
return (
<Box p="1.2vh" fontSize="1.5vh" float="left" w="13%" height="90%" overflowY="scroll">
<VStack align="left">
{initData.resources.map((resource, index) => (
<Box isTruncated key={`${resource}-${index}`}>
<NavLink
to={resource}
style={(state) => ({
color: state.isActive ? 'white' : 'grey',
})}
>
<Box _hover={{ color: 'white' }}>{resource}</Box>
</NavLink>
</Box>
))}
</VStack>
</Box>
);
};
export default LeftBar;
+56
View File
@@ -0,0 +1,56 @@
import { useState } from 'react';
import { Box, VStack, Center, Spacer, Flex, Text } from '@chakra-ui/react';
import { useNuiEvent } from '../../hooks/useNuiEvent';
import { VictoryPie, VictoryTooltip } from 'victory';
import type { InitData } from '../../types';
const RightBar: React.FC = () => {
const [initData, setInitData] = useState<InitData>({
totalQueries: 0,
totalTime: 0,
slowQueries: 0,
resources: [''],
chartData: [{ x: 0, y: 0, z: '' }],
});
// Debug data defined in LeftBar.tsx
useNuiEvent<InitData>('openUI', (data) => {
setInitData(data);
});
return (
<Box float="right" w="20%" h="100%" p="1.2vh">
<Center h="100%">
<Flex direction="column" h="100%">
<Box>
<VStack align="left">
<Text>Number of queries: {initData.totalQueries}</Text>
<Text>Time querying: {Math.trunc(initData.totalTime)} ms</Text>
<Text color="#f3eca1">Slow queries: {initData.slowQueries}</Text>
</VStack>
</Box>
<Spacer />
<Box>
<VictoryPie
colorScale="qualitative"
data={initData.chartData}
labelComponent={<VictoryTooltip flyoutPadding={18} style={{ fontSize: 24 }} cornerRadius={15} />}
style={{
labels: {
fill: 'black',
fontFamily: 'Poppins',
fontSize: 28,
},
}}
labels={({ datum }) => `${datum.z}: ${datum.x} (${Math.trunc(datum.y)}ms)`}
labelPlacement="parallel"
/>
</Box>
</Flex>
</Center>
</Box>
);
};
export default RightBar;
+13
View File
@@ -0,0 +1,13 @@
import { Box, Text } from '@chakra-ui/react';
const TopBar: React.FC = () => {
return (
<Box w="100%" h="5%">
<Text paddingLeft="1.2vh" fontSize="2vh">
Resources
</Text>
</Box>
);
};
export default TopBar;
+210
View File
@@ -0,0 +1,210 @@
import { useParams } from 'react-router-dom';
import { useEffect, useState, useMemo } from 'react';
import { fetchNui } from '../utils/fetchNui';
import { useNuiEvent } from '../hooks/useNuiEvent';
import { Table, Thead, Tbody, Tr, Th, Td, chakra, Flex, IconButton, Text, Spinner, Tooltip } from '@chakra-ui/react';
import {
TriangleDownIcon,
TriangleUpIcon,
ArrowLeftIcon,
ChevronLeftIcon,
ArrowRightIcon,
ChevronRightIcon,
} from '@chakra-ui/icons';
import { useTable, useSortBy, Column, usePagination, useFlexLayout } from 'react-table';
interface QueryData {
date: number;
query: string;
executionTime: number;
slow?: boolean;
}
interface TableData {
query: string;
executionTime: number;
slow?: boolean;
}
interface NuiData {
queries: QueryData[];
pageCount: number;
}
const Resource: React.FC = () => {
const { resource } = useParams();
const [isLoaded, setIsLoaded] = useState(false);
const [resourceData, setResourceData] = useState<QueryData[]>([
{
date: 0,
query: '',
executionTime: 0,
},
]);
const [totalPages, setTotalPages] = useState(1);
const data = useMemo<TableData[]>(() => resourceData, [resourceData]);
const columns = useMemo<Column<TableData>[]>(
() => [
{
Header: 'Query',
accessor: 'query',
},
{
Header: 'Execution time (ms)',
accessor: 'executionTime',
},
{
Header: 'Slow',
accessor: 'slow',
},
],
[]
);
const {
getTableProps,
getTableBodyProps,
headerGroups,
page,
canPreviousPage,
canNextPage,
pageOptions,
pageCount,
gotoPage,
nextPage,
previousPage,
state: { pageIndex, sortBy },
prepareRow,
} = useTable(
{
columns,
data,
initialState: { pageSize: 12, hiddenColumns: ['slow'] },
manualPagination: true,
manualSortBy: true,
pageCount: totalPages,
autoResetPage: false,
},
useSortBy,
usePagination,
useFlexLayout
);
useEffect(() => {
fetchNui('fetchResource', { resource, pageIndex, sortBy });
setIsLoaded(false);
}, [resource, pageIndex, sortBy]);
useNuiEvent<NuiData>('loadResource', (data) => {
setResourceData(data.queries);
setTotalPages(data.pageCount);
setIsLoaded(true);
});
return (
<Flex direction="column" justifyContent="space-between" alignItems="center" h="100%">
<Table {...getTableProps()} size="sm">
<Thead>
{headerGroups.map((header): any => (
<Tr {...header.getHeaderGroupProps()}>
{header.headers.map((column) => (
<Th
{...column.getHeaderProps(column.getSortByToggleProps())}
color="white"
fontFamily="Poppins"
borderBottomColor="#313C4A"
textAlign="center"
>
{column.render('Header')}
<chakra.span pl="4">
{column.isSorted ? (
column.isSortedDesc ? (
<TriangleDownIcon aria-label="sorted descending" />
) : (
<TriangleUpIcon aria-label="sorted ascending" />
)
) : null}
</chakra.span>
</Th>
))}
</Tr>
))}
</Thead>
<Tbody {...getTableBodyProps()}>
{isLoaded && (
<>
{page.map((row) => {
prepareRow(row);
return (
<Tr {...row.getRowProps()}>
{row.cells.map((cell) => (
<Tooltip isDisabled={cell.column.id === 'executionTime'} label={cell.value} openDelay={500}>
<Td
{...cell.getCellProps()}
fontFamily="Poppins"
borderBottomColor="#313C4A"
color={row.values.slow && '#f3eca1'}
isTruncated={cell.column.id === 'query'}
textAlign={cell.column.id === 'executionTime' ? 'center' : 'left'}
>
{cell.render('Cell')}
</Td>
</Tooltip>
))}
</Tr>
);
})}
</>
)}
</Tbody>
</Table>
{!isLoaded && <Spinner />}
<Flex mt={3} justifyContent="center " alignItems="center" p="1.2vh">
<Flex>
<IconButton
icon={<ArrowLeftIcon h={3} w={3} color="black" />}
aria-label="Last page"
onClick={() => gotoPage(0)}
size="sm"
isDisabled={!canPreviousPage}
/>
<IconButton
aria-label="Previous page"
onClick={previousPage}
isDisabled={!canPreviousPage}
icon={<ChevronLeftIcon h={6} w={6} color="black" />}
size="sm"
ml={4}
/>
</Flex>
<Text align="center" pl={4} pr={4}>
Page {pageIndex + 1} of {pageOptions.length}
</Text>
<Flex>
<IconButton
aria-label="Next page"
onClick={nextPage}
size="sm"
isDisabled={!canNextPage}
icon={<ChevronRightIcon h={6} w={6} color="black" />}
/>
<IconButton
aria-label="Last page"
onClick={() => gotoPage(pageCount - 1)}
isDisabled={!canNextPage}
icon={<ArrowRightIcon h={3} w={3} color="black" />}
size="sm"
ml={4}
/>
</Flex>
</Flex>
</Flex>
);
};
export default Resource;
+46
View File
@@ -0,0 +1,46 @@
import { MutableRefObject, useEffect, useRef } from 'react';
import { noop } from '../utils/misc';
interface NuiMessageData<T = unknown> {
action: string;
data: T;
}
type NuiHandlerSignature<T> = (data: T) => void;
/**
* A hook that manage events listeners for receiving data from the client scripts
* @param action The specific `action` that should be listened for.
* @param handler The callback function that will handle data relayed by this hook
*
* @example
* useNuiEvent<{visibility: true, wasVisible: 'something'}>('setVisible', (data) => {
* // whatever logic you want
* })
*
**/
export const useNuiEvent = <T = any>(action: string, handler: (data: T) => void) => {
const savedHandler: MutableRefObject<NuiHandlerSignature<T>> = useRef(noop);
// Make sure we handle for a reactive handler
useEffect(() => {
savedHandler.current = handler;
}, [handler]);
useEffect(() => {
const eventListener = (event: MessageEvent<NuiMessageData<T>>) => {
const { action: eventAction, data } = event.data;
if (savedHandler.current) {
if (eventAction === action) {
savedHandler.current(data);
}
}
};
window.addEventListener('message', eventListener);
// Remove Event Listener on component cleanup
return () => window.removeEventListener('message', eventListener);
}, [action]);
};
+32
View File
@@ -0,0 +1,32 @@
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans',
'Droid Sans', 'Helvetica Neue', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
height: 100vh;
background: none !important;
}
#root {
height: 100%;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
}
::-webkit-scrollbar {
width: 2px;
border-radius: 1vh;
background-color: transparent;
padding: 0;
margin: 0;
}
::-webkit-scrollbar-thumb {
background: grey;
border-radius: 1vh;
}
+20
View File
@@ -0,0 +1,20 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './components/App';
import { VisibilityProvider } from './providers/VisibilityProvider';
import { ChakraProvider } from '@chakra-ui/react';
ReactDOM.render(
<React.StrictMode>
<VisibilityProvider>
<ChakraProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</ChakraProvider>
</VisibilityProvider>
</React.StrictMode>,
document.getElementById('root')
);
+49
View File
@@ -0,0 +1,49 @@
import React, { Context, createContext, useContext, useEffect, useState } from 'react';
import { useNuiEvent } from '../hooks/useNuiEvent';
import { fetchNui } from '../utils/fetchNui';
const VisibilityCtx = createContext<VisibilityProviderValue | null>(null);
interface VisibilityProviderValue {
setVisible: (visible: boolean) => void;
visible: boolean;
}
// This should be mounted at the top level of your application, it is currently set to
// apply a CSS visibility value. If this is non-performant, this should be customized.
export const VisibilityProvider: React.FC = ({ children }) => {
const [visible, setVisible] = useState(false);
useNuiEvent<boolean>('openUI', setVisible);
// Handle pressing escape/backspace
useEffect(() => {
// Only attach listener when we are visible
if (!visible) return;
const keyHandler = (e: KeyboardEvent) => {
if (['Escape'].includes(e.code)) {
fetchNui('exit');
setVisible(false);
}
};
window.addEventListener('keydown', keyHandler);
return () => window.removeEventListener('keydown', keyHandler);
}, [visible]);
return (
<VisibilityCtx.Provider
value={{
visible,
setVisible,
}}
>
<div style={{ visibility: visible ? 'visible' : 'hidden', height: '100%' }}>{children}</div>
</VisibilityCtx.Provider>
);
};
export const useVisibility = () =>
useContext<VisibilityProviderValue>(VisibilityCtx as Context<VisibilityProviderValue>);
+1
View File
@@ -0,0 +1 @@
/// <reference types="react-scripts" />
+13
View File
@@ -0,0 +1,13 @@
interface ChartData {
x: number;
y: number;
z: string;
}
export type InitData = {
resources: string[];
totalQueries: number;
totalTime: number;
slowQueries: number;
chartData: ChartData[];
};
+122
View File
@@ -0,0 +1,122 @@
import {
UseColumnOrderInstanceProps,
UseColumnOrderState,
UseExpandedHooks,
UseExpandedInstanceProps,
UseExpandedOptions,
UseExpandedRowProps,
UseExpandedState,
UseFiltersColumnOptions,
UseFiltersColumnProps,
UseFiltersInstanceProps,
UseFiltersOptions,
UseFiltersState,
UseGlobalFiltersColumnOptions,
UseGlobalFiltersInstanceProps,
UseGlobalFiltersOptions,
UseGlobalFiltersState,
UseGroupByCellProps,
UseGroupByColumnOptions,
UseGroupByColumnProps,
UseGroupByHooks,
UseGroupByInstanceProps,
UseGroupByOptions,
UseGroupByRowProps,
UseGroupByState,
UsePaginationInstanceProps,
UsePaginationOptions,
UsePaginationState,
UseResizeColumnsColumnOptions,
UseResizeColumnsColumnProps,
UseResizeColumnsOptions,
UseResizeColumnsState,
UseRowSelectHooks,
UseRowSelectInstanceProps,
UseRowSelectOptions,
UseRowSelectRowProps,
UseRowSelectState,
UseRowStateCellProps,
UseRowStateInstanceProps,
UseRowStateOptions,
UseRowStateRowProps,
UseRowStateState,
UseSortByColumnOptions,
UseSortByColumnProps,
UseSortByHooks,
UseSortByInstanceProps,
UseSortByOptions,
UseSortByState,
} from 'react-table';
declare module 'react-table' {
// take this file as-is, or comment out the sections that don't apply to your plugin configuration
export interface TableOptions<D extends Record<string, unknown>>
extends UseExpandedOptions<D>,
UseFiltersOptions<D>,
UseGlobalFiltersOptions<D>,
UseGroupByOptions<D>,
UsePaginationOptions<D>,
UseResizeColumnsOptions<D>,
UseRowSelectOptions<D>,
UseRowStateOptions<D>,
UseSortByOptions<D>,
// note that having Record here allows you to add anything to the options, this matches the spirit of the
// underlying js library, but might be cleaner if it's replaced by a more specific type that matches your
// feature set, this is a safe default.
Record<string, any> {}
export interface Hooks<D extends Record<string, unknown> = Record<string, unknown>>
extends UseExpandedHooks<D>,
UseGroupByHooks<D>,
UseRowSelectHooks<D>,
UseSortByHooks<D> {}
export interface TableInstance<D extends Record<string, unknown> = Record<string, unknown>>
extends UseColumnOrderInstanceProps<D>,
UseExpandedInstanceProps<D>,
UseFiltersInstanceProps<D>,
UseGlobalFiltersInstanceProps<D>,
UseGroupByInstanceProps<D>,
UsePaginationInstanceProps<D>,
UseRowSelectInstanceProps<D>,
UseRowStateInstanceProps<D>,
UseSortByInstanceProps<D> {}
export interface TableState<D extends Record<string, unknown> = Record<string, unknown>>
extends UseColumnOrderState<D>,
UseExpandedState<D>,
UseFiltersState<D>,
UseGlobalFiltersState<D>,
UseGroupByState<D>,
UsePaginationState<D>,
UseResizeColumnsState<D>,
UseRowSelectState<D>,
UseRowStateState<D>,
UseSortByState<D> {}
export interface ColumnInterface<D extends Record<string, unknown> = Record<string, unknown>>
extends UseFiltersColumnOptions<D>,
UseGlobalFiltersColumnOptions<D>,
UseGroupByColumnOptions<D>,
UseResizeColumnsColumnOptions<D>,
UseSortByColumnOptions<D> {}
export interface ColumnInstance<D extends Record<string, unknown> = Record<string, unknown>>
extends UseFiltersColumnProps<D>,
UseGroupByColumnProps<D>,
UseResizeColumnsColumnProps<D>,
UseSortByColumnProps<D> {
getSortByToggleProps: (props?: Partial<TableSortByToggleProps> | undefined) => TableSortByToggleProps;
}
export interface Cell<D extends Record<string, unknown> = Record<string, unknown>, V = any>
extends UseGroupByCellProps<D>,
UseRowStateCellProps<D> {}
export interface Row<D extends Record<string, unknown> = Record<string, unknown>>
extends UseExpandedRowProps<D>,
UseGroupByRowProps<D>,
UseRowSelectRowProps<D>,
UseRowStateRowProps<D> {}
}
+30
View File
@@ -0,0 +1,30 @@
import { isEnvBrowser } from './misc';
interface DebugEvent<T = any> {
action: string;
data: T;
}
/**
* Emulates dispatching an event using SendNuiMessage in the lua scripts.
* This is used when developing in browser
*
* @param events - The event you want to cover
* @param timer - How long until it should trigger (ms)
*/
export const debugData = <P>(events: DebugEvent<P>[], timer = 1000): void => {
if (process.env.NODE_ENV === 'development' && isEnvBrowser()) {
for (const event of events) {
setTimeout(() => {
window.dispatchEvent(
new MessageEvent('message', {
data: {
action: event.action,
data: event.data,
},
})
);
}, timer);
}
}
};
+34
View File
@@ -0,0 +1,34 @@
/**
* Simple wrapper around fetch API tailored for CEF/NUI use. This abstraction
* can be extended to include AbortController if needed or if the response isn't
* JSON. Tailor it to your needs.
*
* @param eventName - The endpoint eventname to target
* @param data - Data you wish to send in the NUI Callback
*
* @return returnData - A promise for the data sent back by the NuiCallbacks CB argument
*/
import { isEnvBrowser } from './misc';
export async function fetchNui<T = any>(eventName: string, data?: any): Promise<T> {
const options = {
method: 'post',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify(data),
};
if (isEnvBrowser()) return undefined as any;
const resourceName = (window as any).GetParentResourceName
? (window as any).GetParentResourceName()
: 'nui-frame-app';
const resp = await fetch(`https://${resourceName}/${eventName}`, options);
const respFormatted = await resp.json();
return respFormatted;
}
+6
View File
@@ -0,0 +1,6 @@
// Will return whether the current environment is in a regular browser
// and not CEF
export const isEnvBrowser = (): boolean => !(window as any).invokeNative;
// Basic no operation function
export const noop = () => {};
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}
+10919
View File
File diff suppressed because it is too large. Load diff