refactor(nui): Better organize components

This commit is contained in:
Luke
2022-04-01 21:41:53 +02:00
parent c31fed2c41
commit 993b06e880
10 changed files with 40 additions and 40 deletions

View File

@@ -0,0 +1,101 @@
import {
Modal,
ModalOverlay,
ModalContent,
ModalFooter,
ModalHeader,
ModalBody,
Box,
Input,
Text,
Button,
} from "@chakra-ui/react";
import React from "react";
import { useNuiEvent } from "../../hooks/useNuiEvent";
// import { debugData } from "../utils/debugData";
import { fetchNui } from "../../utils/fetchNui";
interface Props {
heading: string;
inputs: string[];
}
// debugData([
// {
// action: "openDialog",
// data: {
// heading: "Police locker",
// inputs: ["Locker number", "Locker PIN"],
// },
// },
// ]);
const InputDialog: React.FC = () => {
const [inputOptions, setInputOptions] = React.useState<Props>({
heading: "",
inputs: [""],
});
const [inputData, setInputData] = React.useState<string[]>([]);
const [visible, setVisible] = React.useState(false);
useNuiEvent<Props>("openDialog", (data) => {
setInputOptions(data);
setVisible(true);
});
const handleClose = () => {
setVisible(false);
fetchNui("inputData");
};
const handleChange = (
e: React.ChangeEvent<HTMLInputElement>,
index: number
) => {
setInputData((previousData) => {
previousData[index] = e.target.value;
return previousData;
});
};
const handleConfirm = () => {
setVisible(false);
fetchNui("inputData", inputData);
};
return (
<>
<Modal
isOpen={visible}
onClose={handleClose}
isCentered
closeOnEsc
closeOnOverlayClick={false}
size="xs"
>
<ModalOverlay />
<ModalContent>
<ModalHeader textAlign="center">{inputOptions.heading}</ModalHeader>
<ModalBody>
{inputOptions.inputs.map((input: string, index: number) => (
<Box mb={3} key={`input-${index}`}>
<Text>{input}</Text>
<Input onChange={(e) => handleChange(e, index)} />
</Box>
))}
</ModalBody>
<ModalFooter>
<Button mr={3} onClick={handleClose}>
Close
</Button>
<Button colorScheme="blue" onClick={handleConfirm}>
Confirm
</Button>
</ModalFooter>
</ModalContent>
</Modal>
</>
);
};
export default InputDialog;

View File

@@ -0,0 +1,132 @@
import { useNuiEvent } from "../../hooks/useNuiEvent";
import { Box, Text, Flex, ScaleFade } from "@chakra-ui/react";
import { debugData } from "../../utils/debugData";
import { useEffect, useState } from "react";
import { ContextMenuProps } from "../../interfaces";
import Item from "./Item";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { fetchNui } from "../../utils/fetchNui";
debugData<ContextMenuProps>([
{
action: "showContext",
data: {
title: "Vehicle garage",
options: {
"Dinka Blista": {
description: "Super cool vehicle",
menu: "some_other_identifier",
metadata: {
Plate: "KLT 192",
Status: "In garage",
Health: "30%",
},
},
"Elegy Nitro": {
description: "Even cooler vehicle",
metadata: ["Plate: JGM 971", "Status: In garage"],
},
Burger: {
description: "Make a delicious burger",
metadata: {
Bun: 3,
Lettuce: 2,
Meat: 1,
Tomato: 1,
Cheese: 2,
},
},
},
},
},
]);
const openMenu = (id: string | undefined) => {
fetchNui<ContextMenuProps>("openContext", id);
};
const ContextMenu: React.FC = () => {
const [visible, setVisible] = useState(false);
const [contextMenu, setContextMenu] = useState<ContextMenuProps>({
title: "",
options: { "": { description: "", metadata: [] } },
});
// Hides the context menu on ESC
useEffect(() => {
if (!visible) return;
const keyHandler = (e: KeyboardEvent) => {
if (["Escape"].includes(e.code)) {
setVisible(false);
fetchNui("closeContext");
}
};
window.addEventListener("keydown", keyHandler);
return () => window.removeEventListener("keydown", keyHandler);
}, [visible]);
useNuiEvent("hideContext", () => setVisible(false));
useNuiEvent<ContextMenuProps>("showContext", async (data) => {
if (visible) {
setVisible(false);
await new Promise((resolve) => setTimeout(resolve, 100));
}
setContextMenu(data);
setVisible(true);
});
return (
<Flex
position="absolute"
w="75%"
h="80%"
justifyContent="flex-end"
alignItems="center"
>
<ScaleFade in={visible} unmountOnExit>
<Box w="xs" h={580}>
<Flex justifyContent="center" alignItems="center" mb={3}>
{contextMenu.menu && (
<Box
borderRadius="md"
bg="gray.800"
h="100%"
flex="1 15%"
textAlign="center"
marginRight={2}
p={2}
_hover={{ bg: "gray.700" }}
transition="300ms"
onClick={() => openMenu(contextMenu.menu)}
>
<FontAwesomeIcon icon="chevron-left" />
</Box>
)}
<Box borderRadius="md" bg="gray.800" flex="1 85%">
<Text
fontFamily="Poppins"
fontSize="md"
p={2}
textAlign="center"
fontWeight="light"
>
{contextMenu.title}
</Text>
</Box>
</Flex>
<Box maxH={560} overflowY="scroll">
{Object.entries(contextMenu.options).map((option, index) => (
<Item option={option} key={`context-item-${index}`} />
))}
</Box>
</Box>
</ScaleFade>
</Flex>
);
};
export default ContextMenu;

View File

@@ -0,0 +1,134 @@
import {
Portal,
Popover,
PopoverTrigger,
PopoverBody,
PopoverContent,
Box,
Text,
Flex,
Spacer,
} from "@chakra-ui/react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Option, ContextMenuProps } from "../../interfaces";
import { fetchNui } from "../../utils/fetchNui";
interface DataProps {
event?: string;
serverEvent?: string;
args?: any;
}
const openMenu = (id: string | undefined) => {
fetchNui<ContextMenuProps>("openContext", id);
};
const clickContext = (data: DataProps) => {
fetchNui("clickContext", data);
};
const Item: React.FC<{
option: [string, Option];
}> = ({ option }) => {
return (
<>
<Popover
placement="right-start"
trigger="hover"
eventListeners={{ scroll: true }}
isLazy
>
<PopoverTrigger>
<Box
bg="gray.800"
borderRadius="md"
h="fit-content"
w="100%"
p={2}
mb={1}
fontFamily="Poppins"
fontSize="md"
transition="300ms"
_hover={{ bg: "gray.700" }}
>
<Flex
w="100%"
onClick={() =>
option[1].menu
? openMenu(option[1].menu)
: clickContext({
event: option[1].event,
serverEvent: option[1].serverEvent,
args: option[1].args,
})
}
>
<Box>
<Box paddingBottom={1}>
<Text w="100%" fontWeight="medium">
{option[0]}
</Text>
</Box>
{option[1].description && (
<Box paddingBottom={1}>
<Text>{option[1].description}</Text>
</Box>
)}
</Box>
{option[1].menu && (
<>
<Spacer />
<Box
alignSelf="center"
justifySelf="center"
mr={4}
fontSize="xl"
>
<FontAwesomeIcon icon="chevron-right" />
</Box>
</>
)}
</Flex>
<Portal>
{option[1].metadata && (
<PopoverContent
fontFamily="Poppins"
bg="gray.800"
outline="none"
border="none"
w="fit-content"
maxW="2xs"
>
<PopoverBody>
{Array.isArray(option[1].metadata) ? (
option[1].metadata.map(
(metadata: string, index: number) => (
<Text key={`context-metadata-${index}`}>
{metadata}
</Text>
)
)
) : (
<>
{typeof option[1].metadata === "object" &&
Object.entries(option[1].metadata).map(
(metadata: { [key: string]: any }, index) => (
<Text key={`context-metadata-${index}`}>
{metadata[0]}: {metadata[1]}
</Text>
)
)}
</>
)}
</PopoverBody>
</PopoverContent>
)}
</Portal>
</Box>
</PopoverTrigger>
</Popover>
</>
);
};
export default Item;

View File

@@ -0,0 +1,103 @@
import {
useToast,
type ToastPositionWithLogical,
Box,
HStack,
Text,
} from "@chakra-ui/react";
import { useNuiEvent } from "../../hooks/useNuiEvent";
import { debugData } from "../../utils/debugData";
import { IconProp } from "@fortawesome/fontawesome-svg-core";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
interface Props {
title?: string;
description: string;
duration?: number;
position?: ToastPositionWithLogical;
status?: "info" | "warning" | "success" | "error";
id?: number;
}
interface CustomProps {
style?: React.CSSProperties;
description: string;
title?: string;
duration?: number;
icon?: IconProp;
iconColor?: string;
position?: ToastPositionWithLogical;
id?: number;
}
debugData<Props>([
{
action: "notify",
data: {
description: "Dunak is nerd",
title: "Dunak",
id: 1,
},
},
]);
debugData<CustomProps>([
{
action: "customNotify",
data: {
description: "Dunak is nerd",
title: "Dunak",
icon: "basket-shopping",
style: {
backgroundColor: "#2D3748",
color: "white",
},
},
},
]);
const Notifications: React.FC = () => {
const toast = useToast();
// todo: figure out icon support
useNuiEvent<CustomProps>("customNotify", (data) => {
if (data.id && toast.isActive(data.id)) return;
toast({
duration: data.duration || 4000,
position: data.position || "top-right",
render: () => (
<Box style={data.style} p={3} borderRadius="md" boxShadow="lg">
<HStack spacing={0}>
{data.icon && (
<FontAwesomeIcon
icon={data.icon}
fontSize="1.4rem"
style={{ paddingRight: 11 }}
color={data.iconColor}
/>
)}
<Box w="100%">
{data.title && <Text as="b">{data.title}</Text>}
{data.description && <Text>{data.description}</Text>}
</Box>
</HStack>
</Box>
),
});
});
useNuiEvent<Props>("notify", (data) => {
if (data.id && toast.isActive(data.id)) return;
toast({
title: data.title,
description: data.description,
duration: data.duration || 4000,
position: data.position || "top-right",
status: data.status,
});
});
return <></>;
};
export default Notifications;

View File

@@ -0,0 +1,110 @@
import React from "react";
import {
CircularProgress,
CircularProgressLabel,
Flex,
ScaleFade,
} from "@chakra-ui/react";
import { useNuiEvent } from "../../hooks/useNuiEvent";
import { debugData } from "../../utils/debugData";
import { fetchNui } from "../../utils/fetchNui";
interface Props {
duration: number;
position?: "middle" | "bottom";
percent?: boolean;
}
debugData([
{
action: "circleProgress",
data: {
duration: 8000,
},
},
]);
const CircleProgressbar: React.FC = () => {
const [visible, setVisible] = React.useState(false);
const [progressDuration, setProgressDuration] = React.useState(0);
const [position, setPosition] = React.useState<"middle" | "bottom">("middle");
const [value, setValue] = React.useState(0);
const [cancelled, setCancelled] = React.useState(false);
const progressComplete = () => {
setVisible(false);
fetchNui("progressComplete");
};
const progressCancel = () => {
setCancelled(true);
setValue(99); // Sets the final value to 100% kek
setTimeout(() => {
setVisible(false);
}, 2500);
};
useNuiEvent("progressCancel", progressCancel);
useNuiEvent<Props>("circleProgress", (data) => {
if (visible) return;
setCancelled(false);
setVisible(true);
setValue(0);
setProgressDuration(data.duration);
setPosition(data.position || "middle");
const onePercent = data.duration * 0.01;
const updateProgress = setInterval(() => {
setValue((previousValue) => {
const newValue = previousValue + 1;
newValue >= 100 && clearInterval(updateProgress);
return newValue;
});
}, onePercent);
});
return (
<Flex
h={position === "middle" ? "100%" : "20%"}
w="100%"
position="absolute"
bottom="0"
justifyContent="center"
alignItems="center"
>
<ScaleFade in={visible} unmountOnExit>
<CircularProgress
value={value}
size="5rem"
trackColor="rgba(0, 0, 0, 0.6)"
onAnimationEnd={progressComplete}
thickness={6}
color={cancelled ? "rgb(198, 40, 40)" : "white"}
sx={
!cancelled
? {
".chakra-progress__indicator": {
transition: "none !important",
animation: "progress linear forwards !important",
animationDuration: `${progressDuration}ms !important`,
opacity: "1 !important",
},
}
: {
".chakra-progress__indicator": {
transition: "none !important",
strokeDasharray: "264, 0 !important", // sets circle to full
},
}
}
>
<CircularProgressLabel fontFamily="Fira Mono">
{value}%
</CircularProgressLabel>
</CircularProgress>
</ScaleFade>
</Flex>
);
};
export default CircleProgressbar;

View File

@@ -0,0 +1,102 @@
import React from "react";
import {
Progress,
ProgressLabel,
Flex,
Box,
ScaleFade,
} from "@chakra-ui/react";
import { useNuiEvent } from "../../hooks/useNuiEvent";
import { debugData } from "../../utils/debugData";
import { fetchNui } from "../../utils/fetchNui";
interface Props {
label: string;
duration: number;
}
debugData([
{
action: "progress",
data: {
label: "Using Lockpick",
duration: 8000,
},
},
]);
const Progressbar: React.FC = () => {
const [visible, setVisible] = React.useState(false);
const [label, setLabel] = React.useState("");
const [duration, setDuration] = React.useState(0);
const [cancelled, setCancelled] = React.useState(false);
const progressComplete = () => {
setVisible(false);
fetchNui("progressComplete");
};
const progressCancel = () => {
setCancelled(true);
setTimeout(() => {
setVisible(false);
}, 2500);
};
useNuiEvent("progressCancel", progressCancel);
useNuiEvent<Props>("progress", (data) => {
if (visible) return;
setCancelled(false);
setVisible(true);
setLabel(data.label);
setDuration(data.duration);
});
return (
<Flex
h="20%"
w="100%"
position="absolute"
bottom="0"
justifyContent="center"
alignItems="center"
>
<Box width="22rem">
<ScaleFade in={visible} unmountOnExit>
<Progress
value={100}
height="2.8rem"
borderRadius="sm"
fontFamily="Inter"
flex="1 1 auto"
boxShadow="lg"
onAnimationEnd={progressComplete}
sx={
!cancelled
? {
// really scuffed solution but works, wonder if there's a better way to do this?
"> div:first-of-type": {
animation: `progress-bar linear ${duration}ms`,
borderRadius: "none",
},
}
: {
"> div:first-of-type": {
width: "100%",
backgroundColor: "rgb(198, 40, 40)",
},
}
}
>
<ProgressLabel fontSize={22} fontWeight="light">
{label}
</ProgressLabel>
</Progress>
</ScaleFade>
</Box>
</Flex>
);
};
export default Progressbar;

View File

@@ -0,0 +1,69 @@
import React from "react";
import { useNuiEvent } from "../../hooks/useNuiEvent";
import { Box, Flex, ScaleFade } from "@chakra-ui/react";
import { debugData } from "../../utils/debugData";
import ReactMarkdown from "react-markdown";
interface Props {
text: string;
position?: "right-center" | "left-center" | "top-center";
style?: React.CSSProperties;
}
debugData([
{
action: "textUi",
data: {
text: "[E] - Access locker inventory \n [G] - Do something else \n ",
position: "right-center",
},
},
]);
const TextUI: React.FC = () => {
const [data, setData] = React.useState<Props>({
text: "",
position: "right-center",
});
const [visible, setVisible] = React.useState(false);
useNuiEvent<Props>("textUi", (data) => {
setData(data);
setVisible(true);
});
useNuiEvent("textUiHide", () => setVisible(false));
return (
<Flex
w="100%"
h="100%"
p={3}
position="absolute"
alignItems={data.position === "top-center" ? "baseline" : "center"}
justifyContent={
data.position === "right-center"
? "flex-end"
: data.position === "left-center"
? "flex-start"
: "center"
}
>
<ScaleFade in={visible} unmountOnExit>
<Box
bg="gray.700"
boxShadow="lg"
p={3}
fontFamily="DM Mono"
style={data.style}
borderRadius="md"
maxW="xs"
>
<ReactMarkdown>{data.text}</ReactMarkdown>
</Box>
</ScaleFade>
</Flex>
);
};
export default TextUI;