chore(nui): WIP React rewrite

This commit is contained in:
Luke committed 2021-12-30 20:05:07 +01:00
1 parent ce802e7553
commit b2b1a64c8f
35 files changed
+391 -460

No files matched your search

+3 -3
View File
@@ -15,10 +15,10 @@ client_script 'ui.lua'
server_script 'dist/build.js'
files {
'ui/public/index.html',
'ui/public/**/*'
'ui/build/index.html',
'ui/build/**/*'
}
ui_page 'src/ui/public/index.html'
ui_page 'ui/build/index.html'
provide 'mysql-async'
+1 -1
View File
@@ -30,4 +30,4 @@
"postinstall-postinstall": "^2.1.0",
"typescript": "^4.5.4"
}
}
}
+21 -2
View File
@@ -1,4 +1,23 @@
/node_modules/
/public/build/
# 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*
+46
View File
@@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
+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.writeToDisk = true
}
return devServerConfig
}
}
+46 -23
View File
@@ -1,30 +1,53 @@
{
"name": "svelte-app",
"version": "1.0.0",
"name": "web",
"version": "0.1.0",
"homepage": "web/build",
"private": true,
"dependencies": {
"@chakra-ui/react": "^1.7.3",
"@emotion/react": "11",
"@emotion/styled": "11",
"@testing-library/jest-dom": "^5.15.0",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^12.1.10",
"@types/jest": "^26.0.15",
"@types/node": "^16.11.9",
"@types/react": "^17.0.35",
"@types/react-dom": "^17.0.11",
"framer-motion": "4",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3",
"typescript": "^4.5.2",
"web-vitals": "^2.1.2"
},
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public --no-clear"
"start": "cross-env PUBLIC_URL=/ craco start",
"start:game": "cross-env IN_GAME_DEV=1 craco start",
"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": {
"@rollup/plugin-commonjs": "^17.0.0",
"@rollup/plugin-node-resolve": "^11.0.0",
"@rollup/plugin-typescript": "^8.0.0",
"@tsconfig/svelte": "^2.0.0",
"rollup": "^2.3.4",
"rollup-plugin-css-only": "^3.1.0",
"rollup-plugin-livereload": "^2.0.0",
"rollup-plugin-svelte": "^7.0.0",
"rollup-plugin-terser": "^7.0.0",
"svelte": "^3.0.0",
"svelte-check": "^2.0.0",
"svelte-preprocess": "^4.0.0",
"tslib": "^2.0.0",
"typescript": "^4.0.0"
},
"dependencies": {
"sirv-cli": "^1.0.0",
"svelte-spa-router": "^3.2.0"
"craco": "^0.0.3",
"cross-env": "^7.0.3"
}
}
-11
View File
@@ -1,11 +0,0 @@
@import url('https://fonts.googleapis.com/css2?family=Inter&display=swap');
* {
margin: 0;
padding: 0;
text-decoration: none;
}
body {
height: 100vh;
}
+16 -9
View File
@@ -2,15 +2,22 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Svelte app</title>
<link rel="stylesheet" href="./global.css" />
<link rel="stylesheet" href="./build/bundle.css" />
<script defer src="./build/bundle.js"></script>
<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.
<body></body>
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>
-87
View File
@@ -1,87 +0,0 @@
import svelte from "rollup-plugin-svelte";
import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
import livereload from "rollup-plugin-livereload";
import { terser } from "rollup-plugin-terser";
import sveltePreprocess from "svelte-preprocess";
import typescript from "@rollup/plugin-typescript";
import css from "rollup-plugin-css-only";
const production = !process.env.ROLLUP_WATCH;
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require("child_process").spawn(
"npm",
["run", "start", "--", "--dev"],
{
stdio: ["ignore", "inherit", "inherit"],
shell: true,
}
);
process.on("SIGTERM", toExit);
process.on("exit", toExit);
},
};
}
export default {
input: "src/main.ts",
output: {
sourcemap: false,
format: "iife",
name: "app",
file: "public/build/bundle.js",
},
plugins: [
svelte({
preprocess: sveltePreprocess({ sourceMap: !production }),
compilerOptions: {
// enable run-time checks when not in production
dev: !production,
},
}),
// we'll extract any component CSS out into
// a separate file - better for performance
css({ output: "bundle.css" }),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ["svelte"],
}),
commonjs(),
typescript({
sourceMap: !production,
inlineSources: !production,
}),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload("public"),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser(),
],
watch: {
clearScreen: false,
},
};
-36
View File
@@ -1,36 +0,0 @@
<script lang="ts">
import VisibilityProvider from './providers/VisibilityProvider.svelte';
import Main from './components/Main.svelte';
import { debugData } from './utils/debugData';
import { useNuiEvent } from './utils/useNuiEvent';
import { resources } from './store/stores';
import type { InitData } from './types/init';
debugData([
{
action: 'setVisible',
data: true,
},
]);
debugData([
{
action: 'init',
data: {
resources: ['ox_inventory', 'luke_garages', 'npwd'],
totalQueries: 350,
totalTime: 75000,
},
},
]);
useNuiEvent<InitData>('init', (data) => {
resources.set(data.resources);
});
</script>
<main>
<VisibilityProvider>
<Main />
</VisibilityProvider>
</main>
View File
Whitespace-only changes.
+25
View File
@@ -0,0 +1,25 @@
import './App.css';
import { Center, Box } from '@chakra-ui/react';
import { debugData } from '../utils/debugData';
import TopBar from './NavBars/TopBar';
import SideBar from './NavBars/SideBar';
debugData([
{
action: 'setVisible',
data: true,
},
]);
const App: React.FC = () => {
return (
<Center w="100%" h="100%">
<Box width="60%" height="60%" backgroundColor="#191E26" borderRadius="1vh" color="white" fontFamily="Poppins">
<TopBar />
<SideBar />
</Box>
</Center>
);
};
export default App;
-49
View File
@@ -1,49 +0,0 @@
<script lang="ts">
import Router from 'svelte-spa-router';
import Resources from './menu/NavMenu.svelte';
import Home from './routes/Home.svelte';
import ResourceData from './routes/ResourceData.svelte';
const routes = {
'/': Home,
'/*': ResourceData,
};
</script>
<div class="container">
<Resources />
<div class="content-wrapper">
<div class="content-container">
<Router {routes} />
</div>
</div>
</div>
<style>
.container {
width: 55%;
height: 65%;
background-color: rgb(44, 62, 80);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border-radius: 0.25vh;
}
.content-wrapper {
margin-left: 18vh;
height: 100%;
display: grid;
place-items: center;
}
.content-container {
width: 85%;
height: 85%;
background-color: #34495e;
border-radius: 0.25vh;
color: white;
font-family: 'Inter', sans-serif;
}
</style>
+15
View File
@@ -0,0 +1,15 @@
import { Box, VStack } from '@chakra-ui/react';
const SideBar: React.FC = () => {
return (
<Box p="1.2vh" fontSize="1.5vh" position="fixed">
<VStack align="left">
<Box>es_extended</Box>
<Box>ox_inventory</Box>
<Box>luke_garages</Box>
</VStack>
</Box>
);
};
export default SideBar;
+13
View File
@@ -0,0 +1,13 @@
import { Box } from '@chakra-ui/react';
const TopBar: React.FC = () => {
return (
<Box w="100%" h="5%">
<Box p="1.2vh" fontSize="2.2vh">
Resources
</Box>
</Box>
);
};
export default TopBar;
-64
View File
@@ -1,64 +0,0 @@
<script lang="ts">
import { currentResource } from '../../store/stores';
import { resources } from '../../store/stores';
</script>
<div class="container">
<a href="#/"><div class="home-header">Home</div></a>
{#each $resources as resource}
<div class="resource-wrapper">
<a href={`#/${resource}`}>
<div class="resource" on:click={() => currentResource.set(resource)}>
{resource}
</div>
</a>
</div>
{/each}
</div>
<style>
.container {
width: 18vh;
position: fixed;
left: 0;
top: 0;
background-color: #34495e;
height: 100%;
border-top-left-radius: 0.25vh;
border-bottom-left-radius: 0.25vh;
color: white;
font-family: 'Inter', sans-serif;
user-select: none;
}
.home-header {
font-size: 2.2vh;
text-align: left;
padding: 1vh;
border-bottom: 0.25vh solid grey;
}
.resource-wrapper {
padding: 1vh;
}
.resource {
font-family: 'Inter', sans-serif;
font-size: 2.2vh;
width: 100%;
height: 5%;
display: block;
}
.resource-wrapper:hover,
.home-header:hover {
background-color: grey;
}
a,
a:visited,
a:active,
a:focus {
color: white;
}
</style>
-18
View File
@@ -1,18 +0,0 @@
<script lang="ts">
import { useNuiEvent } from '../../utils/useNuiEvent';
import type { InitData } from '../../types/init';
let initData: InitData;
useNuiEvent<InitData>('init', (data) => {
initData = data;
});
</script>
<div>
{#if initData}
<div>Resources: {initData.resources}</div>
<div>Total queries: {initData.totalQueries}</div>
<div>Total time: {initData.totalTime}</div>
{/if}
</div>
@@ -1,40 +0,0 @@
<script lang="ts">
import { currentResource } from '../../store/stores';
import { fetchNui } from '../../utils/fetchNui';
import { onMount } from 'svelte';
import { useNuiEvent } from '../../utils/useNuiEvent';
import { debugData } from '../../utils/debugData';
import type { QueryData } from '../../types/query';
export let params: { wild: string };
let queryData: QueryData[];
let isDataLoaded: boolean = false;
onMount(() => currentResource.set(params.wild));
currentResource.subscribe((resource) => {
isDataLoaded = false;
fetchNui('fetchResource', resource);
debugData([
{
action: 'loadResource',
data: [
{ date: Date.now(), query: 'SELECT * FROM `somewhere`', executionTime: 2 },
{ date: Date.now(), query: 'SELECT * FROM `elsewhere`', executionTime: 5 },
{ date: Date.now(), query: 'SELECT * FROM `somewhere_elsewhere`', executionTime: 3 },
{ date: Date.now(), query: 'SELECT * FROM `selsewhere`', executionTime: 7 },
],
},
]);
});
useNuiEvent('loadResource', (data: QueryData[]) => {
queryData = data;
isDataLoaded = true;
});
</script>
{#if isDataLoaded === true}
{JSON.stringify(queryData)}
{/if}
-1
View File
@@ -1 +0,0 @@
/// <reference types="svelte" />
+49
View File
@@ -0,0 +1,49 @@
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]);
};
+18
View File
@@ -0,0 +1,18 @@
@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;
}
#root {
height: 100%;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
}
+17
View File
@@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from 'react-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>
<App />
</ChakraProvider>
</VisibilityProvider>
</React.StrictMode>,
document.getElementById('root')
);
-7
View File
@@ -1,7 +0,0 @@
import App from "./App.svelte";
const app = new App({
target: document.body,
});
export default app;
@@ -1,35 +0,0 @@
<script lang="ts">
import { useNuiEvent } from '../utils/useNuiEvent';
import { fetchNui } from '../utils/fetchNui';
import { onMount } from 'svelte';
import { visibility } from '../store/stores';
let isVisible: boolean;
visibility.subscribe((visible) => {
isVisible = visible;
});
useNuiEvent<boolean>('setVisible', (visible) => {
visibility.set(visible);
});
onMount(() => {
const keyHandler = (e: KeyboardEvent) => {
if (isVisible && ['Escape'].includes(e.code)) {
fetchNui('hideUI');
visibility.set(false);
}
};
window.addEventListener('keydown', keyHandler);
return () => window.removeEventListener('keydown', keyHandler);
});
</script>
<main>
{#if isVisible}
<slot />
{/if}
</main>
+48
View File
@@ -0,0 +1,48 @@
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>('setVisible', 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');
}
};
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" />
+5
View File
@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
-5
View File
@@ -1,5 +0,0 @@
import { writable } from "svelte/store";
export const visibility = writable(false);
export const currentResource = writable('');
export const resources = writable<string[]>([])
-5
View File
@@ -1,5 +0,0 @@
export type InitData = {
resources: string[];
totalQueries: number;
totalTime: number;
}
-5
View File
@@ -1,5 +0,0 @@
export type QueryData = {
date: number;
query: string;
executionTime: number;
}
+1 -1
View File
@@ -13,7 +13,7 @@ interface DebugEvent<T = any> {
* @param timer - How long until it should trigger (ms)
*/
export const debugData = <P>(events: DebugEvent<P>[], timer = 1000): void => {
if (isEnvBrowser()) {
if (process.env.NODE_ENV === "development" && isEnvBrowser()) {
for (const event of events) {
setTimeout(() => {
window.dispatchEvent(
+16 -19
View File
@@ -1,31 +1,28 @@
/**
* @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
*/
* 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: unknown = {}
): Promise<T> {
export async function fetchNui<T = any>(eventName: string, data?: any): Promise<T> {
const options = {
method: "post",
method: 'post',
headers: {
"Content-Type": "application/json; charset=UTF-8",
'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 resourceName = (window as any).GetParentResourceName ? (window as any).GetParentResourceName() : 'nui-frame-app';
const resp = await fetch(`https://${resourceName}/${eventName}`, options);
return await resp.json();
const respFormatted = await resp.json()
return respFormatted
}
+6 -1
View File
@@ -1 +1,6 @@
export const isEnvBrowser = (): boolean => !(window as any).invokeNative;
// 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 = () => {}
-31
View File
@@ -1,31 +0,0 @@
import { onMount, onDestroy } from "svelte";
interface NuiMessage<T = unknown> {
action: string;
data: T;
}
/**
* A function 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 function
*
* @example
* useNuiEvent<{visibility: true, wasVisible: 'something'}>('setVisible', (data) => {
* // whatever logic you want
* })
*
**/
export function useNuiEvent<T = unknown>(
action: string,
handler: (data: T) => void
) {
const eventListener = (event: MessageEvent<NuiMessage<T>>) => {
const { action: eventAction, data } = event.data;
eventAction === action && handler(data);
};
onMount(() => window.addEventListener("message", eventListener));
onDestroy(() => window.removeEventListener("message", eventListener));
}
+20 -7
View File
@@ -1,13 +1,26 @@
{
"extends": "@tsconfig/svelte/tsconfig.json",
"compilerOptions": {
"strict": true,
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"noFallthroughCasesInSwitch": true
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src/**/*"],
"exclude": ["node_modules/*", "__sapper__/*", "public/*"]
"include": [
"src"
]
}