Skip to content

Commit

Permalink
chore(web): minor clean-ups
Browse files Browse the repository at this point in the history
* chore: use proper default value for useDebounce

* docs: updated useIntersection url to mantine repository

* chore: HOF to avoid repetitions

* fix: useQueue 'remove' fn return type

* chore: unused imports and vars clean-up

* chore: React synthetic default import

* chore: consistency between react hooks usage syntax

* chore: change html title tag :peepolove:
  • Loading branch information
demxn-git authored Feb 17, 2024
1 parent 60751ea commit 3f70927
Show file tree
Hide file tree
Showing 17 changed files with 53 additions and 63 deletions.
2 changes: 1 addition & 1 deletion web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet" />
<title>NUI React Boilerplate</title>
<title>Ox Inventory</title>
</head>
<body>
<div id="root"></div>
Expand Down
8 changes: 4 additions & 4 deletions web/src/components/inventory/InventoryGrid.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useRef } from 'react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Inventory } from '../../typings';
import WeightBar from '../utils/WeightBar';
import InventorySlot from './InventorySlot';
Expand All @@ -9,16 +9,16 @@ import { useIntersection } from '../../hooks/useIntersection';
const PAGE_SIZE = 30;

const InventoryGrid: React.FC<{ inventory: Inventory }> = ({ inventory }) => {
const weight = React.useMemo(
const weight = useMemo(
() => (inventory.maxWeight !== undefined ? Math.floor(getTotalWeight(inventory.items) * 1000) / 1000 : 0),
[inventory.maxWeight, inventory.items]
);
const [page, setPage] = React.useState(0);
const [page, setPage] = useState(0);
const containerRef = useRef(null);
const { ref, entry } = useIntersection({ threshold: 0.5 });
const isBusy = useAppSelector((state) => state.inventory.isBusy);

React.useEffect(() => {
useEffect(() => {
if (entry && entry.isIntersecting) {
setPage((prev) => ++prev);
}
Expand Down
4 changes: 2 additions & 2 deletions web/src/components/inventory/InventorySlot.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useRef } from 'react';
import React, { useCallback, useRef } from 'react';
import { DragSource, Inventory, InventoryType, Slot, SlotWithItem } from '../../typings';
import { useDrag, useDragDropManager, useDrop } from 'react-dnd';
import { useAppDispatch } from '../../store';
Expand Down Expand Up @@ -31,7 +31,7 @@ const InventorySlot: React.ForwardRefRenderFunction<HTMLDivElement, SlotProps> =
const dispatch = useAppDispatch();
const timerRef = useRef<NodeJS.Timer | null>(null);

const canDrag = React.useCallback(() => {
const canDrag = useCallback(() => {
return canPurchaseItem(item, { type: inventoryType, groups: inventoryGroups }) && canCraftItem(item, inventoryType);
}, [item, inventoryType, inventoryGroups]);

Expand Down
4 changes: 2 additions & 2 deletions web/src/components/inventory/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useState } from 'react';
import useNuiEvent from '../../hooks/useNuiEvent';
import InventoryControl from './InventoryControl';
import InventoryHotbar from './InventoryHotbar';
Expand All @@ -15,7 +15,7 @@ import { closeContextMenu } from '../../store/contextMenu';
import Fade from '../utils/transitions/Fade';

const Inventory: React.FC = () => {
const [inventoryVisible, setInventoryVisible] = React.useState(false);
const [inventoryVisible, setInventoryVisible] = useState(false);
const dispatch = useAppDispatch();

useNuiEvent<boolean>('setInventoryVisible', setInventoryVisible);
Expand Down
4 changes: 2 additions & 2 deletions web/src/components/utils/ItemNotifications.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useContext } from 'react';
import { createPortal } from 'react-dom';
import { TransitionGroup } from 'react-transition-group';
import useNuiEvent from '../../hooks/useNuiEvent';
Expand All @@ -19,7 +19,7 @@ export const ItemNotificationsContext = React.createContext<{
} | null>(null);

export const useItemNotifications = () => {
const itemNotificationsContext = React.useContext(ItemNotificationsContext);
const itemNotificationsContext = useContext(ItemNotificationsContext);
if (!itemNotificationsContext) throw new Error(`ItemNotificationsContext undefined`);
return itemNotificationsContext;
};
Expand Down
9 changes: 2 additions & 7 deletions web/src/components/utils/Tooltip.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
import React, { useRef } from 'react';
import { flip, FloatingPortal, offset, shift, useFloating, useTransitionStyles } from '@floating-ui/react';
import React, { useEffect } from 'react';
import { useAppSelector } from '../../store';
import SlotTooltip from '../inventory/SlotTooltip';
import { useDebounce } from '../../hooks/useDebounce';

const Tooltip: React.FC = () => {
const hoverData = useAppSelector((state) => state.tooltip);
const debounce = useDebounce(hoverData.open, 500);
const [open, setOpen] = React.useState(false);
const openTimer = useRef<NodeJS.Timer | null>(null);
const canOpen = useRef(false);

const { refs, context, floatingStyles } = useFloating({
middleware: [flip(), shift(), offset({ mainAxis: 10, crossAxis: 10 })],
Expand Down Expand Up @@ -38,7 +33,7 @@ const Tooltip: React.FC = () => {
});
};

React.useEffect(() => {
useEffect(() => {
window.addEventListener('mousemove', handleMouseMove);

return () => {
Expand Down
4 changes: 2 additions & 2 deletions web/src/components/utils/WeightBar.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useMemo } from 'react';

const colorChannelMixer = (colorChannelA: number, colorChannelB: number, amountToMix: number) => {
let channelA = colorChannelA * amountToMix;
Expand All @@ -21,7 +21,7 @@ const COLORS = {
};

const WeightBar: React.FC<{ percent: number; durability?: boolean }> = ({ percent, durability }) => {
const color = React.useMemo(
const color = useMemo(
() =>
durability
? percent < 50
Expand Down
22 changes: 11 additions & 11 deletions web/src/components/utils/menu/Menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import {
useTransitionStyles,
useTypeahead,
} from '@floating-ui/react';
import * as React from 'react';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { useAppSelector } from '../../../store';

const MenuContext = React.createContext<{
Expand All @@ -54,13 +54,13 @@ interface MenuProps {
export const MenuComponent = React.forwardRef<HTMLButtonElement, MenuProps & React.HTMLProps<HTMLButtonElement>>(
({ children, label, ...props }, forwardedRef) => {
const menu = useAppSelector((state) => state.contextMenu);
const [isOpen, setIsOpen] = React.useState(false);
const [hasFocusInside, setHasFocusInside] = React.useState(false);
const [activeIndex, setActiveIndex] = React.useState<number | null>(null);
const [isOpen, setIsOpen] = useState(false);
const [hasFocusInside, setHasFocusInside] = useState(false);
const [activeIndex, setActiveIndex] = useState<number | null>(null);

const elementsRef = React.useRef<Array<HTMLButtonElement | null>>([]);
const labelsRef = React.useRef<Array<string | null>>([]);
const parent = React.useContext(MenuContext);
const elementsRef = useRef<Array<HTMLButtonElement | null>>([]);
const labelsRef = useRef<Array<string | null>>([]);
const parent = useContext(MenuContext);

const tree = useFloatingTree();
const nodeId = useFloatingNodeId();
Expand All @@ -80,7 +80,7 @@ export const MenuComponent = React.forwardRef<HTMLButtonElement, MenuProps & Rea

const { isMounted, styles } = useTransitionStyles(context);

React.useEffect(() => {
useEffect(() => {
if (isNested) return;
if (menu.coords) {
refs.setPositionReference({
Expand Down Expand Up @@ -142,7 +142,7 @@ export const MenuComponent = React.forwardRef<HTMLButtonElement, MenuProps & Rea
// Event emitter allows you to communicate across tree components.
// This effect closes all menus when an item gets clicked anywhere
// in the tree.
React.useEffect(() => {
useEffect(() => {
if (!tree) return;

function handleTreeClick() {
Expand All @@ -164,7 +164,7 @@ export const MenuComponent = React.forwardRef<HTMLButtonElement, MenuProps & Rea
};
}, [tree, nodeId, parentId]);

React.useEffect(() => {
useEffect(() => {
if (isOpen && tree) {
tree.events.emit('menuopen', { parentId, nodeId });
}
Expand Down Expand Up @@ -242,7 +242,7 @@ export const MenuItem = React.forwardRef<
HTMLButtonElement,
MenuItemProps & React.ButtonHTMLAttributes<HTMLButtonElement>
>(({ label, disabled, ...props }, forwardedRef) => {
const menu = React.useContext(MenuContext);
const menu = useContext(MenuContext);
const item = useListItem({ label: disabled ? null : label });
const tree = useFloatingTree();
const isActive = item.index === menu.activeIndex;
Expand Down
4 changes: 2 additions & 2 deletions web/src/components/utils/transitions/Fade.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useRef } from 'react';
import { CSSTransition } from 'react-transition-group';

interface Props {
Expand All @@ -7,7 +7,7 @@ interface Props {
}

const Fade: React.FC<Props> = (props) => {
const nodeRef = React.useRef(null);
const nodeRef = useRef(null);

return (
<CSSTransition in={props.in} nodeRef={nodeRef} classNames="transition-fade" timeout={200} unmountOnExit>
Expand Down
4 changes: 2 additions & 2 deletions web/src/components/utils/transitions/SlideUp.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useRef } from 'react';
import { CSSTransition } from 'react-transition-group';

interface Props {
Expand All @@ -7,7 +7,7 @@ interface Props {
}

const SlideUp: React.FC<Props> = (props) => {
const nodeRef = React.useRef(null);
const nodeRef = useRef(null);

return (
<CSSTransition nodeRef={nodeRef} in={props.in} timeout={200} classNames="transition-slide-up" unmountOnExit>
Expand Down
1 change: 0 additions & 1 deletion web/src/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
//import { Items } from "../store/items";
import { Inventory, InventoryType, ItemData, Slot, SlotWithItem, State } from '../typings';
import { isEqual } from 'lodash';
import { store } from '../store';
Expand Down
6 changes: 4 additions & 2 deletions web/src/hooks/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { useEffect, useState } from 'react';

export function useDebounce<T>(value: T, delay?: number): T {
export function useDebounce<T>(value: T, delay: number = 500): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);

useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay || 500);
const timer = setTimeout(() => {
setDebouncedValue(value);
}, delay);

return () => {
clearTimeout(timer);
Expand Down
2 changes: 1 addition & 1 deletion web/src/hooks/useIntersection.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// https://github.com/mantinedev/mantine/blob/master/src/mantine-hooks/src/use-intersection/use-intersection.ts
// https://github.com/mantinedev/mantine/blob/master/packages/%40mantine/hooks/src/use-intersection/use-intersection.ts

import { useCallback, useRef, useState } from 'react';

Expand Down
29 changes: 12 additions & 17 deletions web/src/hooks/useKeyPress.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@
import React from 'react';
import { useCallback, useEffect, useState } from 'react';

export const useKeyPress = (targetKey: KeyboardEvent['key']) => {
const [keyPressed, setKeyPressed] = React.useState(false);
const [keyPressed, setKeyPressed] = useState(false);

const downHandler = React.useCallback(
({ key }: KeyboardEvent) => {
if (key === targetKey) {
setKeyPressed(true);
}
},
const keyToggler = useCallback(
(toggle: boolean) =>
({ key }: KeyboardEvent) => {
if (key === targetKey) {
setKeyPressed(toggle);
}
},
[targetKey]
);

const upHandler = React.useCallback(
({ key }: KeyboardEvent) => {
if (key === targetKey) {
setKeyPressed(false);
}
},
[targetKey]
);
const downHandler = keyToggler(true);
const upHandler = keyToggler(false);

React.useEffect(() => {
useEffect(() => {
window.addEventListener('keydown', downHandler);
window.addEventListener('keyup', upHandler);

Expand Down
8 changes: 4 additions & 4 deletions web/src/hooks/useQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useState } from 'react';

export interface QueueMethods<T> {
add: (item: T) => void;
remove: () => void;
remove: () => T | undefined;
first: T;
last: T;
values: T[];
Expand All @@ -16,12 +16,12 @@ const useQueue = <T>(initialValue: T[] = []): QueueMethods<T> => {
set((queue) => [...queue, value]);
},
remove: () => {
let result;
let removed;
set(([first, ...rest]) => {
result = first;
removed = first;
return rest;
});
return result;
return removed;
},
get values() {
return state;
Expand Down
3 changes: 1 addition & 2 deletions web/src/reducers/refreshSlots.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { CaseReducer, PayloadAction } from '@reduxjs/toolkit';
import { itemDurability } from '../helpers';
import { inventorySlice } from '../store/inventory';
import { Items } from '../store/items';
import { InventoryType, Slot, State } from '../typings';
import { inventorySlice } from '../store/inventory';
import RightInventory from '../components/inventory/RightInventory';

export type ItemsPayload = { item: Slot; inventory?: InventoryType };

Expand Down
2 changes: 1 addition & 1 deletion web/src/store/inventory.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { createSlice, current, isFulfilled, isPending, isRejected, PayloadAction } from '@reduxjs/toolkit';
import type { RootState } from '.';
import { Slot, State } from '../typings';
import {
moveSlotsReducer,
refreshSlotsReducer,
setupInventoryReducer,
stackSlotsReducer,
swapSlotsReducer,
} from '../reducers';
import { State } from '../typings';

const initialState: State = {
leftInventory: {
Expand Down

0 comments on commit 3f70927

Please sign in to comment.