diff --git a/src/ErrorBoundary.js b/src/ErrorBoundary.js index fcf04165a..8248f64d2 100644 --- a/src/ErrorBoundary.js +++ b/src/ErrorBoundary.js @@ -1,4 +1,4 @@ -import { Component } from 'react'; +import { Component } from '~/lib/react-debug'; import styled from 'styled-components'; import errorImageSrc from '~/assets/images/hopper.png'; diff --git a/src/Game.js b/src/Game.js index 40df6c61e..1bc918eed 100644 --- a/src/Game.js +++ b/src/Game.js @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from 'react'; +import { useEffect, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { ThemeProvider, createGlobalStyle } from 'styled-components'; import { BrowserRouter as Router, Switch, Route, useHistory } from 'react-router-dom'; @@ -72,7 +72,7 @@ const LauncherRedirect = () => { const dispatchLauncherPage = useStore(s => s.dispatchLauncherPage); // redirect to launcher if initial load and trying to link to /launcher/* - useEffect(() => { + useEffect(import.meta.url, () => { const parts = history.location.pathname.split('/').slice(1); const deeplink = parts[0] === 'launcher'; if (deeplink || !DISABLE_LAUNCHER_LANDING) { @@ -88,7 +88,7 @@ const LauncherRedirect = () => { // redirect to launcher if was logged in and is now logged out (and not already on launcher) const wasLoggedIn = useRef(false); - useEffect(() => { + useEffect(import.meta.url, () => { if (authenticated) { wasLoggedIn.current = true; } else { @@ -114,12 +114,12 @@ const Game = () => { const [ loadingMessage, setLoadingMessage ] = useState('Initializing'); // Initialize tag manager - useEffect(() => { + useEffect(import.meta.url, () => { initializeTagManager(); }, []); const autodetectNeedsInit = graphics?.autodetect === undefined; - useEffect(() => { + useEffect(import.meta.url, () => { if (!gpuInfo) return; if (!gpuInfo.isMobile) { @@ -144,7 +144,7 @@ const Game = () => { } }, [ gpuInfo, createAlert, dispatchGpuInfo, autodetectNeedsInit ]); // eslint-disable-line react-hooks/exhaustive-deps - useEffect(() => { + useEffect(import.meta.url, () => { if (updateNeeded) { createAlert({ type: 'App_Updated', @@ -156,7 +156,7 @@ const Game = () => { } }, [createAlert, updateNeeded, onUpdateVersion]); - useEffect(() => { + useEffect(import.meta.url, () => { if (isInstalling) { const messages = [ 'Correcting for gravitational anomalies', diff --git a/src/ScreensizeWarning.js b/src/ScreensizeWarning.js index 963aa7886..d5f15584f 100644 --- a/src/ScreensizeWarning.js +++ b/src/ScreensizeWarning.js @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useState } from '~/lib/react-debug'; import FullpageInterstitial from '~/components/FullpageInterstitial'; import useScreenSize from '~/hooks/useScreenSize'; diff --git a/src/components/AnimatedIcons.js b/src/components/AnimatedIcons.js index 1ef2b96f1..94d6f89a9 100644 --- a/src/components/AnimatedIcons.js +++ b/src/components/AnimatedIcons.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef } from 'react'; +import { useEffect, useMemo, useRef } from '~/lib/react-debug'; import Lottie from 'lottie-react'; import CrewBusy from '~/assets/icons/animated/CrewBusy.json'; @@ -9,7 +9,7 @@ import Ready from '~/assets/icons/animated/Ready.json'; const LottieIcon = ({ animation, isPaused = false, size = '1em' }) => { const lottieRef = useRef(); - const style = useMemo(() => ({ + const style = useMemo(import.meta.url, () => ({ alignItems: 'center', display: 'flex', height: size, @@ -17,7 +17,7 @@ const LottieIcon = ({ animation, isPaused = false, size = '1em' }) => { width: size, }), [size]); - useEffect(() => { + useEffect(import.meta.url, () => { if (isPaused) lottieRef.current.pause(); else lottieRef.current.play(); }, [isPaused]); diff --git a/src/components/AnnotationBio.js b/src/components/AnnotationBio.js index 0bd6fcab4..903224aea 100644 --- a/src/components/AnnotationBio.js +++ b/src/components/AnnotationBio.js @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useState } from '~/lib/react-debug'; import styled from 'styled-components'; import LoadingAnimation from 'react-spinners/PropagateLoader'; diff --git a/src/components/AsteroidRendering.js b/src/components/AsteroidRendering.js index 60d1aabf5..d09504d07 100644 --- a/src/components/AsteroidRendering.js +++ b/src/components/AsteroidRendering.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { AmbientLight, Color, DirectionalLight } from 'three'; import { Canvas, useThree } from '@react-three/fiber'; @@ -14,7 +14,7 @@ const RenderedAsteroid = ({ asteroid, brightness = 1, varyDistance = false, onRe const { camera, gl, scene } = useThree(); const disposeFunc = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (asteroid?.id && webWorkerPool) { renderDummyAsteroid(asteroid, asteroid.id < 25 ? 64 : 32, webWorkerPool, (asteroidModel, dispose) => { asteroidModel.traverse(function (node) { @@ -90,16 +90,16 @@ const RenderedAsteroidInCanvas = ({ onReady, ...props }) => { // TODO: in general, it might be wise to keep track of all webgl contexts at the app-level and block // any components that require a canvas until the contexts are freed up (this will be a user-specific // limit, but maybe 4-5 simultaneous contexts max would be safe?) - const onReadyInternal = useCallback(() => { + const onReadyInternal = useCallback(import.meta.url, () => { if (canvas.current) setImageSrc(canvas.current.toDataURL()); if (onReady) onReady(); }, [onReady]); - useEffect(() => { + useEffect(import.meta.url, () => { setImageSrc(null); }, [props.asteroid?.id, props.brightness, props.varyDistance]) - const style = useMemo(() => ({ width: '100%', height: '100%', ...(props.style || {}) }), [props.style]); + const style = useMemo(import.meta.url, () => ({ width: '100%', height: '100%', ...(props.style || {}) }), [props.style]); return imageSrc ? diff --git a/src/components/AttentionDot.js b/src/components/AttentionDot.js index 41aef8617..b8e2dabed 100644 --- a/src/components/AttentionDot.js +++ b/src/components/AttentionDot.js @@ -1,4 +1,4 @@ -import React from 'react'; +import React from '~/lib/react-debug'; import styled, { keyframes } from 'styled-components'; const Wrapper = styled.div` diff --git a/src/components/Autocomplete.js b/src/components/Autocomplete.js index a65eca01e..b713a7cd7 100644 --- a/src/components/Autocomplete.js +++ b/src/components/Autocomplete.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { createPortal } from 'react-dom'; import { usePopper } from 'react-popper'; import { PuffLoader } from 'react-spinners'; @@ -74,7 +74,7 @@ const AutocompleteComponent = ({ const [popperEl, setPopperEl] = useState(); const [referenceEl, setReferenceEl] = useState(); - const { userOnBlur, userOnFocus, safeInputProps } = useMemo(() => { + const { userOnBlur, userOnFocus, safeInputProps } = useMemo(import.meta.url, () => { const { onBlur: userOnBlur, onFocus: userOnFocus, ...safeInputProps } = inputProps; return { userOnBlur, userOnFocus, safeInputProps }; }, [inputProps]); @@ -91,19 +91,19 @@ const AutocompleteComponent = ({ ], }); - const options = useMemo( + const options = useMemo(import.meta.url, () => rawOptions.filter((o) => !excludeFunc || !excludeFunc(o)), [excludeFunc, rawOptions] ); - const handleSelection = useCallback((s) => { + const handleSelection = useCallback(import.meta.url, (s) => { onSelect(s); setFocused(false); setHovered(false); textInputEl.current.blur(); }, [onSelect]); - const handleKeyDown = useCallback((e) => { + const handleKeyDown = useCallback(import.meta.url, (e) => { if (e.key === 'Escape') { textInputEl.current.blur(); } else if (e.key === 'Enter') { @@ -119,7 +119,7 @@ const AutocompleteComponent = ({ } }, [allowCustomInput, handleSelection, highlighted, options]); - const handleOptionHover = useCallback((e) => { + const handleOptionHover = useCallback(import.meta.url, (e) => { if (e.type === 'mouseenter') { setHovered(true); } else { @@ -127,17 +127,17 @@ const AutocompleteComponent = ({ } }, []); - const handleBlur = useCallback((e) => { + const handleBlur = useCallback(import.meta.url, (e) => { setFocused(false); if (userOnBlur) userOnBlur(e); }, [userOnBlur]); - const handleFocus = useCallback((e) => { + const handleFocus = useCallback(import.meta.url, (e) => { setFocused(true); if (userOnFocus) userOnFocus(e); }, [userOnFocus]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!focused && !hovered) { setHighlighted(0); setSearchTerm(''); @@ -195,17 +195,17 @@ export const StaticAutocomplete = ({ }) => { const [searchTerm, setSearchTerm] = useState(''); - const formatFootnote = useCallback((o) => { + const formatFootnote = useCallback(import.meta.url, (o) => { if (typeof footnoteKey === 'string') return o[footnoteKey]; if (typeof footnoteKey === 'function') return footnoteKey(o); }, [footnoteKey]); - const formatLabel = useCallback((o) => { + const formatLabel = useCallback(import.meta.url, (o) => { if (typeof labelKey === 'string') return o[labelKey]; if (typeof labelKey === 'function') return labelKey(o); }, [labelKey]); - const filteredOptions = useMemo(() => { + const filteredOptions = useMemo(import.meta.url, () => { const lcSearchTerm = searchTerm.toLowerCase(); return options.filter(o => { return `${formatLabel(o)} ${formatFootnote(o)}`.toLowerCase().includes(lcSearchTerm) diff --git a/src/components/BridgeModalDialog.js b/src/components/BridgeModalDialog.js index 166b64ef8..35d9fdff5 100644 --- a/src/components/BridgeModalDialog.js +++ b/src/components/BridgeModalDialog.js @@ -1,4 +1,4 @@ -import React from 'react'; +import React from '~/lib/react-debug'; import styled from 'styled-components'; import BrightButton from '~/components/BrightButton'; diff --git a/src/components/ButtonAlt.js b/src/components/ButtonAlt.js index 24bf87cf8..760becaf6 100644 --- a/src/components/ButtonAlt.js +++ b/src/components/ButtonAlt.js @@ -1,4 +1,4 @@ -import { useContext, useMemo } from 'react'; +import { useContext, useMemo } from '~/lib/react-debug'; import styled, { css, keyframes } from 'styled-components'; import { Tooltip } from 'react-tooltip'; import BarLoader from 'react-spinners/BarLoader'; @@ -250,8 +250,8 @@ const StandardButton = (props) => { const TransactionButton = (props) => { const { promptingTransaction } = useContext(ChainTransactionContext); - const tooltipId = useMemo(() => uniqueId('alt_button_tooltip_'), []); - const extraProps = useMemo(() => { + const tooltipId = useMemo(import.meta.url, () => uniqueId('alt_button_tooltip_'), []); + const extraProps = useMemo(import.meta.url, () => { if (promptingTransaction) { return { disabled: true, diff --git a/src/components/ChoicesDialog.js b/src/components/ChoicesDialog.js index 78303b7ad..01b079fe1 100644 --- a/src/components/ChoicesDialog.js +++ b/src/components/ChoicesDialog.js @@ -1,4 +1,4 @@ -import React, { useEffect, useMemo, useRef } from 'react'; +import React, { useEffect, useMemo, useRef } from '~/lib/react-debug'; import styled from 'styled-components'; import Button from '~/components/ButtonAlt'; @@ -85,7 +85,7 @@ const ChoicesDialog = ({ rightButton, ...props }) => { - const rightButtonOverride = useMemo(() => { + const rightButtonOverride = useMemo(import.meta.url, () => { if (rightButton) return rightButton; if (!choices || (choices.length === 1 && !choices[0].text)) { @@ -98,7 +98,7 @@ const ChoicesDialog = ({ }, [choices, choicelessButton, choicelessInFooter, props.rightButton]); const contentWrapper = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (contentWrapper.current) { contentWrapper.current.scrollTop = 0; } diff --git a/src/components/CollapsibleBlock.js b/src/components/CollapsibleBlock.js index 1364aec3d..193c00a1a 100644 --- a/src/components/CollapsibleBlock.js +++ b/src/components/CollapsibleBlock.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; import styled, { css, keyframes } from 'styled-components'; import { CloseIcon, CollapsedIcon } from '~/components/Icons'; @@ -162,14 +162,14 @@ const CollapsibleBlock = ({ }) => { const [clickable, setClickable] = useState(); const [collapsed, setCollapsed] = useState(!!initiallyClosed); - const toggleCollapse = useCallback(() => { + const toggleCollapse = useCallback(import.meta.url, () => { if (onClose) return; setCollapsed((c) => !c); }, [onClose]); const hasLoaded = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (hasLoaded.current) { setCollapsed(false); } else { @@ -177,7 +177,7 @@ const CollapsibleBlock = ({ } }, [openOnChange, toggleCollapse]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!collapsed) { setTimeout(() => { setClickable(true); }, 250) } else { diff --git a/src/components/CollapsibleSection.js b/src/components/CollapsibleSection.js index e74469749..8f060b819 100644 --- a/src/components/CollapsibleSection.js +++ b/src/components/CollapsibleSection.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; import styled, { css, keyframes } from 'styled-components'; import { CollapsedIcon } from '~/components/Icons'; @@ -94,17 +94,17 @@ const CollapsibleSection = ({ ...props }) => { const [collapsed, setCollapsed] = useState(!!initiallyClosed); - const toggleCollapse = useCallback(() => { + const toggleCollapse = useCallback(import.meta.url, () => { setCollapsed((c) => !c); }, []); const hasLoaded = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (forceClose) setCollapsed(true); }, [forceClose]); - useEffect(() => { + useEffect(import.meta.url, () => { if (hasLoaded.current) { setCollapsed(false); } else { diff --git a/src/components/ColorPicker.js b/src/components/ColorPicker.js index ea5b891f3..7ef7b1053 100644 --- a/src/components/ColorPicker.js +++ b/src/components/ColorPicker.js @@ -1,4 +1,4 @@ -import { useCallback, useState } from 'react'; +import { useCallback, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { CompactPicker } from 'react-color'; import IconButton from './IconButton'; @@ -65,22 +65,22 @@ const ColorPicker = ({ onChange, initialColor, ...restProps}) => { ], }); - const handleChangeComplete = useCallback((newColor) => { + const handleChangeComplete = useCallback(import.meta.url, (newColor) => { setColor(newColor.hex); if (onChange) onChange(newColor.hex); }, [onChange]); - const onClickAway = useCallback((e) => { + const onClickAway = useCallback(import.meta.url, (e) => { e.stopPropagation(); setOpen((o) => !o); }, []); - const onClick = useCallback((e) => { + const onClick = useCallback(import.meta.url, (e) => { e.stopPropagation(); setOpen(true); }, []); - const stopProp = useCallback((e) => { + const stopProp = useCallback(import.meta.url, (e) => { e.stopPropagation(); }, []); diff --git a/src/components/ConfirmationDialog.js b/src/components/ConfirmationDialog.js index c9664d196..8148236af 100644 --- a/src/components/ConfirmationDialog.js +++ b/src/components/ConfirmationDialog.js @@ -1,4 +1,4 @@ -import React from 'react'; +import React from '~/lib/react-debug'; import styled from 'styled-components'; import Button from '~/components/ButtonAlt'; diff --git a/src/components/CopyReferralLink.js b/src/components/CopyReferralLink.js index 85965d7bf..fa9397e39 100644 --- a/src/components/CopyReferralLink.js +++ b/src/components/CopyReferralLink.js @@ -1,4 +1,4 @@ -import { useCallback } from 'react'; +import { useCallback } from '~/lib/react-debug'; import styled from 'styled-components'; import Clipboard from 'react-clipboard.js'; @@ -14,7 +14,7 @@ const CopyReferralLink = ({ children, fallbackContent }) => { const createAlert = useStore(s => s.dispatchAlertLogged); const playSound = useStore(s => s.dispatchEffectStartRequested); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { playSound('click'); createAlert({ type: 'ClipboardAlert', diff --git a/src/components/CrewIndicator.js b/src/components/CrewIndicator.js index fc3b9ac8b..29e880000 100644 --- a/src/components/CrewIndicator.js +++ b/src/components/CrewIndicator.js @@ -4,7 +4,7 @@ import useCrewContext from '~/hooks/useCrewContext'; import theme from '~/theme'; import { CrewCaptainCardFramed } from './CrewmateCardFramed'; import useCrew from '~/hooks/useCrew'; -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; const CrewLabel = styled.div` align-self: center; @@ -54,7 +54,7 @@ const CrewmateCards = styled.div` const CrewIndicator = ({ cardWidth = 60, crew: inputCrew, noCrewText, flip, label = 'Owned by' }) => { const { crew: myCrew } = useCrewContext(); const { data: fetchedCrew } = useCrew(inputCrew?.id); // (probably already fetched...) - const crew = useMemo(() => fetchedCrew || inputCrew, [inputCrew, fetchedCrew]); + const crew = useMemo(import.meta.url, () => fetchedCrew || inputCrew, [inputCrew, fetchedCrew]); return ( { const { asteroid, building, lotIndex, onLink, ship } = useHydratedLocation(crew?._location, crew?.id); - const genericLabel = useMemo(() => { + const genericLabel = useMemo(import.meta.url, () => { if (asteroid) return formatters.asteroidName(asteroid); if (ship) return ; if (crew?.Ship?.transitDestination) return ; return ''; }, [asteroid, crew, ship]); - const specificLabel = useMemo(() => { + const specificLabel = useMemo(import.meta.url, () => { if (!crew) return ''; if (ship) return formatters.shipName(ship); if (building) return formatters.buildingName(building); return 'Escape Module'; }, [!crew, ship, building]); - const status = useMemo(() => { + const status = useMemo(import.meta.url, () => { if (ship && building) return 'Docked'; if (!lotIndex && (ship || crew).Ship?.transitDestination) return 'In Flight'; if (!lotIndex && !(ship || crew).Ship?.transitDestination) return 'In Orbit'; return ''; }, [building, crew, lotIndex, ship]); - const handleClick = useCallback((e) => { + const handleClick = useCallback(import.meta.url, (e) => { e.stopPropagation(); onLink(); }, [onLink]); diff --git a/src/components/CrewmateCard.js b/src/components/CrewmateCard.js index 3942607e4..aef4b97d1 100644 --- a/src/components/CrewmateCard.js +++ b/src/components/CrewmateCard.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import LoadingAnimation from 'react-spinners/PuffLoader'; import styled, { css } from 'styled-components'; import pick from 'lodash/pick'; @@ -144,19 +144,19 @@ const AbstractCard = ({ imageUrl, onClick, overlay, ...props }) => { // make sure onLoad and onError get called by making sure they are reset to false on imageUrl change const [ readyToLoadUrl, setReadyToLoadUrl ] = useState(imageUrl); - useEffect(() => { + useEffect(import.meta.url, () => { setImageFailed(false); setImageLoaded(false); setReadyToLoadUrl(imageUrl); }, [imageUrl]); - useEffect(() => { + useEffect(import.meta.url, () => { if (imageFailed) setImageLoaded(true); }, [imageFailed]); // TODO: make this a hook? // onLoad is not reliable if, ex. the image is already cached, so we use `complete` - const watchImageLoad = useCallback((input) => { + const watchImageLoad = useCallback(import.meta.url, (input) => { if (!input) { return; } const img = input; const updateFunc = () => setImageLoaded(true); @@ -228,7 +228,7 @@ const CrewmateCard = ({ crewmate = {}, useExplicitAppearance, ...props }) => { ? (crewmate.Name?.name || '') : formatters.crewmateName(crewmate); - let imageUrl = useMemo(() => { + let imageUrl = useMemo(import.meta.url, () => { let url = silhouette; let options = ''; if (props.height) options += `&height=${props.height}`; @@ -261,7 +261,7 @@ export const CrewCaptainCard = ({ crewId, ...props }) => { if (props.height) options += `&height=${props.height}`; if (props.width) options += `&width=${props.width}`; - let imageUrl = useMemo(() => crewId + let imageUrl = useMemo(import.meta.url, () => crewId ? `${process.env.REACT_APP_IMAGES_URL}/v2/crews/${crewId}/captain/image.png?bustOnly=true${options}` : silhouette, [crewId] diff --git a/src/components/CrewmateInfoPane.js b/src/components/CrewmateInfoPane.js index ab59e8b67..cf98b478e 100644 --- a/src/components/CrewmateInfoPane.js +++ b/src/components/CrewmateInfoPane.js @@ -5,7 +5,7 @@ import CrewClassIcon from '~/components/CrewClassIcon'; import CrewTraitIcon from '~/components/CrewTraitIcon'; import DataReadout from '~/components/DataReadout'; import MouseoverInfoPane from './MouseoverInfoPane'; -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import formatters from '~/lib/formatters'; import AddressLink from './AddressLink'; @@ -66,7 +66,7 @@ const NotMine = styled.span` `; const CrewmateInfoPane = ({ crewmate, cssWhenVisible, referenceEl, showOwner, visible, ...props }) => { - const traits = useMemo(() => Crewmate.getCombinedTraits(crewmate.Crewmate), [crewmate]); + const traits = useMemo(import.meta.url, () => Crewmate.getCombinedTraits(crewmate.Crewmate), [crewmate]); if (!crewmate) return null; return ( diff --git a/src/components/DataTable.js b/src/components/DataTable.js index 6d7a7ffc7..6892acec1 100644 --- a/src/components/DataTable.js +++ b/src/components/DataTable.js @@ -2,7 +2,7 @@ import styled from 'styled-components'; import { TriangleDownIcon, TriangleUpIcon } from './Icons'; import { itemColors } from '~/lib/actionItem'; -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import { reactBool } from '~/lib/utils'; const minColumnWidth = 190; @@ -162,17 +162,17 @@ const getEmptyObj = () => ({}); const ExpandableDataTableRow = ({ columns, getRowProps, row, sortDirection, sortField }) => { const [expanded, setExpanded] = useState(false); - const expandableContent = useMemo(() => { + const expandableContent = useMemo(import.meta.url, () => { const getContent = columns.find((c) => c.key === '_expandable')?.selector; if (getContent) return getContent(row); return null; }, [columns, row]); - const onClickExpandable = useCallback(() => { + const onClickExpandable = useCallback(import.meta.url, () => { if (expandableContent) setExpanded((e) => !e); }, [expandableContent]); - const rowProps = useMemo(() => { + const rowProps = useMemo(import.meta.url, () => { return (getRowProps ? getRowProps(row) : null) || {}; }, [getRowProps, row]); diff --git a/src/components/DetailsModal.js b/src/components/DetailsModal.js index 6cc17aa6c..cc4e3909d 100644 --- a/src/components/DetailsModal.js +++ b/src/components/DetailsModal.js @@ -6,7 +6,7 @@ import IconButton from '~/components/IconButton'; import { CloseIcon } from '~/components/Icons'; import ClipCorner from './ClipCorner'; import theme from '~/theme'; -import { useEffect, useState } from 'react'; +import { useEffect, useState } from '~/lib/react-debug'; import useCoachmarkRefSetter from '~/hooks/useCoachmarkRefSetter'; import { COACHMARK_IDS } from '~/contexts/CoachmarkContext'; @@ -142,7 +142,7 @@ const Details = (props) => { // bc can go from details to details page, explicitly reset tooltip so doesn't linger after transition const [showTooltip, setShowTooltip] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { setShowTooltip(false); const timeoutId = setTimeout(() => { setShowTooltip(true); }, 0); return () => clearTimeout(timeoutId); diff --git a/src/components/Dialog.js b/src/components/Dialog.js index 66e61959f..237f0e9c4 100644 --- a/src/components/Dialog.js +++ b/src/components/Dialog.js @@ -1,4 +1,4 @@ -import React from 'react'; +import React from '~/lib/react-debug'; import styled, { keyframes } from 'styled-components'; const fadeIn = keyframes` diff --git a/src/components/DraggableModal.js b/src/components/DraggableModal.js index 4464e86b5..1b6ca774b 100644 --- a/src/components/DraggableModal.js +++ b/src/components/DraggableModal.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import IconButton from '~/components/IconButton'; @@ -114,7 +114,7 @@ const DraggableModal = ({ draggableId, ...props }) => { const draggable = useRef(); - const handleMouseDown = useCallback((e) => { + const handleMouseDown = useCallback(import.meta.url, (e) => { dispatchDraggableToFront(draggableId); setDraggingFrom({ x: e.nativeEvent.offsetX, @@ -122,7 +122,7 @@ const DraggableModal = ({ draggableId, ...props }) => { }); }, [dispatchDraggableToFront, draggableId]); - const handleMouseUp = useCallback(() => { + const handleMouseUp = useCallback(import.meta.url, () => { if (!!draggingFrom) { setDraggingFrom(); if (tmpPosition) { @@ -132,7 +132,7 @@ const DraggableModal = ({ draggableId, ...props }) => { } }, [dispatchDraggableMoved, draggingFrom, draggableId, tmpPosition]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!!draggingFrom) { document.onmousemove = (e) => { setTmpPosition({ diff --git a/src/components/Dropdown.js b/src/components/Dropdown.js index ee9f25641..5c620e85a 100644 --- a/src/components/Dropdown.js +++ b/src/components/Dropdown.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { createPortal } from 'react-dom'; import { usePopper } from 'react-popper'; import styled from 'styled-components'; @@ -60,7 +60,7 @@ const Dropdown = ({ options: rawOptions, ...styleProps }) => { - const [isObjArr, options] = useMemo(() => { + const [isObjArr, options] = useMemo(import.meta.url, () => { if (typeof (rawOptions || [])[0] === 'object') { return [true, [...rawOptions]]; } @@ -86,12 +86,12 @@ const Dropdown = ({ ], }); - const handleToggle = useCallback(() => { + const handleToggle = useCallback(import.meta.url, () => { if (!disabled) setOpen((o) => !o); }, [disabled]); - const handleSelection = useCallback((option) => () => { + const handleSelection = useCallback(import.meta.url, (option) => () => { if (option[valueKey] !== selected[valueKey]) { onChange(isObjArr ? option : option[valueKey]); } @@ -99,18 +99,18 @@ const Dropdown = ({ setOpen(false); }, [onChange, selected]); - const handleMouseEnter = useCallback(() => { + const handleMouseEnter = useCallback(import.meta.url, () => { if (closeTimer.current) { clearTimeout(closeTimer.current); } }, []); - useEffect(() => { + useEffect(import.meta.url, () => { return () => { if (closeTimer.current) clearTimeout(closeTimer.current); } }, []); - const handleMouseLeave = useCallback(() => { + const handleMouseLeave = useCallback(import.meta.url, () => { closeTimer.current = setTimeout(() => { setOpen(false); }, 500); @@ -118,13 +118,13 @@ const Dropdown = ({ // if initialSelection changes, assume that should be my new value // (but don't call onChange since obviously changed from elsewhere) - useEffect(() => { + useEffect(import.meta.url, () => { setSelected( (initialSelection && options.find((o) => o[valueKey] === initialSelection)) || options[0] ); }, [initialSelection, options?.length]); - useEffect(() => { + useEffect(import.meta.url, () => { setOpen(false); }, [disabled]); diff --git a/src/components/EntityLink.js b/src/components/EntityLink.js index 1954ff703..b25aa55d3 100644 --- a/src/components/EntityLink.js +++ b/src/components/EntityLink.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Link } from 'react-router-dom'; import { Entity } from '@influenceth/sdk'; @@ -7,7 +7,7 @@ import EntityName from './EntityName'; const EntityLink = (props) => { const { id, label } = props; - const link = useMemo(() => { + const link = useMemo(import.meta.url, () => { switch (label) { case Entity.IDS.ASTEROID: return `/asteroids/${id}`; case Entity.IDS.BUILDING: return `/building/${id}`; diff --git a/src/components/EntityName.js b/src/components/EntityName.js index d1a2d8472..98a5d41f8 100644 --- a/src/components/EntityName.js +++ b/src/components/EntityName.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Asteroid, Entity } from '@influenceth/sdk'; import formatters from '~/lib/formatters'; @@ -17,7 +17,7 @@ const formatterByLabel = { const EntityName = ({ id, label, forceBaseName }) => { const { data: entity, isLoading } = useEntity(label === Entity.IDS.SPACE ? null : { label, id }); - const name = useMemo(() => { + const name = useMemo(import.meta.url, () => { if (isLoading) return '...'; if (forceBaseName && entity) { if (label === Entity.IDS.ASTEROID) return Asteroid.Entity.getBaseName(entity); diff --git a/src/components/Form.js b/src/components/Form.js index 93ba7c38e..cc5468be8 100644 --- a/src/components/Form.js +++ b/src/components/Form.js @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useState } from '~/lib/react-debug'; import styled, { css } from 'styled-components'; import { Tooltip } from 'react-tooltip'; import LoadingAnimation from 'react-spinners/BarLoader'; diff --git a/src/components/HeroLayout.js b/src/components/HeroLayout.js index 1347d0ac8..1ce6f52e0 100644 --- a/src/components/HeroLayout.js +++ b/src/components/HeroLayout.js @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useState } from 'react'; +import React, { useCallback, useEffect, useState } from '~/lib/react-debug'; import styled, { keyframes } from 'styled-components'; import Button from '~/components/ButtonAlt'; @@ -166,11 +166,11 @@ const HeroLayout = ({ }) => { const [imageLoaded, setImageLoaded] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { setImageLoaded(); }, [coverImage]); - const onImageLoaded = useCallback(() => { + const onImageLoaded = useCallback(import.meta.url, () => { setImageLoaded(coverImage); }, [coverImage]); diff --git a/src/components/InProgressIcon.js b/src/components/InProgressIcon.js index 410999ae7..dacf38895 100644 --- a/src/components/InProgressIcon.js +++ b/src/components/InProgressIcon.js @@ -1,4 +1,4 @@ -import React from 'react'; +import React from '~/lib/react-debug'; import styled, { keyframes } from 'styled-components'; const animation = keyframes` diff --git a/src/components/InfluenceLogo.js b/src/components/InfluenceLogo.js index eb2ac7599..069898d71 100644 --- a/src/components/InfluenceLogo.js +++ b/src/components/InfluenceLogo.js @@ -2,7 +2,7 @@ import { useMemo } from "react"; import { uniqueId } from "lodash"; const InfluenceLogo = () => { - const id = useMemo(() => uniqueId('InfluenceLogo-'), []); + const id = useMemo(import.meta.url, () => uniqueId('InfluenceLogo-'), []); return ( diff --git a/src/components/LiveFoodStatus.js b/src/components/LiveFoodStatus.js index 4be830634..c35f69266 100644 --- a/src/components/LiveFoodStatus.js +++ b/src/components/LiveFoodStatus.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Crew, Time } from '@influenceth/sdk'; @@ -30,7 +30,7 @@ const LiveFoodStatus = ({ crew, fontSize, onClick, ...props }) => { const blockTime = useBlockTime(); const { data: TIME_ACCELERATION } = useConstants('TIME_ACCELERATION'); - const [percentage, isRationing] = useMemo(() => { + const [percentage, isRationing] = useMemo(import.meta.url, () => { const lastFedAgo = Time.toGameDuration(blockTime - (crew?.Crew?.lastFed || 0), parseInt(TIME_ACCELERATION) || 1); return (blockTime > 0 && typeof lastFedAgo === 'number') ? [ diff --git a/src/components/LiveReadyStatus.js b/src/components/LiveReadyStatus.js index ab50bc7f1..d13c3b09b 100644 --- a/src/components/LiveReadyStatus.js +++ b/src/components/LiveReadyStatus.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState } from 'react'; +import { useEffect, useMemo, useState } from '~/lib/react-debug'; import styled, { keyframes } from 'styled-components'; import { CrewBusyIcon, CrewIdleIcon, RandomEventIcon } from '~/components/AnimatedIcons'; @@ -96,7 +96,7 @@ const LiveReadyStatus = ({ crew, ...props }) => { const [crewIsBusy, setCrewIsBusy] = useState(false); const [waitingOnBlock, setWaitingOnBlock] = useState(false); - useEffect(() => { + useEffect(import.meta.url, () => { const readyAtMS = (crew?.Crew?.readyAt || 0) * 1e3; if (readyAtMS > Date.now()) { setCrewIsBusy(true); @@ -109,11 +109,11 @@ const LiveReadyStatus = ({ crew, ...props }) => { } }, [crew?.Crew?.readyAt]); - useEffect(() => { + useEffect(import.meta.url, () => { setWaitingOnBlock(blockTime < (crew?.Crew?.readyAt || 0)); }, [blockTime, crew?.Crew?.readyAt]); - const scheduleEnd = useMemo(() => blockTime + CREW_SCHEDULE_BUFFER, [blockTime, CREW_SCHEDULE_BUFFER]); + const scheduleEnd = useMemo(import.meta.url, () => blockTime + CREW_SCHEDULE_BUFFER, [blockTime, CREW_SCHEDULE_BUFFER]); if (!crew || !blockTime) return null; if (crew._actionTypeTriggered?.pendingEvent) { diff --git a/src/components/LiveTimer.js b/src/components/LiveTimer.js index d7aa9d451..3c5dac044 100644 --- a/src/components/LiveTimer.js +++ b/src/components/LiveTimer.js @@ -1,11 +1,11 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import useSyncedTime from '~/hooks/useSyncedTime'; import { formatTimer } from '~/lib/utils'; const LiveTimer = ({ children, prefix = '', target, maxPrecision, waitingForBlockText = 'Waiting for block...' }) => { const syncedTime = useSyncedTime(); - const [formattedTime, isTimer] = useMemo(() => { + const [formattedTime, isTimer] = useMemo(import.meta.url, () => { const remaining = target === null ? NaN : target - syncedTime; if (isNaN(remaining)) { return ['Initializing...', false]; diff --git a/src/components/LoginPrompt.js b/src/components/LoginPrompt.js index f2af1fe73..eacc91b16 100644 --- a/src/components/LoginPrompt.js +++ b/src/components/LoginPrompt.js @@ -1,4 +1,4 @@ -import { useMemo, useState } from 'react'; +import { useMemo, useState } from '~/lib/react-debug'; import { createPortal } from 'react-dom'; import styled, { css, keyframes } from 'styled-components'; import { ArgentXIcon, BraavosIcon } from './Icons'; @@ -164,7 +164,7 @@ const configs = { const LoginPrompt = ({ onClick, target }) => { const lastConnectedWalletId = useStore(s => s.lastConnectedWalletId); - const conf = useMemo(() => configs[lastConnectedWalletId] || configs.webWallet, [lastConnectedWalletId]); + const conf = useMemo(import.meta.url, () => configs[lastConnectedWalletId] || configs.webWallet, [lastConnectedWalletId]); return createPortal( ( diff --git a/src/components/LotLink.js b/src/components/LotLink.js index eb7b3d879..90fc97de6 100644 --- a/src/components/LotLink.js +++ b/src/components/LotLink.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Entity, Lot } from '@influenceth/sdk'; import useStore from '~/hooks/useStore'; @@ -21,7 +21,7 @@ export const useLotLink = ({ asteroidId: optAsteroidId, lotId: optLotId, resourc const currentZoomScene = useStore(s => s.asteroids.zoomScene); const zoomStatus = useStore(s => s.asteroids.zoomStatus); - const [ asteroidId, lotId ] = useMemo(() => { + const [ asteroidId, lotId ] = useMemo(import.meta.url, () => { if (!optAsteroidId && optLotId) { const loc = Lot.toPosition(optLotId); return [loc.asteroidId, optLotId]; @@ -29,14 +29,14 @@ export const useLotLink = ({ asteroidId: optAsteroidId, lotId: optLotId, resourc return [optAsteroidId, optLotId]; }, [optAsteroidId, optLotId]); - const selectResourceMapAsNeeded = useCallback(() => { + const selectResourceMapAsNeeded = useCallback(import.meta.url, () => { if (resourceId) { dispatchResourceMapSelect(resourceId); dispatchResourceMapToggle(true); } }, [resourceId, dispatchResourceMapSelect, dispatchResourceMapToggle, dispatchHudMenuOpened, openHudMenu]); - const zoomToLotAsNeeded = useCallback(() => { + const zoomToLotAsNeeded = useCallback(import.meta.url, () => { // if zoomToLot !== current zoomToLot, do something if (!!zoomToLot !== (currentZoomScene?.type === 'LOT')) { dispatchZoomScene(zoomToLot ? { type: 'LOT' } : null); @@ -50,7 +50,7 @@ export const useLotLink = ({ asteroidId: optAsteroidId, lotId: optLotId, resourc } }, [zoomToLot, currentZoomScene, dispatchZoomScene, dispatchHudMenuOpened]); - const onClickFunction = useCallback(() => { + const onClickFunction = useCallback(import.meta.url, () => { // if already zoomed into asteroid, just select lot and select resource map if (asteroidId === origin && zoomStatus === 'in') { dispatchLotSelected(lotId); @@ -86,7 +86,7 @@ export const useLotLink = ({ asteroidId: optAsteroidId, lotId: optLotId, resourc } export const LotLink = ({ asteroidId: optAsteroidId, lotId: optLotId, resourceId, zoomToLot }) => { - const [ asteroidId, lotId ] = useMemo(() => { + const [ asteroidId, lotId ] = useMemo(import.meta.url, () => { if (!optAsteroidId && optLotId) { const loc = Lot.toPosition(optLotId); return [loc.asteroidId, optLotId]; @@ -99,7 +99,7 @@ export const LotLink = ({ asteroidId: optAsteroidId, lotId: optLotId, resourceId // NOTE: this should only tries grabbing the name from owned asteroids to save a load... // (will fallback to loading name if it is not an owned asteroid) const { data: owned, isLoading: ownedAreLoading } = useWalletAsteroids(); - const asteroidName = useMemo(() => { + const asteroidName = useMemo(import.meta.url, () => { if (owned) { const match = owned.find(a => a.id === Number(asteroidId)); if (match) { diff --git a/src/components/MarketplaceLink.js b/src/components/MarketplaceLink.js index 99cebb403..4b117d3ef 100644 --- a/src/components/MarketplaceLink.js +++ b/src/components/MarketplaceLink.js @@ -1,9 +1,9 @@ -import { useCallback, useState, } from 'react'; +import { useCallback, useState, } from '~/lib/react-debug'; const MarketplaceLink = ({ assetType, chain, children, id }) => { const [referenceEl, setReferenceEl] = useState(); - const handleMarketplaceClick = useCallback(() => { + const handleMarketplaceClick = useCallback(import.meta.url, () => { let url; // Ethereum > OpenSea diff --git a/src/components/MouseoverInfoPane.js b/src/components/MouseoverInfoPane.js index 2438e2ade..9d97b8c42 100644 --- a/src/components/MouseoverInfoPane.js +++ b/src/components/MouseoverInfoPane.js @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useState } from '~/lib/react-debug'; import { createPortal } from 'react-dom'; import styled from 'styled-components'; diff --git a/src/components/Multiselect.js b/src/components/Multiselect.js index e851516ac..2fa382e14 100644 --- a/src/components/Multiselect.js +++ b/src/components/Multiselect.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { createPortal } from 'react-dom'; import { usePopper } from 'react-popper'; import styled from 'styled-components'; @@ -61,7 +61,7 @@ const Multiselect = ({ valueKey = 'key', ...styleProps }) => { - const [isObjArr, options] = useMemo(() => { + const [isObjArr, options] = useMemo(import.meta.url, () => { if (typeof (rawOptions || [])[0] === 'object') { return [true, [...rawOptions]]; } @@ -86,29 +86,29 @@ const Multiselect = ({ ], }); - const handleToggle = useCallback(() => { + const handleToggle = useCallback(import.meta.url, () => { if (!disabled) setOpen((o) => !o); }, [disabled]); - const handleMouseEnter = useCallback(() => { + const handleMouseEnter = useCallback(import.meta.url, () => { if (closeTimer.current) { clearTimeout(closeTimer.current); } }, []); - const handleMouseLeave = useCallback(() => { + const handleMouseLeave = useCallback(import.meta.url, () => { closeTimer.current = setTimeout(() => { setOpen(false); }, 500); }, []); - useEffect(() => { + useEffect(import.meta.url, () => { return () => { if (closeTimer.current) clearTimeout(closeTimer.current); } }, []); - useEffect(() => { + useEffect(import.meta.url, () => { setOpen(false); }, [disabled]); diff --git a/src/components/NavIcon.js b/src/components/NavIcon.js index ee63a3b47..fd5156b33 100644 --- a/src/components/NavIcon.js +++ b/src/components/NavIcon.js @@ -1,4 +1,4 @@ -import React from 'react'; +import React from '~/lib/react-debug'; import styled, { css, keyframes } from 'styled-components'; const innerDiamondDimensionDefault = 20; diff --git a/src/components/NumberInput.js b/src/components/NumberInput.js index f21b14aa4..d29b597f2 100644 --- a/src/components/NumberInput.js +++ b/src/components/NumberInput.js @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useState } from '~/lib/react-debug'; import styled from 'styled-components'; const StyledInput = styled.input` diff --git a/src/components/Pagination.js b/src/components/Pagination.js index db6262d0f..41d2f8b55 100644 --- a/src/components/Pagination.js +++ b/src/components/Pagination.js @@ -1,4 +1,4 @@ -import { useCallback } from 'react'; +import { useCallback } from '~/lib/react-debug'; import styled from 'styled-components'; import { PreviousIcon, NextIcon, BeginningIcon } from '~/components/Icons'; @@ -14,9 +14,9 @@ const StyledPagination = styled.div` const Pagination = (props) => { const { currentPage, rowsPerPage, rowCount, onChangePage } = props; - const handlePrevious = useCallback(() => onChangePage(currentPage - 1), [ currentPage, onChangePage ]); - const handleNext = useCallback(() => onChangePage(currentPage + 1), [ currentPage, onChangePage ]); - const handleFirst = useCallback(() => onChangePage(1), [ onChangePage ]); + const handlePrevious = useCallback(import.meta.url, () => onChangePage(currentPage - 1), [ currentPage, onChangePage ]); + const handleNext = useCallback(import.meta.url, () => onChangePage(currentPage + 1), [ currentPage, onChangePage ]); + const handleFirst = useCallback(import.meta.url, () => onChangePage(1), [ onChangePage ]); return ( diff --git a/src/components/Popper.js b/src/components/Popper.js index cdd09609e..74efe3f53 100644 --- a/src/components/Popper.js +++ b/src/components/Popper.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { VscListUnordered as PopperIcon } from 'react-icons/vsc'; import { createPortal } from 'react-dom'; @@ -64,7 +64,7 @@ export const PoppableContent = ({ children, ignoreClickAway, open, onClose, titl const contentRef = useRef(); const initialPosition = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (contentRef.current && open) { if (!initialPosition.current) { initialPosition.current = { @@ -114,16 +114,16 @@ export const PoppableContent = ({ children, ignoreClickAway, open, onClose, titl const Poppable = ({ children, closeOnChange, closeOnClickAway = true, disabled, label, title, ...styleProps }) => { const [open, setOpen] = useState(false); - const handleToggle = useCallback(() => { + const handleToggle = useCallback(import.meta.url, () => { if (!disabled) setOpen((o) => !o); }, [disabled]); - useEffect(() => { + useEffect(import.meta.url, () => { setOpen(false); }, [disabled]); - useEffect(() => { + useEffect(import.meta.url, () => { if (open) setOpen(false); }, [closeOnChange]); diff --git a/src/components/Porkchop.js b/src/components/Porkchop.js index 106bc61f8..6a764e16e 100644 --- a/src/components/Porkchop.js +++ b/src/components/Porkchop.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { lambert } from '@influenceth/astro'; import { GM_ADALIA } from '@influenceth/sdk'; @@ -150,12 +150,12 @@ const Porkchop = ({ const canvasRef = useRef(); const runRef = useRef(); - const setCanvasRef = useCallback((canvas) => { + const setCanvasRef = useCallback(import.meta.url, (canvas) => { canvasRef.current = canvas; setCanvasRefIsSet(true); }, []); - useEffect(() => { + useEffect(import.meta.url, () => { if (!canvasRefIsSet) return; if (!originPath || !destinationPath) return; setLoading(true); @@ -259,11 +259,11 @@ const Porkchop = ({ } }, [canvasRefIsSet, lastFedAt, originPath, destinationPath, shipParams]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!travelSolution) setSelectionPos(); }, [travelSolution]) - const getMouseData = useCallback((e) => { + const getMouseData = useCallback(import.meta.url, (e) => { const data = { x: Math.max(0, Math.min(e.nativeEvent.offsetX / size, 1)), y: Math.max(0, Math.min(e.nativeEvent.offsetY / size, 1)), @@ -281,7 +281,7 @@ const Porkchop = ({ return data; }, [baseTime, nowTime, size]); - const handleClick = useCallback(async (e) => { + const handleClick = useCallback(import.meta.url, async (e) => { const mouseData = getMouseData(e); setSelectionPos(mouseData); setMousePos(); @@ -344,7 +344,7 @@ const Porkchop = ({ }); }, [emode, originPath, destinationPath, lastFedAt, shipParams]); - const handleMouseMove = useCallback((e) => { + const handleMouseMove = useCallback(import.meta.url, (e) => { if (loading) return; if (e.type === 'mousemove') { setMousePos(getMouseData(e)); diff --git a/src/components/Reconnecting.js b/src/components/Reconnecting.js index 5cbb2809d..329e1a04e 100644 --- a/src/components/Reconnecting.js +++ b/src/components/Reconnecting.js @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useState } from '~/lib/react-debug'; import FullpageInterstitial from '~/components/FullpageInterstitial'; @@ -6,7 +6,7 @@ const Reconnecting = ({ onLogout, walletName }) => { const [show, setShow] = useState(false); // give a moment to successfully connect without showing an extra screen... - useEffect(() => { + useEffect(import.meta.url, () => { const to = setTimeout(() => { setShow(true); }, 1500); diff --git a/src/components/ResourceRequirement.js b/src/components/ResourceRequirement.js index c6522aae5..7313dbd70 100644 --- a/src/components/ResourceRequirement.js +++ b/src/components/ResourceRequirement.js @@ -1,4 +1,4 @@ -import React from 'react'; +import React from '~/lib/react-debug'; import styled, { keyframes } from 'styled-components'; import { CheckSmallIcon } from '~/components/Icons'; diff --git a/src/components/ResourceSelection.js b/src/components/ResourceSelection.js index 5f5d8669c..8b3a0b3c6 100644 --- a/src/components/ResourceSelection.js +++ b/src/components/ResourceSelection.js @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import React, { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import theme, { hexToRGB } from '~/theme'; @@ -31,7 +31,7 @@ const QuantaInput = styled.input` const PartialSelectMenu = ({ maxSelectable, onChange, onClose, resource, selected }) => { const fieldRef = useRef(); - const onBlur = useCallback(() => { + const onBlur = useCallback(import.meta.url, () => { let useValue = parseInt(fieldRef.current.value) || 0; if (useValue < 0) useValue = 0; if (useValue > maxSelectable) useValue = maxSelectable; @@ -39,14 +39,14 @@ const PartialSelectMenu = ({ maxSelectable, onChange, onClose, resource, selecte onClose(); }, []); - const onKeyDown = useCallback((e) => { + const onKeyDown = useCallback(import.meta.url, (e) => { if (e.key === 'Enter' || e.key === 'Tab' || e.key === 'Escape') { e.preventDefault(); onBlur(); } }, []); - useEffect(() => { + useEffect(import.meta.url, () => { if (fieldRef.current) { fieldRef.current.value = selected || 0; fieldRef.current.select(); @@ -69,7 +69,7 @@ const PartialSelectMenu = ({ maxSelectable, onChange, onClose, resource, selecte }; const ResourceSelection = ({ item, onSelectItem }) => { - const props = useMemo(() => { + const props = useMemo(import.meta.url, () => { const config = {}; if (item.selected > 0) { config.badgeColor = theme.colors.brightMain; @@ -96,7 +96,7 @@ const ResourceSelection = ({ item, onSelectItem }) => { return config; }, [item]); - const onToggleAll = useCallback(() => { + const onToggleAll = useCallback(import.meta.url, () => { if (item.selected > 0) onSelectItem(0); else onSelectItem(item.maxSelectable); }, [item]); diff --git a/src/components/ResourceThumbnail.js b/src/components/ResourceThumbnail.js index 51adba09c..45b2ee211 100644 --- a/src/components/ResourceThumbnail.js +++ b/src/components/ResourceThumbnail.js @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useState, useMemo, useRef } from 'react'; +import React, { useCallback, useEffect, useState, useMemo, useRef } from '~/lib/react-debug'; import styled from 'styled-components'; import { FaEllipsisH as MenuIcon } from 'react-icons/fa'; import Lottie from 'lottie-react'; @@ -45,9 +45,9 @@ const MenuOpenWrapper = styled.div` const LottieOverlayTexture = ({ animation, isPaused = false, size = '100%' }) => { const lottieRef = useRef(); - const style = useMemo(() => ({ opacity: 0.2, width: size, height: size }), [size]); + const style = useMemo(import.meta.url, () => ({ opacity: 0.2, width: size, height: size }), [size]); - useEffect(() => { + useEffect(import.meta.url, () => { if (isPaused) lottieRef.current.pause(); else lottieRef.current.play(); }, [isPaused]); @@ -213,7 +213,7 @@ const BottomBanner = styled(ThumbnailBottomBanner)` const Menu = ({ children }) => { const [open, setOpen] = useState(); - const onClick = useCallback((e) => { + const onClick = useCallback(import.meta.url, (e) => { e.stopPropagation(); setOpen(true); }, []); diff --git a/src/components/SearchFilterTray.js b/src/components/SearchFilterTray.js index 5d3154276..60ea6e8fe 100644 --- a/src/components/SearchFilterTray.js +++ b/src/components/SearchFilterTray.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import Button from '~/components/ButtonAlt'; @@ -25,16 +25,16 @@ const SearchFilterTray = ({ assetType, handleClickFilters }) => { const isAssetSearchMatchingDefault = useStore(s => s.isAssetSearchMatchingDefault); const isAssetSearchFilterMatchingDefault = useStore(s => s.isAssetSearchFilterMatchingDefault); - const onClear = useCallback(() => { + const onClear = useCallback(import.meta.url, () => { resetFilters(); }, []); - const onClickFilters = useCallback((e) => { + const onClickFilters = useCallback(import.meta.url, (e) => { if (handleClickFilters) handleClickFilters(e); }, [handleClickFilters]); - const isDefaultSearch = useMemo(() => isAssetSearchMatchingDefault(assetType), [assetType, filters]); - const activeFilters = useMemo(() => { + const isDefaultSearch = useMemo(import.meta.url, () => isAssetSearchMatchingDefault(assetType), [assetType, filters]); + const activeFilters = useMemo(import.meta.url, () => { return Object.keys(filters || {}) .reduce((acc, fieldName) => acc + (isAssetSearchFilterMatchingDefault(assetType, fieldName) ? 0 : 1), 0) }, [assetType, filters]); diff --git a/src/components/SearchFilters.js b/src/components/SearchFilters.js index 0584c91ee..386effb83 100644 --- a/src/components/SearchFilters.js +++ b/src/components/SearchFilters.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo } from 'react'; +import { useCallback, useEffect, useMemo } from '~/lib/react-debug'; import { Asteroid, Building, Crewmate, Permission, Product } from '@influenceth/sdk'; import useStore from '~/hooks/useStore'; @@ -180,7 +180,7 @@ const SearchFilters = ({ assetType, highlighting, isListView = false }) => { const filters = useStore(s => s.assetSearch[assetType].filters); const updateFilters = useStore(s => s.dispatchFiltersUpdated(assetType)); - const onFiltersChange = useCallback((update) => { + const onFiltersChange = useCallback(import.meta.url, (update) => { const newFilters = {...(filters || {})}; Object.keys(update).forEach((k) => { if (update[k] === undefined) { @@ -192,14 +192,14 @@ const SearchFilters = ({ assetType, highlighting, isListView = false }) => { updateFilters(newFilters); }, [filters, updateFilters]); - const filterProps = useMemo(() => ({ + const filterProps = useMemo(import.meta.url, () => ({ assetType, filters, onChange: onFiltersChange, isListView }), [assetType, filters, highlighting, onFiltersChange, isListView]); - useEffect(() => { + useEffect(import.meta.url, () => { // for most types, default filter to asteroid if one is selected if (['buildings','coresamples','leases','lots'].includes(assetType)) { onFiltersChange({ asteroid: asteroidId }); diff --git a/src/components/SelectHabitatDialog.js b/src/components/SelectHabitatDialog.js index 987a22be3..f00da886a 100644 --- a/src/components/SelectHabitatDialog.js +++ b/src/components/SelectHabitatDialog.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Building, Entity } from '@influenceth/sdk' @@ -87,10 +87,10 @@ const fromEntityFormat = (loc) => { const SelectHabitatDialog = ({ onAccept, onReject }) => { const randomAssignment = 1;// TODO: should not be hardcoded const { data: habitat } = useBuilding(randomAssignment); - const habitatLocation = useMemo(() => fromEntityFormat(habitat?.Location?.location), [habitat]) + const habitatLocation = useMemo(import.meta.url, () => fromEntityFormat(habitat?.Location?.location), [habitat]) const { data: asteroid } = useAsteroid(habitatLocation?.asteroidId); - const onSelectHabitat = useCallback((choice) => () => { + const onSelectHabitat = useCallback(import.meta.url, (choice) => () => { if (choice.id === 1) return onAccept(randomAssignment); return onReject(); }, [randomAssignment]); diff --git a/src/components/SelectUninitializedCrewmateDialog.js b/src/components/SelectUninitializedCrewmateDialog.js index 3b12342b0..78681b1db 100644 --- a/src/components/SelectUninitializedCrewmateDialog.js +++ b/src/components/SelectUninitializedCrewmateDialog.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState } from 'react'; +import { useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import CrewmateCard from '~/components/CrewmateCard'; @@ -92,7 +92,7 @@ const SelectUninitializedCrewmateDialog = ({ arvadiansDisallowed, onSelect }) => const [selected, setSelected] = useState(); - const onCloseDestination = useMemo(() => { + const onCloseDestination = useMemo(import.meta.url, () => { if (crew?.Crew?.roster?.length > 0) { return '/crew'; } else { @@ -100,7 +100,7 @@ const SelectUninitializedCrewmateDialog = ({ arvadiansDisallowed, onSelect }) => } }, [crew]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!loading) { if (arvadiansDisallowed || !arvadianRecruits?.length) { onSelect(adalianRecruits?.[0]?.id || 0); diff --git a/src/components/ShipLink.js b/src/components/ShipLink.js index d7ba75ff3..e44fec65a 100644 --- a/src/components/ShipLink.js +++ b/src/components/ShipLink.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import { ZOOM_OUT_ANIMATION_TIME } from '~/game/scene/Asteroid'; @@ -19,13 +19,13 @@ export const useShipLink = ({ crewId, shipId, zoomToShip }) => { const { data: shipShip } = useShip(shipId); const { data: crewShip } = useCrew(shipId ? undefined : crewId); - const ship = useMemo(() => shipShip || crewShip, [shipShip, crewShip]); + const ship = useMemo(import.meta.url, () => shipShip || crewShip, [shipShip, crewShip]); const zoomToAsteroid = useLotLink({ asteroidId: ship?._location?.asteroidId }); const zoomToLot = useLotLink({ lotId: ship?._location?.lotId }); - const zoomToShipAsNeeded = useCallback(() => { + const zoomToShipAsNeeded = useCallback(import.meta.url, () => { if (!ship) return; let delayToZoomScene = 500; @@ -71,7 +71,7 @@ export const ShipLink = ({ shipId, zoomToShip }) => { const onClick = useShipLink({ shipId, zoomToShip }); const { data: controlled, isLoading: controlledAreLoading } = useCrewShips(); - const shipName = useMemo(() => { + const shipName = useMemo(import.meta.url, () => { if (controlled) { const match = controlled.find(a => a.id === Number(shipId)); return match?.name || `Ship #${shipId.toLocaleString()}`; diff --git a/src/components/SliderInput.js b/src/components/SliderInput.js index b6d991ffe..6810a9530 100644 --- a/src/components/SliderInput.js +++ b/src/components/SliderInput.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef } from 'react'; +import { useCallback, useEffect, useMemo, useRef } from '~/lib/react-debug'; import styled from 'styled-components'; import NavIcon from './NavIcon'; @@ -64,14 +64,14 @@ const SliderInput = ({ disabled, min = 0, max = 1, increment = 1, value, onChang const updating = useRef(false); const expectedChange = useRef(); - const handleChange = useCallback((newValue) => { + const handleChange = useCallback(import.meta.url, (newValue) => { if (disabled) return; const incrementedNewValue = (newValue === max || newValue === min) ? newValue : Math.round((1 / increment) * newValue) * increment; expectedChange.current = incrementedNewValue; if (onChange) onChange(incrementedNewValue); }, [disabled, increment, min, max, onChange]); - useEffect(() => { + useEffect(import.meta.url, () => { const mouseHandler = (e) => { if (e.type === 'mousedown') { updating.current = true; @@ -111,7 +111,7 @@ const SliderInput = ({ disabled, min = 0, max = 1, increment = 1, value, onChang } }, [increment, min, max, handleChange, value]); - const percentage = useMemo(() => Math.max(0, Math.min(100, (value - min) / (max - min))), [value, min, max]) || 0; + const percentage = useMemo(import.meta.url, () => Math.max(0, Math.min(100, (value - min) / (max - min))), [value, min, max]) || 0; return ( diff --git a/src/components/SvgFromSrc.js b/src/components/SvgFromSrc.js index 04412662c..a8e4000b8 100644 --- a/src/components/SvgFromSrc.js +++ b/src/components/SvgFromSrc.js @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from 'react'; +import React, { useEffect, useState } from '~/lib/react-debug'; import styled from 'styled-components'; const SvgWrapper = styled.span` @@ -11,7 +11,7 @@ const SvgFromSrc = ({ src }) => { //const [isLoaded, setIsLoaded] = useState(false); //const [isErrored, setIsErrored] = useState(false); - useEffect(() => { + useEffect(import.meta.url, () => { fetch(src) .then(res => res.text()) .then(setSvg) diff --git a/src/components/TabContainer.js b/src/components/TabContainer.js index e95c601fd..3e3febfcc 100644 --- a/src/components/TabContainer.js +++ b/src/components/TabContainer.js @@ -1,4 +1,4 @@ -import { useCallback, useState } from 'react'; +import { useCallback, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import useStore from '~/hooks/useStore'; @@ -118,7 +118,7 @@ const TabContainer = ({ const active = controller?.active || _active; const setActive = controller?.setActive || _setActive; - const onClick = useCallback((i) => () => { + const onClick = useCallback(import.meta.url, (i) => () => { if (tabs[i].disabled) { playSound('failure'); } else { diff --git a/src/components/TextInput.js b/src/components/TextInput.js index 8cf6678d0..d515b6347 100644 --- a/src/components/TextInput.js +++ b/src/components/TextInput.js @@ -1,4 +1,4 @@ -import { forwardRef, useEffect, useRef, useState } from 'react'; +import { forwardRef, useEffect, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; const StyledInput = styled.input` @@ -44,7 +44,7 @@ const TextInput = forwardRef((props, forwardedRef) => { } }; - useEffect(() => { + useEffect(import.meta.url, () => { _onChange({ target: { value: initialValue || '' } }); }, [resetOnChange]); // eslint-disable-line react-hooks/exhaustive-deps diff --git a/src/components/TimeIcon.js b/src/components/TimeIcon.js index a46f74fb0..996a70f5d 100644 --- a/src/components/TimeIcon.js +++ b/src/components/TimeIcon.js @@ -1,4 +1,4 @@ -import React, { useMemo } from 'react'; +import React, { useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { displayTimeFractionDigits } from '~/lib/utils'; @@ -43,7 +43,7 @@ const BlurCircle = styled.circle` `; const TimeIcon = ({ time, motionBlur, ...props }) => { - const position = useMemo(() => { + const position = useMemo(import.meta.url, () => { const t = parseInt(time.substr(-displayTimeFractionDigits)) / Math.pow(10, displayTimeFractionDigits); if (isNaN(t)) return { x: -100, y: -100 }; const theta = 2 * Math.PI * t; diff --git a/src/components/TrackballModControls.js b/src/components/TrackballModControls.js index 7514a6ece..1779a6ad5 100644 --- a/src/components/TrackballModControls.js +++ b/src/components/TrackballModControls.js @@ -1,4 +1,4 @@ -import { forwardRef, useRef, useLayoutEffect, useEffect, useState } from 'react'; +import { forwardRef, useRef, useLayoutEffect, useEffect, useState } from '~/lib/react-debug'; import { useThree, useFrame } from '@react-three/fiber'; import TrackballModControlsImpl from '~/lib/graphics/TrackballModControlsImpl'; @@ -19,7 +19,7 @@ export const TrackballModControls = forwardRef(({ children, ...props }, ref) => }, [ children, controls ]); // (this is presumably just for static scenes / scenes without a running frameloop) - // useEffect(() => { + // useEffect(import.meta.url, () => { // controls?.addEventListener('change', invalidate); // return () => { @@ -32,7 +32,7 @@ export const TrackballModControls = forwardRef(({ children, ...props }, ref) => if (controls.enabled) controls.update(); }); - useEffect(() => { + useEffect(import.meta.url, () => { set({ controls }); }, [ controls, set ]); diff --git a/src/components/UserPrice.js b/src/components/UserPrice.js index 189358f06..595be8c8f 100644 --- a/src/components/UserPrice.js +++ b/src/components/UserPrice.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { asteroidPrice } from '~/lib/priceUtils'; import usePriceConstants from '~/hooks/usePriceConstants'; @@ -28,7 +28,7 @@ const UserPrice = ({ price, priceToken, format }) => { export const AsteroidUserPrice = ({ lots = 0n, format = true }) => { const { data: priceConstants } = usePriceConstants(); - const price = useMemo(() => { + const price = useMemo(import.meta.url, () => { return asteroidPrice(lots, priceConstants); }, [lots, priceConstants]); diff --git a/src/components/filters/AsteroidNameFilter.js b/src/components/filters/AsteroidNameFilter.js index 0794d943b..becdf931f 100644 --- a/src/components/filters/AsteroidNameFilter.js +++ b/src/components/filters/AsteroidNameFilter.js @@ -1,4 +1,4 @@ -import { useCallback, useRef } from 'react'; +import { useCallback, useRef } from '~/lib/react-debug'; import useStore from '~/hooks/useStore'; import { InputBlock, SearchMenu } from './components'; @@ -14,17 +14,17 @@ const NameFilter = ({ assetType, filters, onChange, isListView }) => { const selectAsteroidId = useStore((s) => s.dispatchOriginSelected); - const handleChange = useCallback((e) => { + const handleChange = useCallback(import.meta.url, (e) => { onChange({ [fieldName]: e.currentTarget.value }); }, [onChange]); - const handleById = useCallback(() => { + const handleById = useCallback(import.meta.url, () => { if (asteroidId.current.value) { selectAsteroidId(asteroidId.current.value); } }, []); - const handleKeydown = useCallback((e) => { + const handleKeydown = useCallback(import.meta.url, (e) => { if (['Enter', 'Tab'].includes(e.key)) { handleById(); } diff --git a/src/components/filters/BooleanFilter.js b/src/components/filters/BooleanFilter.js index 1cf0f8132..c56378064 100644 --- a/src/components/filters/BooleanFilter.js +++ b/src/components/filters/BooleanFilter.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useState } from '~/lib/react-debug'; import { FiCheckSquare as CheckedIcon, FiSquare as UncheckedIcon } from 'react-icons/fi'; import { CheckboxButton, CheckboxRow, SearchMenu } from './components'; @@ -6,7 +6,7 @@ import { CheckboxButton, CheckboxRow, SearchMenu } from './components'; const BooleanFilter = ({ assetType, filters, onChange, title, label, fieldName, initialValue }) => { const [ value, setValue ] = useState(!!initialValue); - useEffect(() => { + useEffect(import.meta.url, () => { if (filters[fieldName] !== undefined) { setValue(filters[fieldName]); } else { @@ -14,7 +14,7 @@ const BooleanFilter = ({ assetType, filters, onChange, title, label, fieldName, } }, [filters[fieldName], initialValue]); - const onClick = useCallback((e) => { + const onClick = useCallback(import.meta.url, (e) => { onChange({ [fieldName]: !value }); }, [fieldName, onChange, value]); diff --git a/src/components/filters/BuildingAccessFilter.js b/src/components/filters/BuildingAccessFilter.js index 81a13fb89..3d627f7b2 100644 --- a/src/components/filters/BuildingAccessFilter.js +++ b/src/components/filters/BuildingAccessFilter.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; import { Address } from '@influenceth/sdk'; import { RadioCheckedIcon, RadioUncheckedIcon } from '~/components/Icons'; @@ -27,7 +27,7 @@ const BuildingAccessFilter = ({ assetType, filters, onChange }) => { const [types, setTypes] = useState(initialValues); console.log({ 'types': types }); - useEffect(() => { + useEffect(import.meta.url, () => { const newTypes = ({ ...initialValues }); if (filters[fieldName] && filters[fieldName].length > 0) { const filterArr = filters[fieldName]; @@ -44,7 +44,7 @@ const BuildingAccessFilter = ({ assetType, filters, onChange }) => { setTypes(newTypes); }, [filters[fieldName]]); - const onClick = useCallback((k) => (e) => { + const onClick = useCallback(import.meta.url, (k) => (e) => { e.stopPropagation(); if (k === 'granted') { onChange({ [fieldName]: [crew?.id, crew?.Crew?.delegatedTo] }); diff --git a/src/components/filters/CheckboxFilter.js b/src/components/filters/CheckboxFilter.js index 46fdd8cc2..2e4b7931f 100644 --- a/src/components/filters/CheckboxFilter.js +++ b/src/components/filters/CheckboxFilter.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { FiCheckSquare as CheckedIcon, FiSquare as UncheckedIcon } from 'react-icons/fi'; @@ -34,14 +34,14 @@ const CheckboxFilter = ({ const highlight = useStore(s => s.assetSearch[assetType].highlight); const fieldHighlight = highlight && highlight.field === highlightFieldName; - const initialValues = useMemo(() => { + const initialValues = useMemo(import.meta.url, () => { return options.reduce((acc, { key, initialValue }) => ({ ...acc, [key]: initialValue }), {}); }, [options]); const [ types, setTypes ] = useState({ ...initialValues }); const [highlightColors, setHighlightColors] = useState({ ...(fieldHighlight?.colorMap || defaultColorMap) }); - useEffect(() => { + useEffect(import.meta.url, () => { const newTypes = ({ ...initialValues }); if (filters[fieldName] !== undefined) { const filterArr = filters[fieldName]; @@ -52,7 +52,7 @@ const CheckboxFilter = ({ setTypes(newTypes); }, [filters[fieldName]]); - const onClick = useCallback((k) => (e) => { + const onClick = useCallback(import.meta.url, (k) => (e) => { e.stopPropagation(); const newTypes = { ...types, @@ -61,18 +61,18 @@ const CheckboxFilter = ({ onChange({ [fieldName]: Object.keys(newTypes).filter((k) => newTypes[k]) }); }, [onChange, types]); - const toggleAllMode = useMemo(() => { + const toggleAllMode = useMemo(import.meta.url, () => { let selectedTally = (filters[fieldName] !== undefined) ? filters[fieldName].length : options.length; return selectedTally < options.length / 2; }, [filters[fieldName]]) - const toggleAll = useCallback(() => { + const toggleAll = useCallback(import.meta.url, () => { onChange({ [fieldName]: toggleAllMode ? Object.keys(types) : [] }); }, [toggleAllMode, fieldName]); - const toggleAllLabel = useMemo(() => { + const toggleAllLabel = useMemo(import.meta.url, () => { if (options.length > 3) { return toggleAllMode ? 'Select All' : 'Deselect All'; } diff --git a/src/components/filters/CrewOwnershipFilter.js b/src/components/filters/CrewOwnershipFilter.js index 81d2545dc..d58ff11ab 100644 --- a/src/components/filters/CrewOwnershipFilter.js +++ b/src/components/filters/CrewOwnershipFilter.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; import { Address } from '@influenceth/sdk'; import useSession from '~/hooks/useSession'; @@ -26,7 +26,7 @@ const CrewOwnershipFilter = ({ assetType, filters, onChange }) => { const addressInput = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { const newTypes = { ...initialValues }; if (filters[fieldName]) { try { @@ -49,7 +49,7 @@ const CrewOwnershipFilter = ({ assetType, filters, onChange }) => { }, [accountAddress, filters[fieldName]]); - const onClick = useCallback((k) => (e) => { + const onClick = useCallback(import.meta.url, (k) => (e) => { e.stopPropagation(); let value = k; if (k === 'ownedByMe' && accountAddress && Address.toStandard(accountAddress)) { @@ -72,7 +72,7 @@ const CrewOwnershipFilter = ({ assetType, filters, onChange }) => { onChange({ [fieldName]: value }); }, [accountAddress, onChange, ownedByAddress]); - const handleEvent = useCallback((e) => { + const handleEvent = useCallback(import.meta.url, (e) => { if (e.type === 'blur' || e.key === 'Enter' || e.key === 'Tab') { let validatedValue = e.currentTarget.value && e.currentTarget.value !== '0' && Address.toStandard(e.currentTarget.value); if (validatedValue) { @@ -89,7 +89,7 @@ const CrewOwnershipFilter = ({ assetType, filters, onChange }) => { } }, [onChange, types]); - useEffect(() => { + useEffect(import.meta.url, () => { if (addressInput.current) addressInput.current.value = ownedByAddress; }, [ownedByAddress]); diff --git a/src/components/filters/LotIdFilter.js b/src/components/filters/LotIdFilter.js index 89bcc3fa1..d8c8bb051 100644 --- a/src/components/filters/LotIdFilter.js +++ b/src/components/filters/LotIdFilter.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useRef } from 'react'; +import { useCallback, useMemo, useRef } from '~/lib/react-debug'; import { Asteroid, Lot } from '@influenceth/sdk'; import IconButton from '~/components/IconButton'; @@ -14,9 +14,9 @@ const LotIdFilter = ({ assetType, filters }) => { const asteroidId = useStore((s) => s.asteroids.origin); const dispatchLotSelected = useStore((s) => s.dispatchLotSelected); const lotIndex = useRef(); - const maxLots = useMemo(() => Asteroid.getSurfaceArea(asteroidId), [asteroidId]); + const maxLots = useMemo(import.meta.url, () => Asteroid.getSurfaceArea(asteroidId), [asteroidId]); - const handleById = useCallback(() => { + const handleById = useCallback(import.meta.url, () => { if (lotIndex.current.value) { let targetIndex = parseInt(lotIndex.current.value); @@ -34,7 +34,7 @@ const LotIdFilter = ({ assetType, filters }) => { } }, [asteroidId, dispatchLotSelected, maxLots]); - const handleKeydown = useCallback((e) => { + const handleKeydown = useCallback(import.meta.url, (e) => { if (['Enter', 'Tab'].includes(e.key)) { handleById(); } diff --git a/src/components/filters/LotLeaseFilter.js b/src/components/filters/LotLeaseFilter.js index bb0e6950d..7ddaf2ba0 100644 --- a/src/components/filters/LotLeaseFilter.js +++ b/src/components/filters/LotLeaseFilter.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useState } from '~/lib/react-debug'; import useStore from '~/hooks/useStore'; import ColorPicker from '~/components/ColorPicker'; @@ -33,7 +33,7 @@ const LotLeaseFilter = ({ assetType, filters, onChange }) => { const [types, setTypes] = useState(initialValues); const [highlightColors, setHighlightColors] = useState({ ...(fieldHighlight?.colorMap || defaultColorMap) }); - useEffect(() => { + useEffect(import.meta.url, () => { const newTypes = ({ ...initialValues }); if (filters[fieldName] && filters[fieldName].length > 0) { const filterArr = filters[fieldName]; @@ -44,7 +44,7 @@ const LotLeaseFilter = ({ assetType, filters, onChange }) => { setTypes(newTypes); }, [filters[fieldName]]); - const onClick = useCallback((k) => (e) => { + const onClick = useCallback(import.meta.url, (k) => (e) => { e.stopPropagation(); onChange({ [fieldName]: k }); }, [onChange]); diff --git a/src/components/filters/LotOccupiedFilter.js b/src/components/filters/LotOccupiedFilter.js index 0e8929376..8c478c321 100644 --- a/src/components/filters/LotOccupiedFilter.js +++ b/src/components/filters/LotOccupiedFilter.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useState } from '~/lib/react-debug'; import useStore from '~/hooks/useStore'; import ColorPicker from '~/components/ColorPicker'; @@ -35,7 +35,7 @@ const LotOccupiedFilter = ({ assetType, filters, onChange }) => { const [types, setTypes] = useState(initialValues); const [highlightColors, setHighlightColors] = useState({ ...(fieldHighlight?.colorMap || defaultColorMap) }); - useEffect(() => { + useEffect(import.meta.url, () => { const newTypes = ({ ...initialValues }); if (filters[fieldName] && filters[fieldName].length > 0) { const filterArr = filters[fieldName]; @@ -46,7 +46,7 @@ const LotOccupiedFilter = ({ assetType, filters, onChange }) => { setTypes(newTypes); }, [filters[fieldName]]); - const onClick = useCallback((k) => (e) => { + const onClick = useCallback(import.meta.url, (k) => (e) => { e.stopPropagation(); onChange({ [fieldName]: k }); }, [onChange]); diff --git a/src/components/filters/OwnershipFilter.js b/src/components/filters/OwnershipFilter.js index 20b132cb6..8cc36bd9a 100644 --- a/src/components/filters/OwnershipFilter.js +++ b/src/components/filters/OwnershipFilter.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { Address } from '@influenceth/sdk'; import useSession from '~/hooks/useSession'; @@ -43,7 +43,7 @@ const OwnershipFilter = ({ assetType, filters, onChange }) => { const addressInput = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { const newTypes = { ...initialValues }; if (['unowned', 'owned'].includes(filters[fieldName])) { newTypes[filters[fieldName]] = true; @@ -68,7 +68,7 @@ const OwnershipFilter = ({ assetType, filters, onChange }) => { setTypes(newTypes); }, [filters[fieldName]]); - const onClick = useCallback((k) => (e) => { + const onClick = useCallback(import.meta.url, (k) => (e) => { e.stopPropagation(); let value = k; if (k === 'ownedByMe' && accountAddress && Address.toStandard(accountAddress)) { @@ -91,7 +91,7 @@ const OwnershipFilter = ({ assetType, filters, onChange }) => { onChange({ [fieldName]: value }); }, [accountAddress, onChange, ownedByAddress]); - const handleEvent = useCallback((e) => { + const handleEvent = useCallback(import.meta.url, (e) => { if (e.type === 'blur' || e.key === 'Enter' || e.key === 'Tab') { let validatedValue = e.currentTarget.value && e.currentTarget.value !== '0' && Address.toStandard(e.currentTarget.value); if (validatedValue) { @@ -108,11 +108,11 @@ const OwnershipFilter = ({ assetType, filters, onChange }) => { } }, [onChange, types]); - useEffect(() => { + useEffect(import.meta.url, () => { if (addressInput.current) addressInput.current.value = ownedByAddress; }, [ownedByAddress]); - const highlightMetadata = useMemo(() => ({ myAddress: accountAddress, address: ownedByAddress }), [accountAddress, ownedByAddress]); + const highlightMetadata = useMemo(import.meta.url, () => ({ myAddress: accountAddress, address: ownedByAddress }), [accountAddress, ownedByAddress]); return ( { const highlight = useStore(s => s.assetSearch[assetType].highlight); const fieldHighlight = highlight && highlight.field === highlightFieldName; - const looseCleansingMax = useMemo(() => 10 ** Math.ceil(Math.log10(rangeLimits.max)) - step, []); + const looseCleansingMax = useMemo(import.meta.url, () => 10 ** Math.ceil(Math.log10(rangeLimits.max)) - step, []); - const toDisplayFormat = useCallback((x) => displayFormatter ? displayFormatter(x) : x, [displayFormatter]); - const toSearchFormat = useCallback((x) => searchFormatter ? searchFormatter(x) : x, [searchFormatter]); + const toDisplayFormat = useCallback(import.meta.url, (x) => displayFormatter ? displayFormatter(x) : x, [displayFormatter]); + const toSearchFormat = useCallback(import.meta.url, (x) => searchFormatter ? searchFormatter(x) : x, [searchFormatter]); const [ focus, setFocus ] = useState(); const [ valueMin, setValueMin ] = useState(initialValues.min); @@ -41,7 +41,7 @@ const RangeFilter = ({ const [ colorFrom, setColorFrom ] = useState(highlightColorMinMax?.min); const [ colorTo, setColorTo ] = useState(highlightColorMinMax?.max); - const handleRangeChange = useCallback((k) => (e) => { + const handleRangeChange = useCallback(import.meta.url, (k) => (e) => { let cleansedValue = e.currentTarget.value.toString().length > 0 ? Math.max(rangeLimits.min, Math.min(e.currentTarget.value, rangeLimits.max)) : ''; @@ -69,21 +69,21 @@ const RangeFilter = ({ } }, [filters, onChange, toSearchFormat]); - const handleFocusChange = useCallback((k) => (e) => { + const handleFocusChange = useCallback(import.meta.url, (k) => (e) => { setFocus(e.type === 'focus' ? k : null); }, []); - useEffect(() => { + useEffect(import.meta.url, () => { if (focus !== fieldNames.min) setValueMin(toDisplayFormat(filters[fieldNames.min]) || initialValues.min); }, [filters && filters[fieldNames.min], focus, toDisplayFormat]); - useEffect(() => { + useEffect(import.meta.url, () => { if (focus !== fieldNames.max) setValueMax(toDisplayFormat(filters[fieldNames.max]) || initialValues.max); }, [filters && filters[fieldNames.max], focus, toDisplayFormat]); - const highlightColorRange = useMemo(() => ({ + const highlightColorRange = useMemo(import.meta.url, () => ({ min: toSearchFormat(valueMin || rangeLimits.min), max: toSearchFormat(valueMax || rangeLimits.max), from: colorFrom, diff --git a/src/components/filters/SurfaceAreaFilter.js b/src/components/filters/SurfaceAreaFilter.js index dae0ff083..730600d56 100644 --- a/src/components/filters/SurfaceAreaFilter.js +++ b/src/components/filters/SurfaceAreaFilter.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo } from 'react'; +import { useCallback, useEffect, useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid, Building, Crewmate, Permission, Product } from '@influenceth/sdk'; @@ -55,7 +55,7 @@ const config = [ const SurfaceAreaFilter = (filterProps) => { const { data: priceConstants } = usePriceConstants(); - const onClick = useCallback(({ min, max }) => () => { + const onClick = useCallback(import.meta.url, ({ min, max }) => () => { const { fieldNames, onChange, searchFormatter } = filterProps; onChange({ [fieldNames.min]: searchFormatter ? searchFormatter(min) : min, @@ -63,11 +63,11 @@ const SurfaceAreaFilter = (filterProps) => { }); }, [filterProps]); - const surfaceAreaFieldNote = useCallback((value) => { + const surfaceAreaFieldNote = useCallback(import.meta.url, (value) => { return priceConstants && ; }, [priceConstants]); - const isActive = useCallback(({ min, max }) => { + const isActive = useCallback(import.meta.url, ({ min, max }) => { const { filters, fieldNames } = filterProps; return (filters[fieldNames.min] === min && filters[fieldNames.max] === max); }, [filterProps]); diff --git a/src/components/filters/TextFilter.js b/src/components/filters/TextFilter.js index a5c35c073..3c3bb17db 100644 --- a/src/components/filters/TextFilter.js +++ b/src/components/filters/TextFilter.js @@ -1,14 +1,14 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { InputBlock, SearchMenu } from './components'; import UncontrolledTextInput from '~/components/TextInputUncontrolled'; const TextFilter = ({ assetType, fieldName, filters, isId, onChange, placeholder, title }) => { - const handleChange = useCallback((e) => { + const handleChange = useCallback(import.meta.url, (e) => { onChange({ [fieldName]: e.currentTarget.value }); }, [onChange]); - const extraProps = useMemo(() => isId ? { step: 1, min: 1, type: "number" } : {}, [isId]); + const extraProps = useMemo(import.meta.url, () => isId ? { step: 1, min: 1, type: "number" } : {}, [isId]); return ( s.dispatchHighlightUpdated(assetType)); const isAssetSearchFilterMatchingDefault = useStore(s => s.isAssetSearchFilterMatchingDefault); - const fieldHighlight = useMemo(() => highlight && highlight.field === highlightFieldName, [highlight, highlightFieldName]); + const fieldHighlight = useMemo(import.meta.url, () => highlight && highlight.field === highlightFieldName, [highlight, highlightFieldName]); - const filterIsOn = useMemo(() => { + const filterIsOn = useMemo(import.meta.url, () => { return !isAssetSearchFilterMatchingDefault(assetType, fieldName); }, [assetType, fieldName, filters[fieldName]]); - const toggleHighlight = useCallback((e) => { + const toggleHighlight = useCallback(import.meta.url, (e) => { e.stopPropagation(); if (fieldHighlight) { updateHighlight(); @@ -149,12 +149,12 @@ export const SearchMenu = ({ } }, [highlightFieldName, fieldHighlight, highlightColorMap, highlightColorRange, highlightMetadata]); - const resetFilter = useCallback((e) => { + const resetFilter = useCallback(import.meta.url, (e) => { e.stopPropagation(); dispatchFilterReset(assetType, fieldName); }, [assetType, dispatchFilterReset, fieldName]); - useEffect(() => { + useEffect(import.meta.url, () => { if (fieldHighlight) { if (highlightColorMap) { updateHighlight({ field: highlightFieldName, colorMap: highlightColorMap, ...(highlightMetadata || {}) }); diff --git a/src/components/porkchop/SolutionLabels.js b/src/components/porkchop/SolutionLabels.js index c310ef3bf..cb83556bf 100644 --- a/src/components/porkchop/SolutionLabels.js +++ b/src/components/porkchop/SolutionLabels.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Crew, Inventory, Ship, Time } from '@influenceth/sdk'; @@ -273,7 +273,7 @@ const SolutionLabels = ({ center, emode, lastFedAt, mousePos, shipParams }) => { invalid: insufficientPropellant, usedPropellant, tof - } = useMemo(() => { + } = useMemo(import.meta.url, () => { if (!travelSolution) return {}; return { @@ -285,7 +285,7 @@ const SolutionLabels = ({ center, emode, lastFedAt, mousePos, shipParams }) => { } }, [coarseTime, travelSolution]); // TODO: coarseTime dependency? - const [currentFood, usedFood] = useMemo(() => { + const [currentFood, usedFood] = useMemo(import.meta.url, () => { if (emode || !lastFedAt || !travelSolution?.arrivalTime) return [100, 100]; const currentFood = Math.round(100 * Crew.getCurrentFoodRatio((coarseTime - lastFedAt) * 86400, crew?._foodBonuses?.consumption)); const arrivalFood = Math.round(100 * Crew.getCurrentFoodRatio((travelSolution?.arrivalTime - lastFedAt) * 86400, crew?._foodBonuses?.consumption)); @@ -296,7 +296,7 @@ const SolutionLabels = ({ center, emode, lastFedAt, mousePos, shipParams }) => { }, [coarseTime, crew?._foodBonuses?.consumption, emode, lastFedAt, travelSolution?.arrivalTime]); // only report the >100% values if they are within the ship/crew's capabilities - const [maxReportableFood, maxReportablePropellant] = useMemo(() => { + const [maxReportableFood, maxReportablePropellant] = useMemo(import.meta.url, () => { if (!shipParams || !travelSolution) return [100, 100]; const shipConfig = Ship.TYPES[shipParams.Ship.shipType]; const propInv = shipParams.Inventories.find((i) => i.slot === shipConfig.propellantSlot); diff --git a/src/contexts/ActionItemContext.js b/src/contexts/ActionItemContext.js index 9fc706467..5dd23b6aa 100644 --- a/src/contexts/ActionItemContext.js +++ b/src/contexts/ActionItemContext.js @@ -1,4 +1,4 @@ -import React, { useEffect, useMemo, useState } from 'react'; +import React, { useEffect, useMemo, useState } from '~/lib/react-debug'; import { useQuery, useQueryClient } from 'react-query'; import { Building, Permission } from '@influenceth/sdk'; import cloneDeep from 'lodash/cloneDeep'; @@ -72,7 +72,7 @@ export function ActionItemProvider({ children }) { ); const { data: crewBuildings, isLoading: plannedBuildingsLoading, dataUpdatedAt: plansUpdatedAt } = useCrewBuildings(); - const plannedBuildings = useMemo(() => { + const plannedBuildings = useMemo(import.meta.url, () => { return crewBuildings ? (crewBuildings || []).filter((a) => a.Building?.status === Building.CONSTRUCTION_STATUSES.PLANNED) : undefined; @@ -89,7 +89,7 @@ export function ActionItemProvider({ children }) { const [agreementItems, setAgreementItems] = useState([]); const [plannedItems, setPlannedItems] = useState([]); - const randomEventItems = useMemo(() => { + const randomEventItems = useMemo(import.meta.url, () => { if (crew?._actionTypeTriggered) { if (!(pendingTransactions || []).find((tx) => tx.key === 'ResolveRandomEvent')) { return [crew?._actionTypeTriggered]; @@ -98,7 +98,7 @@ export function ActionItemProvider({ children }) { return []; }, [crew?._actionTypeTriggered, pendingTransactions]); - useEffect(() => { + useEffect(import.meta.url, () => { (actionItems || []) // find all events that are lease-per-process events... return the agreements that match @@ -133,7 +133,7 @@ export function ActionItemProvider({ children }) { }); }, [actionItems, crewAgreements, perProcessLeases]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!blockTime) return; const sequencedItems = (actionItems || []) @@ -225,7 +225,7 @@ export function ActionItemProvider({ children }) { ); }, [actionItems, busyActivity, crew, crew?._ready, crewAgreements, plannedBuildings, blockTime, itemsUpdatedAt, plansUpdatedAt]); - const allVisibleItems = useMemo(() => { + const allVisibleItems = useMemo(import.meta.url, () => { if (!authenticated) return []; // return the readyItems whose "finishing transaction" is not already pending @@ -295,7 +295,7 @@ export function ActionItemProvider({ children }) { // if there is data for all types (i.e. we know loaded successfully), clean out all // hidden keys that no longer exist to minimize long-term state bloat - useEffect(() => { + useEffect(import.meta.url, () => { if (allVisibleItems?.length > 0 && actionItems?.length > 0 && crewAgreements?.length > 0 && plannedBuildings?.length > 0) { hiddenActionItems.forEach((key) => { if (!allVisibleItems.find((i) => i.uniqueKey === key)) { @@ -309,7 +309,7 @@ export function ActionItemProvider({ children }) { // for not yet ready to finish, set new timers based on time remaining // without memoizing, triggers as if new value on every syncedTime update - const contextValue = useMemo(() => ({ + const contextValue = useMemo(import.meta.url, () => ({ allVisibleItems, pendingTransactions, failedTransactions, @@ -350,7 +350,7 @@ export function ActionItemProvider({ children }) { // const { events } = useEvents(); // const [readyTally, setReadyTally] = useState(0); - // const actionItemz = useMemo(() => { + // const actionItemz = useMemo(import.meta.url, () => { // if (!events) return; // const openItems = []; @@ -392,7 +392,7 @@ export function ActionItemProvider({ children }) { // // TODO: this timer should technically be in service worker so can use push notifications if window is not focused // // only need to watch one timer because will re-fetch all actionItemz when it passes // const nextTimer = useRef(); - // useEffect(() => { + // useEffect(import.meta.url, () => { // actionItemz.forEach((ai) => { // if (!ai.isReady && !nextTimer.current) { // const readyIn = (ai.returnValues.finishTime - syncedTime) + 5; diff --git a/src/contexts/ActivitiesContext.js b/src/contexts/ActivitiesContext.js index b3f3690d1..3eba47ad2 100644 --- a/src/contexts/ActivitiesContext.js +++ b/src/contexts/ActivitiesContext.js @@ -1,4 +1,4 @@ -import { createContext, useCallback, useEffect, useRef, useState } from 'react'; +import { createContext, useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; import { useQueryClient } from 'react-query'; import { isEqual, uniq } from 'lodash'; import { Entity } from '@influenceth/sdk'; @@ -62,13 +62,13 @@ export function ActivitiesProvider({ children }) { const pendingBatchActivities = useRef([]); const pendingTimeout = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (simulation) { setActivities(simulation?.activities || []); } }, [simulation?.activities]) - // useEffect(() => { + // useEffect(import.meta.url, () => { // const onKeydown = (e) => { // if (e.shiftKey && e.which === 32) { // const events = [ @@ -109,7 +109,7 @@ export function ActivitiesProvider({ children }) { // }, []); const debugInvalidation = false; - const handleActivities = useCallback((newActivities, skipInvalidations) => { + const handleActivities = useCallback(import.meta.url, (newActivities, skipInvalidations) => { // return; // prep activities, then handle @@ -298,7 +298,7 @@ export function ActivitiesProvider({ children }) { }, [crew, getActivityConfig, pendingTransactions, refreshReadyAt]); // try to process WS activities grouped by block - const processPendingWSBatch = useCallback(async () => { + const processPendingWSBatch = useCallback(import.meta.url, async () => { if (pendingTimeout.current) { clearTimeout(pendingTimeout.current); pendingTimeout.current = null; @@ -315,7 +315,7 @@ export function ActivitiesProvider({ children }) { const [disconnected, setDisconnected] = useState(); const [stale, setStale] = useState(); - const onWSConnection = useCallback((isOpen) => { + const onWSConnection = useCallback(import.meta.url, (isOpen) => { if (isOpen && stale) { queryClient.resetQueries(); setStale(false); @@ -323,7 +323,7 @@ export function ActivitiesProvider({ children }) { setDisconnected(!isOpen); }, [stale]); - useEffect(() => { + useEffect(import.meta.url, () => { // if disconnected for more than X seconds, set state to `stale`. this will refetch // everything once the connection is restored. any value of X is technically imperfect // here, but it also seems excessive to reset state on any microsecond disconnection @@ -334,7 +334,7 @@ export function ActivitiesProvider({ children }) { } }, [disconnected]); - const onWSMessage = useCallback((message) => { + const onWSMessage = useCallback(import.meta.url, (message) => { if (process.env.NODE_ENV !== 'production') console.log('onWSMessage (activities)', message); const { type, body } = message; if (ignoreEventTypes.includes(type)) return; @@ -347,9 +347,7 @@ export function ActivitiesProvider({ children }) { else if (blockNumber > 0 && body.previous > 0 && body.previous > blockNumber) { console.log(`Missed a block! (new: ${body.blockNumber}, server prev: ${body.previous}, local prev: ${blockNumber})`); - if (process.env.NODE_ENV !== 'production') { - window.alert('Missed a block!'); - } + // if (process.env.NODE_ENV !== 'production') window.alert('Missed a block!'); setIsBlockMissing(true); } @@ -368,7 +366,7 @@ export function ActivitiesProvider({ children }) { }, [blockNumber, blockNumberIsProvisional, processPendingWSBatch]); const isFirstLoad = useRef(true); // (i.e. this is not a crew switch) - useEffect(() => { + useEffect(import.meta.url, () => { if (!wsReady) return; if (!token) return; diff --git a/src/contexts/ChainTransactionContext.js b/src/contexts/ChainTransactionContext.js index 2347e4fad..b39ee00d9 100644 --- a/src/contexts/ChainTransactionContext.js +++ b/src/contexts/ChainTransactionContext.js @@ -1,4 +1,4 @@ -import { createContext, useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { createContext, useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { Address, Asteroid, Entity, Order, Permission, System } from '@influenceth/sdk'; import { isEqual, get } from 'lodash'; import { hash, num, shortString, uint256 } from 'starknet'; @@ -517,7 +517,7 @@ export function ChainTransactionProvider({ children }) { const [nonce, setNonce] = useState(); // Sets the nonce initially to allow for some local management - useEffect(() => { + useEffect(import.meta.url, () => { const retrieveNonce = async () => { const currentNonce = await provider.getNonceForAddress(accountAddress); setNonce(safeBigInt(currentNonce)); @@ -527,10 +527,10 @@ export function ChainTransactionProvider({ children }) { }, [accountAddress, gameplay.useSessions, isDeployed, nonce, provider, simulationEnabled, starknetSession]); // Temporary logging for nonces - useEffect(() => console.log('NONCE', nonce || null), [nonce]); + useEffect(import.meta.url, () => console.log('NONCE', nonce || null), [nonce]); // autoresolve when actionType is set but actionType was not actually triggered by actionRound - const prependEventAutoresolve = useMemo( + const prependEventAutoresolve = useMemo(import.meta.url, // TODO: can we check with a read call that this doesn't predict failure before prepending it // (i.e. in case local crew value is stale)? might be more reliable anyway // ... or we could also refetch crew again first @@ -541,7 +541,7 @@ export function ChainTransactionProvider({ children }) { [blockNumber, crew?.Crew?.actionType, crew?.Crew?.actionRound, crew?._actionTypeTriggered] ); - const executeWithAccount = useCallback(async (calls) => { + const executeWithAccount = useCallback(import.meta.url, async (calls) => { // Format calls for proper stringification const formattedCalls = calls.map((call) => { return { ...call, calldata: call.calldata.map(a => num.toHex(a)) }; @@ -635,7 +635,7 @@ export function ChainTransactionProvider({ children }) { walletAccount ]); - const contracts = useMemo(() => { + const contracts = useMemo(import.meta.url, () => { if (!!walletAccount) { // include all default systems + any virtuals included in customConfigs @@ -903,7 +903,7 @@ export function ChainTransactionProvider({ children }) { usdcPerEth ]); - const getTxEvent = useCallback((txHash) => { + const getTxEvent = useCallback(import.meta.url, (txHash) => { const txHashBInt = safeBigInt(txHash); return (activities || []).find((a) => a.event?.transactionHash && safeBigInt(a.event?.transactionHash) === txHashBInt)?.event; }, [activities?.length]); @@ -911,14 +911,14 @@ export function ChainTransactionProvider({ children }) { const transactionWaiters = useRef([]); // on logout, clear pending (and failed) transactions - useEffect(() => { + useEffect(import.meta.url, () => { if (!authenticated) dispatchClearTransactionHistory(); }, [authenticated, dispatchClearTransactionHistory]); // handle newlyFailedTx in state + effect flow b/c doing directly in catch uses old values // of state (i.e. from when the callback was created) const [newlyFailedTx, setNewlyFailedTx] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { if (newlyFailedTx) { const { err, key, vars, txHash } = newlyFailedTx; @@ -949,7 +949,7 @@ export function ChainTransactionProvider({ children }) { // on initial load, set provider.waitForTransaction for any pendingTransactions // so that we can throw any extension-related or timeout errors needed - useEffect(() => { + useEffect(import.meta.url, () => { if (provider && contracts && pendingTransactions?.length) { pendingTransactions.forEach(({ key, vars, txHash }) => { // (sanity check) this should not be possible since pendingTransaction should not be created @@ -988,7 +988,7 @@ export function ChainTransactionProvider({ children }) { } }, [contracts, pendingTransactions]); // eslint-disable-line react-hooks/exhaustive-deps - useEffect(() => { + useEffect(import.meta.url, () => { // console.log('trigger activities effect', activities, pendingTransactions); if (contracts && pendingTransactions?.length) { pendingTransactions.forEach((tx) => { @@ -1008,7 +1008,7 @@ export function ChainTransactionProvider({ children }) { // on every new block, check for reverted tx's // TODO: parse revert_reason to be more readible // TODO: time out eventually? - useEffect(() => { + useEffect(import.meta.url, () => { if (contracts && pendingTransactions?.length) { pendingTransactions.filter((tx) => !tx.txEvent).forEach((tx) => { // if it's been X+ seconds since submitted, check if it was reverted @@ -1036,7 +1036,7 @@ export function ChainTransactionProvider({ children }) { } }, [blockNumber]); - const isAccountLocked = useCallback(async () => { + const isAccountLocked = useCallback(import.meta.url, async () => { // Check that the account isn't locked, and prompt to unlock if it is try { await walletAccount.walletProvider.request({ @@ -1051,7 +1051,7 @@ export function ChainTransactionProvider({ children }) { }, [walletAccount]); - const handleExecutionExeption = useCallback((e, executeCalls, txDetails = {}) => { + const handleExecutionExeption = useCallback(import.meta.url, (e, executeCalls, txDetails = {}) => { if ((e.message || '').toLowerCase() === 'account not deployed') { createAlert({ type: 'DeployAccount', @@ -1112,7 +1112,7 @@ export function ChainTransactionProvider({ children }) { }, [accountAddress, createAlert, dispatchFailedTransaction, logout]); // Allows for multiple explicit / manual calls to be executed in a single transaction - const executeCalls = useCallback(async (calls) => { + const executeCalls = useCallback(import.meta.url, async (calls) => { if (!walletAccount) { createAlert({ type: 'GenericAlert', @@ -1166,7 +1166,7 @@ export function ChainTransactionProvider({ children }) { }, [createAlert, executeWithAccount, handleExecutionExeption, isAccountLocked, isDeployed, upgradeInsecureSession, walletAccount]) // Primary execute method for system calls (requires name of system, etc.) - const executeSystem = useCallback(async (key, vars, meta = {}) => { + const executeSystem = useCallback(import.meta.url, async (key, vars, meta = {}) => { if (simulationEnabled) { const uuid = `0x${String(performance.now()).replace('.', '')}`; dispatchPendingTransaction({ @@ -1227,7 +1227,7 @@ export function ChainTransactionProvider({ children }) { setPromptingTransaction(false); }, [blockTime, contracts, handleExecutionExeption, walletAccount, simulationEnabled]); // eslint-disable-line react-hooks/exhaustive-deps - const getPendingTx = useCallback((key, vars) => { + const getPendingTx = useCallback(import.meta.url, (key, vars) => { // simulation will only ever have one concurrent? if (simulationEnabled) { return pendingTransactions.find((tx) => tx.key === key); @@ -1250,7 +1250,7 @@ export function ChainTransactionProvider({ children }) { return null; }, [contracts, pendingTransactions]); - const getStatus = useCallback((key, vars) => { + const getStatus = useCallback(import.meta.url, (key, vars) => { return getPendingTx(key, vars) ? 'pending' : 'ready'; }, [getPendingTx]); diff --git a/src/contexts/CoachmarkContext.js b/src/contexts/CoachmarkContext.js index 53678cdee..872d1d802 100644 --- a/src/contexts/CoachmarkContext.js +++ b/src/contexts/CoachmarkContext.js @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import React, { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import { createPortal } from 'react-dom'; import FullscreenAttention, { delay } from '~/components/FullscreenAttention'; @@ -52,7 +52,7 @@ const CoachmarkComponent = ({ refEl }) => { // give the ref element time to "animate in" in case // that is something it does - useEffect(() => { + useEffect(import.meta.url, () => { const to = setTimeout(() => { const boundingRect = refEl && refEl.getBoundingClientRect(); setRect(boundingRect); @@ -70,7 +70,7 @@ const CoachmarkComponent = ({ refEl }) => { }, delay); // update the position as needed if rect or screen changes - const position = useMemo(() => { + const position = useMemo(import.meta.url, () => { if (!rect) return null; return { top: rect.top, @@ -100,11 +100,11 @@ export function CoachmarkProvider({ children }) { const [disabled, setDisabled] = useState(true); const [refEls, setRefEls] = useState({}); - const activeCoachmarkKey = useMemo(() => { + const activeCoachmarkKey = useMemo(import.meta.url, () => { return Object.keys(coachmarks).find((k) => !!coachmarks[k] && !!refEls[k]); }, [coachmarks, refEls]); - const register = useCallback((label) => (r) => { + const register = useCallback(import.meta.url, (label) => (r) => { setRefEls((prev) => { let updated = { ...prev }; if (r) updated[label] = r; @@ -114,7 +114,7 @@ export function CoachmarkProvider({ children }) { }, []); // delay coachmark display on new tutorial step (to encourage reading) - useEffect(() => { + useEffect(import.meta.url, () => { setDisabled(true); const to = setTimeout(() => { setDisabled(false); @@ -122,7 +122,7 @@ export function CoachmarkProvider({ children }) { return () => clearTimeout(to); }, [simulation?.step]) - const contextValue = useMemo(() => ({ + const contextValue = useMemo(import.meta.url, () => ({ activeCoachmarkKey, register }), [activeCoachmarkKey, register]); diff --git a/src/contexts/CrewContext.js b/src/contexts/CrewContext.js index 10a11dd2d..ce01b30a5 100644 --- a/src/contexts/CrewContext.js +++ b/src/contexts/CrewContext.js @@ -1,4 +1,4 @@ -import { createContext, useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { createContext, useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { useQuery, useQueryClient } from 'react-query'; import { Crewmate, Entity, Inventory, Permission, Ship, System } from '@influenceth/sdk'; @@ -35,17 +35,17 @@ export function CrewProvider({ children }) { const dispatchCrewSelected = useStore(s => s.dispatchCrewSelected); const { data: constants, isLoading: constantsLoading } = useConstants(['CREW_SCHEDULE_BUFFER','TIME_ACCELERATION']); - const [CREW_SCHEDULE_BUFFER, TIME_ACCELERATION] = useMemo(() => { + const [CREW_SCHEDULE_BUFFER, TIME_ACCELERATION] = useMemo(import.meta.url, () => { if (!constants) return []; return [constants.CREW_SCHEDULE_BUFFER, constants.TIME_ACCELERATION]; }, [constants]); - const ownedCrewsQueryKey = useMemo( + const ownedCrewsQueryKey = useMemo(import.meta.url, () => entitiesCacheKey(Entity.IDS.CREW, { owner: accountAddress }), [accountAddress] ); - const simulationCrew = useMemo(() => { + const simulationCrew = useMemo(import.meta.url, () => { if (!simulationState) return null; // TODO: put in SIMULATION_CONFIG? @@ -102,9 +102,9 @@ export function CrewProvider({ children }) { () => api.getOwnedCrews(accountAddress), { enabled: !!token } ); - const rawCrews = useMemo(() => simulationCrew ? [simulationCrew] : realRawCrews, [simulationCrew, rawCrewsUpdatedAt]); + const rawCrews = useMemo(import.meta.url, () => simulationCrew ? [simulationCrew] : realRawCrews, [simulationCrew, rawCrewsUpdatedAt]); - const combinedCrewRoster = useMemo( + const combinedCrewRoster = useMemo(import.meta.url, () => (rawCrews || []).reduce((acc, c) => [...acc, ...c.Crew.roster], []), [rawCrews, rawCrewsUpdatedAt] ); @@ -120,7 +120,7 @@ export function CrewProvider({ children }) { { enabled: !!token } ); - const [adalianRecruits, arvadianRecruits] = useMemo(() => { + const [adalianRecruits, arvadianRecruits] = useMemo(import.meta.url, () => { if (!myOwnedCrewmates) return [[], []]; const allRecruits = myOwnedCrewmates.filter((c) => !c.Control?.controller?.id); return [ @@ -133,7 +133,7 @@ export function CrewProvider({ children }) { ]; }, [myOwnedCrewmates]); - const crewmateMap = useMemo(() => { + const crewmateMap = useMemo(import.meta.url, () => { if (!crewsLoading && !crewmatesLoading && !myOwnedCrewmatesLoading) { const map = {}; (myCrewCrewmates || []).forEach((crewmate) => { @@ -164,10 +164,10 @@ export function CrewProvider({ children }) { // NOTE: this covers all queries' loading states because crewmateMap is // null while any of those are true - const crewsAndCrewmatesReady = useMemo(() => !!crewmateMap && TIME_ACCELERATION, [crewmateMap, TIME_ACCELERATION]); + const crewsAndCrewmatesReady = useMemo(import.meta.url, () => !!crewmateMap && TIME_ACCELERATION, [crewmateMap, TIME_ACCELERATION]); // update crews' _ready value - const crews = useMemo(() => { + const crews = useMemo(import.meta.url, () => { if (!crewsAndCrewmatesReady || !rawCrews) return []; return rawCrews.map((c) => { if (!!crewmateMap) { @@ -208,7 +208,7 @@ export function CrewProvider({ children }) { }) }, [blockTime, crewmateMap, crewsAndCrewmatesReady, CREW_SCHEDULE_BUFFER, rawCrews, rawCrewsUpdatedAt]); - const selectedCrew = useMemo(() => { + const selectedCrew = useMemo(import.meta.url, () => { if (crews && crews.length > 0) { if (selectedCrewId) { const previouslySelected = crews.find((crew) => crew.id === selectedCrewId); @@ -223,8 +223,8 @@ export function CrewProvider({ children }) { const { data: selectedCrewLocation } = useEntity(selectedCrew ? { ...selectedCrew.Location.location } : undefined); const [actionTypeTriggered, setActionTypeTriggered] = useState(false); - useEffect(() => setActionTypeTriggered(false), [selectedCrew?.id]); // recheck random event status on crew change - useEffect(() => { + useEffect(import.meta.url, () => setActionTypeTriggered(false), [selectedCrew?.id]); // recheck random event status on crew change + useEffect(import.meta.url, () => { if (!actionTypeTriggered) { // TODO: actionRound tmp fix if (selectedCrew?.Crew?.actionType && selectedCrew.Crew.actionRound) {// && (selectedCrew.Crew.actionRound + RandomEvent.MIN_ROUNDS) <= blockNumber) { @@ -268,7 +268,7 @@ export function CrewProvider({ children }) { }, [actionTypeTriggered, selectedCrew?.Crew?.actionType, selectedCrew?.Crew?.actionRound, provider]); // add final data to selected crew - const finalSelectedCrew = useMemo(() => { + const finalSelectedCrew = useMemo(import.meta.url, () => { if (!selectedCrew) return null; return { ...selectedCrew, @@ -282,14 +282,14 @@ export function CrewProvider({ children }) { }, [actionTypeTriggered, selectedCrew, selectedCrew?._ready, selectedCrewLocation, CREW_SCHEDULE_BUFFER, TIME_ACCELERATION]); // return all pending transactions that are specific to this crew AND those that are not specific to any crew - const pendingTransactions = useMemo(() => { + const pendingTransactions = useMemo(import.meta.url, () => { if (!selectedCrew?.id) { return (allPendingTransactions || []).filter((tx) => !tx.vars?.caller_crew?.id); } return (allPendingTransactions || []).filter((tx) => !tx.vars?.caller_crew?.id || (tx.vars.caller_crew.id === selectedCrew.id)); }, [allPendingTransactions, selectedCrew?.id]) - const refreshReadyAt = useCallback(async () => { + const refreshReadyAt = useCallback(import.meta.url, async () => { const updatedCrew = await api.getEntityById({ label: Entity.IDS.CREW, id: selectedCrewId, components: ['Crew'] }); if (updatedCrew) { queryClient.setQueryData(ownedCrewsQueryKey, (prevRawCrews = []) => { @@ -314,18 +314,18 @@ export function CrewProvider({ children }) { }, [ownedCrewsQueryKey, selectedCrewId]); // make sure a default-selected crew makes it into state (if logged in) - useEffect(() => { + useEffect(import.meta.url, () => { if (authenticated && crewsAndCrewmatesReady && selectedCrew?.id !== selectedCrew) { dispatchCrewSelected(selectedCrew?.id || undefined); } }, [authenticated, crewsAndCrewmatesReady, selectedCrew]); - const captain = useMemo(() => { + const captain = useMemo(import.meta.url, () => { if (simulationState && !simulationState.crewmate) return null; return selectedCrew?._crewmates?.[0] || null; }, [crewmateMap, selectedCrew, simulationState]); - const crewCan = useCallback( + const crewCan = useCallback(import.meta.url, (permission, hydratedTarget) => (finalSelectedCrew && hydratedTarget) ? Permission.isPermitted(finalSelectedCrew, permission, hydratedTarget, blockTime) : false, @@ -333,7 +333,7 @@ export function CrewProvider({ children }) { ); const isBlurred = useRef(false); - const onBlur = useCallback(() => { + const onBlur = useCallback(import.meta.url, () => { isBlurred.current = true; }, []); @@ -347,7 +347,7 @@ export function CrewProvider({ children }) { // probably also want to reload // TODO: when first create crew, should probably reload all queries since they were not being updated // in the time before crew creation - const onFocus = useCallback(() => { + const onFocus = useCallback(import.meta.url, () => { if (isBlurred.current) { isBlurred.current = false; @@ -360,7 +360,7 @@ export function CrewProvider({ children }) { } }, [isBlockMissing]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!!finalSelectedCrew) { window.addEventListener('blur', onBlur); window.addEventListener('focus', onFocus); @@ -373,7 +373,7 @@ export function CrewProvider({ children }) { // handle game launch (on a timeout rather than blocktime) const [gameIsLaunched, setGameIsLaunched] = useState(openAccessJSTime < Date.now()); - useEffect(() => { + useEffect(import.meta.url, () => { const msUntilLaunch = openAccessJSTime - Date.now(); if (msUntilLaunch > 0) { setGameIsLaunched(false); diff --git a/src/contexts/DevToolContext.js b/src/contexts/DevToolContext.js index abca16ffe..c5eb677f5 100644 --- a/src/contexts/DevToolContext.js +++ b/src/contexts/DevToolContext.js @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import React, { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import useStore from '~/hooks/useStore'; @@ -37,7 +37,7 @@ export function DevToolProvider({ children }) { const [starStrength, setStarStrength] = useState(); // reset most overrides on change of asset type - useEffect(() => { + useEffect(import.meta.url, () => { setBackground(); setBackgroundOverrideName(); setBackgroundStrength(); @@ -64,7 +64,7 @@ export function DevToolProvider({ children }) { setTrackCamera(); }, [assetType]); - const contextValue = useMemo(() => ({ + const contextValue = useMemo(import.meta.url, () => ({ assetType, overrides: showDevTools ? { modelUrl, diff --git a/src/contexts/ScreensizeContext.js b/src/contexts/ScreensizeContext.js index a24063102..82a657f60 100644 --- a/src/contexts/ScreensizeContext.js +++ b/src/contexts/ScreensizeContext.js @@ -1,4 +1,4 @@ -import React, { useEffect, useMemo } from 'react'; +import React, { useEffect, useMemo } from '~/lib/react-debug'; import { useThrottle } from '@react-hook/throttle'; import theme from '~/theme'; @@ -9,7 +9,7 @@ export function ScreensizeProvider({ children }) { const [ height, setHeight ] = useThrottle(window.innerHeight, 30, true); const [ width, setWidth ] = useThrottle(window.innerWidth, 30, true); - useEffect(() => { + useEffect(import.meta.url, () => { const updateSize = () => { setHeight(window.innerHeight); setWidth(window.innerWidth); @@ -18,7 +18,7 @@ export function ScreensizeProvider({ children }) { return () => window.removeEventListener('resize', updateSize); }, []); - const contextValue = useMemo(() => ({ + const contextValue = useMemo(import.meta.url, () => ({ height, width, isMobile: width <= theme.breakpoints.mobile, diff --git a/src/contexts/SessionContext.js b/src/contexts/SessionContext.js index 8d06d9159..dd97be994 100644 --- a/src/contexts/SessionContext.js +++ b/src/contexts/SessionContext.js @@ -1,4 +1,4 @@ -import { createContext, useCallback, useEffect, useRef, useMemo, useState } from 'react'; +import { createContext, useCallback, useEffect, useRef, useMemo, useState } from '~/lib/react-debug'; import { useQueryClient } from 'react-query'; import { isExpired } from 'react-jwt'; import { num, RpcProvider, WalletAccount, shortString } from 'starknet'; @@ -84,8 +84,8 @@ export function SessionProvider({ children }) { const [isBlockMissing, setIsBlockMissing] = useState(false); const [error, setError] = useState(); - const authenticated = useMemo(() => status === STATUSES.AUTHENTICATED, [status]); - const provider = useMemo(() => { + const authenticated = useMemo(import.meta.url, () => status === STATUSES.AUTHENTICATED, [status]); + const provider = useMemo(import.meta.url, () => { let nodeUrl = process.env.REACT_APP_STARKNET_PROVIDER; if (process.env.REACT_APP_STARKNET_PROVIDER_BACKUP && Math.random() > 0.5) { @@ -96,7 +96,7 @@ export function SessionProvider({ children }) { }, []); // Login entry point, starts by connecting to wallet provider - const connect = useCallback(async (auto = false, enabledConnectors = { webWallet: true, argentX: true, braavos: true, argentMobile: true }) => { + const connect = useCallback(import.meta.url, async (auto = false, enabledConnectors = { webWallet: true, argentX: true, braavos: true, argentMobile: true }) => { if (currentSession?.walletId) { localStorage.setItem('starknetLastConnectedWallet', currentSession.walletId); auto = true; @@ -187,20 +187,20 @@ export function SessionProvider({ children }) { }, [currentSession, sessions]); // eslint-disable-line react-hooks/exhaustive-deps // Disconnect from the wallet provider and suspend session (don't fully logout) - const disconnect = useCallback(() => { + const disconnect = useCallback(import.meta.url, () => { dispatchSessionSuspended(); setStatus(STATUSES.DISCONNECTED); }, [dispatchSessionSuspended]); // End / delete session, disconnect wallet and forget last wallet provider (full reset) - const logout = useCallback(() => { + const logout = useCallback(import.meta.url, () => { dispatchSessionEnded(); setStatus(STATUSES.DISCONNECTED); if (window.starknet) starknetDisconnect({ clearLastWallet: true }); }, [ dispatchSessionEnded ]); // While connecting or connected, listen for network changes from extension - useEffect(() => { + useEffect(import.meta.url, () => { const onAccountsChanged = (e) => { const eventAccount = Address.toStandard(Array.isArray(e) ? e[0] : e); @@ -244,7 +244,7 @@ export function SessionProvider({ children }) { // Determines whether the wallet should use sessions based on user settings and wallet id // useSessions: (null = default, true, false) - const shouldUseSessionKeys = useCallback(async (skipSettingsCheck = false) => { + const shouldUseSessionKeys = useCallback(import.meta.url, async (skipSettingsCheck = false) => { const setting = skipSettingsCheck || gameplay.useSessions; // explicitly disabled @@ -270,7 +270,7 @@ export function SessionProvider({ children }) { }, [connectedAccount, gameplay.useSessions, provider]); // Checks the account contract do determine if it's deployed on-chain yet - const checkDeployed = useCallback(async () => { + const checkDeployed = useCallback(import.meta.url, async () => { try { await provider.getClassAt(connectedAccount); // if this throws, the contract is not deployed return true; @@ -281,7 +281,7 @@ export function SessionProvider({ children }) { }, [connectedAccount, provider]); // Authenticate with a signed message against the API and create a new session - const authenticate = useCallback(async ({ isUpgradeInsecure = false, isUpgradeSessionKey = false } = {}) => { + const authenticate = useCallback(import.meta.url, async ({ isUpgradeInsecure = false, isUpgradeSessionKey = false } = {}) => { const newSession = {}; // Check if the account contract has been deployed yet and should use sessions @@ -384,12 +384,12 @@ export function SessionProvider({ children }) { logout ]); - const upgradeInsecureSession = useCallback(() => { + const upgradeInsecureSession = useCallback(import.meta.url, () => { if (currentSession && !currentSession.isDeployed) return authenticate({ isUpgradeInsecure: true }); }, [authenticate, currentSession]); // Resumes a current session or starts a new one - const resumeOrAuthenticate = useCallback(async () => { + const resumeOrAuthenticate = useCallback(import.meta.url, async () => { // If somehow we've lost wallet connection, disconnect if (!connectedAccount || !walletAccount) { disconnect(); @@ -410,13 +410,13 @@ export function SessionProvider({ children }) { }, [authenticate, connectedAccount, walletAccount, sessions, disconnect, dispatchSessionStarted]); // Upgrades a current session to use a session key - const upgradeToSessionKey = useCallback(async () => { + const upgradeToSessionKey = useCallback(import.meta.url, async () => { if (currentSession?.isDeployed && !currentSession?.sessionRequest) { return authenticate({ isUpgradeSessionKey: true }); } }, [authenticate, currentSession, gameplay.useSessions]); - const createSessionAccount = useCallback(async () => { + const createSessionAccount = useCallback(import.meta.url, async () => { const offchainSessionAccount = await buildSessionAccount({ accountSessionSignature: currentSession.sessionSignature, sessionRequest: currentSession.sessionRequest, @@ -431,7 +431,7 @@ export function SessionProvider({ children }) { }, [currentSession, provider]); // Start a session with the Argent Web Wallet - useEffect(() => { + useEffect(import.meta.url, () => { if (!currentSession?.isDeployed) return; if (authenticated && gameplay.useSessions !== false && currentSession.sessionSignature) { createSessionAccount(); @@ -439,12 +439,12 @@ export function SessionProvider({ children }) { }, [authenticated, currentSession, gameplay.useSessions]); // End session and disconnect wallet if session expires - useEffect(() => { + useEffect(import.meta.url, () => { if (currentSession.token && isExpired(currentSession.token)) logout(); }, [currentSession, logout]); // Connect / auth flow manager - useEffect(() => { + useEffect(import.meta.url, () => { // console.log(Object.keys(STATUSES).find(key => STATUSES[key] === status)); if (status === STATUSES.DISCONNECTED) { if (currentSession?.walletId) { @@ -464,7 +464,7 @@ export function SessionProvider({ children }) { }, [currentSession, status]); // eslint-disable-line react-hooks/exhaustive-deps // Catch errors and display in an alert - useEffect(() => { + useEffect(import.meta.url, () => { if (error) { createAlert({ type: 'GenericAlert', @@ -479,7 +479,7 @@ export function SessionProvider({ children }) { }, [error, createAlert, logout]); const [isFeeAbstractionCompatible, setIsFeeAbstractionCompatible] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { if (currentSession?.isDeployed) { gasless.fetchAccountCompatibility( currentSession.accountAddress, @@ -493,7 +493,7 @@ export function SessionProvider({ children }) { } }, [currentSession.accountAddress, currentSession?.isDeployed]); - const payGasWithSwayIfPossible = useMemo(() => { + const payGasWithSwayIfPossible = useMemo(import.meta.url, () => { // check if we should use fee abstraction (is set to use sway or is set to default + using webwallet) if (gameplay.feeToken === 'SWAY' || (!gameplay.feeToken && currentSession?.walletId === 'argentWebWallet')) { return !!isFeeAbstractionCompatible; @@ -506,7 +506,7 @@ export function SessionProvider({ children }) { ]); // Retrieves an outside execution call and signs it - const getOutsideExecutionData = useCallback(async (calldata, gasTokenAddress, maxGasTokenAmount, canUseSessionKey) => { + const getOutsideExecutionData = useCallback(import.meta.url, async (calldata, gasTokenAddress, maxGasTokenAmount, canUseSessionKey) => { let typedData = await gasless.fetchBuildTypedData( currentSession.accountAddress, calldata, @@ -545,7 +545,7 @@ export function SessionProvider({ children }) { // Block management ------------------------------------------------------------------------------------------------- // If using devnet, put "create block" on a timer since otherwise, blocks will not be advancing in the background - useEffect(() => { + useEffect(import.meta.url, () => { if (process.env.REACT_APP_IS_DEVNET) { let blockInterval = setInterval(() => { api.createDevnetBlock(); }, 15e3); return () => { @@ -555,13 +555,13 @@ export function SessionProvider({ children }) { }, []); // Argent is slow to put together it's final "starknet" object, so we check explicitly for getBlock method - const canCheckBlock = useMemo(() => { + const canCheckBlock = useMemo(import.meta.url, () => { return status >= STATUSES.CONNECTED && !!provider?.getBlock; }, [provider?.getBlock, status]); // Initialize block number and block time const lastBlockNumberTime = useRef(0); - const initializeBlockData = useCallback(async () => { + const initializeBlockData = useCallback(import.meta.url, async () => { if (!canCheckBlock) return; try { const block = await provider.getBlock('pending'); @@ -590,10 +590,10 @@ export function SessionProvider({ children }) { console.error('failed to init block data', e) } }, [canCheckBlock, provider]); - useEffect(() => { initializeBlockData(); }, [initializeBlockData]); + useEffect(import.meta.url, () => { initializeBlockData(); }, [initializeBlockData]); const reattempts = useRef(); - const capturePendingBlockTimestampUpdate = useCallback(async () => { + const capturePendingBlockTimestampUpdate = useCallback(import.meta.url, async () => { if (!provider) return; reattempts.current++; @@ -616,7 +616,7 @@ export function SessionProvider({ children }) { // get pending block time on every new block // TODO: if no crew, then we won't receive websockets, and blockNumber will not get updated // (i.e. for logged out users) -- does that matter? - useEffect(() => { + useEffect(import.meta.url, () => { if (blockNumber > lastBlockNumberTime.current) { reattempts.current = 0; capturePendingBlockTimestampUpdate(); @@ -624,7 +624,7 @@ export function SessionProvider({ children }) { }, [blockNumber, capturePendingBlockTimestampUpdate]); // reset any cached, but time-dependent queries - useEffect(() => { + useEffect(import.meta.url, () => { [ [ 'orderList' ], [ 'inventoryOrders' ], @@ -636,12 +636,12 @@ export function SessionProvider({ children }) { }, [blockTime]); const [promptLogin, setPromptLogin] = useState(); - const login = useCallback(async () => { + const login = useCallback(import.meta.url, async () => { if ([STATUSES.AUTHENTICATING, STATUSES.AUTHENTICATED].includes(status)) return; setPromptLogin(true); }, [authenticated, connect]); - const handleLoginPrompt = useCallback((choice) => { + const handleLoginPrompt = useCallback(import.meta.url, (choice) => { setPromptLogin(false); if (choice === false) { connect(); // show all wallets diff --git a/src/contexts/SyncedTimeContext.js b/src/contexts/SyncedTimeContext.js index 8555d321c..9cac33d6a 100644 --- a/src/contexts/SyncedTimeContext.js +++ b/src/contexts/SyncedTimeContext.js @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from 'react'; +import React, { useEffect, useState } from '~/lib/react-debug'; const SyncedTimeContext = React.createContext(); @@ -7,7 +7,7 @@ const getSeconds = () => Math.floor(Date.now() / 1000); export function SyncedTimeProvider({ children }) { const [time, setTime] = useState(getSeconds()); - useEffect(() => { + useEffect(import.meta.url, () => { const int = setInterval(() => setTime(getSeconds()), 1000); return () => clearInterval(int); }, []); diff --git a/src/contexts/WebsocketContext.js b/src/contexts/WebsocketContext.js index af5e2709e..7aa2f29fd 100644 --- a/src/contexts/WebsocketContext.js +++ b/src/contexts/WebsocketContext.js @@ -1,4 +1,4 @@ -import { createContext, useCallback, useEffect, useRef, useState } from 'react'; +import { createContext, useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; import { io } from 'socket.io-client'; import useSession from '~/hooks/useSession'; @@ -19,7 +19,7 @@ export function WebsocketProvider({ children }) { const [wsReady, setWsReady] = useState(false); - const handleMessage = useCallback((messageLabel, payload) => { + const handleMessage = useCallback(import.meta.url, (messageLabel, payload) => { // for consistency, set type from messageLabel if not set if (messageLabel && !payload.type) payload.type = messageLabel; @@ -44,13 +44,13 @@ export function WebsocketProvider({ children }) { }); }, []); - const handleConnection = useCallback((isConnected) => { + const handleConnection = useCallback(import.meta.url, (isConnected) => { Object.values(connectionHandlers.current).forEach((callback) => callback(isConnected)); }, []); // NOTE: this is currently limited to one callback registered per room b/c that's // all we need, but it could always be switched to an array of listeners if needed - const registerMessageHandler = useCallback((callback, room = null) => { + const registerMessageHandler = useCallback(import.meta.url, (callback, room = null) => { if (!socket.current) return; const regId = wsUuid++; @@ -68,7 +68,7 @@ export function WebsocketProvider({ children }) { return regId; }, []); - const unregisterMessageHandler = useCallback((regId) => { + const unregisterMessageHandler = useCallback(import.meta.url, (regId) => { if (!socket.current) return; const handler = messageHandlers.current[regId]; if (handler) { @@ -82,17 +82,17 @@ export function WebsocketProvider({ children }) { } }, []); - const registerConnectionHandler = useCallback((callback) => { + const registerConnectionHandler = useCallback(import.meta.url, (callback) => { const regId = wsUuid++; connectionHandlers.current[regId] = callback; return regId; }, []); - const unregisterConnectionHandler = useCallback((regId) => { + const unregisterConnectionHandler = useCallback(import.meta.url, (regId) => { delete connectionHandlers.current[regId]; }, []); - useEffect(() => { + useEffect(import.meta.url, () => { const config = {}; config.transports = [ 'websocket' ]; if (token) config.query = `token=${token}`; @@ -113,7 +113,7 @@ export function WebsocketProvider({ children }) { } }, [token]); - const emitMessage = useCallback(async (eventName, eventArgs, timeout = 5000) => { + const emitMessage = useCallback(import.meta.url, async (eventName, eventArgs, timeout = 5000) => { try { if (!socket.current) throw new Error('no websocket connection'); return await socket.current?.timeout(timeout).emitWithAck(eventName, eventArgs); diff --git a/src/game/Audio.js b/src/game/Audio.js index 08546f816..cb67ba8c6 100644 --- a/src/game/Audio.js +++ b/src/game/Audio.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; import { Howler, Howl } from 'howler'; import useStore from '~/hooks/useStore'; @@ -153,7 +153,7 @@ const Audio = () => { const cutsceneWasPlaying = useRef(); // sound enabler (don't enable any sounds until use has interacted with page b/c audiocontext will fail) - useEffect(() => { + useEffect(import.meta.url, () => { const onClick = () => { setSoundEnabled(true); document.body.removeEventListener('click', onClick); @@ -169,7 +169,7 @@ const Audio = () => { // // SOUND EFFECTS - const stopEffect = useCallback((toStop, { fadeOut }) => { + const stopEffect = useCallback(import.meta.url, (toStop, { fadeOut }) => { if (!toStop) return; try { @@ -189,7 +189,7 @@ const Audio = () => { } }, [effectsVolume, effectEnded]); - const playEffect = useCallback((toPlay, { loop, duration }) => { + const playEffect = useCallback(import.meta.url, (toPlay, { loop, duration }) => { if (!toPlay || !soundEnabled) return; try { @@ -213,7 +213,7 @@ const Audio = () => { } }, [effectsVolume, effectEnded, stopEffect, soundEnabled]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!soundEnabled) return; Object.entries(currentEffects).forEach(([ sound, settings ]) => { @@ -234,14 +234,14 @@ const Audio = () => { // AMBIENT MUSIC EFFECTS const ambientVolume = useRef(0); - useEffect(() => { + useEffect(import.meta.url, () => { ambientVolume.current = musicVolume; if (currentTrack?.playing()) { currentTrack.volume(currentTrack.baseVolume * musicVolume / 100); } }, [musicVolume]); - const fadeInAmbientTrack = useCallback(() => { + const fadeInAmbientTrack = useCallback(import.meta.url, () => { if (!currentTrack) return; currentTrack.fade(0, currentTrack.baseVolume * ambientVolume.current / 100, 10000); @@ -251,7 +251,7 @@ const Audio = () => { // select current ambient track (whenever there is none) const lastTrack = useRef(); const disableMusic = musicVolume === 0; - useEffect(() => { + useEffect(import.meta.url, () => { if (!soundEnabled) return; if (!!currentTrack) return; if (disableMusic) return; @@ -272,7 +272,7 @@ const Audio = () => { }, [currentTrack, disableMusic, soundEnabled]); // eslint-disable-line react-hooks/exhaustive-deps // manage volume of current ambient track - useEffect(() => { + useEffect(import.meta.url, () => { if (!soundEnabled) return; if (!currentTrack) return; diff --git a/src/game/ChatListener.js b/src/game/ChatListener.js index af46e5ed5..ad8453caa 100644 --- a/src/game/ChatListener.js +++ b/src/game/ChatListener.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useState } from '~/lib/react-debug'; import useStore from '~/hooks/useStore'; import useWebsocket from '~/hooks/useWebsocket'; @@ -18,11 +18,11 @@ const ChatListener = () => { // for debug: // const dispatchClearChatHistory = useStore(s => s.dispatchClearChatHistory); - // useEffect(() => { + // useEffect(import.meta.url, () => { // dispatchClearChatHistory(); // }, []) - // useEffect(() => { + // useEffect(import.meta.url, () => { // const i = setInterval(() => { // dispatchChatMessage({ // asteroidId: 1, @@ -34,11 +34,11 @@ const ChatListener = () => { // }, []); const [disconnected, setDisconnected] = useState(); - const handleWSConnection = useCallback((isOpen) => { + const handleWSConnection = useCallback(import.meta.url, (isOpen) => { setDisconnected(!isOpen); }, []); - useEffect(() => { + useEffect(import.meta.url, () => { if (disconnected) { const to = setTimeout(() => { dispatchChatDisconnectedMessage(); @@ -49,7 +49,7 @@ const ChatListener = () => { } }, [disconnected]); - const handleWSMessage = useCallback((message) => { + const handleWSMessage = useCallback(import.meta.url, (message) => { if (process.env.NODE_ENV !== 'production') console.log('onWSMessage (chat)', message); const { type, body, message: errorMessage } = message; @@ -69,7 +69,7 @@ const ChatListener = () => { } }, [dispatchChatMessage]); - useEffect(() => { + useEffect(import.meta.url, () => { if (wsReady) { const connectionRegId = registerConnectionHandler(handleWSConnection); const messageRegId = registerMessageHandler(handleWSMessage); diff --git a/src/game/Cutscene.js b/src/game/Cutscene.js index 65777d159..c3c2aec78 100644 --- a/src/game/Cutscene.js +++ b/src/game/Cutscene.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; import ReactPlayer from 'react-player/lazy'; import styled from 'styled-components'; import BrightButton from '~/components/BrightButton'; @@ -45,28 +45,28 @@ const Cutscene = () => { const [hiding, setHiding] = useState(true); const [highlightButtons, setHighlightButtons] = useState(true); - useEffect(() => { + useEffect(import.meta.url, () => { setHiding(false); }, []); - const onComplete = useCallback(() => { + const onComplete = useCallback(import.meta.url, () => { setHiding(true); setTimeout(() => { dispatchCutscene(); }, cutsceneHideTime); }, [dispatchCutscene]); - const onError = useCallback((err) => { + const onError = useCallback(import.meta.url, (err) => { console.error(err); onComplete(); }, [onComplete]); - const onSkip = useCallback(() => { + const onSkip = useCallback(import.meta.url, () => { onComplete(); }, [onComplete]); // onload, set buttons to show up in 8 seconds - useEffect(() => { + useEffect(import.meta.url, () => { const to = setTimeout(() => { setHighlightButtons(false); }, 8000); diff --git a/src/game/GpuContextLost.js b/src/game/GpuContextLost.js index 1f013142a..30ee54dd3 100644 --- a/src/game/GpuContextLost.js +++ b/src/game/GpuContextLost.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect } from 'react'; +import { useCallback, useEffect } from '~/lib/react-debug'; import { useThree } from '@react-three/fiber'; import styled from 'styled-components'; @@ -31,7 +31,7 @@ const GpuContextLostContainer = styled.div` export const GpuContextLostReporter = ({ setContextLost }) => { const { gl } = useThree(); - useEffect(() => { + useEffect(import.meta.url, () => { if (!gl?.domElement) return; const onEvent = (e) => { setContextLost(e.type === 'webglcontextlost'); @@ -45,7 +45,7 @@ export const GpuContextLostReporter = ({ setContextLost }) => { }, []); // // TODO: vvv for debugging - // useEffect(() => { + // useEffect(import.meta.url, () => { // setTimeout(() => { // const x = gl.getContext().getExtension('WEBGL_lose_context'); // console.log('losing...'); @@ -64,7 +64,7 @@ export const GpuContextLostReporter = ({ setContextLost }) => { export const GpuContextLostMessage = () => { const dispatchLauncherPage = useStore(s => s.dispatchLauncherPage); - const openHelpChannel = useCallback(() => { + const openHelpChannel = useCallback(import.meta.url, () => { window.open(process.env.REACT_APP_HELP_URL || 'https://discord.gg/influenceth', '_blank'); }, []); diff --git a/src/game/Interface.js b/src/game/Interface.js index 4ede0c012..e43ae7e38 100644 --- a/src/game/Interface.js +++ b/src/game/Interface.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect } from 'react'; +import { useCallback, useEffect } from '~/lib/react-debug'; import styled from 'styled-components'; import { Tooltip } from 'react-tooltip'; import { Switch, Route, Redirect } from 'react-router-dom'; @@ -90,7 +90,7 @@ const Interface = () => { const dispatchToggleInterface = useStore(s => s.dispatchToggleInterface); const dispatchToggleDevTools = useStore(s => s.dispatchToggleDevTools); - const handleInterfaceShortcut = useCallback((e) => { + const handleInterfaceShortcut = useCallback(import.meta.url, (e) => { // ctrl+- if (e.ctrlKey && e.which === 189) dispatchLauncherPage(launcherPage ? undefined : 'play'); // ctrl+1 @@ -112,7 +112,7 @@ const Interface = () => { if (e.ctrlKey && e.which === 220) dispatchReorientCamera(true); }, [dispatchToggleInterface, dispatchToggleDevTools, dispatchRecenterCamera, dispatchReorientCamera, launcherPage]); - useEffect(() => { + useEffect(import.meta.url, () => { document.addEventListener('keyup', handleInterfaceShortcut); return () => { document.removeEventListener('keyup', handleInterfaceShortcut); @@ -121,7 +121,7 @@ const Interface = () => { // TODO: _launcher vvv const { create, destroy } = useControlledAlert(); - useEffect(() => { + useEffect(import.meta.url, () => { if (!isLaunched) { const alertId = create({ icon: , diff --git a/src/game/Intro.js b/src/game/Intro.js index 9cadf8de7..6e43e096a 100644 --- a/src/game/Intro.js +++ b/src/game/Intro.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; import { createPortal } from 'react-dom'; import Lottie from 'lottie-react'; import styled from 'styled-components'; @@ -25,12 +25,12 @@ const Intro = () => { const [hiding, setHiding] = useState(false); const [paused, setPaused] = useState(true); - const onReady = useCallback(() => { + const onReady = useCallback(import.meta.url, () => { setPaused(true); setTimeout(() => setPaused(false), 1000); }, []); - const onComplete = useCallback(() => { + const onComplete = useCallback(import.meta.url, () => { setHiding(true); // (so they fade back out) gsap.to(container.current, { delay: 1, @@ -41,7 +41,7 @@ const Intro = () => { }); }, []); - useEffect(() => { + useEffect(import.meta.url, () => { if (paused) lottieRef.current.pause(); else lottieRef.current.play(); }, [paused]); diff --git a/src/game/Launcher.js b/src/game/Launcher.js index bb3248be7..427b56496 100644 --- a/src/game/Launcher.js +++ b/src/game/Launcher.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useState } from '~/lib/react-debug'; import styled, { css, keyframes } from 'styled-components'; import { PuffLoader as Loader } from 'react-spinners'; import { Tooltip } from 'react-tooltip'; @@ -342,7 +342,7 @@ const Launcher = (props) => { const [isNew, setIsNew] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { if (!interfaceHidden) { dispatchToggleInterface(true); } @@ -353,20 +353,20 @@ const Launcher = (props) => { } }, [interfaceHidden]); - useEffect(() => { + useEffect(import.meta.url, () => { if (wasNew) { setIsNew(true); dispatchIsNotNew(); } }, [wasNew]); - useEffect(() => { + useEffect(import.meta.url, () => { if (authenticated) { setIsNew(false); } }, [authenticated]) - useEffect(() => { + useEffect(import.meta.url, () => { // NOTE: (currently not disallowing any for logged out users) // limit selection if logged out // if (!authenticated && !['play', 'help', 'rewards', 'settings', 'store'].includes(launcherPage)) { @@ -378,7 +378,7 @@ const Launcher = (props) => { } }, [launcherPage, authenticated, priceConstants, priceConstantsLoading]); - const onInstallApp = useCallback(async () => { + const onInstallApp = useCallback(import.meta.url, async () => { window.installPrompt.prompt(); const { outcome } = await window.installPrompt.userChoice; if (outcome === 'accepted') { @@ -386,7 +386,7 @@ const Launcher = (props) => { } }, []); - const onClickPlay = useCallback(() => { + const onClickPlay = useCallback(import.meta.url, () => { fireTrackingEvent('play', { externalId: accountAddress }); dispatchLauncherPage(); if (!hasSeenIntroVideo && !DISABLE_LAUNCHER_TRAILER) { @@ -398,27 +398,27 @@ const Launcher = (props) => { } }, [accountAddress, , hasSeenIntroVideo]); - const onEnterSimulation = useCallback(() => { + const onEnterSimulation = useCallback(import.meta.url, () => { if (!authenticated && !simulationEnabled) { // is authenticated check necessary? dispatchSimulationEnabled(true); } onClickPlay(); }, [authenticated, onClickPlay, simulationEnabled]); - const onExitSimulation = useCallback(() => { + const onExitSimulation = useCallback(import.meta.url, () => { dispatchSimulationEnabled(false); dispatchSimulationStep(); // TODO: remove this? (i.e. to not reset on exit) }, []); - const openHelpChannel = useCallback(() => { + const openHelpChannel = useCallback(import.meta.url, () => { window.open(process.env.REACT_APP_HELP_URL, '_blank', 'noopener'); }, []); - const openAssetsPortal = useCallback(() => { + const openAssetsPortal = useCallback(import.meta.url, () => { window.open(process.env.REACT_APP_BRIDGE_URL, '_blank', 'noopener'); }, []); - const openWebWalletDashboard = useCallback(() => { + const openWebWalletDashboard = useCallback(import.meta.url, () => { window.open(`${process.env.REACT_APP_ARGENT_WEB_WALLET_URL}`, '_blank', 'noopener'); }, []); diff --git a/src/game/Postprocessor.js b/src/game/Postprocessor.js index dafe9c480..16c936a8d 100644 --- a/src/game/Postprocessor.js +++ b/src/game/Postprocessor.js @@ -1,4 +1,4 @@ -import { useEffect, useRef } from 'react'; +import { useEffect, useRef } from '~/lib/react-debug'; import { useFrame, useThree } from '@react-three/fiber'; import { MeshBasicMaterial, ShaderMaterial, Vector2, WebGLRenderTarget, FloatType, RGBAFormat, SRGBColorSpace, ACESFilmicToneMapping } from 'three'; @@ -107,15 +107,15 @@ const Postprocessor = ({ enabled, bloomParams = defaultBloomParams }) => { } } - useEffect(() => { + useEffect(import.meta.url, () => { renderer.toneMapping = bloomParams?.toneMapping === undefined ? ACESFilmicToneMapping : bloomParams?.toneMapping; }, [bloomParams?.toneMapping]); - useEffect(() => { + useEffect(import.meta.url, () => { renderer.toneMappingExposure = bloomParams?.toneMappingExposure || 1; }, [bloomParams?.toneMappingExposure]); - useEffect(() => { + useEffect(import.meta.url, () => { renderer.setPixelRatio(pixelRatio); const renderScene = new RenderPass(scene, camera); diff --git a/src/game/Postprocessor.pmndrs.js b/src/game/Postprocessor.pmndrs.js index d5f8f8159..e878c3656 100644 --- a/src/game/Postprocessor.pmndrs.js +++ b/src/game/Postprocessor.pmndrs.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useState } from '~/lib/react-debug'; import { useThree } from '@react-three/fiber'; import { EffectComposer, SelectiveBloom } from '@react-three/postprocessing' @@ -28,7 +28,7 @@ const Postprocessor = ({ enabled, bloomParams = defaultBloomParams }) => { const { scene } = useThree(); const [lights, setLights] = useState([]); - const resetLights = useCallback(() => { + const resetLights = useCallback(import.meta.url, () => { const l = []; scene.traverse((obj) => { if (obj.isLight) { @@ -38,7 +38,7 @@ const Postprocessor = ({ enabled, bloomParams = defaultBloomParams }) => { // console.log('lights', l); setLights(l); }, []); - useEffect(() => resetLights(), []); + useEffect(import.meta.url, () => resetLights(), []); useInterval(() => { resetLights(); diff --git a/src/game/Referral.js b/src/game/Referral.js index a163c3f0a..16bdb557f 100644 --- a/src/game/Referral.js +++ b/src/game/Referral.js @@ -1,4 +1,4 @@ -import { useEffect } from 'react'; +import { useEffect } from '~/lib/react-debug'; import { useLocation } from 'react-router-dom'; import useStore from '~/hooks/useStore'; @@ -7,7 +7,7 @@ const Referrals = () => { const params = useLocation().search; const setRefCode = useStore(s => s.dispatchReferrerSet); - useEffect(() => { + useEffect(import.meta.url, () => { const query = new URLSearchParams(params); const refCode = query.get('r'); diff --git a/src/game/Scene.js b/src/game/Scene.js index 377b18dfe..68dd7caa8 100644 --- a/src/game/Scene.js +++ b/src/game/Scene.js @@ -1,4 +1,4 @@ -import { useContext, useEffect, useMemo, useState } from 'react'; +import { useContext, useEffect, useMemo, useState } from '~/lib/react-debug'; import { useQueryClient, QueryClientProvider } from 'react-query'; import { Object3D, Vector3 } from 'three'; import { Canvas, useThree } from '@react-three/fiber'; @@ -51,12 +51,12 @@ const WrappedScene = () => { const zoomStatus = useStore(s => s.asteroids.zoomStatus); // if three is started with frameloop == 'never', clock is not set to autoStart, so we need to set it - useEffect(() => { + useEffect(import.meta.url, () => { if (clock && !clock.autoStart) clock.autoStart = true; }, []); // reset to "zoomed out" control settings if zoomed out to belt view - useEffect(() => { + useEffect(import.meta.url, () => { if (!!controls && (zoomStatus === 'zooming-out' || zoomStatus === 'out')) { controls.maxDistance = 10 * constants.AU; controls.minDistance = 0.3 * constants.AU; @@ -100,9 +100,9 @@ const Scene = () => { const statsOn = useStore(s => s.graphics.stats); const [contextLost, setContextLost] = useState(false); - const canvasStyle = useMemo(() => (contextLost ? { opacity: 0, pointerEvents: 'none' } : { zIndex: 0 }), [contextLost]); + const canvasStyle = useMemo(import.meta.url, () => (contextLost ? { opacity: 0, pointerEvents: 'none' } : { zIndex: 0 }), [contextLost]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!zoomedFrom) { setZoomedFrom({ scene: new Vector3(0, 0, 0), @@ -115,7 +115,7 @@ const Scene = () => { const { assetType, overrides } = useContext(DevToolContext); - const [postprocessingEnabled, bloomParams] = useMemo(() => { + const [postprocessingEnabled, bloomParams] = useMemo(import.meta.url, () => { const defaults = visualConfigs.scene; const o = assetType === 'scene' ? overrides : {}; return [ @@ -131,7 +131,7 @@ const Scene = () => { ]; }, [overrides]); - const frameloop = useMemo(() => canvasStack?.length === 0 ? 'always' : 'never', [canvasStack]); + const frameloop = useMemo(import.meta.url, () => canvasStack?.length === 0 ? 'always' : 'never', [canvasStack]); return ( diff --git a/src/game/interface/Alerts.js b/src/game/interface/Alerts.js index f60d9f947..046b97116 100644 --- a/src/game/interface/Alerts.js +++ b/src/game/interface/Alerts.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { ReactNotifications, Store as notify } from 'react-notifications-component'; import 'react-notifications-component/dist/theme.css'; @@ -155,7 +155,7 @@ const getOptions = ({ level, duration, hideCloseIcon, onRemoval, width }) => { } export const useControlledAlert = () => { - const create = useCallback((alertData) => { + const create = useCallback(import.meta.url, (alertData) => { return send( @@ -169,7 +169,7 @@ export const useControlledAlert = () => { ); }, []); - const destroy = useCallback((id) => { + const destroy = useCallback(import.meta.url, (id) => { return notify.removeNotification(id); }, []); @@ -183,7 +183,7 @@ const Alerts = () => { const stacks = useRef({}); - const collapseStack = useCallback((stackId) => { + const collapseStack = useCallback(import.meta.url, (stackId) => { if (!stacks.current[stackId]) stacks.current[stackId] = {}; if (stacks.current[stackId].messageId && stacks.current[stackId].endTime > Date.now()) { @@ -195,7 +195,7 @@ const Alerts = () => { } }, []); - const updateStack = useCallback((stackId, newMessageId, duration) => { + const updateStack = useCallback(import.meta.url, (stackId, newMessageId, duration) => { stacks.current[stackId] = { messageId: newMessageId, endTime: Date.now() + duration, @@ -203,7 +203,7 @@ const Alerts = () => { }; }, []); - useEffect(() => { + useEffect(import.meta.url, () => { if (alerts?.length === 0) return; alerts.filter(a => !a.notified).forEach(a => { const { type, data, level, duration } = a; diff --git a/src/game/interface/DeepLink.js b/src/game/interface/DeepLink.js index d02ce6427..3fe7e86ad 100644 --- a/src/game/interface/DeepLink.js +++ b/src/game/interface/DeepLink.js @@ -4,7 +4,7 @@ import { Entity, Lot } from '@influenceth/sdk'; import { useLotLink } from '~/components/LotLink'; import { useShipLink } from '~/components/ShipLink'; import useEntity from '~/hooks/useEntity'; -import { useEffect } from 'react'; +import { useEffect } from '~/lib/react-debug'; import useShip from '~/hooks/useShip'; export const LotDeepLink = () => { @@ -12,7 +12,7 @@ export const LotDeepLink = () => { const { id } = useParams(); const onLink = useLotLink({ lotId: id }); - useEffect(() => { + useEffect(import.meta.url, () => { history.replace('/'); // cleanup url if (id) { onLink(); @@ -29,7 +29,7 @@ export const ShipDeepLink = () => { const { isLoading } = useShip({ label: Entity.IDS.SHIP, id }); // this is to ensure we wait until useShipLink is ready const onLink = useShipLink({ shipId: id, zoomToShip: true }); - useEffect(() => { + useEffect(import.meta.url, () => { if (isLoading) return; history.replace('/'); // cleanup url @@ -47,7 +47,7 @@ export const BuildingDeepLink = () => { const { data: building, isLoading } = useEntity({ label: Entity.IDS.BUILDING, id }); const onLink = useLotLink({ lotId: building?.Location?.location?.id, zoomToLot: true }); - useEffect(() => { + useEffect(import.meta.url, () => { if (isLoading) return; history.replace('/'); // cleanup url diff --git a/src/game/interface/HUD.js b/src/game/interface/HUD.js index a3b559673..74931b0de 100644 --- a/src/game/interface/HUD.js +++ b/src/game/interface/HUD.js @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useState } from '~/lib/react-debug'; import { useHistory } from 'react-router-dom'; import styled from 'styled-components'; @@ -97,13 +97,13 @@ const SimulationRedirector = ({ simulationEnabled }) => { const [readyToRedirect, setReadyToRedirect] = useState(); // redirect to /recruit when unmounted (if on last step) - useEffect(() => { + useEffect(import.meta.url, () => { if (simulationEnabled && simulationActions.includes('RedirectToRecruitOnLogin')) { setReadyToRedirect(true); } }, [simulationEnabled, simulationActions]); - useEffect(() => { + useEffect(import.meta.url, () => { if (readyToRedirect && !!accountAddress) { history.push('/recruit/0'); setReadyToRedirect(false); diff --git a/src/game/interface/MainMenu.js b/src/game/interface/MainMenu.js index b42a52350..b4b8b7444 100644 --- a/src/game/interface/MainMenu.js +++ b/src/game/interface/MainMenu.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef, useState } from 'react'; +import { useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { useLocation, useHistory } from 'react-router-dom'; import styled from 'styled-components'; import { MdFullscreen as FullscreenIcon, MdFullscreenExit as ExitFullscreenIcon } from 'react-icons/md'; @@ -128,21 +128,21 @@ const MainMenu = () => { // TODO: genesis book deprecation vvv // const { crew, crewmateMap } = useCrewContext(); - // const hasGenesisCrewmate = useMemo(() => { + // const hasGenesisCrewmate = useMemo(import.meta.url, () => { // return crew && crew?._crewmates && crewmateMap && crew._crewmates.find((i) => [1,2,3].includes(crewmateMap[i]?.coll)); // }, [crew?._crewmates, crewmateMap]); // eslint-disable-line react-hooks/exhaustive-deps // ^^^ // const [ showMenu, setShowMenu ] = useState(!isMobile); - // const openSection = useCallback((section) => { + // const openSection = useCallback(import.meta.url, (section) => { // // activateSection(section); // // TODO: ... this used to reference outliner, but outliner is gone // playSound('effects.click'); // if (isMobile) setShowMenu(false); // }, [isMobile]); - useEffect(() => { + useEffect(import.meta.url, () => { if (screenfull.isEnabled) { screenfull.on('change', () => { setFullscreen(screenfull.isEnabled && screenfull.isFullscreen); @@ -150,7 +150,7 @@ const MainMenu = () => { } }, []); - const { backLabel, onClickBack } = useMemo(() => { + const { backLabel, onClickBack } = useMemo(import.meta.url, () => { if (location.pathname.includes('/model/resource')) { return { backLabel: 'Exit', diff --git a/src/game/interface/ModelViewer.js b/src/game/interface/ModelViewer.js index 17a6536f5..a107ce7e9 100644 --- a/src/game/interface/ModelViewer.js +++ b/src/game/interface/ModelViewer.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { ACESFilmicToneMapping, AgXToneMapping, AnimationMixer, Box3, CineonToneMapping, Color, DirectionalLight, EquirectangularReflectionMapping, LinearToneMapping, LoopRepeat, @@ -107,12 +107,12 @@ const Model = ({ url, onLoaded, onProgress, onCameraUpdate, ...settings }) => { const { camera, clock, gl, scene } = useThree(); const pixelRatio = useStore(s => s.graphics.pixelRatio); - useEffect(() => { + useEffect(import.meta.url, () => { gl.setPixelRatio(pixelRatio || 1); }, [pixelRatio]); // if three is started with frameloop == 'never', clock is not set to autoStart, so we need to set it - useEffect(() => { + useEffect(import.meta.url, () => { if (clock && !clock.autoStart) clock.autoStart = true; }, []); @@ -129,7 +129,7 @@ const Model = ({ url, onLoaded, onProgress, onCameraUpdate, ...settings }) => { const raycaster = useRef(new Raycaster()); // init the camera (reset when url changes) - useEffect(() => { + useEffect(import.meta.url, () => { // TODO (enhancement): on mobile, aspect ratio is such that zoomed out to 1 may not have // view of full width of 1.0 at 0,0,0... so on mobile, should probably set this to 1.5+ const zoom = settings.initialZoom || 1; @@ -143,7 +143,7 @@ const Model = ({ url, onLoaded, onProgress, onCameraUpdate, ...settings }) => { }, [settings.initialZoom, url]); // eslint-disable-line react-hooks/exhaustive-deps // init orbitcontrols - useEffect(() => { + useEffect(import.meta.url, () => { controls.current = new OrbitControls(camera, gl.domElement); controls.current.target.set(0, 0, 0); controls.current.zoomSpeed = 0.33; @@ -157,7 +157,7 @@ const Model = ({ url, onLoaded, onProgress, onCameraUpdate, ...settings }) => { }; }, [camera, gl, settings.enablePostprocessing, url]); - useEffect(() => { + useEffect(import.meta.url, () => { if (settings.enableZoomLimits && settings.simpleZoomConstraints) { controls.current.minDistance = settings.simpleZoomConstraints[0]; controls.current.maxDistance = settings.simpleZoomConstraints[1]; @@ -168,7 +168,7 @@ const Model = ({ url, onLoaded, onProgress, onCameraUpdate, ...settings }) => { }, [settings.simpleZoomConstraints, settings.enableZoomLimits]); // // init axeshelper - // useEffect(() => { + // useEffect(import.meta.url, () => { // const axesHelper = new THREE.AxesHelper(5); // scene.add(axesHelper); // return () => { @@ -177,7 +177,7 @@ const Model = ({ url, onLoaded, onProgress, onCameraUpdate, ...settings }) => { // }, []); // eslint-disable-line react-hooks/exhaustive-deps // load the model on url change - useEffect(() => { + useEffect(import.meta.url, () => { if (model.current) { console.log('previous model not unloaded', model.current); return; @@ -402,7 +402,7 @@ const Model = ({ url, onLoaded, onProgress, onCameraUpdate, ...settings }) => { // eslint-disable-next-line react-hooks/exhaustive-deps }, [onLoaded, url]); // (do not include settings here, update in their own hooks) - useEffect(() => { + useEffect(import.meta.url, () => { scene.environmentIntensity = settings.envmapStrength; if (!model.current) return; @@ -415,7 +415,7 @@ const Model = ({ url, onLoaded, onProgress, onCameraUpdate, ...settings }) => { }); }, [settings.envmapStrength]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!model.current) return; model.current.traverse(function (node) { if (node.isMesh) { @@ -426,7 +426,7 @@ const Model = ({ url, onLoaded, onProgress, onCameraUpdate, ...settings }) => { }); }, [settings.lightmapStrength]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!model.current) return; model.current.traverse(function (node) { if (node.isSpotLight) { @@ -435,11 +435,11 @@ const Model = ({ url, onLoaded, onProgress, onCameraUpdate, ...settings }) => { }); }, [settings.spotlightReduction]); - useEffect(() => { + useEffect(import.meta.url, () => { scene.backgroundIntensity = settings.backgroundStrength; }, [settings.backgroundStrength]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!!controls?.current) { controls.current.autoRotate = !!settings.enableRevolution; controls.current.autoRotateSpeed = -0.15; @@ -533,7 +533,7 @@ const Skybox = ({ background, envmap, onLoaded, backgroundOverrideName = '', env { path: `${process.env.PUBLIC_URL}/textures/skybox/`} ); - useEffect(() => { + useEffect(import.meta.url, () => { let cleanupTextures = []; let waitingOn = 0; @@ -587,7 +587,7 @@ const Skybox = ({ background, envmap, onLoaded, backgroundOverrideName = '', env const Lighting = ({ keylightIntensity = 1.0, rimlightIntensity = 0.25 }) => { const { gl, scene } = useThree(); - useEffect(() => { + useEffect(import.meta.url, () => { let keyLight; if (keylightIntensity > 0) { keyLight = new DirectionalLight(0xFFFFFF); @@ -725,7 +725,7 @@ const ModelViewer = ({ assetType, modelUrl, ...overrides }) => { const [loadingModel, setLoadingModel] = useState(true); const [isLoading, setIsLoading] = useState(true); - const settings = useMemo(() => { + const settings = useMemo(import.meta.url, () => { const overridden = { ...visualConfigs.modelViewer[assetType] }; Object.keys(overrides).forEach((k) => { if (overrides[k] !== null && overrides[k] !== undefined) { @@ -735,29 +735,29 @@ const ModelViewer = ({ assetType, modelUrl, ...overrides }) => { return overridden; }, [assetType, overrides]); - useEffect(() => { + useEffect(import.meta.url, () => { dispatchCanvasStacked(assetType); return () => dispatchCanvasUnstacked(assetType); }, []); - useEffect(() => { + useEffect(import.meta.url, () => { if (modelUrl) setLoadingModel(true); }, [modelUrl]); - useEffect(() => { + useEffect(import.meta.url, () => { setLoadingSkybox(true); }, [settings.background, settings.envmap]); - const onModelLoaded = useCallback(() => setLoadingModel(false), []); - const onSkyboxLoaded = useCallback(() => setLoadingSkybox(false), []); + const onModelLoaded = useCallback(import.meta.url, () => setLoadingModel(false), []); + const onSkyboxLoaded = useCallback(import.meta.url, () => setLoadingSkybox(false), []); - useEffect(() => { + useEffect(import.meta.url, () => { setIsLoading(loadingModel || loadingSkybox); }, [ loadingModel, loadingSkybox ]); const [progress, setProgress] = useState(0); - const bloomParams = useMemo(() => ({ + const bloomParams = useMemo(import.meta.url, () => ({ radius: settings?.bloomRadius, strength: settings?.bloomStrength, threshold: settings?.bloomThreshold, diff --git a/src/game/interface/RandomEvent.js b/src/game/interface/RandomEvent.js index 20f713e77..a6e7daf76 100644 --- a/src/game/interface/RandomEvent.js +++ b/src/game/interface/RandomEvent.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useMemo, useState } from 'react'; +import { useCallback, useContext, useEffect, useMemo, useState } from '~/lib/react-debug'; import { useHistory } from 'react-router-dom'; import { RandomEvent } from '@influenceth/sdk'; @@ -67,24 +67,24 @@ const RandomEventAssignment = () => { const { bookTokens } = useBookTokens(bookIds[`RANDOM_${randomEvent}`]); const [finishing, setFinishing] = useState(false); - const isPending = useMemo( + const isPending = useMemo(import.meta.url, () => (pendingTransactions || []).find((tx) => tx.key === 'ResolveRandomEvent'), [pendingTransactions] ); - const onAccept = useCallback((choice) => { + const onAccept = useCallback(import.meta.url, (choice) => { execute('ResolveRandomEvent', { choice, caller_crew: { id: crew?.id, label: crew?.label } }); }, [crew, execute]); - const onFinishAssignment = useCallback(() => { + const onFinishAssignment = useCallback(import.meta.url, () => { setFinishing(true); }, [randomEvent]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!randomEvent) history.push('/'); }, [randomEvent]); - const overrides = useMemo(() => { + const overrides = useMemo(import.meta.url, () => { if (finishing || isPending) { return { content: , diff --git a/src/game/interface/RecruitCrewmate.js b/src/game/interface/RecruitCrewmate.js index 3f54baed4..07a340c38 100644 --- a/src/game/interface/RecruitCrewmate.js +++ b/src/game/interface/RecruitCrewmate.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect } from 'react'; +import { useCallback, useEffect } from '~/lib/react-debug'; import { useHistory, useParams } from 'react-router-dom'; import SelectHabitatDialog from '~/components/SelectHabitatDialog'; @@ -22,23 +22,23 @@ const RecruitCrewmate = () => { // - if crewId > 0, crewId is not full // - if locationId > 0, locationId is a habitat - const onSelectAssignedHabitat = useCallback((locationId) => { + const onSelectAssignedHabitat = useCallback(import.meta.url, (locationId) => { history.push(`/recruit/0/${locationId}/`) }, []); - const onRejectAssignedHabitat = useCallback(() => { + const onRejectAssignedHabitat = useCallback(import.meta.url, () => { history.push('/'); }, []); - const onSelectCrewmate = useCallback((crewmateId) => { + const onSelectCrewmate = useCallback(import.meta.url, (crewmateId) => { history.push(`/recruit/${crewId}/${locationId}/${crewmateId}`); }, [crewId, locationId]); - const onFinishAssignment = useCallback(() => { + const onFinishAssignment = useCallback(import.meta.url, () => { history.push(`/recruit/${crewId}/${locationId}/${crewmateId}/create`); }, [crewId, locationId, crewmateId]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!authenticated) history.push('/'); // Select a random habitat out of the first 100 const habitat = process.env.REACT_APP_DEPLOYMENT === 'production' ? Math.ceil(Math.random() * 100) : 1; diff --git a/src/game/interface/details/AsteroidDetails.js b/src/game/interface/details/AsteroidDetails.js index 61f5cd733..f6a09ab2d 100644 --- a/src/game/interface/details/AsteroidDetails.js +++ b/src/game/interface/details/AsteroidDetails.js @@ -1,4 +1,4 @@ -import { useEffect } from 'react'; +import { useEffect } from '~/lib/react-debug'; import { useHistory, useParams } from 'react-router-dom'; import { css } from 'styled-components'; import { Address } from '@influenceth/sdk'; @@ -44,7 +44,7 @@ const AsteroidDetails = () => { const dispatchOriginSelected = useStore(s => s.dispatchOriginSelected); // Force the asteroid to load into the origin if coming direct from URL - useEffect(() => { + useEffect(import.meta.url, () => { if (i) dispatchOriginSelected(Number(i)); }, [ i, dispatchOriginSelected ]); diff --git a/src/game/interface/details/CrewAssignments.js b/src/game/interface/details/CrewAssignments.js index a6ef674bc..543a2af8c 100644 --- a/src/game/interface/details/CrewAssignments.js +++ b/src/game/interface/details/CrewAssignments.js @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import React, { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import { useHistory, useParams } from 'react-router-dom'; import styled from 'styled-components'; @@ -332,7 +332,7 @@ const CrewAssignments = () => { const [selectedStory, setSelectedStory] = useState(); // TODO: genesis book deprecation vvv - const eligibleCrew = useMemo(() => { + const eligibleCrew = useMemo(import.meta.url, () => { if (crew && crewmateMap) { const eligible = crew._crewmates .filter((i) => [1,2,3].includes(crewmateMap[i]?.crewCollection)) @@ -344,7 +344,7 @@ const CrewAssignments = () => { }, [crew, crewmateMap]); // eslint-disable-line react-hooks/exhaustive-deps // ^^^ - const selectStory = useCallback((story) => () => { + const selectStory = useCallback(import.meta.url, (story) => () => { if (story) { playSound('click'); setSelectedStory(story); @@ -354,7 +354,7 @@ const CrewAssignments = () => { } }, [playSound]); - const selectCrewmate = useCallback((crewId) => async () => { + const selectCrewmate = useCallback(import.meta.url, (crewId) => async () => { if (bookReady && selectedStory) { const crewStatus = selectedStory.crewStatuses[crewId]; if (crewStatus && !['notReady', 'loading'].includes(crewStatus)) { @@ -386,7 +386,7 @@ const CrewAssignments = () => { playSound('failure'); }, [bookId, bookReady, createStorySession, history, playSound, selectedStory]); - useEffect(() => { + useEffect(import.meta.url, () => { if (book && eligibleCrew) { let firstIncompleteStory = null; let initialSelectedStory = null; @@ -458,7 +458,7 @@ const CrewAssignments = () => { } }, [book, eligibleCrew, initialSelectedId]); - const togglePart = useCallback((partId) => () => { + const togglePart = useCallback(import.meta.url, (partId) => () => { playSound('click'); if (collapsedParts.includes(partId)) { setCollapsedParts( diff --git a/src/game/interface/details/CrewDetails.js b/src/game/interface/details/CrewDetails.js index 00b9d3830..3e5f59622 100644 --- a/src/game/interface/details/CrewDetails.js +++ b/src/game/interface/details/CrewDetails.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import { useHistory, useParams } from 'react-router-dom'; import styled, { css } from 'styled-components'; import { Address, Building, Entity, Name, Time } from '@influenceth/sdk'; @@ -264,31 +264,31 @@ const CrewDetails = ({ crewId, crew, isMyCrew, isDelegatedCrew, isOwnedCrew, sel const [hovered, setHovered] = useState(); const [newName, setNewName] = useState(crew.Name?.name || ''); - const viewingAs = useMemo(() => ({ id: crewId, label: Entity.IDS.CREW }), [crewId]); - const hasMyCrewmates = useMemo(() => { + const viewingAs = useMemo(import.meta.url, () => ({ id: crewId, label: Entity.IDS.CREW }), [crewId]); + const hasMyCrewmates = useMemo(import.meta.url, () => { return crew._crewmates.filter((c) => accountAddress && Address.areEqual(accountAddress, c.Nft?.owner))?.length; }, [accountAddress, crew._crewmates]); // reset - useEffect(() => { + useEffect(import.meta.url, () => { if (editing) setNewName(crew.Name?.name || ''); }, [editing]); - useEffect(() => { + useEffect(import.meta.url, () => { if (changingName) setEditing(false); }, [changingName]) - const saveName = useCallback(async () => { + const saveName = useCallback(import.meta.url, async () => { if (await isNameValid(newName, crew?.id)) { changeName(newName); } }, [newName, crew?.id]); - const onClickCrewmate = useCallback((crewmate) => () => { + const onClickCrewmate = useCallback(import.meta.url, (crewmate) => () => { history.push(`/crewmate/${crewmate.id}`); }, []); - const onClickRecruit = useCallback(() => { + const onClickRecruit = useCallback(import.meta.url, () => { if (hydratedLocation?.building?.Building?.buildingType === Building.IDS.HABITAT) { history.push(`/recruit/${crew.id}/${hydratedLocation.building.id}`); } else { @@ -301,12 +301,12 @@ const CrewDetails = ({ crewId, crew, isMyCrew, isDelegatedCrew, isOwnedCrew, sel } }, [crew, hydratedLocation?.building]); - const onClickLocation = useCallback(() => { + const onClickLocation = useCallback(import.meta.url, () => { hydratedLocation.onLink(); history.push('/'); }, [hydratedLocation]); - const formationDate = useMemo(() => { + const formationDate = useMemo(import.meta.url, () => { if (earliestLoading) return '...'; if (!earliestActivity) return 'Unknown'; return `${Time.fromUnixSeconds(earliestActivity?.event?.timestamp, TIME_ACCELERATION).toGameClockADays(true)} SA`; @@ -316,7 +316,7 @@ const CrewDetails = ({ crewId, crew, isMyCrew, isDelegatedCrew, isOwnedCrew, sel // TODO: was this just debug? remove? const ready = true; // const [ready, setReady] = useState(); - // useEffect(() => { + // useEffect(import.meta.url, () => { // setTimeout(() => setReady(true), 1000); // }, []); @@ -529,7 +529,7 @@ const Wrapper = () => { const createAlert = useStore(s => s.dispatchAlertLogged); - useEffect(() => { + useEffect(import.meta.url, () => { // if id is specified... if (i) { // ...return to / with error if crew not found diff --git a/src/game/interface/details/CrewmateDetails.js b/src/game/interface/details/CrewmateDetails.js index e95d8f45f..314f09182 100644 --- a/src/game/interface/details/CrewmateDetails.js +++ b/src/game/interface/details/CrewmateDetails.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import { useHistory, useParams } from 'react-router-dom'; import styled, { css } from 'styled-components'; import { Address, Crewmate, Entity, Time } from '@influenceth/sdk'; @@ -329,15 +329,15 @@ const CrewmateDetails = ({ crewmateId, crewmate, isOwnedCrewmate }) => { const { data: TIME_ACCELERATION } = useConstants('TIME_ACCELERATION'); - const viewingAs = useMemo(() => ({ id: crewmateId, label: Entity.IDS.CREWMATE }), [crewmateId]); + const viewingAs = useMemo(import.meta.url, () => ({ id: crewmateId, label: Entity.IDS.CREWMATE }), [crewmateId]); - const onBackToCrew = useCallback(() => { + const onBackToCrew = useCallback(import.meta.url, () => { if (crewmate?.Control?.controller.id) { history.push(`/crew/${crewmate?.Control?.controller.id}`); } }, [crewmate]); - const formationDate = useMemo(() => { + const formationDate = useMemo(import.meta.url, () => { if (earliestLoading) return '...'; if (!earliestActivity) return 'Unknown'; return `${Time.fromUnixSeconds(earliestActivity?.event?.timestamp, TIME_ACCELERATION).toGameClockADays(true)} SA`; @@ -451,7 +451,7 @@ const Wrapper = () => { const createAlert = useStore(s => s.dispatchAlertLogged); - useEffect(() => { + useEffect(import.meta.url, () => { // if id is specified... if (i) { // ...return to / with error if crew not found diff --git a/src/game/interface/details/EntityActivityLog.js b/src/game/interface/details/EntityActivityLog.js index 304fb46a8..0160941f6 100644 --- a/src/game/interface/details/EntityActivityLog.js +++ b/src/game/interface/details/EntityActivityLog.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import moment from 'moment'; import LoadingAnimation from 'react-spinners/PropagateLoader'; @@ -146,7 +146,7 @@ const RemainingChars = styled.div` const AnnotationItem = ({ annotation }) => { const { data: content, isLoading } = useAnnotationContent(annotation); - const ago = useMemo(() => { + const ago = useMemo(import.meta.url, () => { if (!annotation.createdAt) return 'a long time ago'; const m = moment(new Date(annotation.createdAt)); return m.fromNow(); @@ -176,18 +176,18 @@ const AddAnnotationItem = ({ activity }) => { const [annotation, setAnnotation] = useState(); - const handleChange = useCallback(async (e) => { + const handleChange = useCallback(import.meta.url, async (e) => { setAnnotation(e.currentTarget.value || ''); resizeOnKeydown(95)(e); }, []); - const saveNewAnnotation = useCallback(async () => { + const saveNewAnnotation = useCallback(import.meta.url, async () => { if (isValidAnnotation(annotation)) { saveAnnotation(annotation); } }, [annotation]); - const remaining = useMemo(() => maxAnnotationLength - (annotation?.length || 0), [annotation?.length]); + const remaining = useMemo(import.meta.url, () => maxAnnotationLength - (annotation?.length || 0), [annotation?.length]); return ( @@ -252,13 +252,13 @@ const EntityActivityLog = ({ entity, viewingAs }) => { const getActivityConfig = useGetActivityConfig(); const { data: activities } = useActivities(entity); - const activityRows = useMemo(() => { + const activityRows = useMemo(import.meta.url, () => { return (activities || []) .map((a) => ({ ...a, _logContent: getActivityConfig(a, viewingAs)?.logContent })) .filter((a) => !!a._logContent); }, [activities, getActivityConfig, viewingAs]); - const columns = useMemo(() => { + const columns = useMemo(import.meta.url, () => { return [ { key: 'createdAt', diff --git a/src/game/interface/details/ListView.js b/src/game/interface/details/ListView.js index 960c99fd3..cf7c7aefe 100644 --- a/src/game/interface/details/ListView.js +++ b/src/game/interface/details/ListView.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Tooltip } from 'react-tooltip'; @@ -274,7 +274,7 @@ const ListViewComponent = ({ assetType, onAssetTypeChange, onParamsApplied, para const [disabledColumns, setDisabledColumns] = useState([]); const [filtersOpen, setFiltersOpen] = useState(); - const onCopyLink = useCallback(() => { + const onCopyLink = useCallback(import.meta.url, () => { try { const { origin, pathname } = window.location || {}; navigator.clipboard.writeText(`${origin}${pathname}?filters=${JSON.stringify(filters)}&sort=${JSON.stringify(sort)}`); @@ -288,7 +288,7 @@ const ListViewComponent = ({ assetType, onAssetTypeChange, onParamsApplied, para } }, [filters, sort]); - useEffect(() => { + useEffect(import.meta.url, () => { try { if (params?.filters) updateFilters(JSON.parse(params?.filters)); if (params?.sort) setSort(JSON.parse(params?.sort)); @@ -298,7 +298,7 @@ const ListViewComponent = ({ assetType, onAssetTypeChange, onParamsApplied, para } }, [params]) - const onToggleColumns = useCallback((col) => () => { + const onToggleColumns = useCallback(import.meta.url, (col) => () => { setDisabledColumns((colKeys) => { if (colKeys.find((k) => k === col.key)) { return colKeys.filter((k) => k !== col.key); @@ -307,15 +307,15 @@ const ListViewComponent = ({ assetType, onAssetTypeChange, onParamsApplied, para }); }, []); - const onToggleFilters = useCallback(() => { + const onToggleFilters = useCallback(import.meta.url, () => { setFiltersOpen((o) => !o); }, []); - const onClickFilters = useCallback(() => { + const onClickFilters = useCallback(import.meta.url, () => { setFiltersOpen(true); }, []); - const handleSort = useCallback((field, options = {}) => () => { + const handleSort = useCallback(import.meta.url, (field, options = {}) => () => { if (!field) return; let updatedSortField = sortField; @@ -330,27 +330,27 @@ const ListViewComponent = ({ assetType, onAssetTypeChange, onParamsApplied, para setSort([updatedSortField, updatedSortDirection, options]); }, [sortDirection, sortField, sortOptions]); - useEffect(() => { + useEffect(import.meta.url, () => { if (query?.data?.length === 0) setPage(1); }, [ query?.data, setPage ]); // on asset type change - useEffect(() => { + useEffect(import.meta.url, () => { setDisabledColumns([]); setPage(1); }, [assetType, setPage]); - const enabledColumns = useMemo(() => { + const enabledColumns = useMemo(import.meta.url, () => { return columns.filter((c) => !disabledColumns.includes(c.key)); }, [columns, disabledColumns]); - const hideableColumns = useMemo(() => { + const hideableColumns = useMemo(import.meta.url, () => { return columns.filter((c) => !c.skip).filter((c) => !c.unhideable); }, [columns]); - const enabledColumnKeys = useMemo(() => enabledColumns.map((c) => c.key), [enabledColumns]); + const enabledColumnKeys = useMemo(import.meta.url, () => enabledColumns.map((c) => c.key), [enabledColumns]); - const activeFilters = useMemo(() => { + const activeFilters = useMemo(import.meta.url, () => { return Object.keys(filters || {}) .reduce((acc, fieldName) => acc + (isAssetSearchFilterMatchingDefault(assetType, fieldName) ? 0 : 1), 0) }, [assetType, filters]); @@ -475,17 +475,17 @@ const ListView = () => { const { search } = useLocation(); const history = useHistory(); - const onAssetTypeChange = useCallback(({ value }) => { + const onAssetTypeChange = useCallback(import.meta.url, ({ value }) => { history.push(`/listview/${value}`); }, []); - useEffect(() => { + useEffect(import.meta.url, () => { if (!assetType) history.push('/listview/asteroids'); else if (!assetTypes[assetType]) history.replace('/listview/asteroids'); }, [assetType]); - const params = useMemo(() => Object.fromEntries(new URLSearchParams(search)), [search]); - const onParamsApplied = useCallback(() => { + const params = useMemo(import.meta.url, () => Object.fromEntries(new URLSearchParams(search)), [search]); + const onParamsApplied = useCallback(import.meta.url, () => { history.replace(`/listview/${assetType}`); }, [assetType]); diff --git a/src/game/interface/details/Marketplace.js b/src/game/interface/details/Marketplace.js index 834994ccc..028455ce9 100644 --- a/src/game/interface/details/Marketplace.js +++ b/src/game/interface/details/Marketplace.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { useHistory, useLocation, useParams } from 'react-router-dom'; import { Entity, Lot, Product } from '@influenceth/sdk'; @@ -103,7 +103,7 @@ const Marketplace = () => { const history = useHistory(); const { asteroidId, lotIndex, discriminator } = useParams(); const product = discriminator === 'orders' ? null : discriminator; - const lotId = useMemo(() => Lot.toId(Number(asteroidId), lotIndex === 'all' ? null : Number(lotIndex)), [asteroidId, lotIndex]); + const lotId = useMemo(import.meta.url, () => Lot.toId(Number(asteroidId), lotIndex === 'all' ? null : Number(lotIndex)), [asteroidId, lotIndex]); const setCoachmarkRef = useCoachmarkRefSetter(); const coachmarkHelperProduct = useStore(s => s.coachmarks?.[COACHMARK_IDS.asteroidMarketsHelper]); @@ -111,7 +111,7 @@ const Marketplace = () => { const [mode, setMode] = useState('buy'); const { search } = useLocation(); - const backOverride = useMemo(() => { + const backOverride = useMemo(import.meta.url, () => { const q = new URLSearchParams(search); return q.get('back'); }, [search]); @@ -127,7 +127,7 @@ const Marketplace = () => { const [marketplaceTally, setMarketplaceTally] = useState(0); const [products, setProducts] = useState([]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroidId) return; if (lotIndex === 'all') { // TODO: getAsteroidMarketplaceAggs @@ -141,7 +141,7 @@ const Marketplace = () => { } }, [asteroidId, lot?.building, lotIndex]); - const [listings, orderTally] = useMemo(() => { + const [listings, orderTally] = useMemo(import.meta.url, () => { let buyOrderTally = 0; let sellOrderTally = 0; // show all products that are allowedProducts or have active orders available @@ -171,20 +171,20 @@ const Marketplace = () => { return [productListings, buyOrderTally + sellOrderTally]; }, [orderSummary, products]); - const marketplace = useMemo(() => { + const marketplace = useMemo(import.meta.url, () => { if (lot?.building?.Exchange) return lot.building; return null; }, [lot]); // TODO: if lot is loaded and this is not a marketplace, go back? - const myLocalOrders = useMemo(() => (myOpenOrders || []).filter((o) => { + const myLocalOrders = useMemo(import.meta.url, () => (myOpenOrders || []).filter((o) => { const orderAsteroidId = o.locations.find((l) => l.label === Entity.IDS.ASTEROID)?.id; const orderLotId = o.locations.find((l) => l.label === Entity.IDS.LOT)?.id; return orderAsteroidId === Number(asteroidId) && (lotIndex === 'all' || Number(lot?.id) === orderLotId); }), [asteroidId, lot?.id, lotIndex, myOpenOrders]); - const goBack = useCallback(() => { + const goBack = useCallback(import.meta.url, () => { if (backOverride === 'all') { history.push(`/marketplace/${asteroidId}/all/${product || ''}`); } else { @@ -192,11 +192,11 @@ const Marketplace = () => { } }, [backOverride, product]); - const goToMyOrders = useCallback(() => { + const goToMyOrders = useCallback(import.meta.url, () => { history.push(`/marketplace/${asteroidId}/${lotIndex}/orders`); }, []); - const onSelectListing = useCallback((listing) => { + const onSelectListing = useCallback(import.meta.url, (listing) => { history.push(`/marketplace/${asteroidId}/${lotIndex}/${listing?.product || ''}`); }, []); diff --git a/src/game/interface/details/asteroidDetails/AsteroidBonuses.js b/src/game/interface/details/asteroidDetails/AsteroidBonuses.js index a08ce1d51..d9ff820e2 100644 --- a/src/game/interface/details/asteroidDetails/AsteroidBonuses.js +++ b/src/game/interface/details/asteroidDetails/AsteroidBonuses.js @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useState } from '~/lib/react-debug'; import styled from 'styled-components'; import BonusBar from '~/components/BonusBar'; diff --git a/src/game/interface/details/asteroidDetails/Information.js b/src/game/interface/details/asteroidDetails/Information.js index 82b80bddd..bfdca3fef 100644 --- a/src/game/interface/details/asteroidDetails/Information.js +++ b/src/game/interface/details/asteroidDetails/Information.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid, Entity, Name } from '@influenceth/sdk'; @@ -281,9 +281,9 @@ const AsteroidInformation = ({ abundances, asteroid, isManager, isOwner }) => { const [newName, setNewName] = useState(''); const [openNameChangeForm, setOpenNameChangeForm] = useState(false); - const viewingAs = useMemo(() => ({ id: Number(asteroid?.id), label: Entity.IDS.ASTEROID }), [asteroid?.id]); + const viewingAs = useMemo(import.meta.url, () => ({ id: Number(asteroid?.id), label: Entity.IDS.ASTEROID }), [asteroid?.id]); - const download3dModel = useCallback(() => { + const download3dModel = useCallback(import.meta.url, () => { if (exportingModel || !asteroid) return; setExportingModel(true); renderDummyAsteroid(asteroid, constants.MODEL_EXPORT_RESOLUTION, webWorkerPool, (asteroidModel, dispose) => { @@ -297,30 +297,30 @@ const AsteroidInformation = ({ abundances, asteroid, isManager, isOwner }) => { }, [asteroid, exportingModel, webWorkerPool]); // on asteroid change, reset name input field on asteroid change - useEffect(() => { + useEffect(import.meta.url, () => { setNewName(''); setOpenNameChangeForm(false); }, [asteroid.Name?.name]); - const attemptUpdateAsteroidName = useCallback(async () => { + const attemptUpdateAsteroidName = useCallback(import.meta.url, async () => { if (await isNameValid(newName, asteroid?.id)) { changeName(newName); } }, [changeName, isNameValid, newName, asteroid?.id]); - const price = useMemo(() => { + const price = useMemo(import.meta.url, () => { if (!asteroid || !priceConstants) return 0; const lots = Asteroid.getSurfaceArea(undefined, asteroid.Celestial.radius); return asteroidPrice(lots, priceConstants); }, [asteroid, priceConstants]); - const sufficientFunds = useMemo(() => { + const sufficientFunds = useMemo(import.meta.url, () => { if (!price || !priceConstants || !walletBalances) return false; const balance = safeBigInt(walletBalances?.combinedBalance?.to(priceConstants.ASTEROID_PURCHASE_TOKEN)); return price <= balance; }, [price, priceConstants, walletBalances]); - const attemptBuyAsteroid = useCallback(async () => { + const attemptBuyAsteroid = useCallback(import.meta.url, async () => { const limited = await checkForLimit(); if (limited) return; diff --git a/src/game/interface/details/asteroidDetails/Resources.js b/src/game/interface/details/asteroidDetails/Resources.js index be4634853..d0a913b39 100644 --- a/src/game/interface/details/asteroidDetails/Resources.js +++ b/src/game/interface/details/asteroidDetails/Resources.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import { useHistory, useParams } from 'react-router-dom'; import styled from 'styled-components'; import { Tooltip } from 'react-tooltip'; @@ -411,7 +411,7 @@ const ResourceDetails = ({ abundances, asteroid, isManager }) => { const [selected, setSelected] = useState(); const [hover, setHover] = useState(); - const handleClick = useCallback((categoryIndex) => () => { + const handleClick = useCallback(import.meta.url, (categoryIndex) => () => { const toBeSelected = categoryIndex >= 0 ? abundances[categoryIndex] : null; setSelected(toBeSelected); setHover(null); @@ -419,17 +419,17 @@ const ResourceDetails = ({ abundances, asteroid, isManager }) => { history.replace(`/asteroids/${asteroid.id}/resources${toBeSelected ? `/${toBeSelected.categoryKey}` : ``}`); }, [abundances, asteroid.id]); // eslint-disable-line react-hooks/exhaustive-deps - const handleHover = useCallback((category, isHovering) => () => { + const handleHover = useCallback(import.meta.url, (category, isHovering) => () => { setHover(isHovering ? category : null); }, []); - const goToResourceViewer = useCallback((resource) => (e) => { + const goToResourceViewer = useCallback(import.meta.url, (resource) => (e) => { e.stopPropagation(); history.push(`/model/resource/${resource.name}?back=${encodeURIComponent(history.location.pathname)}`) return false; }, []); // eslint-disable-line react-hooks/exhaustive-deps - const goToResourceMap = useCallback((resource) => (e) => { + const goToResourceMap = useCallback(import.meta.url, (resource) => (e) => { e.stopPropagation(); selectOrigin(asteroid.id); if (zoomStatus !== 'in') updateZoomStatus('zooming-in'); @@ -444,7 +444,7 @@ const ResourceDetails = ({ abundances, asteroid, isManager }) => { setInfoPaneAnchor(which ? e.target : null); }; - useEffect(() => { + useEffect(import.meta.url, () => { if (abundances?.length > 0 && initialCategory) { const a = abundances.find((a) => a.categoryKey === initialCategory); if (a) { @@ -454,8 +454,8 @@ const ResourceDetails = ({ abundances, asteroid, isManager }) => { } }, [abundances?.length, initialCategory]); // eslint-disable-line react-hooks/exhaustive-deps - const unpackedBonuses = useMemo(() => Asteroid.Entity.getBonuses(asteroid) || [], [asteroid]); - const nonzeroBonuses = useMemo(() => unpackedBonuses.filter((b) => b.level > 0), [unpackedBonuses]); + const unpackedBonuses = useMemo(import.meta.url, () => Asteroid.Entity.getBonuses(asteroid) || [], [asteroid]); + const nonzeroBonuses = useMemo(import.meta.url, () => unpackedBonuses.filter((b) => b.level > 0), [unpackedBonuses]); return ( diff --git a/src/game/interface/details/asteroidDetails/components/AsteroidComposition.js b/src/game/interface/details/asteroidDetails/components/AsteroidComposition.js index b7ae88e9c..9814294cd 100644 --- a/src/game/interface/details/asteroidDetails/components/AsteroidComposition.js +++ b/src/game/interface/details/asteroidDetails/components/AsteroidComposition.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; import { BackSide, CircleGeometry, @@ -43,7 +43,7 @@ const AsteroidComposition = ({ abundances, asteroid, focus, noColor, noGradient, const focusKey = keyify(focus); - useEffect(() => { + useEffect(import.meta.url, () => { if (asteroid && abundances) { hovered.current = null; obscurerTheta.current = 0; @@ -140,12 +140,12 @@ const AsteroidComposition = ({ abundances, asteroid, focus, noColor, noGradient, } }, [!!asteroid, abundances]); // eslint-disable-line react-hooks/exhaustive-deps - useEffect(() => { + useEffect(import.meta.url, () => { hovered.current = hover; onAnimationChange(true); }, [hover]); // eslint-disable-line react-hooks/exhaustive-deps - useEffect(() => { + useEffect(import.meta.url, () => { const target = resources.current.find((c) => c.categoryKey === focusKey); if (target) { targetRotation.current = -1 * target.start; @@ -212,7 +212,7 @@ const AsteroidComposition = ({ abundances, asteroid, focus, noColor, noGradient, }, [focusKey]); // eslint-disable-line react-hooks/exhaustive-deps // this triggers the intro effect (i.e. removing the obscurer layer) - useEffect(() => { + useEffect(import.meta.url, () => { if (ready) { onAnimationChange(true); } @@ -302,11 +302,11 @@ const AsteroidCompositionInCanvas = ({ animationDelay, ready, ...props }) => { const [delayedReady, setDelayedReady] = useState(); const [frameloop, setFrameloop] = useState(); - const onAnimationChange = useCallback((which) => { + const onAnimationChange = useCallback(import.meta.url, (which) => { setFrameloop(which ? 'always' : 'never'); }, []); - useEffect(() => { + useEffect(import.meta.url, () => { if (ready) { setTimeout(() => { setDelayedReady(true); diff --git a/src/game/interface/details/asteroidDetails/components/AsteroidGraphic.js b/src/game/interface/details/asteroidDetails/components/AsteroidGraphic.js index 87ab66ffa..d954fbdfd 100644 --- a/src/game/interface/details/asteroidDetails/components/AsteroidGraphic.js +++ b/src/game/interface/details/asteroidDetails/components/AsteroidGraphic.js @@ -1,4 +1,4 @@ -import { useCallback, useState } from 'react'; +import { useCallback, useState } from '~/lib/react-debug'; import styled, { css, keyframes } from 'styled-components'; import { Asteroid, Entity } from '@influenceth/sdk'; @@ -94,7 +94,7 @@ const AsteroidGraphic = ({ asteroid, defaultLastRow, ...compositionProps }) => { const [ready, setReady] = useState(); - const onReady = useCallback(() => { + const onReady = useCallback(import.meta.url, () => { setReady(true); }, []); diff --git a/src/game/interface/details/asteroidDetails/components/AsteroidSpinner.js b/src/game/interface/details/asteroidDetails/components/AsteroidSpinner.js index 8616b4721..410bc53bf 100644 --- a/src/game/interface/details/asteroidDetails/components/AsteroidSpinner.js +++ b/src/game/interface/details/asteroidDetails/components/AsteroidSpinner.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef } from 'react'; +import { useEffect, useMemo, useRef } from '~/lib/react-debug'; import { CircleGeometry, Mesh, @@ -15,11 +15,11 @@ const AsteroidSpinner = () => { const meshRef = useRef(); const initialTime = useRef(Date.now()); - const pixelDensity = useMemo(() => { + const pixelDensity = useMemo(import.meta.url, () => { return gl.getPixelRatio() || 1; // or viewport.dpr? }, []); - useEffect(() => { + useEffect(import.meta.url, () => { const geometry = new CircleGeometry(1.2, 120); const material = new ShaderMaterial({ transparent: true, diff --git a/src/game/interface/details/crewAssignments/Assignment.js b/src/game/interface/details/crewAssignments/Assignment.js index 182d6accb..4ffd5643b 100644 --- a/src/game/interface/details/crewAssignments/Assignment.js +++ b/src/game/interface/details/crewAssignments/Assignment.js @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import React, { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import { useHistory, useParams } from 'react-router-dom'; import styled, { keyframes } from 'styled-components'; @@ -107,24 +107,24 @@ const CrewAssignment = ({ crewId, crewmateId, crewmateMap, onFinish, overrides = onCloseDestination = '/'; } - useEffect(() => { + useEffect(import.meta.url, () => { if (bookError) history.push(onCloseDestination); }, [bookError, onCloseDestination]); // on step change, clear selection (to close modal) and set pseudo path-loading - useEffect(() => { + useEffect(import.meta.url, () => { setSelection(); setPathLoading(true); setTimeout(() => { setPathLoading(false); }, 100); }, [storySession?.currentStep]); - const confirmPath = useCallback(() => { + const confirmPath = useCallback(import.meta.url, () => { playSound('click'); choosePath(selection.id); }, [choosePath, playSound, selection]); - const selectPath = useCallback((path) => () => { + const selectPath = useCallback(import.meta.url, (path) => () => { playSound('click' ); // if only one choice (or auto confirming), don't need to confirm @@ -137,16 +137,16 @@ const CrewAssignment = ({ crewId, crewmateId, crewmateMap, onFinish, overrides = } }, [choosePath, playSound, storySession]); - const onGoBack = useCallback(() => { + const onGoBack = useCallback(import.meta.url, () => { playSound('click'); history.push(onCloseDestination); }, [history, playSound, onCloseDestination]); - const onUndoPath = useCallback(() => { + const onUndoPath = useCallback(import.meta.url, () => { undoPath(); }, [undoPath]); - const finish = useCallback(() => { + const finish = useCallback(import.meta.url, () => { if (overrides?.onFinish) { overrides?.onFinish(); return; @@ -156,15 +156,15 @@ const CrewAssignment = ({ crewId, crewmateId, crewmateMap, onFinish, overrides = onFinish(); // ${bookSession?.isMintingStory ? 'create' : 'complete'} }, [history, playSound, bookSession?.isMintingStory, overrides?.onFinish]); - const confirmExitStoryMode = useCallback(() => { + const confirmExitStoryMode = useCallback(import.meta.url, () => { setConfirmingExitStoryMode(true); }, []); - const onConfirmExitStoryMode = useCallback(() => { + const onConfirmExitStoryMode = useCallback(import.meta.url, () => { onFinish(); // ${bookSession?.isMintingStory ? 'create' : 'complete'} }, []); - const backButton = useMemo(() => { + const backButton = useMemo(import.meta.url, () => { if (bookSession && storySession && !(bookSession.currentStoryIndex === 0 && storySession.currentStep === 0)) { return { label: 'Back', @@ -174,7 +174,7 @@ const CrewAssignment = ({ crewId, crewmateId, crewmateMap, onFinish, overrides = return null; }, [bookSession, onUndoPath, onGoBack, overrides?.onBack, storySession]); - const dialogProps = useMemo(() => { + const dialogProps = useMemo(import.meta.url, () => { if (!bookSession || !storySession) return {}; const isMintingStory = bookSession.isMintingStory; diff --git a/src/game/interface/details/crewAssignments/Complete.js b/src/game/interface/details/crewAssignments/Complete.js index 418b79847..00d88c3bb 100644 --- a/src/game/interface/details/crewAssignments/Complete.js +++ b/src/game/interface/details/crewAssignments/Complete.js @@ -1,4 +1,4 @@ -// import React, { useCallback, useEffect, useMemo } from 'react'; +// import React, { useCallback, useEffect, useMemo } from '~/lib/react-debug'; // import { useHistory, useParams } from 'react-router-dom'; // import styled, { keyframes } from 'styled-components'; // import { Crewmate } from '@influenceth/sdk'; @@ -290,24 +290,24 @@ // const { crewmateMap } = useCrewContext(); // const { storyState } = useStorySession(sessionId); -// const onCloseDestination = useMemo( +// const onCloseDestination = useMemo(import.meta.url, // () => `/crew-assignments/${storyState?.book}/${storyState?.story}`, // [storyState?.book, storyState?.story] // ); -// const crew = useMemo( +// const crew = useMemo(import.meta.url, // () => crewmateMap && storyState && crewmateMap[storyState.owner], // [storyState, crewmateMap] // ); -// const rewards = useMemo(() => { +// const rewards = useMemo(import.meta.url, () => { // return (storyState?.accruedTraits || []).map((id) => ({ // id, // ...Crewmate.getTrait(id) // })); // }, [storyState?.accruedTraits]); -// const shareOnTwitter = useCallback(() => { +// const shareOnTwitter = useCallback(import.meta.url, () => { // const params = new URLSearchParams({ // text: [ // `I just completed the Crew Assignment: "${storyState.title}"`, @@ -321,18 +321,18 @@ // window.open(`https://twitter.com/intent/tweet?${params.toString()}`, '_blank'); // }, [accountAddress, sessionId, storyState]); -// const handleFinish = useCallback(() => { +// const handleFinish = useCallback(import.meta.url, () => { // history.push(onCloseDestination); // }, [history, onCloseDestination]); // // show "create" page for recruitment assignments -// useEffect(() => { +// useEffect(import.meta.url, () => { // if (storyState && (storyState.tags || []).includes('ADALIAN_RECRUITMENT')) { // history.push(`/crew-assignment/${sessionId}/create`); // } // }, [!!storyState]); // eslint-disable-line react-hooks/exhaustive-deps -// const slideOutContents = useMemo(() => +// const slideOutContents = useMemo(import.meta.url, () => // rewards?.length > 0 // ? ( // diff --git a/src/game/interface/details/crewAssignments/Create.js b/src/game/interface/details/crewAssignments/Create.js index 06e70e2af..834a279bd 100644 --- a/src/game/interface/details/crewAssignments/Create.js +++ b/src/game/interface/details/crewAssignments/Create.js @@ -1,4 +1,4 @@ -import React, { Fragment, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; +import React, { Fragment, useCallback, useContext, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { useHistory } from 'react-router-dom'; import styled, { css, keyframes } from 'styled-components'; import { Crewmate, Entity, Name } from '@influenceth/sdk'; @@ -748,7 +748,7 @@ const MouseoverInfoContent = ({ title, description }) => ( const ClassSelector = ({ classObjects, crewmate, onUpdateClass, onClose }) => { const [hovered, setHovered] = useState(); - const classDisplay = useMemo(() => classObjects[hovered || crewmate?.Crewmate?.class], [hovered, crewmate?.Crewmate?.class]) + const classDisplay = useMemo(import.meta.url, () => classObjects[hovered || crewmate?.Crewmate?.class], [hovered, crewmate?.Crewmate?.class]) return ( @@ -787,7 +787,7 @@ const ClassSelector = ({ classObjects, crewmate, onUpdateClass, onClose }) => { const TraitSelector = ({ crewmate, currentTraits, onUpdateTraits, onClose, traitIndex }) => { const changeTrait = currentTraits[traitIndex]; const priorTraits = currentTraits.slice(0, traitIndex).map((t) => t.id); - const options = useMemo(() => { + const options = useMemo(import.meta.url, () => { return Crewmate.nextTraits( crewmate.Crewmate.coll, crewmate.Crewmate.class, @@ -797,11 +797,11 @@ const TraitSelector = ({ crewmate, currentTraits, onUpdateTraits, onClose, trait const [hovered, setHovered] = useState(); - const onSelect = useCallback((newTrait) => { + const onSelect = useCallback(import.meta.url, (newTrait) => { onUpdateTraits(changeTrait?.id === newTrait ? currentTraits.map((t) => t.id) : [...priorTraits, newTrait]); }, [changeTrait, priorTraits]); - const traitDisplay = useMemo(() => Crewmate.TRAITS[hovered || changeTrait?.id], [hovered, changeTrait]) + const traitDisplay = useMemo(import.meta.url, () => Crewmate.TRAITS[hovered || changeTrait?.id], [hovered, changeTrait]) return ( @@ -870,18 +870,18 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c const [finalizing, setFinalizing] = useState(); const [name, setName] = useState(''); - const mappedCrewmate = useMemo(() => crewmateMap?.[crewmateId] || null, [crewmateMap, crewmateId]); + const mappedCrewmate = useMemo(import.meta.url, () => crewmateMap?.[crewmateId] || null, [crewmateMap, crewmateId]); - const finalized = useMemo(() => mappedCrewmate?.Crewmate?.status > 0, [mappedCrewmate]); + const finalized = useMemo(import.meta.url, () => mappedCrewmate?.Crewmate?.status > 0, [mappedCrewmate]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!bookSession && !pendingCrewmate && !mappedCrewmate) { history.push(onCloseDestination); } }, [bookSession, pendingCrewmate, mappedCrewmate]); // derive crewmate-structured crewmate based on selections - const crewmate = useMemo(() => { + const crewmate = useMemo(import.meta.url, () => { // if already finalized, return final version if (finalized) return mappedCrewmate; @@ -995,21 +995,21 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c bookSession ]); - const traitTally = useMemo(() => { + const traitTally = useMemo(import.meta.url, () => { if (crewmate?.Crewmate?.coll === Crewmate.COLLECTION_IDS.ADALIAN) return 4; if (crewmate?.Crewmate?.coll) return 8; return 0; }, [crewmate?.Crewmate?.coll]); - useEffect(() => { + useEffect(import.meta.url, () => { if (isPurchasingPack) setPackPromptDismissed(true); }, [isPurchasingPack]); - const isPackPurchaseIsProcessing = useMemo(() => { + const isPackPurchaseIsProcessing = useMemo(import.meta.url, () => { return !!(pendingTransactions || []).find(tx => tx.key === 'PurchaseStarterPack'); }, [pendingTransactions]); - const shouldPromptForPack = useMemo(() => { + const shouldPromptForPack = useMemo(import.meta.url, () => { // always show prompt while processing (so can see "loading") if (isPurchasingPack || isPackPurchaseIsProcessing) return true; @@ -1020,7 +1020,7 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c // init appearance options as desired const originalSimulationState = useStore(s => s.simulation); const [namePrepopped, setNamePrepopped] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { if (crewmate && safeBigInt(crewmate.Crewmate?.appearance) === 0n && appearanceOptions?.length === 0) { if (originalSimulationState?.crewmate?.appearance) { const { clothes, ...unpacked } = Crewmate.unpackAppearance(originalSimulationState?.crewmate?.appearance); @@ -1033,7 +1033,7 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c } }, [!!crewmate, appearanceOptions?.length, originalSimulationState]); - useEffect(() => { + useEffect(import.meta.url, () => { if (crewmate && !crewmate.Name?.name) { if (originalSimulationState?.crewmate?.name) { setName(originalSimulationState.crewmate.name); @@ -1045,12 +1045,12 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c }, [!!crewmate, originalSimulationState]); // handle finalizing - useEffect(() => { + useEffect(import.meta.url, () => { if (crewmate?._finalizing || crewmate?.Crewmate?.status > 0) setFinalizing(true); }, [crewmate?._finalizing, crewmate?.Crewmate?.status]); // handle finalized - useEffect(() => { + useEffect(import.meta.url, () => { if (finalized) { setFinalizing(false); @@ -1061,7 +1061,7 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c } }, [ crewmateId, finalized, mappedCrewmate ]); - // const shareOnTwitter = useCallback(() => { + // const shareOnTwitter = useCallback(import.meta.url, () => { // // TODO: ... // const params = new URLSearchParams({ // text: [ @@ -1076,30 +1076,30 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c // window.open(`https://twitter.com/intent/tweet?${params.toString()}`, '_blank'); // }, [account]); - // const handleFinish = useCallback(() => { + // const handleFinish = useCallback(import.meta.url, () => { // history.push(onCloseDestination); // }, [history]); - const handleNameChange = useCallback((newName) => { + const handleNameChange = useCallback(import.meta.url, (newName) => { setName(newName); }, []); - const rerollAppearance = useCallback(async () => { + const rerollAppearance = useCallback(import.meta.url, async () => { setAppearanceOptions((prevValue) => { setAppearanceSelection((prevValue || []).length); return [...(prevValue || []), getRandomAdalianAppearance()] }); }, []); - const rollBackAppearance = useCallback(() => { + const rollBackAppearance = useCallback(import.meta.url, () => { setAppearanceSelection(Math.max(0, appearanceSelection - 1)); }, [appearanceSelection]); - const rollForwardAppearance = useCallback(() => { + const rollForwardAppearance = useCallback(import.meta.url, () => { setAppearanceSelection(Math.min(appearanceOptions.length - 1, appearanceSelection + 1)); }, [appearanceOptions.length, appearanceSelection]); - const rerollTraits = useCallback(async () => { + const rerollTraits = useCallback(import.meta.url, async () => { const c = cloneDeep(crewmate); if (!c?.Crewmate?.coll) return; @@ -1124,7 +1124,7 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c setSelectedTraits(traits); }, [crewmate?.Crewmate?.class, selectedTraits, traitTally]); - const confirmFinalize = useCallback(async () => { + const confirmFinalize = useCallback(import.meta.url, async () => { if (simulationEnabled) { dispatchSimulationState('crewmate', { id: SIMULATION_CONFIG.crewmateId, name, appearance: crewmate?.Crewmate?.appearance }); history.push('/'); @@ -1138,17 +1138,17 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c } }, [isNameValid, name, crewmate?.id, crewmate?._canRename, crewmate?.Crewmate?.appearance, crewmate?.Name?.name, simulationEnabled]); - const finalize = useCallback(() => { + const finalize = useCallback(import.meta.url, () => { setConfirming(false); purchaseAndOrInitializeCrewmate({ crewmate }); }, [crewmate, purchaseAndOrInitializeCrewmate]); // eslint-disable-line react-hooks/exhaustive-deps - const handleBack = useCallback(() => { + const handleBack = useCallback(import.meta.url, () => { history.push(simulationEnabled ? '/' : backLocation); }, [backLocation, simulationEnabled]); // // show "complete" page (instead of "create") for non-recruitment assignments - // useEffect(() => { + // useEffect(import.meta.url, () => { // if (bookSession && !bookSession.isMintingStory) { // history.push(`/crew-assignment/${crewmateId}/complete`); // } @@ -1156,7 +1156,7 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c // place mouseovers after animation complete const [animationComplete, setAnimationComplete] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { if (!!crewmate) { const to = setTimeout(() => { setAnimationComplete(true); @@ -1167,7 +1167,7 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c } }, [!!crewmate]); - const onUpdateClass = useCallback((newClass) => { + const onUpdateClass = useCallback(import.meta.url, (newClass) => { if (selectedClass !== newClass) { setSelectedTraits([]); } @@ -1175,16 +1175,16 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c setToggling(); }, [selectedClass]); - const onUpdateTraits = useCallback((newTraits) => { + const onUpdateTraits = useCallback(import.meta.url, (newTraits) => { setSelectedTraits(newTraits); setToggling(); }, []); - const traitObjects = useMemo(() => { + const traitObjects = useMemo(import.meta.url, () => { return (selectedTraits || []).map((id) => ({ id, ...Crewmate.TRAITS[id] })); }, [selectedTraits]); - const classObjects = useMemo(() => { + const classObjects = useMemo(import.meta.url, () => { return Object.values(Crewmate.CLASS_IDS).reduce((acc, id) => ({ ...acc, [id]: { @@ -1197,7 +1197,7 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c }), {}); }, []); - const recruitTally = useMemo(() => { + const recruitTally = useMemo(import.meta.url, () => { if (crewmate?.Crewmate?.coll === Crewmate.COLLECTION_IDS.ADALIAN) return adalianRecruits?.length || 0; return 0; }, [adalianRecruits, crewmate?.Crewmate?.coll]); @@ -1206,7 +1206,7 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c const [checkingName, setCheckingName] = useState(false); const [nameError, setNameError] = useState(null); - useEffect(() => { + useEffect(import.meta.url, () => { if (!crewmate?._canRename) return; // only check for name validity if can rename setNameError(''); @@ -1229,7 +1229,7 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c } }, [name, crewmate?.id, crewmate?._canRename, isNameValid]); - const readyForSubmission = useMemo(() => { + const readyForSubmission = useMemo(import.meta.url, () => { if (!name) return false; if (simulationEnabled) return true; if (!selectedClass) return false; @@ -1237,7 +1237,7 @@ const CrewAssignmentCreate = ({ backLocation, bookSession, coverImage, crewId, c return true; }, [name, selectedClass, selectedTraits?.length, traitTally, simulationEnabled]); - const confirmationProps = useMemo(() => { + const confirmationProps = useMemo(import.meta.url, () => { if (crewmate?.id) { return { onConfirm: finalize, @@ -1678,17 +1678,17 @@ const Wrapper = ({ backLocation, crewId, crewmateId, locationId }) => { const dispatchCrewAssignmentRestart = useStore((s) => s.dispatchCrewAssignmentRestart); - const coverImage = useMemo(() => getBookCompletionImage(book), [book]); + const coverImage = useMemo(import.meta.url, () => getBookCompletionImage(book), [book]); // for recruit of crewmateId 0, things get weird when completed const finalizing = useRef(); - const pendingCrewmate = useMemo(() => getPendingCrewmate(), [getPendingCrewmate]); - useEffect(() => { + const pendingCrewmate = useMemo(import.meta.url, () => getPendingCrewmate(), [getPendingCrewmate]); + useEffect(import.meta.url, () => { if (pendingCrewmate) finalizing.current = true; // TODO (enhancement): set a timeout? what if crewmateMap is already updated? }, [ pendingCrewmate ]); - useEffect(() => { + useEffect(import.meta.url, () => { if (finalizing.current) { if (crewId === 0 || crewmateId === 0) { if (crews && crewmateMap) { diff --git a/src/game/interface/details/listViews/actionItems.js b/src/game/interface/details/listViews/actionItems.js index e1ccfcf0f..82838c6f3 100644 --- a/src/game/interface/details/listViews/actionItems.js +++ b/src/game/interface/details/listViews/actionItems.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Lot } from '@influenceth/sdk'; @@ -48,7 +48,7 @@ const useColumns = () => { const { accountAddress } = useSession(); const { crew } = useCrewContext(); - return useMemo(() => { + return useMemo(import.meta.url, () => { const columns = [ { key: 'icon', diff --git a/src/game/interface/details/listViews/agreements.js b/src/game/interface/details/listViews/agreements.js index a59f33121..62447c2ba 100644 --- a/src/game/interface/details/listViews/agreements.js +++ b/src/game/interface/details/listViews/agreements.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import theme from '~/theme'; import styled from 'styled-components'; import { Entity, Permission } from '@influenceth/sdk'; @@ -66,7 +66,7 @@ const My = styled.span` const Progress = ({ start, finish, overrideColor }) => { const blockTime = useBlockTime(); - const [progress, timeRemaining] = useMemo(() => ([ + const [progress, timeRemaining] = useMemo(import.meta.url, () => ([ 100 * (Date.now() / 1000 - start) / (finish - start), formatTimer(finish - (Date.now() / 1000), 2) ]), [blockTime, start, finish]) @@ -85,7 +85,7 @@ const useColumns = () => { const { props: actionProps } = useActionButtons(); const blockTime = useBlockTime(); - return useMemo(() => { + return useMemo(import.meta.url, () => { const columns = [ { key: 'expandedIcon', diff --git a/src/game/interface/details/listViews/asteroids.js b/src/game/interface/details/listViews/asteroids.js index 1f0e59fb4..501cec16e 100644 --- a/src/game/interface/details/listViews/asteroids.js +++ b/src/game/interface/details/listViews/asteroids.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Address, Asteroid } from '@influenceth/sdk'; import { constants } from '@influenceth/astro'; @@ -47,7 +47,7 @@ const useColumns = () => { const watchAsteroid = useWatchAsteroid(); const unWatchAsteroid = useUnWatchAsteroid(); - const toggleWatchlist = useCallback((id) => () => { + const toggleWatchlist = useCallback(import.meta.url, (id) => () => { if (watchlistIds.includes(id)) { unWatchAsteroid.mutate(id); } else { @@ -55,7 +55,7 @@ const useColumns = () => { } }, [watchlistIds]); - return useMemo(() => { + return useMemo(import.meta.url, () => { const columns = [ { key: 'my', diff --git a/src/game/interface/details/listViews/buildings.js b/src/game/interface/details/listViews/buildings.js index e1b7f7bc1..c06fb67c8 100644 --- a/src/game/interface/details/listViews/buildings.js +++ b/src/game/interface/details/listViews/buildings.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid, Building, Lot, Permission } from '@influenceth/sdk'; @@ -47,7 +47,7 @@ const useColumns = () => { const blockTime = useBlockTime(); const { crew } = useCrewContext(); - return useMemo(() => { + return useMemo(import.meta.url, () => { const columns = [ { // TODO: implement this per agreements/ownership key: 'my', diff --git a/src/game/interface/details/listViews/coreSamples.js b/src/game/interface/details/listViews/coreSamples.js index add49395a..05972123b 100644 --- a/src/game/interface/details/listViews/coreSamples.js +++ b/src/game/interface/details/listViews/coreSamples.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Entity, Lot, Product } from '@influenceth/sdk'; import { MyAssetIcon } from '~/components/Icons'; @@ -11,7 +11,7 @@ const useColumns = () => { const { accountAddress } = useSession(); const { crew } = useCrewContext(); - return useMemo(() => { + return useMemo(import.meta.url, () => { const columns = [ { key: 'my', diff --git a/src/game/interface/details/listViews/crewmates.js b/src/game/interface/details/listViews/crewmates.js index 4eebdbe2f..34b39cd82 100644 --- a/src/game/interface/details/listViews/crewmates.js +++ b/src/game/interface/details/listViews/crewmates.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Address, Crewmate } from '@influenceth/sdk'; import { @@ -16,7 +16,7 @@ const useColumns = () => { const { accountAddress } = useSession(); const { crewmateMap } = useCrewContext(); - return useMemo(() => { + return useMemo(import.meta.url, () => { const columns = [ { key: 'my', diff --git a/src/game/interface/details/listViews/crews.js b/src/game/interface/details/listViews/crews.js index 0080ef45c..e9e2b4d02 100644 --- a/src/game/interface/details/listViews/crews.js +++ b/src/game/interface/details/listViews/crews.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Address } from '@influenceth/sdk'; import { MyAssetIcon } from '~/components/Icons'; @@ -11,7 +11,7 @@ import formatters from '~/lib/formatters'; const useColumns = () => { const { accountAddress } = useSession(); - return useMemo(() => { + return useMemo(import.meta.url, () => { const columns = [ { key: 'my', diff --git a/src/game/interface/details/listViews/events.js b/src/game/interface/details/listViews/events.js index c94482248..ebe571bab 100644 --- a/src/game/interface/details/listViews/events.js +++ b/src/game/interface/details/listViews/events.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import moment from 'moment'; @@ -36,7 +36,7 @@ const useColumns = () => { const { accountAddress } = useSession(); const { crew } = useCrewContext(); - return useMemo(() => { + return useMemo(import.meta.url, () => { const columns = [ { key: 'icon', diff --git a/src/game/interface/details/listViews/ships.js b/src/game/interface/details/listViews/ships.js index 0c2a5bcef..5596a437a 100644 --- a/src/game/interface/details/listViews/ships.js +++ b/src/game/interface/details/listViews/ships.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Entity, Lot, Ship } from '@influenceth/sdk'; import { MyAssetIcon, SwayIcon } from '~/components/Icons'; @@ -24,7 +24,7 @@ const useColumns = () => { const { accountAddress } = useSession(); const { crew } = useCrewContext(); - return useMemo(() => { + return useMemo(import.meta.url, () => { const columns = [ { // TODO: implement this per agreements/ownership key: 'my', diff --git a/src/game/interface/details/marketplace/AsteroidResourcePrices.js b/src/game/interface/details/marketplace/AsteroidResourcePrices.js index 3b53fdf88..09196641f 100644 --- a/src/game/interface/details/marketplace/AsteroidResourcePrices.js +++ b/src/game/interface/details/marketplace/AsteroidResourcePrices.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import { useHistory } from 'react-router-dom'; import styled from 'styled-components'; import { Asteroid, Entity, Lot, Permission } from '@influenceth/sdk'; @@ -178,10 +178,10 @@ const AsteroidResourcePrices = ({ asteroid, mode, resource }) => { const { data: orderSummary } = useOrderSummaryByExchange(asteroid.id, resource.i); - const marketPlaceIds = useMemo(() => Array.from(new Set((orderSummary || []).map((o) => o.marketplace.id))), [orderSummary]); + const marketPlaceIds = useMemo(import.meta.url, () => Array.from(new Set((orderSummary || []).map((o) => o.marketplace.id))), [orderSummary]); const { data: resourceMarketplaceEntities, isLoading: marketplacesLoading } = useEntities({ ids: marketPlaceIds, label: Entity.IDS.BUILDING }); - const isPermitted = useCallback(({ exchange, mode, type, isCancellation }) => { + const isPermitted = useCallback(import.meta.url, ({ exchange, mode, type, isCancellation }) => { if (isCancellation) return true; let perm = 0; @@ -192,7 +192,7 @@ const AsteroidResourcePrices = ({ asteroid, mode, resource }) => { return crewCan(perm, exchange); }, [crewCan]); - const resourceMarketplaces = useMemo(() => { + const resourceMarketplaces = useMemo(import.meta.url, () => { if (!orderSummary) return []; const transformedOrders = orderSummary.map((o) => { const exchange = resourceMarketplaceEntities?.find((mp) => mp.id === o.marketplace.id); @@ -244,11 +244,11 @@ const AsteroidResourcePrices = ({ asteroid, mode, resource }) => { return transformedOrders; }, [asteroid.id, coachmarkHelperProduct, crew, orderSummary, simulationEnabled, simulationActions, resourceMarketplaceEntities]); - const selectedSupply = useMemo(() => { + const selectedSupply = useMemo(import.meta.url, () => { return resourceMarketplaces.find((m) => m.lotId === selected)?.supply || 0; }, [selected]); - const handleSort = useCallback((field) => () => { + const handleSort = useCallback(import.meta.url, (field) => () => { if (!field) return; let updatedSortField = sortField; @@ -267,7 +267,7 @@ const AsteroidResourcePrices = ({ asteroid, mode, resource }) => { ]); }, [sortDirection, sortField]); - const sortedMarketplaces = useMemo(() => { + const sortedMarketplaces = useMemo(import.meta.url, () => { const fieldSortOrder = (a, b) => { if (a[sortField] < b[sortField]) { return sortDirection === 'asc' ? -1 : 1; @@ -294,7 +294,7 @@ const AsteroidResourcePrices = ({ asteroid, mode, resource }) => { }); }, [resourceMarketplaces, sortField, sortDirection]); - const columns = useMemo(() => { + const columns = useMemo(import.meta.url, () => { const c = [ { key: 'marketplaceName', @@ -446,7 +446,7 @@ const AsteroidResourcePrices = ({ asteroid, mode, resource }) => { return c; }, [asteroid, crew, marketplacesLoading, resource]); - const getRowProps = useCallback((row) => { + const getRowProps = useCallback(import.meta.url, (row) => { return { onClick: () => { setSelected(row.lotId); @@ -455,11 +455,11 @@ const AsteroidResourcePrices = ({ asteroid, mode, resource }) => { } }, [selected]); - const onViewMarketplace = useCallback(() => { + const onViewMarketplace = useCallback(import.meta.url, () => { history.push(`/marketplace/${asteroid.id}/${Lot.toIndex(selected)}/${resource.i}?back=all`); }, [asteroid, resource, selected]); - const [ totalSupply, totalDemand, medianPrice ] = useMemo(() => { + const [ totalSupply, totalDemand, medianPrice ] = useMemo(import.meta.url, () => { let s = 0, d = 0, m = 0; if (resourceMarketplaces.length > 0) { resourceMarketplaces.forEach((m) => { diff --git a/src/game/interface/details/marketplace/DepthChart.js b/src/game/interface/details/marketplace/DepthChart.js index a355621ab..a12426711 100644 --- a/src/game/interface/details/marketplace/DepthChart.js +++ b/src/game/interface/details/marketplace/DepthChart.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { useHistory, useLocation } from 'react-router-dom'; import styled from 'styled-components'; import { Building, Crewmate, Entity, Lot, Order, Permission, Product } from '@influenceth/sdk'; @@ -366,7 +366,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) const history = useHistory(); const { search } = useLocation(); - const urlMode = useMemo(() => { + const urlMode = useMemo(import.meta.url, () => { const q = new URLSearchParams(search); return q.get('mode'); }, [search]); @@ -376,7 +376,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) const simulationEnabled = useSimulationEnabled(); const setCoachmarkRef = useCoachmarkRefSetter(); - const setCoachmarkHelperRef = useMemo(() => setCoachmarkRef(COACHMARK_IDS.asteroidMarketsHelper), [setCoachmarkRef]); + const setCoachmarkHelperRef = useMemo(import.meta.url, () => setCoachmarkRef(COACHMARK_IDS.asteroidMarketsHelper), [setCoachmarkRef]); const actionDialog = useStore(s => s.actionDialog); const coachmarkHelperProduct = useStore(s => s.coachmarks?.[COACHMARK_IDS.asteroidMarketsHelper]); @@ -387,7 +387,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) const { getPendingOrder } = useMarketplaceManager(marketplace?.id); - const [buyOrders, sellOrders, bid, ask] = useMemo(() => { + const [buyOrders, sellOrders, bid, ask] = useMemo(import.meta.url, () => { const buys = (orders || []).filter((o) => o.orderType === Order.IDS.LIMIT_BUY); const sells = (orders || []).filter((o) => o.orderType === Order.IDS.LIMIT_SELL); const highestBuy = Math.max(...buys.map(b => b.price)); @@ -395,7 +395,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) return [buys, sells, highestBuy, lowestSell]; }, [orders]); - const buyBuckets = useMemo(() => { + const buyBuckets = useMemo(import.meta.url, () => { const buckets = buyOrders.reduce((acc, { price, amount }) => ({ ...acc, [price]: (acc[price] || 0) + amount @@ -405,7 +405,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) .sort((a, b) => a.price > b.price ? -1 : 1); }, [buyOrders]); - const sellBuckets = useMemo(() => { + const sellBuckets = useMemo(import.meta.url, () => { const buckets = sellOrders.reduce((acc, { price, amount }) => ({ ...acc, [price]: (acc[price] || 0) + amount @@ -421,14 +421,14 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) // make sure render again once chartWrapperRef is ready const [refIsReady, setRefIsReady] = useState(); - const checkRefIsReady = useCallback(() => { + const checkRefIsReady = useCallback(import.meta.url, () => { if (chartWrapperRef.current.clientWidth > 0) { setRefIsReady(true); } else if (!refIsReady) { setTimeout(checkRefIsReady, 50); } }, [refIsReady]); - useEffect(checkRefIsReady, []); + useEffect(import.meta.url, checkRefIsReady, []); const { xViewbox, @@ -441,7 +441,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) centerPrice, totalBuying, totalSelling - } = useMemo(() => { + } = useMemo(import.meta.url, () => { if (!chartWrapperRef.current) return {}; if (!(buyBuckets?.length > 0 || sellBuckets?.length > 0)) return {}; @@ -529,7 +529,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) }, [refIsReady, buyBuckets, sellBuckets, height, width]); // if nothing available for market order, default to limit - useEffect(() => { + useEffect(import.meta.url, () => { if (type === 'market' && mode === 'buy' && totalSelling === 0) setType('limit'); }, [mode, totalBuying, totalSelling]); @@ -538,22 +538,22 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) let volumeBenchmark = Math.max(totalBuying, totalSelling); // TODO: re-release sdk and reference there - const feeReductionBonus = useMemo(() => { + const feeReductionBonus = useMemo(import.meta.url, () => { if (!crew) return {}; return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.MARKETPLACE_FEE_REDUCTION, crew); }, [crew]); - const feeEnforcementBonus = useMemo(() => { + const feeEnforcementBonus = useMemo(import.meta.url, () => { if (!marketplaceOwner) return {}; return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.MARKETPLACE_FEE_ENFORCEMENT, marketplaceOwner) || {}; }, [marketplaceOwner]); - const baseMarketplaceFee = useMemo( + const baseMarketplaceFee = useMemo(import.meta.url, () => marketplace?.Exchange?.[type === 'market' ? 'takerFee' : 'makerFee'], [marketplace, type] ); - const marketplaceFee = useMemo(() => { + const marketplaceFee = useMemo(import.meta.url, () => { const adjusted = Order.adjustedFee(baseMarketplaceFee, feeReductionBonus.totalBonus, feeEnforcementBonus.totalBonus); return adjusted; }, [baseMarketplaceFee, feeReductionBonus, feeEnforcementBonus]); @@ -561,11 +561,11 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) const [quantity, setQuantity] = useState(); const [limitPrice, setLimitPrice] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { setLimitPrice(0); }, [mode, type]); - const createOrder = useCallback(() => { + const createOrder = useCallback(import.meta.url, () => { onSetAction('MARKETPLACE_ORDER', { asteroidId: lot?.asteroid, lotId: lot?.id, @@ -576,7 +576,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) }); }, [limitPrice, lot, mode, quantity, resource, type]); - const handleChangeQuantity = useCallback((e) => { + const handleChangeQuantity = useCallback(import.meta.url, (e) => { let input = parseInt(e.currentTarget.value) || 0; if (input && type === 'market') { if (mode === 'buy') input = Math.max(0, Math.min(input, totalSelling)); @@ -586,7 +586,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) setQuantity(input); }, [mode, type, totalBuying, totalSelling]); - const handleChangeLimitPrice = useCallback((price, blur = false) => { + const handleChangeLimitPrice = useCallback(import.meta.url, (price, blur = false) => { if (blur) { if ((mode === 'buy' && price >= ask) || (mode === 'sell' && price <= bid)) { setType('market'); @@ -598,7 +598,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) }, [bid, ask, mode]); // TODO: is quantity right here for non-atomic? - const [totalMarketPrice, avgMarketPrice] = useMemo(() => { + const [totalMarketPrice, avgMarketPrice] = useMemo(import.meta.url, () => { let total = 0; let needed = quantity; const priceSortMult = mode === 'buy' ? 1 : -1; @@ -613,26 +613,26 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) return [total, total / quantity]; }, [buyOrders, mode, quantity, sellOrders]); - const totalLimitPrice = useMemo(() => { + const totalLimitPrice = useMemo(import.meta.url, () => { return (limitPrice || 0) * quantity; }, [limitPrice, quantity]); - const fee = useMemo(() => { + const fee = useMemo(import.meta.url, () => { return (type === 'market' ? totalMarketPrice : totalLimitPrice) * marketplaceFee / Order.FEE_SCALE; }, [marketplaceFee, totalMarketPrice, totalLimitPrice, type]); - const total = useMemo(() => { + const total = useMemo(import.meta.url, () => { let sum = type === 'limit' ? totalLimitPrice : totalMarketPrice; return sum + (mode === 'buy' ? fee : -fee); }, [fee, mode, totalLimitPrice, totalMarketPrice, type]); - const loading = useMemo( + const loading = useMemo(import.meta.url, () => getPendingOrder(mode, type, { product: resource.i, exchange: marketplace }), [mode, type, resource, marketplace, getPendingOrder] ); - const sameAsteroid = useMemo(() => { + const sameAsteroid = useMemo(import.meta.url, () => { if (marketplace?.Location?.locations) { return !!marketplace?.Location?.locations.find((l) => { return l.id === crew?._location?.asteroidId && l.label === Entity.IDS.ASTEROID; @@ -642,7 +642,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) return false; }, [crew, marketplace]); - const hasPermission = useMemo(() => { + const hasPermission = useMemo(import.meta.url, () => { let perm = 0; if (type === 'limit' && mode === 'buy') perm = Permission.IDS.LIMIT_BUY; if (type === 'limit' && mode === 'sell') perm = Permission.IDS.LIMIT_SELL; @@ -651,7 +651,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) return crewCan(perm, marketplace); }, [crewCan, mode, type]); - const [coachToBuy, coachToSell, coachToLimit, coachToMarket, coachToQuantity, coachToUnitPrice, coachToButton] = useMemo(() => { + const [coachToBuy, coachToSell, coachToLimit, coachToMarket, coachToQuantity, coachToUnitPrice, coachToButton] = useMemo(import.meta.url, () => { let disable = (coachmarkHelperProduct !== resource.i) || !!actionDialog?.type; const toBuy = !disable && mode === 'sell' && !(simulationActions.includes('MarketSell') || simulationActions.includes('LimitSell')); @@ -680,7 +680,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) }, [actionDialog?.type, coachmarkHelperProduct, limitPrice, mode, quantity, resource.i, simulationActions, total, type]); const simulation = useSimulationState(); - const handleQuantityFocus = useCallback((e) => { + const handleQuantityFocus = useCallback(import.meta.url, (e) => { if (coachToQuantity && !quantity) { let q = ''; if (SIMULATION_CONFIG.marketplaceAmounts[coachmarkHelperProduct] === true) { @@ -693,7 +693,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) } }, [coachToQuantity, quantity, simulation]); - const handleLimitPriceFocus = useCallback((e) => { + const handleLimitPriceFocus = useCallback(import.meta.url, (e) => { if (coachToUnitPrice && !limitPrice) { let p = 1; if (sellBuckets?.length) { @@ -705,7 +705,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) } }, [coachToUnitPrice, limitPrice]); - const actionButtonDetails = useMemo(() => { + const actionButtonDetails = useMemo(import.meta.url, () => { const a = { label: '', icon: null }; if (type === 'limit') { @@ -741,7 +741,7 @@ const MarketplaceDepthChart = ({ lot, marketplace, marketplaceOwner, resource }) return a; }, [crew, loading, hasPermission, mode, sameAsteroid, simulationActions, simulationEnabled, total, type]); - const goToListings = useCallback(() => { + const goToListings = useCallback(import.meta.url, () => { const { asteroidId, lotIndex } = Lot.toPosition(lot?.id) || {}; history.push(`/marketplace/${asteroidId}/${lotIndex}`); }, [lot]); diff --git a/src/game/interface/details/marketplace/Home.js b/src/game/interface/details/marketplace/Home.js index 9d3611d8d..6176f4f9a 100644 --- a/src/game/interface/details/marketplace/Home.js +++ b/src/game/interface/details/marketplace/Home.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import Ticker from 'react-ticker'; import { Product } from '@influenceth/sdk'; @@ -294,18 +294,18 @@ const MarketplaceHome = ({ asteroid, listings, mode, setMode, orderTally, onSele const setCoachmarkRef = useCoachmarkRefSetter(); const coachmarkHelperProduct = useStore(s => s.coachmarks?.[COACHMARK_IDS.asteroidMarketsHelper]); - const setCoachmarkHelperRef = useMemo(() => setCoachmarkRef(COACHMARK_IDS.asteroidMarketsHelper), [setCoachmarkRef]); + const setCoachmarkHelperRef = useMemo(import.meta.url, () => setCoachmarkRef(COACHMARK_IDS.asteroidMarketsHelper), [setCoachmarkRef]); const options = [ { value: 'liquidity', label: 'Liquidity' }, { value: 'alphabetical', label: 'Alphabetical'} ]; - const tickerEnabled = useMemo(() => { + const tickerEnabled = useMemo(import.meta.url, () => { return !marketplace; }, [!!marketplace]); - const tickerListings = useMemo(() => { + const tickerListings = useMemo(import.meta.url, () => { if (!tickerEnabled) return []; return listings @@ -319,7 +319,7 @@ const MarketplaceHome = ({ asteroid, listings, mode, setMode, orderTally, onSele .slice(0, 10); }, [tickerEnabled, listings, mode]); - const [ filteredCount, filteredListings ] = useMemo(() => { + const [ filteredCount, filteredListings ] = useMemo(import.meta.url, () => { const filtered = listings .filter(({ product }) => { return nameFilter.length === 0 || @@ -335,7 +335,7 @@ const MarketplaceHome = ({ asteroid, listings, mode, setMode, orderTally, onSele // unclear why this is required, but if no timeout, then ticker just renders a "0" const [tickerReady, setTickerReady] = useState(false); - useEffect(() => { + useEffect(import.meta.url, () => { if (!!tickerListings?.length) { setTimeout(() => { setTickerReady(true); @@ -343,11 +343,11 @@ const MarketplaceHome = ({ asteroid, listings, mode, setMode, orderTally, onSele } }, [!!tickerListings?.length]); - const coachmarkHelperProductIsOnPage = useMemo(() => { + const coachmarkHelperProductIsOnPage = useMemo(import.meta.url, () => { return !!filteredListings.find((l) => l.product === coachmarkHelperProduct); }, [coachmarkHelperProduct, filteredListings]); - const handleNameFilterFocus = useCallback((e) => { + const handleNameFilterFocus = useCallback(import.meta.url, (e) => { if (coachmarkHelperProduct && !coachmarkHelperProductIsOnPage && !nameFilter) { setNameFilter(`${(Product.TYPES[coachmarkHelperProduct].name || '').toLowerCase()}`); } diff --git a/src/game/interface/details/marketplace/OpenOrders.js b/src/game/interface/details/marketplace/OpenOrders.js index 7d1f9ab5a..807fdeacc 100644 --- a/src/game/interface/details/marketplace/OpenOrders.js +++ b/src/game/interface/details/marketplace/OpenOrders.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import moment from 'moment'; import { Lot, Order, Product } from '@influenceth/sdk'; @@ -95,7 +95,7 @@ const MarketplaceOpenOrders = ({ asteroid, orders, marketplace = null, marketpla const onSetAction = useStore(s => s.dispatchActionDialog); const simulationEnabled = useSimulationEnabled(); - const onCancelOrder = useCallback((order) => { + const onCancelOrder = useCallback(import.meta.url, (order) => { onSetAction('MARKETPLACE_ORDER', { exchange: order?.marketplace, asteroidId: asteroid?.id, @@ -115,7 +115,7 @@ const MarketplaceOpenOrders = ({ asteroid, orders, marketplace = null, marketpla }); }, []); - const handleSort = useCallback((field) => () => { + const handleSort = useCallback(import.meta.url, (field) => () => { if (!field) return; let updatedSortField = sortField; @@ -133,7 +133,7 @@ const MarketplaceOpenOrders = ({ asteroid, orders, marketplace = null, marketpla ]); }, [sortDirection, sortField]); - const sortedOrders = useMemo(() => { + const sortedOrders = useMemo(import.meta.url, () => { return (orders || []) .map((o) => ({ ...o, @@ -161,7 +161,7 @@ const MarketplaceOpenOrders = ({ asteroid, orders, marketplace = null, marketpla ); } - const columns = useMemo(() => { + const columns = useMemo(import.meta.url, () => { const c = [ { key: 'orderType', diff --git a/src/game/interface/hud/ActionDialog.js b/src/game/interface/hud/ActionDialog.js index c136ee5fc..1a1a05718 100644 --- a/src/game/interface/hud/ActionDialog.js +++ b/src/game/interface/hud/ActionDialog.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo } from 'react'; +import { useEffect, useMemo } from '~/lib/react-debug'; import styled, { keyframes } from 'styled-components'; import { PuffLoader } from 'react-spinners'; import { Tooltip } from 'react-tooltip'; @@ -153,13 +153,13 @@ theming[actionStage.COMPLETED].label = 'Results'; export const useAsteroidAndLot = (props = {}) => { const lotId = useStore(s => props.lotId || s.asteroids.lot); - const lotAsteroidId = useMemo(() => Lot.toPosition(lotId)?.asteroidId, [lotId]); + const lotAsteroidId = useMemo(import.meta.url, () => Lot.toPosition(lotId)?.asteroidId, [lotId]); const { data: asteroid, isLoading: asteroidIsLoading } = useAsteroid(props.asteroidId || lotAsteroidId); const { data: lot, isLoading: lotIsLoading } = useLot(lotId); // close dialog if cannot load asteroid and lot - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot) { if (!asteroidIsLoading && !lotIsLoading) { if (props.onClose) props.onClose(); @@ -215,13 +215,13 @@ export const ActionDialogInner = ({ actionImage, children, isLoading, stage }) = const ActionDialog = ({ type, params }) => { const setAction = useStore(s => s.dispatchActionDialog); - const allProps = useMemo(() => ({ + const allProps = useMemo(import.meta.url, () => ({ ...params, onSetAction: setAction, onClose: () => setAction(), }), [params, setAction]); - useEffect(() => { + useEffect(import.meta.url, () => { const onKeyUp = (e) => { if (e.key === 'Escape') setAction(); }; diff --git a/src/game/interface/hud/ActionItem.js b/src/game/interface/hud/ActionItem.js index 9743c1963..eb2f775c8 100644 --- a/src/game/interface/hud/ActionItem.js +++ b/src/game/interface/hud/ActionItem.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { useHistory } from 'react-router-dom'; import styled, { css, keyframes } from 'styled-components'; import BarLoader from 'react-spinners/BarLoader'; @@ -215,7 +215,7 @@ const ActionItem = ({ data, getActivityConfig }) => { const type = data?.type; // TODO: can probably clean up the `formatted` structure - const item = useMemo(() => { + const item = useMemo(import.meta.url, () => { return formatActionItem( data, !['randomEvent', 'plan', 'agreement', 'pending'].includes(data.type) ? getActivityConfig(data)?.actionItem : {} @@ -231,7 +231,7 @@ const ActionItem = ({ data, getActivityConfig }) => { resourceId: resourceMap?.active ? item.resourceId : undefined, // only open resourcemap if a resourcemap is open }); - const onClick = useCallback(() => { + const onClick = useCallback(import.meta.url, () => { if (item.asteroidId) { goToAction(); } @@ -280,13 +280,13 @@ const ActionItem = ({ data, getActivityConfig }) => { zoomStatus, ]); - const onDismiss = useCallback((e) => { + const onDismiss = useCallback(import.meta.url, (e) => { e.stopPropagation(); dismissFailedTx(item._timestamp); return false; }, [item]); - const handleToggleHide = useCallback((key) => (e) => { + const handleToggleHide = useCallback(import.meta.url, (key) => (e) => { e.stopPropagation(); dispatchToggleHideActionItem(key); }, []); diff --git a/src/game/interface/hud/ActionItems.js b/src/game/interface/hud/ActionItems.js index 7041d4752..4a4ffef69 100644 --- a/src/game/interface/hud/ActionItems.js +++ b/src/game/interface/hud/ActionItems.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useMemo, useState } from 'react'; +import { useCallback, useContext, useEffect, useMemo, useState } from '~/lib/react-debug'; import { Link } from 'react-router-dom'; import styled from 'styled-components'; @@ -295,7 +295,7 @@ const ActionItems = () => { const [confirmingTutorialDismissal, setConfirmingTutorialDismissal] = useState(); const [displayItems, setDisplayItems] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { if (displayItems) { // TODO: maybe this should show new ones while transitioning out old ones? // set to transition state @@ -320,24 +320,24 @@ const ActionItems = () => { const [selectedFilter, setSelectedFilter] = useState('all'); const [lastClick, setLastClick] = useState(); - const onClickFilter = useCallback((filter) => (e) => { + const onClickFilter = useCallback(import.meta.url, (filter) => (e) => { e.stopPropagation(); setSelectedFilter(filter); setLastClick(Date.now()); }, []); - const onUnhideAll = useCallback(() => { + const onUnhideAll = useCallback(import.meta.url, () => { dispatchUnhideAllActionItems(); setSelectedFilter('all'); setLastClick(Date.now()); }, []); - const isFinishingAll = useMemo( + const isFinishingAll = useMemo(import.meta.url, () => getStatus('FinishAllReady') === 'pending', [getStatus] ); - const autoFinishCalls = useMemo(() => { + const autoFinishCalls = useMemo(import.meta.url, () => { return allItems .map((a) => { if (a.type === 'ready') { @@ -351,12 +351,12 @@ const ActionItems = () => { .filter((a) => !!a); }, [allItems, crew, getActivityConfig]); - const onFinishAll = useCallback(() => { + const onFinishAll = useCallback(import.meta.url, () => { if (isFinishingAll) return; execute('FinishAllReady', { finishCalls: autoFinishCalls }); }, [autoFinishCalls, execute, isFinishingAll]); - const tallies = useMemo(() => { + const tallies = useMemo(import.meta.url, () => { return (displayItems || []).reduce( (acc, cur) => { if (!cur.hidden) { @@ -377,7 +377,7 @@ const ActionItems = () => { ) }, [displayItems]); - const filteredDisplayItems = useMemo(() => { + const filteredDisplayItems = useMemo(import.meta.url, () => { let filter; if (selectedFilter === 'all') filter = (i) => !i.hidden; if (selectedFilter === 'ready') filter = (i) => !i.hidden && ['failed', 'randomEvent', 'ready'].includes(i.type); @@ -387,7 +387,7 @@ const ActionItems = () => { return (displayItems || []).filter(filter); }, [displayItems, selectedFilter]); - const filteredDisplayCategories = useMemo(() => { + const filteredDisplayCategories = useMemo(import.meta.url, () => { const categorized = {}; filteredDisplayItems.forEach((i) => { if (!categorized[i.category]) { @@ -401,7 +401,7 @@ const ActionItems = () => { return Object.values(categorized); }, [filteredDisplayItems]); - const onConfirmTutorialDismissal = useCallback(() => { + const onConfirmTutorialDismissal = useCallback(import.meta.url, () => { dispatchDismissCrewTutorial(crew?.id, true); setConfirmingTutorialDismissal(); }, [crew?.id]); diff --git a/src/game/interface/hud/AvatarMenu.js b/src/game/interface/hud/AvatarMenu.js index 7abd51e78..26a7fa5ad 100644 --- a/src/game/interface/hud/AvatarMenu.js +++ b/src/game/interface/hud/AvatarMenu.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { useHistory } from 'react-router-dom'; import styled, { css, keyframes } from 'styled-components'; @@ -200,7 +200,7 @@ const AvatarMenu = () => { const [ffTarget, setFFTarget] = useState(); - const silhouetteOverlay = useMemo(() => { + const silhouetteOverlay = useMemo(import.meta.url, () => { if (!captain) { return { alwaysOn: ['icon'], @@ -214,7 +214,7 @@ const AvatarMenu = () => { return null; }, [captain]); - const onClick = useCallback((crewmateId) => () => { + const onClick = useCallback(import.meta.url, (crewmateId) => () => { if (simulation) { if (!crewmateId || (crewmateId === SIMULATION_CONFIG.crewmateId)) { // TODO: should/could link back to simulation crewmate @@ -228,7 +228,7 @@ const AvatarMenu = () => { return history.push('/crew'); }, [simulation, simulationActions]); - useEffect(() => { + useEffect(import.meta.url, () => { const { canFastForward, crewReadyAt, taskReadyAt } = simulation || {}; if (!ffTarget) { if (canFastForward && (crewReadyAt || taskReadyAt)) { diff --git a/src/game/interface/hud/HudMenu.js b/src/game/interface/hud/HudMenu.js index a0a99ecbb..d21a6b0c4 100644 --- a/src/game/interface/hud/HudMenu.js +++ b/src/game/interface/hud/HudMenu.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import { useHistory } from 'react-router-dom'; import { Tooltip } from 'react-tooltip'; import styled from 'styled-components'; @@ -281,7 +281,7 @@ const HudMenu = () => { const { data: asteroid } = useAsteroid(asteroidId); const { data: lot } = useLot(lotId); const { data: zoomShip } = useShip(zoomScene?.type === 'SHIP' && zoomScene.shipId); - const ship = useMemo(() => zoomScene?.type === 'SHIP' ? zoomShip : lot?.surfaceShip, [lot, zoomShip, zoomScene]); + const ship = useMemo(import.meta.url, () => zoomScene?.type === 'SHIP' ? zoomShip : lot?.surfaceShip, [lot, zoomShip, zoomScene]); const { data: marketplaces } = useAsteroidBuildings(asteroidId, 'Exchange'); const chatHistory = useStore(s => s.chatHistory); @@ -290,7 +290,7 @@ const HudMenu = () => { const [open, setOpen] = useState(); const [hidden, setHidden] = useState(); - const handleButtonClick = useCallback((selected, onOpen, hideInsteadOfClose) => { + const handleButtonClick = useCallback(import.meta.url, (selected, onOpen, hideInsteadOfClose) => { // clicking button of already-open --> close if (openHudMenu === selected) { @@ -318,7 +318,7 @@ const HudMenu = () => { setHidden(false); }, [open, openHudMenu]); - useEffect(() => { + useEffect(import.meta.url, () => { // TODO: refactor this now that organization changed... if (openHudMenu) { const category = openHudMenu.split('_').shift(); @@ -329,32 +329,32 @@ const HudMenu = () => { } }, [dispatchHudMenuOpened, zoomScene, zoomStatus]); - useEffect(() => { + useEffect(import.meta.url, () => { // if just zoomed in and resourcemap is active, then open asteroid resources if (zoomStatus === 'in' && !zoomScene && resourceMap.active) { dispatchHudMenuOpened('RESOURCES'); } }, [zoomStatus, zoomScene]) - useEffect(() => { + useEffect(import.meta.url, () => { setOpen(!!openHudMenu); }, [openHudMenu]); - const asteroidFilterTally = useMemo(() => { + const asteroidFilterTally = useMemo(import.meta.url, () => { return Object.keys(asteroidFilters || {}) .reduce((acc, fieldName) => acc + (isAssetSearchFilterMatchingDefault('asteroidsMapped', fieldName) ? 0 : 1), 0) }, [asteroidFilters]); - const lotFilterTally = useMemo(() => { + const lotFilterTally = useMemo(import.meta.url, () => { return Object.keys(lotFilters || {}) .reduce((acc, fieldName) => acc + (isAssetSearchFilterMatchingDefault('lotsMapped', fieldName) ? 0 : 1), 0) }, [lotFilters]); - const unreadChatTally = useMemo(() => { + const unreadChatTally = useMemo(import.meta.url, () => { return chatHistory.filter((c) => c.asteroidId === asteroidId && c.unread)?.length; }, [asteroidId, chatHistory]); - const [menuButtons, pageButtons] = useMemo(() => { + const [menuButtons, pageButtons] = useMemo(import.meta.url, () => { const menuButtons = []; const pageButtons = []; @@ -657,18 +657,18 @@ const HudMenu = () => { zoomScene ]); - const { label, onDetailClick, detailType, Component, componentProps, hideInsteadOfClose, noClose, noDetail } = useMemo(() => { + const { label, onDetailClick, detailType, Component, componentProps, hideInsteadOfClose, noClose, noDetail } = useMemo(import.meta.url, () => { return menuButtons.find((b) => b.key === openHudMenu) || {}; }, [menuButtons, openHudMenu]); - const [visibleMenuButtons, visibleUniversalButtons, visiblePageButtons] = useMemo(() => ([ + const [visibleMenuButtons, visibleUniversalButtons, visiblePageButtons] = useMemo(import.meta.url, () => ([ menuButtons.filter((b) => b.isVisible && !b.isUniversal && (!b.requireLogin || authenticated)), menuButtons.filter((b) => b.isVisible && b.isUniversal && (!b.requireLogin || authenticated)), pageButtons.filter((b) => b.isVisible && (!b.requireLogin || authenticated)), ]), [authenticated, menuButtons, pageButtons]); // if open hud menu is no longer visible (or if get logged out and "requireLogin" menu), close - useEffect(() => { + useEffect(import.meta.url, () => { if (openHudMenu) { const openMenuConfig = menuButtons.find((b) => b.key === openHudMenu); if (!openMenuConfig?.isVisible || (openMenuConfig?.requireLogin && !authenticated)) { diff --git a/src/game/interface/hud/InfoPane.js b/src/game/interface/hud/InfoPane.js index 740c67605..242638189 100644 --- a/src/game/interface/hud/InfoPane.js +++ b/src/game/interface/hud/InfoPane.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { useHistory } from 'react-router-dom'; import styled, { css, keyframes } from 'styled-components'; import { Asteroid, Building, Crewmate, Entity } from '@influenceth/sdk'; @@ -269,7 +269,7 @@ const CaptainCard = ({ crewId }) => { const simulation = useSimulationState(); // onclick should open up crew profile - const onClick = useCallback(() => { + const onClick = useCallback(import.meta.url, () => { if (!crewId) return; history.push(`/crew/${crewId}`); }, [crewId, !simulation]); @@ -363,7 +363,7 @@ const InfoPane = () => { const onMouseEvent = (e) => setHover(e.type === 'mouseenter'); - const onClickPane = useCallback(() => { + const onClickPane = useCallback(import.meta.url, () => { // open lot if (asteroidId && lotId && zoomStatus === 'in') { dispatchZoomScene({ type: 'LOT' }); @@ -378,7 +378,7 @@ const InfoPane = () => { } }, [asteroidId, lotId, zoomStatus, lot?.building]); - const onClosePane = useCallback((e) => { + const onClosePane = useCallback(import.meta.url, (e) => { e.stopPropagation(); // deselect lot @@ -394,7 +394,7 @@ const InfoPane = () => { }, [asteroidId, lotId, zoomStatus]); // Control sounds for buildings - useEffect(() => { + useEffect(import.meta.url, () => { let soundName; if (lot?.building) soundName = Building.TYPES[lot?.building?.Building?.buildingType]?.name?.toLowerCase(); @@ -410,7 +410,7 @@ const InfoPane = () => { } }, [lot?.building?.id, stopSound, playSound, currentSound]); - useEffect(() => { + useEffect(import.meta.url, () => { setHover(false); }, [asteroidId, lotId, zoomStatus, zoomScene]); @@ -422,7 +422,7 @@ const InfoPane = () => { hoverSubtitle, thumbnail, thumbVisible, - } = useMemo(() => { + } = useMemo(import.meta.url, () => { const pane = {}; if (zoomStatus === 'out' && zoomScene?.type === 'SHIP') { diff --git a/src/game/interface/hud/SceneBanner.js b/src/game/interface/hud/SceneBanner.js index fdad9054e..2e29adcb7 100644 --- a/src/game/interface/hud/SceneBanner.js +++ b/src/game/interface/hud/SceneBanner.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import useStore from '~/hooks/useStore'; import SearchAsteroidsBanner from './hudBanners/SearchAsteroidsBanner'; @@ -14,7 +14,7 @@ const SceneBanner = () => { const openHudMenu = useStore(s => s.openHudMenu); const isAssetSearchMatchingDefault = useStore(s => s.isAssetSearchMatchingDefault); - const { searchAsteroids, searchLots, travel } = useMemo(() => ({ + const { searchAsteroids, searchLots, travel } = useMemo(import.meta.url, () => ({ searchAsteroids: { enabled: zoomStatus === 'out', visible: openHudMenu === 'BELT_MAP_SEARCH' || !isAssetSearchMatchingDefault('asteroidsMapped') diff --git a/src/game/interface/hud/SystemControls.js b/src/game/interface/hud/SystemControls.js index d51cb11b9..13318ca9a 100644 --- a/src/game/interface/hud/SystemControls.js +++ b/src/game/interface/hud/SystemControls.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { FaCaretRight } from 'react-icons/fa'; @@ -164,20 +164,20 @@ const SystemControls = () => { const [showAuthedButton, setShowAuthedButton] = useState(!(authenticated && launcherPage)); - const totalRecruitCredits = useMemo(() => (adalianRecruits?.length + arvadianRecruits?.length), [adalianRecruits, arvadianRecruits]) + const totalRecruitCredits = useMemo(import.meta.url, () => (adalianRecruits?.length + arvadianRecruits?.length), [adalianRecruits, arvadianRecruits]) const formattedAccount = useAccountFormatted({ address: accountAddress, truncate: true, doNotReplaceYou: true }); - const onToggleLauncher = useCallback(() => { + const onToggleLauncher = useCallback(import.meta.url, () => { if (launcherPage) dispatchLauncherPage(); else dispatchLauncherPage('play'); }, [launcherPage]); // (just used for animation in/out of auth button) - useEffect(() => { + useEffect(import.meta.url, () => { setTimeout(() => { setShowAuthedButton(authenticated && launcherPage); }, 0); }, [authenticated, !launcherPage]); - const onCopyWalletAddress = useCallback(() => { + const onCopyWalletAddress = useCallback(import.meta.url, () => { try { navigator.clipboard.writeText(`${accountAddress}`); createAlert({ diff --git a/src/game/interface/hud/TutorialActionItems.js b/src/game/interface/hud/TutorialActionItems.js index e913fd440..849ed802d 100644 --- a/src/game/interface/hud/TutorialActionItems.js +++ b/src/game/interface/hud/TutorialActionItems.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useState } from '~/lib/react-debug'; import styled, { css, keyframes } from 'styled-components'; import { TutorialIcon } from '~/components/Icons'; @@ -96,7 +96,7 @@ const ActionItemRow = styled.div` const TutorialActionItems = ({ tutorialSteps }) => { const [selectedStep, setSelectedStep] = useState(); - const goToStep = useCallback((nextStep) => { + const goToStep = useCallback(import.meta.url, (nextStep) => { if (selectedStep) { setSelectedStep(); setTimeout(() => { @@ -107,7 +107,7 @@ const TutorialActionItems = ({ tutorialSteps }) => { } }, [selectedStep]); - useEffect(() => { + useEffect(import.meta.url, () => { let nextStep; // if steps changed... diff --git a/src/game/interface/hud/WelcomeSimulation.js b/src/game/interface/hud/WelcomeSimulation.js index 2d6c9e822..df31ab318 100644 --- a/src/game/interface/hud/WelcomeSimulation.js +++ b/src/game/interface/hud/WelcomeSimulation.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; import { createPortal } from 'react-dom'; import { useHistory } from 'react-router-dom'; import styled from 'styled-components'; @@ -109,12 +109,12 @@ const WelcomeSimulation = () => { const launcherPage = useStore(s => s.launcherPage); const openHudMenu = useStore(s => s.openHudMenu); const [locationPath, setLocationPath] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { // (returns unlisten, so can just return directly to useEffect) return history.listen((location) => setLocationPath(location.pathname)); }, [history]); - useEffect(() => { + useEffect(import.meta.url, () => { if (initialLoad.current) { initialLoad.current = false; } else if (canAutohide) { @@ -124,7 +124,7 @@ const WelcomeSimulation = () => { // we want to unhide the message on step change // then we want to hide it on first coachmark change for step (i.e. user has read and is now doing) - useEffect(() => { + useEffect(import.meta.url, () => { setIsHidden(false); setCanAutohide(false); setTimeout(() => { @@ -132,7 +132,7 @@ const WelcomeSimulation = () => { }, 1000); }, [currentStepIndex]); - const handleSkip = useCallback(() => { + const handleSkip = useCallback(import.meta.url, () => { fireTrackingEvent('simulation', { step: 'skip-to-login' }); // webWallet does not work from localhost... diff --git a/src/game/interface/hud/actionButtons/ActionButton.js b/src/game/interface/hud/actionButtons/ActionButton.js index cf7bd0dbd..910d48ec1 100644 --- a/src/game/interface/hud/actionButtons/ActionButton.js +++ b/src/game/interface/hud/actionButtons/ActionButton.js @@ -1,4 +1,4 @@ -import { forwardRef, useCallback, useMemo, useState } from 'react'; +import { forwardRef, useCallback, useMemo, useState } from '~/lib/react-debug'; import ReactDOMServer from 'react-dom/server'; import styled, { css, keyframes } from 'styled-components'; import { Permission } from '@influenceth/sdk'; @@ -346,7 +346,7 @@ const ActionButtonComponent = forwardRef(({ const [isHovering, setIsHovering] = useState(); - const [flags, labelAddendum] = useMemo(() => { + const [flags, labelAddendum] = useMemo(import.meta.url, () => { const f = rawFlags || {}; let l = rawLabelAddendum; if (!enablePrelaunch && !isLaunched) { @@ -356,11 +356,11 @@ const ActionButtonComponent = forwardRef(({ return [f, l]; }, [enablePrelaunch, isLaunched, rawFlags, rawLabelAddendum]); - const _onClick = useCallback(() => { + const _onClick = useCallback(import.meta.url, () => { if (!flags?.disabled && onClick) onClick(); }, [flags?.disabled, onClick]); - const handleHover = useCallback((e) => { + const handleHover = useCallback(import.meta.url, (e) => { if (e.type === 'mouseenter') setIsHovering(true); else if (e.type === 'mouseleave') { setTimeout(() => { @@ -369,7 +369,7 @@ const ActionButtonComponent = forwardRef(({ } }, []); - const safeFlags = useMemo(() => { + const safeFlags = useMemo(import.meta.url, () => { return Object.keys(flags).reduce((acc, k) => { if (k === 'badge') acc[k] = flags[k]; else acc[k] = k === 'disabled' ? nativeBool(flags[k]) : reactBool(flags[k]); @@ -377,7 +377,7 @@ const ActionButtonComponent = forwardRef(({ }, {}) }, [flags]); - const tooltipContent = useMemo(() => { + const tooltipContent = useMemo(import.meta.url, () => { try { return ReactDOMServer.renderToStaticMarkup( diff --git a/src/game/interface/hud/actionButtons/ActionButtonStack.js b/src/game/interface/hud/actionButtons/ActionButtonStack.js index 3a948436a..a9234260d 100644 --- a/src/game/interface/hud/actionButtons/ActionButtonStack.js +++ b/src/game/interface/hud/actionButtons/ActionButtonStack.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled, { css } from 'styled-components'; import MouseoverInfoPane from '~/components/MouseoverInfoPane'; @@ -69,7 +69,7 @@ const StackItem = ({ label, finishTime, preloadEntity, onClick }) => { const blockTime = useBlockTime(); const { data: entity } = useEntity(preloadEntity); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onClick(entity); }, [entity, onClick]); @@ -87,11 +87,11 @@ const StackItemButton = ({ label, finishTime, preloadEntity, onClick, ...props } const blockTime = useBlockTime(); const { data: entity } = useEntity(preloadEntity); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onClick(entity); }, [entity, onClick]); - const attention = useMemo(() => finishTime && (finishTime <= blockTime), [blockTime, finishTime]) + const attention = useMemo(import.meta.url, () => finishTime && (finishTime <= blockTime), [blockTime, finishTime]) return ( { const [refEl, setRefEl] = useState(); const [stackHovered, setStackHovered] = useState(); - const stackAttention = useMemo(() => { + const stackAttention = useMemo(import.meta.url, () => { return stack.find((a) => a.finishTime && (a.finishTime <= blockTime)); }, [blockTime, stack]); - const handleClick = useCallback((onClick) => (...args) => { + const handleClick = useCallback(import.meta.url, (onClick) => (...args) => { setStackHovered(); if (onClick) onClick(...args); }, []); diff --git a/src/game/interface/hud/actionButtons/AssembleShip.js b/src/game/interface/hud/actionButtons/AssembleShip.js index 4da741264..a7facd3f6 100644 --- a/src/game/interface/hud/actionButtons/AssembleShip.js +++ b/src/game/interface/hud/actionButtons/AssembleShip.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { DryDock, Permission } from '@influenceth/sdk'; import { AssembleShipIcon } from '~/components/Icons'; @@ -23,15 +23,15 @@ const AssembleShip = ({ asteroid, blockTime, crew, lot, onSetAction, simulation, const { assemblyStatus, currentAssembly } = useDryDockManager(lot?.id); const setCoachmarkRef = useCoachmarkRefSetter(); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('ASSEMBLE_SHIP'); }, [onSetAction]); - const prepaidLeaseConfig = useMemo(() => { + const prepaidLeaseConfig = useMemo(import.meta.url, () => { return getProcessorLeaseConfig(lot?.building, Permission.IDS.ASSEMBLE_SHIP, crew, blockTime); }, [blockTime, crew, lot?.building]) - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (assemblyStatus === 'READY') { return getCrewDisabledReason({ diff --git a/src/game/interface/hud/actionButtons/ClaimArrivalReward.js b/src/game/interface/hud/actionButtons/ClaimArrivalReward.js index 9c49c8bf2..917e08af7 100644 --- a/src/game/interface/hud/actionButtons/ClaimArrivalReward.js +++ b/src/game/interface/hud/actionButtons/ClaimArrivalReward.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Address, Asteroid } from '@influenceth/sdk'; import { ClaimRewardIcon } from '~/components/Icons'; @@ -11,11 +11,11 @@ const isVisible = ({ account, asteroid, crew }) => { }; const ClaimArrivalReward = ({ asteroid, crew, onSetAction, _disabled }) => { - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('CLAIM_ARRIVAL_REWARD', { asteroid, crew}); }, [onSetAction]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (asteroid?.Celestial?.scanStatus < Asteroid.SCAN_STATUSES.SURFACE_SCANNED) return 'asteroid un-scanned'; return getCrewDisabledReason({ asteroid, crew, requireAsteroid: false, requireSurface: false }); diff --git a/src/game/interface/hud/actionButtons/ClaimPrepareReward.js b/src/game/interface/hud/actionButtons/ClaimPrepareReward.js index bb6739701..7854d639b 100644 --- a/src/game/interface/hud/actionButtons/ClaimPrepareReward.js +++ b/src/game/interface/hud/actionButtons/ClaimPrepareReward.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Address } from '@influenceth/sdk'; import { ClaimRewardIcon } from '~/components/Icons'; @@ -11,11 +11,11 @@ const isVisible = ({ account, asteroid }) => { }; const ClaimPrepareReward = ({ asteroid, onSetAction, _disabled }) => { - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('CLAIM_PREPARE_REWARD', { asteroid }); }, [onSetAction]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; }, [_disabled]); diff --git a/src/game/interface/hud/actionButtons/Construct.js b/src/game/interface/hud/actionButtons/Construct.js index 85db1a272..5afa1d054 100644 --- a/src/game/interface/hud/actionButtons/Construct.js +++ b/src/game/interface/hud/actionButtons/Construct.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import { ConstructIcon } from '~/components/Icons'; import useConstructionManager from '~/hooks/actionManagers/useConstructionManager'; @@ -22,11 +22,11 @@ const isVisible = ({ constructionStatus, crew, lot }) => { const Construct = ({ asteroid, crew, lot, onSetAction, simulation, simulationActions, _disabled }) => { const { constructionStatus } = useConstructionManager(lot?.id); const setCoachmarkRef = useCoachmarkRefSetter(); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('CONSTRUCT'); }, [onSetAction]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (constructionStatus === 'PLANNED') { return getCrewDisabledReason({ diff --git a/src/game/interface/hud/actionButtons/ControlAsteroid.js b/src/game/interface/hud/actionButtons/ControlAsteroid.js index d4035cb31..0fa2c370d 100644 --- a/src/game/interface/hud/actionButtons/ControlAsteroid.js +++ b/src/game/interface/hud/actionButtons/ControlAsteroid.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { BecomeAdminIcon } from '~/components/Icons'; import useAsteroid from '~/hooks/useAsteroid'; @@ -14,11 +14,11 @@ const isVisible = ({ account, asteroid, lot, crew, zoomScene }) => { const ControlAsteroid = ({ asteroid, onSetAction, _disabled }) => { const { takingControl } = useControlAsteroid(asteroid?.id); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('CONTROL_ASTEROID'); }, [asteroid?.id]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (takingControl) return 'updating...'; return ''; diff --git a/src/game/interface/hud/actionButtons/ControlShip.js b/src/game/interface/hud/actionButtons/ControlShip.js index b686756c9..749f8095e 100644 --- a/src/game/interface/hud/actionButtons/ControlShip.js +++ b/src/game/interface/hud/actionButtons/ControlShip.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Address } from '@influenceth/sdk'; import { BecomeAdminIcon } from '~/components/Icons'; @@ -14,11 +14,11 @@ const isVisible = ({ account, ship, crew }) => { const ControlShip = ({ crew, ship, onSetAction, _disabled, ...props }) => { const { takingControl } = useControlShip(ship?.id); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('CONTROL_SHIP', { shipId: ship?.id }); }, [ship?.id]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (takingControl) return 'updating...'; if (!crew?._ready) return 'crew busy'; diff --git a/src/game/interface/hud/actionButtons/CoreSample.js b/src/game/interface/hud/actionButtons/CoreSample.js index e0d061aae..05d9902a7 100644 --- a/src/game/interface/hud/actionButtons/CoreSample.js +++ b/src/game/interface/hud/actionButtons/CoreSample.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useRef } from 'react'; +import { useCallback, useMemo, useRef } from '~/lib/react-debug'; import { Asteroid, Building, Deposit, Lot, Product } from '@influenceth/sdk'; import { NewCoreSampleIcon, ImproveCoreSampleIcon } from '~/components/Icons'; @@ -38,7 +38,7 @@ const NewCoreSample = ({ asteroid, crew, lot, onSetAction, overrideResourceId, i const resourceId = overrideResourceId || defaultResourceId; - const currentSamplingStack = useMemo(() => { + const currentSamplingStack = useMemo(import.meta.url, () => { return (currentSamplingActions || []) .map((sampling) => ({ label: `${labelDict[sampling.status]} (${Product.TYPES[sampling?.action?.resourceId]?.name})`, @@ -52,12 +52,12 @@ const NewCoreSample = ({ asteroid, crew, lot, onSetAction, overrideResourceId, i }, [currentSamplingActions, onSetAction]); // get lot abundance - const lotAbundance = useMemo(() => { + const lotAbundance = useMemo(import.meta.url, () => { if (!resourceId || !asteroid?.Celestial?.abundanceSeed || !asteroid.Celestial?.abundances) return 0; return Asteroid.Entity.getAbundanceAtLot(asteroid, Lot.toIndex(lot.id), resourceId); }, [asteroid, lot, resourceId]); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { if (improveSample) { onSetAction('IMPROVE_CORE_SAMPLE', { preselect: { ...improveSample, sampleId: improveSample.id } }); } else { @@ -65,7 +65,7 @@ const NewCoreSample = ({ asteroid, crew, lot, onSetAction, overrideResourceId, i } }, [improveSample, onSetAction, resourceId]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (improveSample && improveSample?.Deposit?.status === Deposit.STATUSES.USED) return 'already used'; if (improveSample && improveSample?.Deposit?.status !== Deposit.STATUSES.SAMPLED) return 'not yet analyzed'; @@ -82,7 +82,7 @@ const NewCoreSample = ({ asteroid, crew, lot, onSetAction, overrideResourceId, i if (improveSample) label = 'Improve Core Sample'; else if (lotAbundance > 0) label += ` (${formatFixed(100 * lotAbundance, 1)}%)`; - const stackIsImprovement = useMemo(() => { + const stackIsImprovement = useMemo(import.meta.url, () => { return !currentSamplingActions.find((a) => a.action?.isNew); }, [currentSamplingActions]); diff --git a/src/game/interface/hud/actionButtons/Deconstruct.js b/src/game/interface/hud/actionButtons/Deconstruct.js index d1cca47a3..c8ca08a6f 100644 --- a/src/game/interface/hud/actionButtons/Deconstruct.js +++ b/src/game/interface/hud/actionButtons/Deconstruct.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Inventory } from '@influenceth/sdk'; import { DeconstructIcon } from '~/components/Icons'; @@ -19,11 +19,11 @@ const isVisible = ({ constructionStatus, building, crew, ship }) => { const Deconstruct = ({ asteroid, crew, lot, onSetAction, _disabled }) => { const { constructionStatus } = useConstructionManager(lot?.id); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('DECONSTRUCT'); }, [onSetAction]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if ( diff --git a/src/game/interface/hud/actionButtons/EjectCrew.js b/src/game/interface/hud/actionButtons/EjectCrew.js index a8eff0fe2..d943934bd 100644 --- a/src/game/interface/hud/actionButtons/EjectCrew.js +++ b/src/game/interface/hud/actionButtons/EjectCrew.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { EjectMyCrewIcon } from '~/components/Icons'; import ActionButton, { getCrewDisabledReason } from './ActionButton'; @@ -22,15 +22,15 @@ const isVisible = ({ crew, building, ship }) => { // (can eject self from ship or building, whether own it or not) const EjectCrew = ({ crew, ship, onSetAction, _disabled }) => { const { currentEjections } = useEjectCrewManager(crew?.Location?.location); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('EJECT_CREW'); }, [onSetAction]); - const currentEjection = useMemo(() => { + const currentEjection = useMemo(import.meta.url, () => { return currentEjections?.find((e) => e.vars.ejected_crew.id === crew?.id); }, [currentEjections, crew?.id]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (ship?.Ship?.emergencyAt > 0) return 'emergency mode'; return getCrewDisabledReason({ crew }); diff --git a/src/game/interface/hud/actionButtons/EjectGuestCrew.js b/src/game/interface/hud/actionButtons/EjectGuestCrew.js index 431cbd9f6..7d810e3c0 100644 --- a/src/game/interface/hud/actionButtons/EjectGuestCrew.js +++ b/src/game/interface/hud/actionButtons/EjectGuestCrew.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Entity, Permission } from '@influenceth/sdk'; import { EjectPassengersIcon } from '~/components/Icons'; @@ -24,7 +24,7 @@ const isVisible = ({ crew, building, ship }) => { // NOTE: this is "eject guest(s)" // (can eject guests from ship or building i control) const EjectGuestCrew = ({ asteroid, blockTime, crew, lot, ship, onSetAction, dialogProps = {}, _disabled }) => { - const [station, entityId] = useMemo(() => { + const [station, entityId] = useMemo(import.meta.url, () => { const station = ship || lot?.building; const entityId = { id: station.id, label: station.label }; return [station, entityId]; @@ -32,22 +32,22 @@ const EjectGuestCrew = ({ asteroid, blockTime, crew, lot, ship, onSetAction, dia const { currentEjections } = useEjectCrewManager(entityId); const { data: allStationedCrews } = useStationedCrews(entityId); - const allGuestCrews = useMemo(() => (allStationedCrews || []).filter((c) => c.id !== crew?.id), [allStationedCrews, crew?.id]); + const allGuestCrews = useMemo(import.meta.url, () => (allStationedCrews || []).filter((c) => c.id !== crew?.id), [allStationedCrews, crew?.id]); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('EJECT_GUEST_CREW', { origin: station, ...dialogProps }); }, [station, onSetAction, dialogProps]); - const activeEjections = useMemo(() => { + const activeEjections = useMemo(import.meta.url, () => { return currentEjections?.filter((e) => e.vars.ejected_crew.id === crew?.id); }, [currentEjections, crew?.id]); // Differentiate between a Habitat and a ship - const actionLabel = useMemo(() => { + const actionLabel = useMemo(import.meta.url, () => { return `Force Eject ${entityId?.label === Entity.IDS.SHIP ? 'Passenger' : 'Resident'} Crew`; }, [entityId]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (allGuestCrews?.length === 0) return 'no guests'; if (station) { diff --git a/src/game/interface/hud/actionButtons/EjectShip.js b/src/game/interface/hud/actionButtons/EjectShip.js index 9b42e06c3..88bc7a4f8 100644 --- a/src/game/interface/hud/actionButtons/EjectShip.js +++ b/src/game/interface/hud/actionButtons/EjectShip.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Permission } from '@influenceth/sdk'; import { LaunchShipIcon } from '~/components/Icons'; @@ -23,13 +23,13 @@ const isVisible = ({ crew, building, lot, ship }) => { const EjectShip = ({ asteroid, blockTime, crew, lot, ship, onSetAction, _disabled }) => { const { currentUndockingAction } = useShipDockingManager(ship?.id); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('LAUNCH_SHIP', { shipId: ship?.id }); }, [onSetAction, ship?.id]); const { data: shipController } = useHydratedCrew(ship?.Control?.controller?.id); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (lot?.building) { // cannot force eject if ship has permission to be there diff --git a/src/game/interface/hud/actionButtons/EmergencyModeCollect.js b/src/game/interface/hud/actionButtons/EmergencyModeCollect.js index 4abda7227..ce0780081 100644 --- a/src/game/interface/hud/actionButtons/EmergencyModeCollect.js +++ b/src/game/interface/hud/actionButtons/EmergencyModeCollect.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import { Crewmate, Inventory, Product, Ship, Time } from '@influenceth/sdk'; import { EmergencyModeCollectIcon } from '~/components/Icons'; @@ -16,11 +16,11 @@ const isVisible = ({ crew, ship }) => { const EmergencyModeCollect = ({ crew, onSetAction, _disabled }) => { const { data: maybeShip } = useShip(crew?._location?.shipId); - const ship = useMemo(() => { + const ship = useMemo(import.meta.url, () => { return (!maybeShip && crew?.Ship?.emergencyAt > 0) ? crew : maybeShip; }, [maybeShip]); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('EMERGENCY_MODE_COLLECT'); }, [onSetAction]); @@ -29,7 +29,7 @@ const EmergencyModeCollect = ({ crew, onSetAction, _disabled }) => { const { hasCollectedMax, finishTime, - } = useMemo(() => { + } = useMemo(import.meta.url, () => { const shipConfig = Ship.TYPES[ship.Ship.shipType]; const propellantInventory = ship.Inventories.find((i) => i.slot === shipConfig.propellantSlot); const propellantInventoryConfig = Inventory.getType(propellantInventory.inventoryType, crew?._inventoryBonuses); @@ -44,7 +44,7 @@ const EmergencyModeCollect = ({ crew, onSetAction, _disabled }) => { }; }, [crew, resourceId, ship]); - useEffect(() => { + useEffect(import.meta.url, () => { const now = Date.now() / 1000; if (finishTime > now) { setHasGeneratedMax(false); @@ -57,7 +57,7 @@ const EmergencyModeCollect = ({ crew, onSetAction, _disabled }) => { } }, [finishTime]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (!ship) return 'ship is not crewed'; if (ship.Ship?.transitDestination) return 'ship is in flight'; diff --git a/src/game/interface/hud/actionButtons/EmergencyModeToggle.js b/src/game/interface/hud/actionButtons/EmergencyModeToggle.js index d72beff75..b30c04d14 100644 --- a/src/game/interface/hud/actionButtons/EmergencyModeToggle.js +++ b/src/game/interface/hud/actionButtons/EmergencyModeToggle.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { EmergencyModeEnterIcon, EmergencyModeExitIcon } from '~/components/Icons'; import useShip from '~/hooks/useShip'; @@ -26,11 +26,11 @@ const EmergencyModeToggle = ({ crew, onSetAction, _disabled }) => { const { data: crewedShip } = useShip(crew?._location?.shipId); const ready = useReadyAtWatcher(crewedShip?.Ship?.readyAt); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('EMERGENCY_MODE_TOGGLE'); }, [onSetAction]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (!crewedShip) return 'ship is not crewed'; if (crewedShip?._location.lotId || crewedShip?._location.spaceId) return 'must be in orbit'; diff --git a/src/game/interface/hud/actionButtons/EndAgreement.js b/src/game/interface/hud/actionButtons/EndAgreement.js index ca7aa5af0..a326779f5 100644 --- a/src/game/interface/hud/actionButtons/EndAgreement.js +++ b/src/game/interface/hud/actionButtons/EndAgreement.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { CancelAgreementIcon, GiveNoticeIcon } from '~/components/Icons'; import useAgreementManager from '~/hooks/actionManagers/useAgreementManager'; @@ -15,11 +15,11 @@ const EndAgreement = ({ blockTime, entity, permission, agreementPath, _disabled const onSetAction = useStore(s => s.dispatchActionDialog); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('END_AGREEMENT', { entity, permission, agreementPath }); }, [entity, permission]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (pendingChange) return 'updating...'; if (currentAgreement?.noticeTime > 0) return 'notice already given'; diff --git a/src/game/interface/hud/actionButtons/ExtendAgreement.js b/src/game/interface/hud/actionButtons/ExtendAgreement.js index 2108b151b..e03228769 100644 --- a/src/game/interface/hud/actionButtons/ExtendAgreement.js +++ b/src/game/interface/hud/actionButtons/ExtendAgreement.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { ExtendAgreementIcon } from '~/components/Icons'; import ActionButton from './ActionButton'; @@ -12,11 +12,11 @@ const ExtendAgreement = ({ entity, permission, onSetAction, _disabled }) => { const { pendingChange, currentAgreement } = useAgreementManager(entity, permission); const simulationEnabled = useSimulationEnabled(); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('EXTEND_AGREEMENT', { entity, permission }); }, [entity, permission]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (pendingChange) return 'updating...'; if (currentAgreement?.noticeTime > 0) return 'notice given'; diff --git a/src/game/interface/hud/actionButtons/Extract.js b/src/game/interface/hud/actionButtons/Extract.js index b4aaaf444..cf4d92751 100644 --- a/src/game/interface/hud/actionButtons/Extract.js +++ b/src/game/interface/hud/actionButtons/Extract.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Deposit, Permission } from '@influenceth/sdk'; import { CoreSampleIcon, ExtractionIcon } from '~/components/Icons'; @@ -27,17 +27,17 @@ const Extract = ({ onSetAction, asteroid, blockTime, crew, lot, preselect, simul const { currentExtraction, extractionStatus } = useExtractionManager(lot?.id); const setCoachmarkRef = useCoachmarkRefSetter(); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('EXTRACT_RESOURCE', { preselect }); }, [onSetAction, preselect]); - const prepaidLeaseConfig = useMemo(() => { + const prepaidLeaseConfig = useMemo(import.meta.url, () => { return getProcessorLeaseConfig(lot?.building, Permission.IDS.EXTRACT_RESOURCES, crew, blockTime); }, [blockTime, crew, lot?.building]) // badge shows full count of *useable* core samples of crew // TODO: this should ideally also check for pending use of samples (i.e. in core sample improvement) - const myUsableSamples = useMemo(() => { + const myUsableSamples = useMemo(import.meta.url, () => { // if no access to use extractor, then 0 usable samples if (!crewCan(Permission.IDS.EXTRACT_RESOURCES, lot?.building) && !prepaidLeaseConfig) return 0; @@ -55,7 +55,7 @@ const Extract = ({ onSetAction, asteroid, blockTime, crew, lot, preselect, simul // const attention = !_disabled && (extractionStatus === 'READY_TO_FINISH' || (myUsableSamples?.length > 0) && extractionStatus === 'READY'); const attention = !_disabled && (simulation || extractionStatus === 'READY_TO_FINISH'); const badge = ((extractionStatus === 'READY' && !preselect) ? myUsableSamples?.length : 0); - let disabledReason = useMemo(() => { + let disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (extractionStatus === 'READY') { const crewDisabledReason = getCrewDisabledReason({ diff --git a/src/game/interface/hud/actionButtons/FormAgreement.js b/src/game/interface/hud/actionButtons/FormAgreement.js index a6c6978a0..701e56ba8 100644 --- a/src/game/interface/hud/actionButtons/FormAgreement.js +++ b/src/game/interface/hud/actionButtons/FormAgreement.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Permission } from '@influenceth/sdk'; import { FormAgreementIcon, FormLotAgreementIcon } from '~/components/Icons'; @@ -15,11 +15,11 @@ const FormAgreement = ({ entity, permission, _disabled }) => { const onSetAction = useStore(s => s.dispatchActionDialog); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('FORM_AGREEMENT', { entity, permission }); }, [entity, permission]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { // if (_disabled) return 'loading...'; if (pendingChange) return 'updating...'; if (simulationEnabled) return 'simulation restricted'; diff --git a/src/game/interface/hud/actionButtons/FormLotLeaseAgreement.js b/src/game/interface/hud/actionButtons/FormLotLeaseAgreement.js index cd6962e3a..1d847b62f 100644 --- a/src/game/interface/hud/actionButtons/FormLotLeaseAgreement.js +++ b/src/game/interface/hud/actionButtons/FormLotLeaseAgreement.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import { FormLotAgreementIcon } from '~/components/Icons'; import useAgreementManager from '~/hooks/actionManagers/useAgreementManager'; @@ -24,11 +24,11 @@ const FormLotLeaseAgreement = ({ lot, permission, simulation, simulationActions, const onSetAction = useStore(s => s.dispatchActionDialog); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('FORM_AGREEMENT', { entity: lot, permission: Permission.IDS.USE_LOT }); }, [lot, permission]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (pendingChange) return 'updating...'; if (simulation) { diff --git a/src/game/interface/hud/actionButtons/JettisonCargo.js b/src/game/interface/hud/actionButtons/JettisonCargo.js index 2f8805873..2f2f7c4e5 100644 --- a/src/game/interface/hud/actionButtons/JettisonCargo.js +++ b/src/game/interface/hud/actionButtons/JettisonCargo.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Inventory, Permission } from '@influenceth/sdk'; import { JettisonCargoIcon } from '~/components/Icons'; @@ -13,14 +13,14 @@ const isVisible = ({ crew, lot, ship }) => false; };*/ const JettisonCargo = ({ asteroid, blockTime, crew, lot, ship, onSetAction, dialogProps = {}, _disabled, _disabledReason }) => { - const origin = useMemo(() => ship || lot?.surfaceShip || lot?.building, [ship, lot]); + const origin = useMemo(import.meta.url, () => ship || lot?.surfaceShip || lot?.building, [ship, lot]); const { currentJettison } = useJettisonCargoManager(origin); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('JETTISON_CARGO', { origin, ...dialogProps }); }, [dialogProps, origin]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabledReason) return _disabledReason; if (_disabled) return 'loading...'; if (currentJettison) return 'jettisoning...'; diff --git a/src/game/interface/hud/actionButtons/LandShip.js b/src/game/interface/hud/actionButtons/LandShip.js index 0aa5bde3f..7593ecc1e 100644 --- a/src/game/interface/hud/actionButtons/LandShip.js +++ b/src/game/interface/hud/actionButtons/LandShip.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Asteroid, Dock, Permission, Ship } from '@influenceth/sdk'; import { LandShipIcon } from '~/components/Icons'; @@ -24,7 +24,7 @@ const LandShip = ({ asteroid, lot, onSetAction, _disabled }) => { const { data: crewedShip } = useShip(crew?._location?.shipId) const ready = useReadyAtWatcher(crewedShip?.Ship?.readyAt); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction( 'LAND_SHIP', { @@ -34,7 +34,7 @@ const LandShip = ({ asteroid, lot, onSetAction, _disabled }) => { ); }, [crew?._location.shipId, lot?.id]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (!crewedShip) return 'ship is not crewed'; if (!ready) return 'ship is not ready'; // in flight or stuck in port traffic diff --git a/src/game/interface/hud/actionButtons/LaunchShip.js b/src/game/interface/hud/actionButtons/LaunchShip.js index 54f3c2e9a..3a578c16c 100644 --- a/src/game/interface/hud/actionButtons/LaunchShip.js +++ b/src/game/interface/hud/actionButtons/LaunchShip.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import { LaunchShipIcon } from '~/components/Icons'; @@ -21,8 +21,8 @@ const LaunchShip = ({ asteroid, blockTime, lot, onSetAction, _disabled, simulati const { crew } = useCrewContext(); const setCoachmarkRef = useCoachmarkRefSetter(); - const crewedShip = useMemo(() => lot?.ships?.find((s) => s.id === crew?._location?.shipId), [crew?._location?.shipId]); - const ship = useMemo(() => props.ship || crewedShip, [crewedShip, props.ship]); + const crewedShip = useMemo(import.meta.url, () => lot?.ships?.find((s) => s.id === crew?._location?.shipId), [crew?._location?.shipId]); + const ship = useMemo(import.meta.url, () => props.ship || crewedShip, [crewedShip, props.ship]); const { data: shipCrews } = useStationedCrews(ship); @@ -30,11 +30,11 @@ const LaunchShip = ({ asteroid, blockTime, lot, onSetAction, _disabled, simulati const { currentDeliveries } = useDeliveryManager(ship?.id ? { destination: { label: Entity.IDS.SHIP, id: ship?.id } } : {}); const shipReady = useReadyAtWatcher(ship?.Ship?.readyAt); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('LAUNCH_SHIP', { shipId: ship?.id }); }, [ship?.id]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (ship?.id !== crewedShip?.id) return 'ship is not crewed'; if (!shipReady) return 'ship is busy'; diff --git a/src/game/interface/hud/actionButtons/MultiBuy.js b/src/game/interface/hud/actionButtons/MultiBuy.js index fb483a4bc..e94e74205 100644 --- a/src/game/interface/hud/actionButtons/MultiBuy.js +++ b/src/game/interface/hud/actionButtons/MultiBuy.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Permission } from '@influenceth/sdk'; import { MultiBuyIcon } from '~/components/Icons'; @@ -8,14 +8,14 @@ import ActionButton, { getCrewDisabledReason } from './ActionButton'; const isVisible = () => false; const MultiBuy = ({ asteroid, blockTime, crew, lot, ship, onSetAction, dialogProps = {}, _disabled, _disabledReason }) => { - const destination = useMemo(() => ship || lot?.surfaceShip || lot?.building, [ship, lot]); + const destination = useMemo(import.meta.url, () => ship || lot?.surfaceShip || lot?.building, [ship, lot]); const { pendingAction } = useMarketplaceManager(destination.id); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('SHOPPING_LIST', { destination, ...dialogProps }); // TODO: destinationSlot (if not set, use primary) }, [destination, dialogProps]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabledReason) return _disabledReason; if (_disabled) return 'loading...'; if (pendingAction) return 'transacting...'; diff --git a/src/game/interface/hud/actionButtons/MultiSell.js b/src/game/interface/hud/actionButtons/MultiSell.js index e8e4bb2c0..7f33e8e8c 100644 --- a/src/game/interface/hud/actionButtons/MultiSell.js +++ b/src/game/interface/hud/actionButtons/MultiSell.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Inventory, Permission } from '@influenceth/sdk'; import { MultiSellIcon } from '~/components/Icons'; @@ -10,16 +10,16 @@ const isVisible = ({ crew, lot, ship }) => false; const MultiSell = ({ asteroid, blockTime, crew, lot, ship, onSetAction, dialogProps = {}, _disabled, _disabledReason }) => { const { pendingTransactions } = useCrewContext(); - const origin = useMemo(() => ship || lot?.surfaceShip || lot?.building, [ship, lot]); - const pendingAction = useMemo(() => { + const origin = useMemo(import.meta.url, () => ship || lot?.surfaceShip || lot?.building, [ship, lot]); + const pendingAction = useMemo(import.meta.url, () => { return !!(pendingTransactions || []).find((tx) => tx.key === 'EscrowWithdrawalAndFillBuyOrders' && tx.meta?.originLotId === lot?.id); }, [lot?.id, pendingTransactions]); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('SELLING_LIST', { origin, ...dialogProps }); // originSlot (if not set, use primary) }, [dialogProps, origin]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabledReason) return _disabledReason; if (_disabled) return 'loading...'; if (pendingAction) return 'transacting...'; diff --git a/src/game/interface/hud/actionButtons/PlanBuilding.js b/src/game/interface/hud/actionButtons/PlanBuilding.js index 4a0987627..aed761b13 100644 --- a/src/game/interface/hud/actionButtons/PlanBuilding.js +++ b/src/game/interface/hud/actionButtons/PlanBuilding.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import { Permission } from '@influenceth/sdk'; import { PlanBuildingIcon } from '~/components/Icons'; @@ -24,11 +24,11 @@ const isVisible = ({ constructionStatus, crew, lot, ship }) => { const PlanBuilding = ({ asteroid, blockTime, crew, lot, onSetAction, simulation, simulationActions, _disabled }) => { const { constructionStatus } = useConstructionManager(lot?.id); const setCoachmarkRef = useCoachmarkRefSetter(); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('PLAN_BUILDING'); }, [onSetAction]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { const isControlledByMe = crew && lot && Permission.isPermitted(crew, Permission.IDS.USE_LOT, lot, blockTime); if (_disabled) return 'loading...'; diff --git a/src/game/interface/hud/actionButtons/Processors.js b/src/game/interface/hud/actionButtons/Processors.js index 15f1389fc..ccad3c55f 100644 --- a/src/game/interface/hud/actionButtons/Processors.js +++ b/src/game/interface/hud/actionButtons/Processors.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo } from 'react'; +import { useCallback, useEffect, useMemo } from '~/lib/react-debug'; import { Permission, Processor } from '@influenceth/sdk'; import { getProcessorLeaseConfig, getProcessorProps } from '~/lib/utils'; @@ -15,17 +15,17 @@ const Button = ({ asteroid, blockTime, crew, lot, processor, onSetAction, simula const { currentProcess, processStatus } = useProcessManager(lot?.id, processor.slot); const setCoachmarkRef = useCoachmarkRefSetter(); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('PROCESS', { processorSlot: processor.slot }); }, [onSetAction, processor]); - const buttonProps = useMemo(() => getProcessorProps(processor?.processorType), [processor?.processorType]); + const buttonProps = useMemo(import.meta.url, () => getProcessorProps(processor?.processorType), [processor?.processorType]); - const prepaidLeaseConfig = useMemo(() => { + const prepaidLeaseConfig = useMemo(import.meta.url, () => { return getProcessorLeaseConfig(lot?.building, Permission.IDS.RUN_PROCESS, crew, blockTime); }, [blockTime, crew, lot?.building]) - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (processStatus === 'READY') { return getCrewDisabledReason({ diff --git a/src/game/interface/hud/actionButtons/PurchaseAsteroid.js b/src/game/interface/hud/actionButtons/PurchaseAsteroid.js index dbbe265e0..372a818c4 100644 --- a/src/game/interface/hud/actionButtons/PurchaseAsteroid.js +++ b/src/game/interface/hud/actionButtons/PurchaseAsteroid.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { useHistory } from 'react-router-dom'; import { Entity } from '@influenceth/sdk'; @@ -17,11 +17,11 @@ const PurchaseAsteroid = ({ asteroid, _disabled }) => { const { buying } = useBuyAsteroid(Number(asteroid?.id)); const saleIsActive = useSale(Entity.IDS.ASTEROID); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { history.push(`/asteroids/${asteroid?.id}`); }, [asteroid?.id]); - let disabledReason = useMemo(() => { + let disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (!saleIsActive) return 'sale is currently closed'; }, [_disabled, saleIsActive]); diff --git a/src/game/interface/hud/actionButtons/PurchaseEntity.js b/src/game/interface/hud/actionButtons/PurchaseEntity.js index ab85fcca5..0dee033c2 100644 --- a/src/game/interface/hud/actionButtons/PurchaseEntity.js +++ b/src/game/interface/hud/actionButtons/PurchaseEntity.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Address } from '@influenceth/sdk'; import { PurchaseEntityIcon } from '~/components/Icons'; @@ -14,11 +14,11 @@ const isVisible = ({ account, ship }) => { const PurchaseEntity = ({ ship, onSetAction, _disabled }) => { const { isPendingPurchase } = useNftSaleManager(ship); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('PURCHASE_ENTITY', { entity: ship }); }, []); - let disabledReason = useMemo(() => { + let disabledReason = useMemo(import.meta.url, () => { if (_disabled || isPendingPurchase) return 'loading...'; }, [_disabled, isPendingPurchase]); diff --git a/src/game/interface/hud/actionButtons/RecruitCrewmate.js b/src/game/interface/hud/actionButtons/RecruitCrewmate.js index fa0fb8082..76335e2b5 100644 --- a/src/game/interface/hud/actionButtons/RecruitCrewmate.js +++ b/src/game/interface/hud/actionButtons/RecruitCrewmate.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { useHistory } from 'react-router-dom'; import { Building, Permission } from '@influenceth/sdk'; @@ -18,7 +18,7 @@ const RecruitCrewmate = ({ asteroid, blockTime, crew, lot, simulation, _disabled const createAlert = useStore(s => s.dispatchAlertLogged); - const [tooltipExtra, recruitToCrew, clickWarning] = useMemo(() => { + const [tooltipExtra, recruitToCrew, clickWarning] = useMemo(import.meta.url, () => { let tip = ''; let ontoCrew = 0; let warning = ''; @@ -47,7 +47,7 @@ const RecruitCrewmate = ({ asteroid, blockTime, crew, lot, simulation, _disabled }, [crew, lot]); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { if (clickWarning) { createAlert({ type: 'GenericAlert', @@ -58,9 +58,9 @@ const RecruitCrewmate = ({ asteroid, blockTime, crew, lot, simulation, _disabled history.push(`/recruit/${recruitToCrew || 0}/${lot?.building?.id}`) }, [recruitToCrew, clickWarning, lot?.building?.id]); - const pendingCrewmate = useMemo(getPendingCrewmate, [getPendingCrewmate]); + const pendingCrewmate = useMemo(import.meta.url, getPendingCrewmate, [getPendingCrewmate]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (pendingCrewmate) return 'recruiting...'; if (simulation) return 'simulation restricted'; diff --git a/src/game/interface/hud/actionButtons/RepoBuilding.js b/src/game/interface/hud/actionButtons/RepoBuilding.js index 50b40ee81..ce9728dcd 100644 --- a/src/game/interface/hud/actionButtons/RepoBuilding.js +++ b/src/game/interface/hud/actionButtons/RepoBuilding.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { TakeControlIcon } from '~/components/Icons'; import ActionButton, { getCrewDisabledReason } from './ActionButton'; @@ -26,17 +26,17 @@ const isVisible = ({ crew, isAtRisk, lot }) => { const RepoBuilding = ({ asteroid, crew, lot, onSetAction, _disabled }) => { const { currentRepo } = useRepoManager(lot?.id); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('REPO_BUILDING'); }, [onSetAction]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled || !!currentRepo) return 'loading...'; if (!currentRepo) return getCrewDisabledReason({ asteroid, crew }); return ''; }, [_disabled, asteroid, crew]); - const buttonParams = useMemo(() => { + const buttonParams = useMemo(import.meta.url, () => { // if i am the lot controller but not the building controller... if (crew?.id === lot?.Control?.controller?.id && crew?.id !== lot?.building?.Control?.controller?.id) { return { diff --git a/src/game/interface/hud/actionButtons/ScanAsteroid.js b/src/game/interface/hud/actionButtons/ScanAsteroid.js index 8517eaf86..865f9758f 100644 --- a/src/game/interface/hud/actionButtons/ScanAsteroid.js +++ b/src/game/interface/hud/actionButtons/ScanAsteroid.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { useHistory } from 'react-router'; import { Asteroid } from '@influenceth/sdk'; @@ -20,7 +20,7 @@ const ScanAsteroid = ({ asteroid, _disabled }) => { const { scanStatus, scanType } = useScanManager(asteroid); const { crew, isLaunched } = useCrewContext(); - const { disabledReason, label, flags, handleClick } = useMemo(() => { + const { disabledReason, label, flags, handleClick } = useMemo(import.meta.url, () => { let flags = { attention: undefined, disabled: _disabled, diff --git a/src/game/interface/hud/actionButtons/SelectTravelDestination.js b/src/game/interface/hud/actionButtons/SelectTravelDestination.js index 717fa255f..80586ab6c 100644 --- a/src/game/interface/hud/actionButtons/SelectTravelDestination.js +++ b/src/game/interface/hud/actionButtons/SelectTravelDestination.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect } from 'react'; +import { useCallback, useEffect } from '~/lib/react-debug'; import { SimulateRouteIcon } from '~/components/Icons'; import useStore from '~/hooks/useStore'; @@ -33,7 +33,7 @@ const SelectTravelDestination = ({ crew, simulation, simulationActions }) => { const setCoachmarkRef = useCoachmarkRefSetter(); const canSelect = inTravelMode && zoomStatus === 'out'; - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { if (zoomStatus !== 'out') { dispatchZoomStatusChanged('zooming-out'); dispatchTravelMode(true); @@ -46,7 +46,7 @@ const SelectTravelDestination = ({ crew, simulation, simulationActions }) => { } }, [dispatchTravelMode, dispatchDestinationSelected, dispatchHudMenuOpened, inTravelMode, zoomStatus]); - useEffect(() => { + useEffect(import.meta.url, () => { if (origin && destination && inTravelMode) { dispatchHudMenuOpened('BELT_PLAN_FLIGHT'); } diff --git a/src/game/interface/hud/actionButtons/SetCourse.js b/src/game/interface/hud/actionButtons/SetCourse.js index 6065bb8e4..12b3ebe74 100644 --- a/src/game/interface/hud/actionButtons/SetCourse.js +++ b/src/game/interface/hud/actionButtons/SetCourse.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useEffect } from 'react'; +import { useCallback, useMemo, useEffect } from '~/lib/react-debug'; import { Asteroid } from '@influenceth/sdk'; import { SetCourseIcon } from '~/components/Icons'; @@ -29,15 +29,15 @@ const SetCourse = ({ asteroid, crew, ship, onSetAction, simulation, simulationAc const { data: destination } = useAsteroid(travelSolution?.destinationId); const setCoachmarkRef = useCoachmarkRefSetter(); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('SET_COURSE'); }, [travelSolution]); - const validDestination = useMemo(() => { + const validDestination = useMemo(import.meta.url, () => { return destination?.Celestial?.scanStatus >= Asteroid.SCAN_STATUSES.SURFACE_SCANNED; }, [destination]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (!crew?._location?.shipId && !inEscapeModule) return 'crew is not on ship'; if (travelStatus === 'READY') { diff --git a/src/game/interface/hud/actionButtons/StationCrew.js b/src/game/interface/hud/actionButtons/StationCrew.js index 3b4c1519e..8e0bb3cd7 100644 --- a/src/game/interface/hud/actionButtons/StationCrew.js +++ b/src/game/interface/hud/actionButtons/StationCrew.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Permission, Station } from '@influenceth/sdk'; import { StationCrewIcon, StationPassengersIcon } from '~/components/Icons'; @@ -22,16 +22,16 @@ const isVisible = ({ crew, building, ship }) => { }; const StationCrew = ({ asteroid, blockTime, crew, lot, ship, onSetAction, simulation, simulationActions, _disabled }) => { - const stationEntity = useMemo(() => ship || (lot?.building?.Station ? lot.building : null), [ship, lot?.building]); + const stationEntity = useMemo(import.meta.url, () => ship || (lot?.building?.Station ? lot.building : null), [ship, lot?.building]); const { currentStationing } = useStationCrewManager(stationEntity); const setCoachmarkRef = useCoachmarkRefSetter(); const crewIsController = stationEntity?.Control?.controller?.id === crew?.id; - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction(crewIsController ? 'STATION_CREW' : 'STATION_CREW_AS_GUESTS'); }, [crewIsController, onSetAction]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled || !stationEntity) return 'loading...'; if (!currentStationing) { const stationConfig = Station.TYPES[stationEntity.Station?.stationType]; @@ -51,7 +51,7 @@ const StationCrew = ({ asteroid, blockTime, crew, lot, ship, onSetAction, simula return ''; }, [_disabled, asteroid, blockTime, crew, crewIsController, currentStationing, simulationActions, stationEntity]); - const buttonParams = useMemo(() => { + const buttonParams = useMemo(import.meta.url, () => { if (ship) { if (crewIsController) { return { diff --git a/src/game/interface/hud/actionButtons/SurfaceTransferIncoming.js b/src/game/interface/hud/actionButtons/SurfaceTransferIncoming.js index 0fb7836d5..3799f950f 100644 --- a/src/game/interface/hud/actionButtons/SurfaceTransferIncoming.js +++ b/src/game/interface/hud/actionButtons/SurfaceTransferIncoming.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Inventory, Order, Permission, Process } from '@influenceth/sdk'; import { TransferP2PIcon, TransferToIcon } from '~/components/Icons'; @@ -15,16 +15,16 @@ const isVisible = ({ crew, lot, ship }) => { }; const SurfaceTransferIncoming = ({ asteroid, blockTime, crew, lot, ship, onSetAction, dialogProps = {}, _disabled, _disabledReason }) => { - const destination = useMemo(() => ship || lot?.surfaceShip || lot?.building, [ship, lot]); + const destination = useMemo(import.meta.url, () => ship || lot?.surfaceShip || lot?.building, [ship, lot]); const { data: inventoryOrders } = useOrdersByInventory(destination); const { currentDeliveryActions: destDeliveryActions, isLoading } = useDeliveryManager({ destination }); const { data: destActionItems } = useUnresolvedActivities(destination); - const deliveryDeparting = useMemo(() => { + const deliveryDeparting = useMemo(import.meta.url, () => { return (destDeliveryActions || []).find((a) => a.status === 'DEPARTING'); }, [destDeliveryActions]); - const currentDeliveryStack = useMemo(() => { + const currentDeliveryStack = useMemo(import.meta.url, () => { const actionStack = []; if (crew && destination && Permission.isPermitted(crew, Permission.IDS.ADD_PRODUCTS, destination, blockTime)) { (destDeliveryActions || []).forEach((delivery) => { @@ -102,11 +102,11 @@ const SurfaceTransferIncoming = ({ asteroid, blockTime, crew, lot, ship, onSetAc }); }, [blockTime, crew, destination, destDeliveryActions, destActionItems, inventoryOrders, onSetAction]); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('SURFACE_TRANSFER', { deliveryId: 0, destination, ...dialogProps }); }, [onSetAction, destination, dialogProps]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabledReason) return _disabledReason; if (_disabled) return 'loading...'; if (!destination) return ''; @@ -126,7 +126,7 @@ const SurfaceTransferIncoming = ({ asteroid, blockTime, crew, lot, ship, onSetAc return getCrewDisabledReason({ asteroid, crew, requireReady: false }); }, [destination, crew]); - const isP2P = useMemo( + const isP2P = useMemo(import.meta.url, () => crew && destination && !Permission.isPermitted(crew, Permission.IDS.ADD_PRODUCTS, destination, blockTime), [blockTime, crew, destination] ); diff --git a/src/game/interface/hud/actionButtons/SurfaceTransferOutgoing.js b/src/game/interface/hud/actionButtons/SurfaceTransferOutgoing.js index ae654da48..a68013a25 100644 --- a/src/game/interface/hud/actionButtons/SurfaceTransferOutgoing.js +++ b/src/game/interface/hud/actionButtons/SurfaceTransferOutgoing.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import { Inventory, Order, Permission } from '@influenceth/sdk'; import { TransferFromIcon } from '~/components/Icons'; @@ -16,18 +16,18 @@ const isVisible = ({ crew, lot, ship }) => { }; const SurfaceTransferOutgoing = ({ asteroid, blockTime, crew, lot, ship, onSetAction, dialogProps = {}, _disabled, _disabledReason }) => { - const origin = useMemo(() => ship || lot?.surfaceShip || lot?.building, [ship, lot]); + const origin = useMemo(import.meta.url, () => ship || lot?.surfaceShip || lot?.building, [ship, lot]); const { data: inventoryOrders } = useOrdersByInventory(origin); const { currentDeliveryActions: originDeliveryActions, isLoading } = useDeliveryManager({ origin }); const { data: originActionItems } = useUnresolvedActivities(origin); - const deliveryDeparting = useMemo(() => { + const deliveryDeparting = useMemo(import.meta.url, () => { return (originDeliveryActions || []).find((a) => a.status === 'DEPARTING'); }, [originDeliveryActions]); // if outgoing package from origin, prompt anyone with remove_products perms on // origin to review/potentially cancel package - const currentDeliveryStack = useMemo( + const currentDeliveryStack = useMemo(import.meta.url, () => { const actionStack = []; if (crew && origin && Permission.isPermitted(crew, Permission.IDS.REMOVE_PRODUCTS, origin, blockTime)) { @@ -77,11 +77,11 @@ const SurfaceTransferOutgoing = ({ asteroid, blockTime, crew, lot, ship, onSetAc [blockTime, crew, origin, originDeliveryActions, originActionItems, inventoryOrders, onSetAction] ); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('SURFACE_TRANSFER', { deliveryId: 0, origin, ...dialogProps }); }, [onSetAction, origin, dialogProps]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabledReason) return _disabledReason; if (_disabled) return 'loading...'; if (!origin) return ''; diff --git a/src/game/interface/hud/actionButtons/UnplanBuilding.js b/src/game/interface/hud/actionButtons/UnplanBuilding.js index 851a875e8..d07995bbe 100644 --- a/src/game/interface/hud/actionButtons/UnplanBuilding.js +++ b/src/game/interface/hud/actionButtons/UnplanBuilding.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { Inventory } from '@influenceth/sdk'; import { UnplanBuildingIcon } from '~/components/Icons'; @@ -18,16 +18,16 @@ const isVisible = ({ constructionStatus, crew, lot }) => { const UnplanBuilding = ({ asteroid, crew, lot, onSetAction, _disabled }) => { const { constructionStatus } = useConstructionManager(lot?.id); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { onSetAction('UNPLAN_BUILDING'); }, [onSetAction]); - const siteEmpty = useMemo(() => { + const siteEmpty = useMemo(import.meta.url, () => { const inv = (lot?.building?.Inventories || []).find((i) => Inventory.TYPES[i.inventoryType].category === Inventory.CATEGORIES.SITE); return ((inv?.mass + inv?.reservedMass) === 0); }, [lot?.building]); - const disabledReason = useMemo(() => { + const disabledReason = useMemo(import.meta.url, () => { if (_disabled) return 'loading...'; if (!siteEmpty) return 'not empty'; return getCrewDisabledReason({ asteroid, crew, requireReady: false }); diff --git a/src/game/interface/hud/actionButtons/ViewAgreements.js b/src/game/interface/hud/actionButtons/ViewAgreements.js index 3adeb7807..1962320e1 100644 --- a/src/game/interface/hud/actionButtons/ViewAgreements.js +++ b/src/game/interface/hud/actionButtons/ViewAgreements.js @@ -1,4 +1,4 @@ -import { useCallback } from 'react'; +import { useCallback } from '~/lib/react-debug'; import { useHistory } from 'react-router-dom'; import { AgreementsListIcon } from '~/components/Icons'; @@ -8,7 +8,7 @@ const isVisible = () => false; const ViewAgreements = ({ entity, permission, tally, _disabled }) => { const history = useHistory(); - const handleClick = useCallback(() => { + const handleClick = useCallback(import.meta.url, () => { history.push(`/listview/agreements?uuid=${entity.uuid}&permission=${permission}`) }, [entity, permission]); diff --git a/src/game/interface/hud/actionDialogs/AssembleShip.js b/src/game/interface/hud/actionDialogs/AssembleShip.js index 692cf713f..00a80ee1b 100644 --- a/src/game/interface/hud/actionDialogs/AssembleShip.js +++ b/src/game/interface/hud/actionDialogs/AssembleShip.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid, Building, Crewmate, Entity, Lot, Permission, Product, Ship, Time } from '@influenceth/sdk'; @@ -72,12 +72,12 @@ const AssembleShip = ({ asteroid, lot, dryDockManager, stage, ...props }) => { const [selectedOrigin, setSelectedOrigin] = useState(currentAssembly ? { ...currentAssembly?.origin, slot: currentAssembly?.originSlot } : undefined); const { data: origin } = useEntity(selectedOrigin); - const originLotId = useMemo(() => origin && locationsArrToObj(origin?.Location?.locations || []).lotId, [origin]); - const originLotIndex = useMemo(() => Lot.toIndex(originLotId), [originLotId]); + const originLotId = useMemo(import.meta.url, () => origin && locationsArrToObj(origin?.Location?.locations || []).lotId, [origin]); + const originLotIndex = useMemo(import.meta.url, () => Lot.toIndex(originLotId), [originLotId]); const { data: originLot } = useLot(originLotId); const originSlot = selectedOrigin?.slot; // TODO: is both below and above needed? just using below in other Process action dialogs... - const originInventory = useMemo(() => (origin?.Inventories || []).find((i) => i.slot === selectedOrigin?.slot), [origin, selectedOrigin?.slot]); + const originInventory = useMemo(import.meta.url, () => (origin?.Inventories || []).find((i) => i.slot === selectedOrigin?.slot), [origin, selectedOrigin?.slot]); const { data: currentDestinationEntity } = useEntity(currentAssembly?.destination ? { ...currentAssembly.destination } : undefined); const [selectedDestinationIndex, setSelectedDestinationIndex] = useState(); @@ -91,7 +91,7 @@ const AssembleShip = ({ asteroid, lot, dryDockManager, stage, ...props }) => { const [originSelectorOpen, setOriginSelectorOpen] = useState(false); const [processSelectorOpen, setProcessSelectorOpen] = useState(false); - useEffect(() => { + useEffect(import.meta.url, () => { if (currentDestinationEntity) { setSelectedDestinationIndex( Lot.toIndex(currentDestinationEntity?.Location?.locations?.find((l) => l.label === Entity.IDS.LOT)?.lotId) @@ -106,7 +106,7 @@ const AssembleShip = ({ asteroid, lot, dryDockManager, stage, ...props }) => { const shipConfig = shipType ? Ship.getType(shipType) : null; const shipConstruction = shipType ? Ship.getConstructionType(shipType) : null; - const [crewTravelBonus, crewDistBonus, assemblyTimeBonus] = useMemo(() => { + const [crewTravelBonus, crewDistBonus, assemblyTimeBonus] = useMemo(import.meta.url, () => { const bonusIds = [ Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, @@ -116,7 +116,7 @@ const AssembleShip = ({ asteroid, lot, dryDockManager, stage, ...props }) => { return bonusIds.map((id) => abilities[id] || {}); }, [crew]); - const [assemblyTime, setupTime] = useMemo(() => { + const [assemblyTime, setupTime] = useMemo(import.meta.url, () => { if (!shipConstruction) return [0, 0]; return [ Time.toRealDuration(shipConstruction?.constructionTime / assemblyTimeBonus.totalBonus, crew?._timeAcceleration), @@ -124,7 +124,7 @@ const AssembleShip = ({ asteroid, lot, dryDockManager, stage, ...props }) => { ]; }, [amount, crew?._timeAcceleration, assemblyTimeBonus, shipConstruction]); - const { totalTime: crewTravelTime, tripDetails } = useMemo(() => { + const { totalTime: crewTravelTime, tripDetails } = useMemo(import.meta.url, () => { if (!asteroid?.id || !crew?._location?.lotId || !lot?.id) return {}; const crewLotIndex = Lot.toIndex(crew?._location?.lotId); return getTripDetails(asteroid.id, crewTravelBonus, crewDistBonus, crewLotIndex, [ @@ -133,7 +133,7 @@ const AssembleShip = ({ asteroid, lot, dryDockManager, stage, ...props }) => { ], crew?._timeAcceleration); }, [asteroid?.id, lot?.id, crew?._location?.lotId, crew?._timeAcceleration, crewTravelBonus, crewDistBonus]); - const [inputTransportDistance, inputTransportTime] = useMemo(() => { + const [inputTransportDistance, inputTransportTime] = useMemo(import.meta.url, () => { if (!originLot?.id) return []; return [ Asteroid.getLotDistance(asteroid?.id, Lot.toIndex(originLot?.id), Lot.toIndex(lot?.id)) || 0, @@ -150,7 +150,7 @@ const AssembleShip = ({ asteroid, lot, dryDockManager, stage, ...props }) => { ]; }, [asteroid?.id, lot?.id, crew?._timeAcceleration, originLot?.id, crewDistBonus, crewTravelBonus]); - const [outputTransportDistance, outputTransportTime] = useMemo(() => { + const [outputTransportDistance, outputTransportTime] = useMemo(import.meta.url, () => { if (!lot?.id || !destinationLot?.id) return []; return [ Asteroid.getLotDistance(asteroid?.id, Lot.toIndex(lot?.id), Lot.toIndex(destinationLot?.id)) || 0, @@ -167,7 +167,7 @@ const AssembleShip = ({ asteroid, lot, dryDockManager, stage, ...props }) => { ]; }, [asteroid?.id, lot?.id, crew?._timeAcceleration, destinationLot?.id, crewDistBonus, crewTravelBonus]); - const [inputArr, inputMass, inputVolume] = useMemo(() => { + const [inputArr, inputMass, inputVolume] = useMemo(import.meta.url, () => { if (!process || !amount) return [[], 0, 0, [], 0, 0]; const inputArr = Object.keys(process?.inputs || {}).map(Number); return [ @@ -177,7 +177,7 @@ const AssembleShip = ({ asteroid, lot, dryDockManager, stage, ...props }) => { ]; }, [process]); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { const onewayCrewTravelTime = crewTravelTime / 2; return [ Math.max(onewayCrewTravelTime, inputTransportTime) + (setupTime + assemblyTime) / 8 + onewayCrewTravelTime, @@ -185,7 +185,7 @@ const AssembleShip = ({ asteroid, lot, dryDockManager, stage, ...props }) => { ]; }, [crewTravelTime, inputTransportTime, setupTime, assemblyTime]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Crew Travel', value: formatTimer(crewTravelTime), @@ -232,11 +232,11 @@ const AssembleShip = ({ asteroid, lot, dryDockManager, stage, ...props }) => { }, ]), [assemblyTime, assemblyTimeBonus, crewTravelTime, crewTravelBonus, tripDetails, inputTransportDistance, inputTransportTime]); - const prepaidLeaseConfig = useMemo(() => { + const prepaidLeaseConfig = useMemo(import.meta.url, () => { return getProcessorLeaseConfig(lot?.building, Permission.IDS.ASSEMBLE_SHIP, crew, blockTime); }, [blockTime, crew, lot?.building]); - const { leasePayment, desiredLeaseTerm, actualLeaseTerm } = useMemo(() => { + const { leasePayment, desiredLeaseTerm, actualLeaseTerm } = useMemo(import.meta.url, () => { return getProcessorLeaseSelections( prepaidLeaseConfig, taskTimeRequirement, @@ -245,7 +245,7 @@ const AssembleShip = ({ asteroid, lot, dryDockManager, stage, ...props }) => { ); }, [blockTime, crew?.Crew?.readyAt, prepaidLeaseConfig, taskTimeRequirement]); - const onStart = useCallback(() => { + const onStart = useCallback(import.meta.url, () => { if (leasePayment && !buildingOwner?.Crew?.delegatedTo) return; startShipAssembly( shipType, @@ -266,13 +266,13 @@ const AssembleShip = ({ asteroid, lot, dryDockManager, stage, ...props }) => { originSlot ]); - const onFinish = useCallback(() => { + const onFinish = useCallback(import.meta.url, () => { finishShipAssembly(destination); }, [destination]); // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { // (close on status change from) if (['READY', 'READY_TO_FINISH', 'FINISHING'].includes(lastStatus.current)) { if (assemblyStatus !== lastStatus.current) { @@ -282,13 +282,13 @@ const AssembleShip = ({ asteroid, lot, dryDockManager, stage, ...props }) => { lastStatus.current = assemblyStatus; }, [assemblyStatus]); - const isOriginSufficient = useMemo(() => { + const isOriginSufficient = useMemo(import.meta.url, () => { if (!originInventory) return false; const sourceContentObj = (originInventory?.contents || []).reduce((acc, cur) => ({ ...acc, [cur.product]: cur.amount }), {}); return !inputArr.find((i) => (sourceContentObj[i] || 0) < process.inputs[i]); }, [inputArr, originInventory?.contents, process]); - const goLabel = useMemo(() => { + const goLabel = useMemo(import.meta.url, () => { if (leasePayment) { return ( @@ -545,7 +545,7 @@ const Wrapper = (props) => { const dryDockManager = useDryDockManager(lot?.id); const { actionStage } = dryDockManager; - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/ClaimArrivalReward.js b/src/game/interface/hud/actionDialogs/ClaimArrivalReward.js index c77a5aa15..8e930be0b 100644 --- a/src/game/interface/hud/actionDialogs/ClaimArrivalReward.js +++ b/src/game/interface/hud/actionDialogs/ClaimArrivalReward.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Entity } from '@influenceth/sdk'; @@ -42,14 +42,14 @@ const Content = styled.div` const ClaimArrivalReward = ({ asteroid, crew, onClose }) => { const { execute } = useContext(ChainTransactionContext); - const payload = useMemo(() => { + const payload = useMemo(import.meta.url, () => { return { asteroid: { id: asteroid?.id, label: Entity.IDS.ASTEROID }, caller_crew: { id: crew?.id, label: Entity.IDS.CREW } }; }, [asteroid?.id, crew?.id]); - const handleClaim = useCallback(async () => { + const handleClaim = useCallback(import.meta.url, async () => { await execute('ClaimArrivalReward', payload); onClose(); }, [payload]); diff --git a/src/game/interface/hud/actionDialogs/ClaimPrepareReward.js b/src/game/interface/hud/actionDialogs/ClaimPrepareReward.js index 2652353ec..99d5d6de8 100644 --- a/src/game/interface/hud/actionDialogs/ClaimPrepareReward.js +++ b/src/game/interface/hud/actionDialogs/ClaimPrepareReward.js @@ -1,4 +1,4 @@ -import { useCallback, useContext } from 'react'; +import { useCallback, useContext } from '~/lib/react-debug'; import styled from 'styled-components'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -41,7 +41,7 @@ const Content = styled.div` const ClaimPrepareReward = ({ asteroid, onClose }) => { const { execute } = useContext(ChainTransactionContext); - const handleClaim = useCallback(async () => { + const handleClaim = useCallback(import.meta.url, async () => { if (asteroid?.AsteroidProof?.used) { await execute('ClaimPrepareForLaunchReward', { asteroid }); } else { diff --git a/src/game/interface/hud/actionDialogs/Construct.js b/src/game/interface/hud/actionDialogs/Construct.js index 56c2d5366..a4e5e4ca5 100644 --- a/src/game/interface/hud/actionDialogs/Construct.js +++ b/src/game/interface/hud/actionDialogs/Construct.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef } from 'react'; +import { useCallback, useEffect, useMemo, useRef } from '~/lib/react-debug'; import styled from 'styled-components'; import { Building, Crewmate, Lot, Time } from '@influenceth/sdk'; @@ -61,7 +61,7 @@ const Construct = ({ asteroid, lot, constructionManager, stage, ...props }) => { const crew = useActionCrew(currentConstructionAction); - const [crewTravelBonus, crewDistBonus, constructionBonus] = useMemo(() => { + const [crewTravelBonus, crewDistBonus, constructionBonus] = useMemo(import.meta.url, () => { const bonusIds = [ Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, @@ -72,7 +72,7 @@ const Construct = ({ asteroid, lot, constructionManager, stage, ...props }) => { return bonusIds.map((id) => abilities[id] || {}); }, [crew]); - const { totalTime: crewTravelTime, tripDetails } = useMemo(() => { + const { totalTime: crewTravelTime, tripDetails } = useMemo(import.meta.url, () => { if (!asteroid?.id || !crew?._location?.lotId || !lot?.id) return {}; const crewLotIndex = crew?._location?.asteroidId === asteroid.id ? Lot.toIndex(crew?._location?.lotId) : 0; return getTripDetails(asteroid.id, crewTravelBonus, crewDistBonus, crewLotIndex, [ @@ -81,7 +81,7 @@ const Construct = ({ asteroid, lot, constructionManager, stage, ...props }) => { ], crew?._timeAcceleration); }, [asteroid?.id, lot?.id, crew?._location?.lotId, crew?._timeAcceleration, crewTravelBonus, crewDistBonus]); - const constructionTime = useMemo(() => + const constructionTime = useMemo(import.meta.url, () => Time.toRealDuration( lot?.building?.Building?.buildingType ? Building.getConstructionTime(lot?.building?.Building?.buildingType, constructionBonus.totalBonus) @@ -91,14 +91,14 @@ const Construct = ({ asteroid, lot, constructionManager, stage, ...props }) => { [lot?.building?.Building?.buildingType, constructionBonus.totalBonus, crew?._timeAcceleration] ); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { return [ crewTravelTime + constructionTime / 8, crewTravelTime / 2 + constructionTime ]; }, [crewTravelTime, constructionTime]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Crew Travel', value: formatTimer(crewTravelTime), @@ -127,7 +127,7 @@ const Construct = ({ asteroid, lot, constructionManager, stage, ...props }) => { }, ]), [constructionBonus, constructionTime, crewTravelTime, crewTravelBonus, tripDetails]); - const status = useMemo(() => { + const status = useMemo(import.meta.url, () => { if (constructionStatus === 'PLANNED') { return 'BEFORE'; } else if (constructionStatus === 'UNDER_CONSTRUCTION') { @@ -138,7 +138,7 @@ const Construct = ({ asteroid, lot, constructionManager, stage, ...props }) => { // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { // (always close on) if (['OPERATIONAL'].includes(constructionStatus)) { props.onClose(); @@ -152,15 +152,15 @@ const Construct = ({ asteroid, lot, constructionManager, stage, ...props }) => { lastStatus.current = constructionStatus; }, [constructionStatus]); - const transferToSite = useCallback(() => { + const transferToSite = useCallback(import.meta.url, () => { props.onSetAction('TRANSFER_TO_SITE', {}); }, []); - const purchaseOnMarket = useCallback(() => { + const purchaseOnMarket = useCallback(import.meta.url, () => { props.onSetAction('SHOPPING_LIST', {}); }, []); - const [buildingRequirements, requirementsMet, waitingOnTransfer] = useMemo(() => { + const [buildingRequirements, requirementsMet, waitingOnTransfer] = useMemo(import.meta.url, () => { const reqs = getBuildingRequirements(lot?.building, constructionStatus === 'PLANNED' ? currentDeliveryActions : []); const met = !reqs.find((req) => req.inNeed > 0); const wait = reqs.find((req) => req.inTransit > 0); @@ -298,7 +298,7 @@ const Wrapper = (props) => { const constructionManager = useConstructionManager(lot?.id); const { stageByActivity } = constructionManager; - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/ControlAsteroid.js b/src/game/interface/hud/actionDialogs/ControlAsteroid.js index 3744cabf9..595a6018f 100644 --- a/src/game/interface/hud/actionDialogs/ControlAsteroid.js +++ b/src/game/interface/hud/actionDialogs/ControlAsteroid.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef } from 'react'; +import { useEffect, useMemo, useRef } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid } from '@influenceth/sdk'; @@ -51,7 +51,7 @@ const ControlAsteroid = ({ asteroid, controlManager, stage, ...props }) => { // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (lastStatus.current && stage !== lastStatus.current) { props.onClose(); } @@ -120,7 +120,7 @@ const Wrapper = (props) => { const { data: asteroid, isLoading } = useAsteroid(asteroidId); const controlManager = useControlAsteroid(asteroidId); - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid && !isLoading) { if (props.onClose) props.onClose(); } else if (controlManager.alreadyControlled) { @@ -128,7 +128,7 @@ const Wrapper = (props) => { } }, [asteroid, controlManager, isLoading]); - const stage = useMemo(() => controlManager.takingControl ? actionStage.COMPLETING : actionStage.NOT_STARTED, [controlManager.takingControl]); + const stage = useMemo(import.meta.url, () => controlManager.takingControl ? actionStage.COMPLETING : actionStage.NOT_STARTED, [controlManager.takingControl]); return ( { + useEffect(import.meta.url, () => { if (lastStatus.current && stage !== lastStatus.current) { props.onClose(); } @@ -101,11 +101,11 @@ const Wrapper = (props) => { const { data: ship, isLoading: shipIsLoading } = useShip(props.shipId); const controlManager = useControlShip(props.shipId); - const loc = useMemo(() => locationsArrToObj(ship?.Location?.locations || []), [ship]); + const loc = useMemo(import.meta.url, () => locationsArrToObj(ship?.Location?.locations || []), [ship]); const { data: asteroid, isLoading: asteroidIsLoading } = useAsteroid(loc.asteroidId); const { data: lot, isLoading: lotIsLoading } = useEntity({ id: loc.lotId, label: Entity.IDS.LOT }); - useEffect(() => { + useEffect(import.meta.url, () => { if (props.onClose) { if (!ship && !shipIsLoading) { props.onClose(); @@ -117,7 +117,7 @@ const Wrapper = (props) => { } }, [asteroid, controlManager, asteroidIsLoading, shipIsLoading]); - const stage = useMemo(() => controlManager.takingControl ? actionStage.COMPLETING : actionStage.NOT_STARTED, [controlManager.takingControl]); + const stage = useMemo(import.meta.url, () => controlManager.takingControl ? actionStage.COMPLETING : actionStage.NOT_STARTED, [controlManager.takingControl]); return ( const { crew } = useCrewContext(); const { deconstruct } = constructionManager; - const crewTravelBonus = useMemo(() => getCrewAbilityBonuses(Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, crew), [crew]); - const crewDistBonus = useMemo(() => getCrewAbilityBonuses(Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, crew), [crew]); - const crewDeconstructBonus = useMemo(() => getCrewAbilityBonuses(Crewmate.ABILITY_IDS.DECONSTRUCTION_YIELD, crew), [crew]); - const deconstructionPenalty = useMemo(() => Building.DECONSTRUCTION_PENALTY / (crewDeconstructBonus?.totalBonus || 1), [crewDeconstructBonus]); + const crewTravelBonus = useMemo(import.meta.url, () => getCrewAbilityBonuses(Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, crew), [crew]); + const crewDistBonus = useMemo(import.meta.url, () => getCrewAbilityBonuses(Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, crew), [crew]); + const crewDeconstructBonus = useMemo(import.meta.url, () => getCrewAbilityBonuses(Crewmate.ABILITY_IDS.DECONSTRUCTION_YIELD, crew), [crew]); + const deconstructionPenalty = useMemo(import.meta.url, () => Building.DECONSTRUCTION_PENALTY / (crewDeconstructBonus?.totalBonus || 1), [crewDeconstructBonus]); - const { totalTime: crewTravelTime, tripDetails } = useMemo(() => { + const { totalTime: crewTravelTime, tripDetails } = useMemo(import.meta.url, () => { if (!asteroid?.id || !crew?._location?.lotId || !lot?.id) return {}; const crewLotIndex = Lot.toIndex(crew?._location?.lotId); return getTripDetails(asteroid.id, crewTravelBonus, crewDistBonus, crewLotIndex, [ @@ -45,11 +45,11 @@ const Deconstruct = ({ asteroid, lot, constructionManager, stage, ...props }) => ], crew?._timeAcceleration); }, [asteroid?.id, lot?.id, crew?._location?.lotId, crew?._timeAcceleration, crewTravelBonus, crewDistBonus]); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { return [crewTravelTime, 0]; }, [crewTravelTime]); - const stats = useMemo(() => [ + const stats = useMemo(import.meta.url, () => [ { label: 'Crew Travel', value: formatTimer(crewTravelTime), @@ -77,7 +77,7 @@ const Deconstruct = ({ asteroid, lot, constructionManager, stage, ...props }) => }, ], [crewDeconstructBonus, deconstructionPenalty, tripDetails]); - const itemsReturned = useMemo(() => { + const itemsReturned = useMemo(import.meta.url, () => { if (!lot?.building) return []; return getBuildingRequirements(lot?.building).map((item) => ({ ...item, @@ -143,7 +143,7 @@ const Wrapper = (props) => { const constructionManager = useConstructionManager(lot?.id); const { stageByActivity } = constructionManager; - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot?.building) { if (!isLoading) { if (props.onClose) props.onClose(); @@ -152,7 +152,7 @@ const Wrapper = (props) => { }, [asteroid, lot, isLoading]); // stay in this window until PLANNED (and lot updated), then swap to UNPLAN / SURFACE_TRANSFER - useEffect(() => { + useEffect(import.meta.url, () => { if (!['OPERATIONAL', 'DECONSTRUCTING'].includes(constructionManager.constructionStatus)) { const siteInventory = (lot?.building?.Inventories || []).find((i) => Inventory.TYPES[i.inventoryType].category === Inventory.CATEGORIES.SITE); if (siteInventory?.status === Inventory.STATUSES.AVAILABLE) { diff --git a/src/game/interface/hud/actionDialogs/EjectCrew.js b/src/game/interface/hud/actionDialogs/EjectCrew.js index 129f782a8..c633c5bfe 100644 --- a/src/game/interface/hud/actionDialogs/EjectCrew.js +++ b/src/game/interface/hud/actionDialogs/EjectCrew.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { Asteroid, Building, Crewmate, Permission, Ship, Station, Time } from '@influenceth/sdk'; import { EjectMyCrewIcon, EjectPassengersIcon, WarningIcon, WarningOutlineIcon } from '~/components/Icons'; @@ -51,10 +51,10 @@ const EjectCrew = ({ asteroid, origin, originLot, stationedCrews, manager, stage const myCrewIsTarget = targetCrew?.id === crew?.id; - const hopperBonus = useMemo(() => getCrewAbilityBonuses(Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, crew), [crew]); - const distBonus = useMemo(() => getCrewAbilityBonuses(Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, crew), [crew]); + const hopperBonus = useMemo(import.meta.url, () => getCrewAbilityBonuses(Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, crew), [crew]); + const distBonus = useMemo(import.meta.url, () => getCrewAbilityBonuses(Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, crew), [crew]); - const ejectionTime = useMemo(() => { + const ejectionTime = useMemo(import.meta.url, () => { // if from surface if (originLot) { const travelTime = Asteroid.getLotTravelTime(asteroid?.id, originLot.index, 0, hopperBonus.totalBonus, distBonus.totalBonus); @@ -71,7 +71,7 @@ const EjectCrew = ({ asteroid, origin, originLot, stationedCrews, manager, stage return 0; }, [asteroid, blockTime, crew?._timeAcceleration, distBonus, hopperBonus, originLot, origin?.Ship?.transitArrival]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ ejectionTime > 0 && { label: 'Time to Orbit', value: formatTimer(ejectionTime), @@ -91,7 +91,7 @@ const EjectCrew = ({ asteroid, origin, originLot, stationedCrews, manager, stage }, ]), [targetCrew]); - const crewHasPermission = useCallback((c) => { + const crewHasPermission = useCallback(import.meta.url, (c) => { if (c && origin) { const perm = Permission.getPolicyDetails(origin, c, blockTime)[Permission.IDS.STATION_CREW]; if (perm && (perm.crewStatus === 'controller' || perm.crewStatus === 'granted')) { @@ -101,15 +101,15 @@ const EjectCrew = ({ asteroid, origin, originLot, stationedCrews, manager, stage return false; }, [blockTime, origin]); - const targetCrewHasPermission = useMemo(() => crewHasPermission(targetCrew), [origin, targetCrew]); + const targetCrewHasPermission = useMemo(import.meta.url, () => crewHasPermission(targetCrew), [origin, targetCrew]); - const onEject = useCallback(() => { + const onEject = useCallback(import.meta.url, () => { ejectCrew(targetCrewId); }, [targetCrewId]); // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { // (close on status change from) if (lastStatus.current && ejectionStatus !== lastStatus.current) { props.onClose(); @@ -117,7 +117,7 @@ const EjectCrew = ({ asteroid, origin, originLot, stationedCrews, manager, stage lastStatus.current = ejectionStatus; }, [ejectionStatus]); - const actionDetails = useMemo(() => { + const actionDetails = useMemo(import.meta.url, () => { const icon = myCrewIsTarget ? : ; const label = myCrewIsTarget ? 'Eject My Crew' : 'Force Eject Crew'; const status = stage === actionStages.NOT_STARTED @@ -126,7 +126,7 @@ const EjectCrew = ({ asteroid, origin, originLot, stationedCrews, manager, stage return { icon, label, status }; }, [myCrewIsTarget, origin, stage]); - const allowAction = useMemo(() => { + const allowAction = useMemo(import.meta.url, () => { if (targetCrew) { // can eject if ejecting self OR the crew does not have permission to be there if (myCrewIsTarget || !targetCrewHasPermission) return true; @@ -275,10 +275,10 @@ const Wrapper = (props) => { const { crew } = useCrewContext(); // NOTE: use props.origin for guests - const originEntity = useMemo(() => props.origin || crew?.Location?.location, [crew?.Location?.location, props.origin]); + const originEntity = useMemo(import.meta.url, () => props.origin || crew?.Location?.location, [crew?.Location?.location, props.origin]); const { data: allStationedCrews } = useStationedCrews(originEntity); const { data: origin, isLoading: entityIsLoading } = useEntity(originEntity); - const originLocation = useMemo(() => locationsArrToObj(origin?.Location?.locations || []), [origin]); + const originLocation = useMemo(import.meta.url, () => locationsArrToObj(origin?.Location?.locations || []), [origin]); // asteroid is origin's asteroid OR destination asteroid (if origin is ship in flight) const { data: asteroid, isLoading: asteroidIsLoading } = useAsteroid(originLocation?.asteroidId || origin?.Ship?.transitDestination?.id); @@ -287,7 +287,7 @@ const Wrapper = (props) => { const ejectCrewManager = useEjectCrewManager(origin); // ejection is weird, so create a psuedo manager to make it seem more normal - const manager = useMemo(() => { + const manager = useMemo(import.meta.url, () => { const currentEjection = ejectCrewManager.currentEjections?.[0]; // TODO: ... return { ejectCrew: ejectCrewManager.ejectCrew, @@ -297,7 +297,7 @@ const Wrapper = (props) => { }, [ejectCrewManager]); const isLoading = entityIsLoading || asteroidIsLoading || lotIsLoading; - useEffect(() => { + useEffect(import.meta.url, () => { if (!origin) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/EmergencyModeCollect.js b/src/game/interface/hud/actionDialogs/EmergencyModeCollect.js index 003fd4dbd..075262128 100644 --- a/src/game/interface/hud/actionDialogs/EmergencyModeCollect.js +++ b/src/game/interface/hud/actionDialogs/EmergencyModeCollect.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Crewmate, Inventory, Product, Ship, Time } from '@influenceth/sdk'; @@ -70,7 +70,7 @@ const EmergencyModeCollect = ({ asteroid, lot, manager, ship, stage, ...props }) startingAmount, totalAmount, totalEmergencyFraction - } = useMemo(() => { + } = useMemo(import.meta.url, () => { const shipConfig = Ship.TYPES[ship.Ship.shipType]; const propellantInventory = ship.Inventories.find((i) => i.slot === shipConfig.propellantSlot); const propellantInventoryConfig = Inventory.getType(propellantInventory.inventoryType, crew?._inventoryBonuses); @@ -90,7 +90,7 @@ const EmergencyModeCollect = ({ asteroid, lot, manager, ship, stage, ...props }) }; }, [crew?._inventoryBonuses, resourceId, ship, collectableAmount]); - const recalculateCollectableAmount = useCallback(() => { + const recalculateCollectableAmount = useCallback(import.meta.url, () => { setCollectableAmount( Math.floor( Ship.Entity.getEmergencyPropellantAmount(ship, crew?._inventoryBonuses, crew?._timeAcceleration) - startingAmount @@ -98,20 +98,20 @@ const EmergencyModeCollect = ({ asteroid, lot, manager, ship, stage, ...props }) ); }, [crew, ship, startingAmount]); - useEffect(() => { + useEffect(import.meta.url, () => { recalculateCollectableAmount(); const i = setInterval(recalculateCollectableAmount, 1000); return () => clearInterval(i); }, [recalculateCollectableAmount]); - const maxGenerationTime = useMemo(() => { + const maxGenerationTime = useMemo(import.meta.url, () => { return Time.toRealDuration( Ship.Entity.getTimeUntilEmergencyPropellantFull(ship, crew?._inventoryBonuses), crew?._timeAcceleration ); }, [crew?._timeAcceleration, ship]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Generation Time', value: formatTimer( @@ -142,13 +142,13 @@ const EmergencyModeCollect = ({ asteroid, lot, manager, ship, stage, ...props }) }, ]), [maxGenerationTime, ship, syncedTime]); - const onCollect = useCallback(() => { + const onCollect = useCallback(import.meta.url, () => { collectEmergencyPropellant(); }, [collectEmergencyPropellant]); // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { // (close on status change from) if (lastStatus.current && actionStage !== lastStatus.current) { props.onClose(); @@ -251,7 +251,7 @@ const Wrapper = (props) => { const { data: lot, isLoading: lotIsLoading } = useAsteroid(crew?._location?.lotId); const { data: maybeShip, isLoading: shipIsLoading } = useShip(crew?._location?.shipId); - const ship = useMemo(() => { + const ship = useMemo(import.meta.url, () => { return (!maybeShip && crew?.Ship?.emergencyAt > 0) ? crew : maybeShip; }, [crew]); @@ -259,7 +259,7 @@ const Wrapper = (props) => { const { actionStage } = manager; const isLoading = asteroidIsLoading || lotIsLoading || shipIsLoading; - useEffect(() => { + useEffect(import.meta.url, () => { if ((!asteroid || !ship) && !isLoading && props.onClose) { props.onClose(); } diff --git a/src/game/interface/hud/actionDialogs/EmergencyModeToggle.js b/src/game/interface/hud/actionDialogs/EmergencyModeToggle.js index 5dc9c7fd8..2f4525049 100644 --- a/src/game/interface/hud/actionDialogs/EmergencyModeToggle.js +++ b/src/game/interface/hud/actionDialogs/EmergencyModeToggle.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef } from 'react'; +import { useCallback, useEffect, useMemo, useRef } from '~/lib/react-debug'; import styled from 'styled-components'; import { Inventory, Product, Ship } from '@influenceth/sdk'; @@ -54,25 +54,25 @@ const EmergencyModeToggle = ({ asteroid, lot, manager, ship, stage, ...props }) const { crew } = useCrewContext(); const { data: shipCrews } = useStationedCrews(ship); - const shipPassengerCrews = useMemo(() => (shipCrews || []).filter((c) => c.id !== crew?.id), [shipCrews]); + const shipPassengerCrews = useMemo(import.meta.url, () => (shipCrews || []).filter((c) => c.id !== crew?.id), [shipCrews]); - const inEmergencyMode = useMemo(() => { + const inEmergencyMode = useMemo(import.meta.url, () => { if (manager.isActivating) return false; if (manager.isDeactivating) return true; return ship?.Ship?.emergencyAt > 0; }, [manager, ship]); - const cargoInventory = useMemo(() => { + const cargoInventory = useMemo(import.meta.url, () => { const shipConfig = Ship.TYPES[ship.Ship.shipType]; return ship.Inventories.find((i) => i.slot === shipConfig.cargoSlot); }, [ship]); - const propellantInventory = useMemo(() => { + const propellantInventory = useMemo(import.meta.url, () => { const shipConfig = Ship.TYPES[ship.Ship.shipType]; return ship.Inventories.find((i) => i.slot === shipConfig.propellantSlot); }, [ship]); - const propellantJettisoned = useMemo(() => { + const propellantJettisoned = useMemo(import.meta.url, () => { if (inEmergencyMode) { // if exiting emergency mode, jettison up to 10% of max propellant const shipConfig = Ship.TYPES[ship.Ship.shipType]; const maxProp = shipConfig.emergencyPropellantCap * Inventory.getType(propellantInventory.inventoryType, crew?._inventoryBonuses)?.massConstraint; @@ -81,7 +81,7 @@ const EmergencyModeToggle = ({ asteroid, lot, manager, ship, stage, ...props }) return 0; }, [crew?._inventoryBonuses, inEmergencyMode, propellantInventory, ship]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Cargo Mass Jettisoned', value: formatMass(inEmergencyMode ? 0 : cargoInventory.mass), @@ -104,7 +104,7 @@ const EmergencyModeToggle = ({ asteroid, lot, manager, ship, stage, ...props }) }, ]), [cargoInventory, inEmergencyMode, propellantInventory]); - const onToggle = useCallback(() => { + const onToggle = useCallback(import.meta.url, () => { if (inEmergencyMode) { deactivateEmergencyMode(); } else { @@ -114,7 +114,7 @@ const EmergencyModeToggle = ({ asteroid, lot, manager, ship, stage, ...props }) // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { // (close on status change from) if (lastStatus.current && actionStage !== lastStatus.current) { props.onClose(); @@ -122,7 +122,7 @@ const EmergencyModeToggle = ({ asteroid, lot, manager, ship, stage, ...props }) lastStatus.current = actionStage; }, [actionStage]); - const actionDetails = useMemo(() => { + const actionDetails = useMemo(import.meta.url, () => { const icon = inEmergencyMode ? : ; const label = `${inEmergencyMode ? 'Exit' : 'Enter'} Emergency Mode`; const status = stage === actionStages.NOT_STARTED @@ -131,7 +131,7 @@ const EmergencyModeToggle = ({ asteroid, lot, manager, ship, stage, ...props }) return { icon, label, status }; }, [ship, stage]); - const warnings = useMemo(() => { + const warnings = useMemo(import.meta.url, () => { const w = []; const shipConfig = Ship.TYPES[ship.Ship.shipType]; if (inEmergencyMode) { @@ -230,7 +230,7 @@ const Wrapper = (props) => { const { actionStage } = manager; const isLoading = asteroidIsLoading || lotIsLoading || shipIsLoading; - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !ship) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/EvictShip.js b/src/game/interface/hud/actionDialogs/EvictShip.js index 4b093baf6..cd309dfcb 100644 --- a/src/game/interface/hud/actionDialogs/EvictShip.js +++ b/src/game/interface/hud/actionDialogs/EvictShip.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { Crew, Crewmate, Ship } from '@influenceth/sdk'; import { LaunchShipIcon, RouteIcon, ShipIcon, WarningOutlineIcon } from '~/components/Icons'; @@ -44,7 +44,7 @@ const EvictShip = ({ asteroid, lot, manager, stage, ...props }) => { const [tab, setTab] = useState(0); const ship = Ship.TYPES[1]; // TODO - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Propellant Used', value: `0 tonnes`, @@ -88,13 +88,13 @@ const EvictShip = ({ asteroid, lot, manager, stage, ...props }) => { }, ]), []); - const onLaunch = useCallback(() => { + const onLaunch = useCallback(import.meta.url, () => { startLaunch(); }, []); // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { // (close on status change from) if (['READY', 'READY_TO_FINISH', 'FINISHING'].includes(lastStatus.current)) { if (launchStatus !== lastStatus.current) { @@ -227,7 +227,7 @@ const Wrapper = (props) => { const manager = {}; const actionStage = actionStages.NOT_STARTED; - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/Extract.js b/src/game/interface/hud/actionDialogs/Extract.js index 45fff607a..37c6be17b 100644 --- a/src/game/interface/hud/actionDialogs/Extract.js +++ b/src/game/interface/hud/actionDialogs/Extract.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid, Crewmate, Deposit, Extractor, Inventory, Lot, Permission, Product, Time } from '@influenceth/sdk'; import cloneDeep from 'lodash/cloneDeep'; @@ -88,7 +88,7 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { const { data: buildingOwner } = useCrew(lot?.building?.Control?.controller?.id); - const isPurchase = useMemo( + const isPurchase = useMemo(import.meta.url, () => selectedCoreSample && selectedCoreSample?.Control?.controller?.id !== crew?.id, [crew?.id, selectedCoreSample?.Control?.controller?.id] ); @@ -97,11 +97,11 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { // get destinationLot and destinationInventory const [destinationSelection, setDestinationSelection] = useState(); const { data: destination } = useEntity(destinationSelection ? { id: destinationSelection.id, label: destinationSelection.label } : undefined); - const destinationLotId = useMemo(() => destination && locationsArrToObj(destination?.Location?.locations || []).lotId, [destination]); + const destinationLotId = useMemo(import.meta.url, () => destination && locationsArrToObj(destination?.Location?.locations || []).lotId, [destination]); const { data: destinationLot } = useLot(destinationLotId); - const destinationInventory = useMemo(() => (destination?.Inventories || []).find((i) => i.slot === destinationSelection?.slot), [destination, destinationSelection]); + const destinationInventory = useMemo(import.meta.url, () => (destination?.Inventories || []).find((i) => i.slot === destinationSelection?.slot), [destination, destinationSelection]); - useEffect(() => { + useEffect(import.meta.url, () => { const defaultSelection = props.preselect || currentExtraction; if (defaultSelection?.destination) { setDestinationSelection({ @@ -113,7 +113,7 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { } }, [currentExtraction?.destination]); - const [crewTravelBonus, crewDistBonus, extractionBonus] = useMemo(() => { + const [crewTravelBonus, crewDistBonus, extractionBonus] = useMemo(import.meta.url, () => { const bonusIds = [ Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, @@ -139,7 +139,7 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { return bonusIds.map((id) => abilities[id] || {}); }, [crew, selectedCoreSample?.Deposit?.resource]); - const usableSamples = useMemo(() => { + const usableSamples = useMemo(import.meta.url, () => { return (lot?.deposits || []).filter((d) => ( (d.Control.controller.id === crew?.id || d.PrivateSale?.amount > 0) && d.Deposit.remainingYield > 0 @@ -147,7 +147,7 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { )); }, [lot?.deposits, crew?.id]); - const selectCoreSample = useCallback((sample) => { + const selectCoreSample = useCallback(import.meta.url, (sample) => { setSelectedCoreSample(sample); setAmount(0); if (sample) { @@ -157,7 +157,7 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { } }, []); - useEffect(() => { + useEffect(import.meta.url, () => { let defaultSelection; // handle "currentExtraction" state @@ -183,12 +183,12 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { } }, [currentExtraction, !selectedCoreSample, lot?.deposits, usableSamples]); - const resource = useMemo(() => { + const resource = useMemo(import.meta.url, () => { if (!selectedCoreSample) return null; return Product.TYPES[selectedCoreSample.Deposit.resource]; }, [selectedCoreSample]); - const extractionTime = useMemo(() => { + const extractionTime = useMemo(import.meta.url, () => { if (!selectedCoreSample) return 0; return Time.toRealDuration( Extractor.getExtractionTime( @@ -201,7 +201,7 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { ); }, [amount, crew?._timeAcceleration, extractionBonus, resource, selectedCoreSample]); - const { totalTime: crewTravelTime, tripDetails } = useMemo(() => { + const { totalTime: crewTravelTime, tripDetails } = useMemo(import.meta.url, () => { if (!asteroid?.id || !crew?._location?.lotId || !lot?.id) return {}; const crewLotIndex = Lot.toIndex(crew?._location?.lotId); return getTripDetails(asteroid.id, crewTravelBonus, crewDistBonus, crewLotIndex, [ @@ -210,7 +210,7 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { ], crew?._timeAcceleration); }, [asteroid?.id, lot?.id, crew?._location?.lotId, crew?._timeAcceleration, crewTravelBonus, crewDistBonus]); - const [transportDistance, transportTime] = useMemo(() => { + const [transportDistance, transportTime] = useMemo(import.meta.url, () => { if (!destinationLot?.id) return []; return [ Asteroid.getLotDistance(asteroid?.id, Lot.toIndex(lot?.id), Lot.toIndex(destinationLot?.id)) || 0, @@ -227,7 +227,7 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { ]; }, [asteroid?.id, lot?.id, crew?._timeAcceleration, destinationLot?.id, crewDistBonus, crewTravelBonus]); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { const oneWayCrewTravelTime = crewTravelTime / 2; return [ crewTravelTime + extractionTime / 8, @@ -235,7 +235,7 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { ]; }, [crew?._timeAcceleration, extractionTime, crewTravelTime, transportTime]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Extraction Mass', value: `${formatSampleMass(amount * resource?.massPerUnit || 0)} tonnes`, @@ -292,11 +292,11 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { }, ]), [amount, crewTravelBonus, crewTravelTime, extractionBonus, extractionTime, resource, transportDistance, transportTime]); - const prepaidLeaseConfig = useMemo(() => { + const prepaidLeaseConfig = useMemo(import.meta.url, () => { return getProcessorLeaseConfig(lot?.building, Permission.IDS.EXTRACT_RESOURCES, crew, blockTime); }, [blockTime, crew, lot?.building]); - const { leasePayment, desiredLeaseTerm, actualLeaseTerm } = useMemo(() => { + const { leasePayment, desiredLeaseTerm, actualLeaseTerm } = useMemo(import.meta.url, () => { return getProcessorLeaseSelections( prepaidLeaseConfig, taskTimeRequirement, @@ -305,7 +305,7 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { ); }, [blockTime, crew?.Crew?.readyAt, prepaidLeaseConfig, taskTimeRequirement]); - const onStartExtraction = useCallback(() => { + const onStartExtraction = useCallback(import.meta.url, () => { if (!(amount && selectedCoreSample && destination && destinationInventory)) return; if (isPurchase && !depositOwner) return; if (leasePayment && !buildingOwner?.Crew?.delegatedTo) return; @@ -359,7 +359,7 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { // (close on status change from) if (['READY', 'READY_TO_FINISH', 'FINISHING'].includes(lastStatus.current)) { if (extractionStatus !== lastStatus.current) { @@ -369,7 +369,7 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { lastStatus.current = extractionStatus; }, [extractionStatus]); - const [extraDepositProps, extraDepositThumbnailProps] = useMemo(() => { + const [extraDepositProps, extraDepositThumbnailProps] = useMemo(import.meta.url, () => { if (isPurchase && stage === actionStage.NOT_STARTED) { return [ { @@ -407,7 +407,7 @@ const Extract = ({ asteroid, lot, extractionManager, stage, ...props }) => { return [{}, {}]; }, [depositOwner, selectedCoreSample]); - const goLabel = useMemo(() => { + const goLabel = useMemo(import.meta.url, () => { const paymentTotal = (selectedCoreSample?.PrivateSale?.amount || 0) + (leasePayment || 0); if (paymentTotal) { return ( @@ -631,7 +631,7 @@ const Wrapper = (props) => { const extractionManager = useExtractionManager(lot?.id); const { actionStage } = extractionManager; - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/FeedCrew.js b/src/game/interface/hud/actionDialogs/FeedCrew.js index fae85f029..767f41c1f 100644 --- a/src/game/interface/hud/actionDialogs/FeedCrew.js +++ b/src/game/interface/hud/actionDialogs/FeedCrew.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { Asteroid, Crew, Crewmate, Lot, Permission, Product, Time } from '@influenceth/sdk'; import styled from 'styled-components'; @@ -99,12 +99,12 @@ const FeedCrew = ({ const { crew, crewCan } = useCrewContext(); const blockTime = useBlockTime(); - const crewTravelBonus = useMemo(() => { + const crewTravelBonus = useMemo(import.meta.url, () => { if (!crew) return {}; return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, crew) || {}; }, [crew]); - const crewDistBonus = useMemo(() => { + const crewDistBonus = useMemo(import.meta.url, () => { if (!crew) return {}; return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, crew) || {}; }, [crew]); @@ -134,29 +134,29 @@ const FeedCrew = ({ }) || undefined ); - const originId = useMemo(() => { + const originId = useMemo(import.meta.url, () => { if (exchangeSelection) return exchangeSelection.entity; if (inventorySelection) return { id: inventorySelection.id, label: inventorySelection.label }; return undefined; }, [exchangeSelection, inventorySelection]); const { data: origin } = useEntity(originId); - const originLotId = useMemo(() => origin && locationsArrToObj(origin?.Location?.locations || []).lotId, [origin]); + const originLotId = useMemo(import.meta.url, () => origin && locationsArrToObj(origin?.Location?.locations || []).lotId, [origin]); const { data: originLot } = useLot(originLotId); - const originInventory = useMemo(() => (origin?.Inventories || []).find((i) => i.slot === inventorySelection?.slot), [origin, inventorySelection]); + const originInventory = useMemo(import.meta.url, () => (origin?.Inventories || []).find((i) => i.slot === inventorySelection?.slot), [origin, inventorySelection]); // handle "currentFeeding" state (or selectedItems for exchanges) - useEffect(() => { + useEffect(import.meta.url, () => { if (currentFeeding) { setSelectedItems({ [Product.IDS.FOOD]: currentFeeding.vars?.food || 0 }); } }, [currentFeeding]); - const handleExchangeSelection = useCallback((selection) => { + const handleExchangeSelection = useCallback(import.meta.url, (selection) => { setExchangeSelection(selection); setSelectedItems(selection ? { [Product.IDS.FOOD]: selection?.fillAmount || 0 } : {}); }, []); - const [transportDistance, transportTime] = useMemo(() => { + const [transportDistance, transportTime] = useMemo(import.meta.url, () => { if (!asteroid?.id || !originLot?.id) return [0, 0]; const originLotIndex = Lot.toIndex(originLot?.id); const destinationLotIndex = crew?._location?.lotIndex; @@ -170,7 +170,7 @@ const FeedCrew = ({ return [transportDistance, transportTime]; }, [asteroid?.id, originLot?.id, crewTravelBonus, crewDistBonus, crew?._location?.lotIndex, crew?._timeAcceleration]); - const { totalMass, totalVolume } = useMemo(() => { + const { totalMass, totalVolume } = useMemo(import.meta.url, () => { return Object.keys(selectedItems).reduce((acc, resourceId) => { acc.totalMass += selectedItems[resourceId] * Product.TYPES[resourceId].massPerUnit; acc.totalVolume += selectedItems[resourceId] * Product.TYPES[resourceId].volumePerUnit; @@ -178,14 +178,14 @@ const FeedCrew = ({ }, { totalMass: 0, totalVolume: 0 }) }, [selectedItems]); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { return [ transportTime, 0 ]; }, [transportTime]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Task Duration', value: formatTimer(transportTime), @@ -216,7 +216,7 @@ const FeedCrew = ({ }, ]), [totalMass, totalVolume, transportDistance, transportTime]); - const onClear = useCallback(() => { + const onClear = useCallback(import.meta.url, () => { setExchangeSelection(); setInventorySelection(); setSelectedItems({}); @@ -225,7 +225,7 @@ const FeedCrew = ({ const { data: exchangeOwnerCrew } = useCrew(exchangeSelection ? origin?.Control?.controller?.id : undefined); const { data: sellerCrew } = useCrew(exchangeSelection?.crew?.id); - const onStartFeedingFromExchange = useCallback(() => { + const onStartFeedingFromExchange = useCallback(import.meta.url, () => { feedCrew({ ...exchangeSelection, sellerAccount: sellerCrew?.Crew?.delegatedTo, @@ -233,7 +233,7 @@ const FeedCrew = ({ }); }, [exchangeSelection, exchangeOwnerCrew, sellerCrew]); - const onStartFeedingFromInventory = useCallback(() => { + const onStartFeedingFromInventory = useCallback(import.meta.url, () => { feedCrew({ origin, originSlot: originInventory?.slot, @@ -241,12 +241,12 @@ const FeedCrew = ({ }); }, [origin, originInventory, selectedItems]); - const onStartFeeding = useCallback(() => { + const onStartFeeding = useCallback(import.meta.url, () => { if (exchangeSelection) onStartFeedingFromExchange(); else onStartFeedingFromInventory(); }, [exchangeSelection, onStartFeedingFromExchange, onStartFeedingFromInventory]); - const foodStats = useMemo(() => { + const foodStats = useMemo(import.meta.url, () => { const maxFood = (crew?._crewmates?.length || 1) * Crew.CREWMATE_FOOD_PER_YEAR; const timeSinceFed = Time.toGameDuration(blockTime - (crew?.Crew?.lastFed || 0), crew?._timeAcceleration); const currentFood = Math.floor(maxFood * Crew.getCurrentFoodRatio(timeSinceFed, crew._foodBonuses?.consumption)); // floor to quanta @@ -271,7 +271,7 @@ const FeedCrew = ({ } }, [crew?._crewmates, crew?.Crew?.lastFed, crew?._timeAcceleration, blockTime, selectedItems]); - const disabled = useMemo(() => { + const disabled = useMemo(import.meta.url, () => { if (!origin) return true; if (totalMass === 0) return true; if (inventorySelection) return !crewCan(Permission.IDS.REMOVE_PRODUCTS, origin); @@ -485,7 +485,7 @@ const Wrapper = (props) => { // handle auto-closing on any status change const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (lastStatus.current && stage !== lastStatus.current) { props.onClose(); } diff --git a/src/game/interface/hud/actionDialogs/FormAgreement.js b/src/game/interface/hud/actionDialogs/FormAgreement.js index 46a502982..b82470d26 100644 --- a/src/game/interface/hud/actionDialogs/FormAgreement.js +++ b/src/game/interface/hud/actionDialogs/FormAgreement.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { Entity, Permission, Time } from '@influenceth/sdk'; import styled from 'styled-components'; import Clipboard from 'react-clipboard.js'; @@ -158,7 +158,7 @@ const FormAgreement = ({ // NOTE: this flow is only relevant to prepaid and contract policy types now, so no account-permitted stuff here yet const { data: permitted } = useCrew(currentAgreement?.permitted?.id); - const maxTerm = useMemo(() => { + const maxTerm = useMemo(import.meta.url, () => { const now = Math.floor(Date.now() / 1000); if (isExtension && currentAgreement?.endTime > now) { return 365 - secondsToDays(Math.max(0, currentAgreement?.endTime - currentAgreement?.startTime)); @@ -166,9 +166,9 @@ const FormAgreement = ({ return 365; }, [currentAgreement, isExtension]); - const maxTermFloored = useMemo(() => Math.floor(maxTerm * 10) / 10, [maxTerm]); + const maxTermFloored = useMemo(import.meta.url, () => Math.floor(maxTerm * 10) / 10, [maxTerm]); - const minTerm = useMemo(() => { + const minTerm = useMemo(import.meta.url, () => { return (isExtension) ? 1 : currentPolicy?.policyDetails?.initialTerm || 0 }, [currentPolicy]); @@ -178,11 +178,11 @@ const FormAgreement = ({ : (isExtension ? Math.min(maxTermFloored, 30) : (currentPolicy?.policyDetails?.initialTerm || 0)) ); - const remainingPeriod = useMemo(() => currentAgreement?.endTime - blockTime, [blockTime, currentAgreement?.endTime]); - const refundablePeriod = useMemo(() => Math.max(0, remainingPeriod - monthsToSeconds(currentAgreement?.noticePeriod)), [currentAgreement?.noticePeriod, remainingPeriod]); - const refundableAmount = useMemo(() => refundablePeriod * (currentAgreement?.rate_swayPerSec || 0), [currentAgreement?.rate_swayPerSec, refundablePeriod]); + const remainingPeriod = useMemo(import.meta.url, () => currentAgreement?.endTime - blockTime, [blockTime, currentAgreement?.endTime]); + const refundablePeriod = useMemo(import.meta.url, () => Math.max(0, remainingPeriod - monthsToSeconds(currentAgreement?.noticePeriod)), [currentAgreement?.noticePeriod, remainingPeriod]); + const refundableAmount = useMemo(import.meta.url, () => refundablePeriod * (currentAgreement?.rate_swayPerSec || 0), [currentAgreement?.rate_swayPerSec, refundablePeriod]); - const stats = useMemo(() => { + const stats = useMemo(import.meta.url, () => { if (isTermination) { return [ { @@ -216,18 +216,18 @@ const FormAgreement = ({ return []; }, [crew, currentAgreement, currentPolicy, initialPeriod, isExtension, isTermination, remainingPeriod]); - const totalLeaseCost = useMemo(() => { + const totalLeaseCost = useMemo(import.meta.url, () => { return (initialPeriod || 0) * 24 * (currentPolicy?.policyDetails?.rate || 0); }, [initialPeriod, currentPolicy]); - const insufficientAssets = useMemo( + const insufficientAssets = useMemo(import.meta.url, () => safeBigInt(Math.ceil(isTermination ? refundableAmount : totalLeaseCost)) > swayBalance, [swayBalance, refundableAmount, totalLeaseCost, isTermination] ); const [eligible, setEligible] = useState(false); const [eligibilityLoading, setEligibilityLoading] = useState(false); - const updateContractEligibility = useCallback(async () => { + const updateContractEligibility = useCallback(import.meta.url, async () => { if (!provider) return; if (!currentPolicy?.policyDetails?.contract) return; try { @@ -248,11 +248,11 @@ const FormAgreement = ({ setEligibilityLoading(false); }, [crew?.id, crew?.label, currentPolicy?.policyDetails?.contract, entity, permission, provider]); - useEffect(() => { + useEffect(import.meta.url, () => { updateContractEligibility() }, [updateContractEligibility]); - const handleCopyAddress = useCallback(() => { + const handleCopyAddress = useCallback(import.meta.url, () => { createAlert({ type: 'ClipboardAlert', data: { content: 'Contract address copied to clipboard.' }, @@ -260,20 +260,20 @@ const FormAgreement = ({ }); }, [createAlert]); - const handlePeriodChange = useCallback((e) => { + const handlePeriodChange = useCallback(import.meta.url, (e) => { if (e.currentTarget.value === '') return setInitialPeriod(''); const parsed = numeral(e.currentTarget.value); if (!parsed) return setInitialPeriod(e.currentTarget.value); setInitialPeriod(parsed.value()); - }); + }, []); - const handlePeriodBlur = useCallback((e) => { + const handlePeriodBlur = useCallback(import.meta.url, (e) => { if (e.currentTarget.value === '') return setInitialPeriod(''); const parsed = numeral(e.currentTarget.value); setInitialPeriod(numeral(Math.max(minTerm, Math.min(parsed.value(), maxTerm))).format('0.00')); }, [currentPolicy?.policyDetails?.initialTerm, maxTerm]); - const onEnterAgreement = useCallback(() => { + const onEnterAgreement = useCallback(import.meta.url, () => { const recipient = controller?.Crew?.delegatedTo; // TODO: should these conversions be in useAgreementManager? const term = daysToSeconds(initialPeriod); @@ -281,7 +281,7 @@ const FormAgreement = ({ enterAgreement({ recipient, term, termPrice }); }, [controller?.Crew?.delegatedTo, enterAgreement, initialPeriod, totalLeaseCost]); - const onExtendAgreement = useCallback(() => { + const onExtendAgreement = useCallback(import.meta.url, () => { const recipient = controller?.Crew?.delegatedTo; // TODO: should these conversions be in useAgreementManager? const term = Math.round(daysToSeconds(initialPeriod)); @@ -289,21 +289,21 @@ const FormAgreement = ({ extendAgreement({ recipient, term, termPrice }); }, [controller?.Crew?.delegatedTo, extendAgreement, initialPeriod, totalLeaseCost]); - const onTerminateAgreement = useCallback(() => { + const onTerminateAgreement = useCallback(import.meta.url, () => { cancelAgreement({ recipient: permitted?.Crew?.delegatedTo, refundAmount: Math.ceil(refundableAmount * TOKEN_SCALE[TOKEN.SWAY]) }) }, [cancelAgreement, permitted, refundableAmount]); - const alertScheme = useMemo(() => { + const alertScheme = useMemo(import.meta.url, () => { if (currentPolicy?.policyType === Permission.POLICY_IDS.CONTRACT) { if (!eligibilityLoading) return eligible ? 'success' : 'error'; } return '' }, [currentPolicy, eligibilityLoading, eligible]); - const actionDetails = useMemo(() => { + const actionDetails = useMemo(import.meta.url, () => { const policyType = currentPolicy?.policyType; if (isTermination) { return { @@ -334,7 +334,7 @@ const FormAgreement = ({ } }, [currentAgreement?.noticePeriod, currentPolicy?.policyType, entity, isExtension, isTermination, onEnterAgreement, onExtendAgreement, onTerminateAgreement, stage]); - const disableGo = useMemo(() => { + const disableGo = useMemo(import.meta.url, () => { if (insufficientAssets) return true; if (isTermination && currentAgreement?._canGiveNoticeStart > blockTime) return true; if (initialPeriod === '' || initialPeriod <= 0) return true; @@ -603,7 +603,7 @@ const Wrapper = ({ entity: entityId, permission, isExtension, agreementPath, ... // handle auto-closing on any status change const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (lastStatus.current && stage !== lastStatus.current) { props.onClose(); } @@ -612,7 +612,7 @@ const Wrapper = ({ entity: entityId, permission, isExtension, agreementPath, ... } }, [stage, props]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!entityIsLoading && !entity) { props.onClose(); } diff --git a/src/game/interface/hud/actionDialogs/ImproveCoreSample.js b/src/game/interface/hud/actionDialogs/ImproveCoreSample.js index c056285a0..6238ce554 100644 --- a/src/game/interface/hud/actionDialogs/ImproveCoreSample.js +++ b/src/game/interface/hud/actionDialogs/ImproveCoreSample.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { Asteroid, Crewmate, Deposit, Lot, Product, Time } from '@influenceth/sdk'; import { CoreSampleIcon, ImproveCoreSampleIcon, ResourceIcon, SwayIcon, WarningIcon } from '~/components/Icons'; @@ -80,7 +80,7 @@ const ImproveCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAc const dispatchResourceMapSelect = useStore(s => s.dispatchResourceMapSelect); const resourceMap = useStore(s => s.asteroids.resourceMap); - const prepop = useMemo(() => ({ + const prepop = useMemo(import.meta.url, () => ({ sampleId: currentSamplingAction?.sampleId || props.preselect?.sampleId, resourceId: currentSamplingAction?.resourceId || props.preselect?.resourceId, origin: currentSamplingAction?.origin ? { ...currentSamplingAction.origin } : props.preselect?.origin, @@ -94,7 +94,7 @@ const ImproveCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAc const [sampleSelectorOpen, setSampleSelectorOpen] = useState(false); const [sourceSelectorOpen, setSourceSelectorOpen] = useState(false); - const improvableSamples = useMemo(() => { + const improvableSamples = useMemo(import.meta.url, () => { return (lot?.deposits || []) .filter((c) => ( (c.id === currentSamplingAction?.sampleId) @@ -107,7 +107,7 @@ const ImproveCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAc .map((c) => ({ ...c, tonnage: c.Deposit.initialYield * Product.TYPES[c.Deposit.resource].massPerUnit })); }, [lot?.deposits]); - const [selectedSample, resourceId, initialYieldTonnage] = useMemo(() => { + const [selectedSample, resourceId, initialYieldTonnage] = useMemo(import.meta.url, () => { const selected = (improvableSamples || []).find((s) => s.id === sampleId); const initialYield = selected?.Deposit.initialYield || 0; const initialYieldTonnage = initialYield * (Product.TYPES[selected?.Deposit.resource]?.massPerUnit || 0); @@ -118,7 +118,7 @@ const ImproveCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAc ]; }, [improvableSamples, sampleId]); - useEffect(() => { + useEffect(import.meta.url, () => { if (currentSamplingAction?.sampleId) { setSampleId(currentSamplingAction.sampleId); } else { @@ -142,23 +142,23 @@ const ImproveCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAc } }, [currentSamplingAction, originEntity, improvableSamples, prepop.sampleId]); - const lotAbundance = useMemo(() => { + const lotAbundance = useMemo(import.meta.url, () => { if (!resourceId || !asteroid?.Celestial?.abundances || !lot?.id) return 0; return Asteroid.Entity.getAbundanceAtLot(asteroid, Lot.toIndex(lot.id), resourceId); }, [asteroid, lot, resourceId]); - const originalYield = useMemo(() => selectedSample?.Deposit?.initialYield, [selectedSample?.id]); // only update on id change - const originalTonnage = useMemo(() => originalYield ? originalYield * Product.TYPES[selectedSample?.Deposit.resource]?.massPerUnit : 0, [selectedSample, originalYield]); + const originalYield = useMemo(import.meta.url, () => selectedSample?.Deposit?.initialYield, [selectedSample?.id]); // only update on id change + const originalTonnage = useMemo(import.meta.url, () => originalYield ? originalYield * Product.TYPES[selectedSample?.Deposit.resource]?.massPerUnit : 0, [selectedSample, originalYield]); - useEffect(() => { + useEffect(import.meta.url, () => { // if open to a different resource map, switch... if a resource map is not open, don't open one if (resourceId && resourceMap?.active && resourceMap.selected !== resourceId) { dispatchResourceMapSelect(resourceId); } }, [resourceId, resourceMap]); - const [crewTravelBonus, crewDistBonus, sampleQualityBonus, sampleTimeBonus] = useMemo(() => { + const [crewTravelBonus, crewDistBonus, sampleQualityBonus, sampleTimeBonus] = useMemo(import.meta.url, () => { const bonusIds = [ Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, @@ -170,7 +170,7 @@ const ImproveCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAc return bonusIds.map((id) => abilities[id] || {}); }, [crew]); - const { totalTime: crewTravelTime, tripDetails } = useMemo(() => { + const { totalTime: crewTravelTime, tripDetails } = useMemo(import.meta.url, () => { if (!asteroid?.id || !crew?._location?.lotId || !lot?.id) return {}; const crewLotIndex = Lot.toIndex(crew?._location?.lotId); return getTripDetails(asteroid.id, crewTravelBonus, crewDistBonus, crewLotIndex, [ @@ -179,14 +179,14 @@ const ImproveCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAc ], crew?._timeAcceleration); }, [asteroid?.id, lot?.id, crew?._location?.lotId, crew?._timeAcceleration, crewTravelBonus, crewDistBonus]); - const [sampleBounds, sampleTime] = useMemo(() => { + const [sampleBounds, sampleTime] = useMemo(import.meta.url, () => { return [ lotAbundance ? Deposit.getSampleBounds(lotAbundance, originalYield * 1e3, sampleQualityBonus.totalBonus) : null, Time.toRealDuration(Deposit.getSampleTime(sampleTimeBonus.totalBonus), crew?._timeAcceleration) ]; }, [lotAbundance, originalYield, sampleQualityBonus, sampleTimeBonus, crew?._timeAcceleration]); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { if (!asteroid?.id || !crew?._location?.lotId || !lot?.id || !drillSource?.lotIndex) return []; const oneWayCrewTravelTime = crewTravelTime / 2; const drillTravelTime = Time.toRealDuration( @@ -205,7 +205,7 @@ const ImproveCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAc ]; }, [asteroid?.id, crew?._location?.lotId, crew?._timeAcceleration, drillSource?.lotIndex, lot?.id, crewDistBonus, crewTravelBonus]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Crew Travel', value: formatTimer(crewTravelTime), @@ -260,7 +260,7 @@ const ImproveCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAc // handle auto-closing const miniStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { let newMiniStatus = 1; if (currentSamplingAction) newMiniStatus = 2; if (currentSamplingAction?.sampleId) newMiniStatus = 3; @@ -273,20 +273,20 @@ const ImproveCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAc miniStatus.current = newMiniStatus; }, [currentSamplingAction]); - const isPurchase = useMemo( + const isPurchase = useMemo(import.meta.url, () => selectedSample && selectedSample?.Control?.controller?.id !== crew?.id, [crew?.id, selectedSample?.Control?.controller?.id] ); const { data: depositOwner } = useCrew(isPurchase ? selectedSample?.Control?.controller?.id : null); - const onImprove = useCallback(() => { + const onImprove = useCallback(import.meta.url, () => { if (isPurchase && !depositOwner) return; startImproving(selectedSample?.id, drillSource, depositOwner); }, [startImproving, selectedSample, drillSource, isPurchase, depositOwner]); - const onFinish = useCallback(() => { + const onFinish = useCallback(import.meta.url, () => { finishSampling(currentSamplingAction?.sampleId) }, [finishSampling, currentSamplingAction]); @@ -460,13 +460,13 @@ const Wrapper = (props) => { const coreSampleManager = useCoreSampleManager(lot?.id); const { currentSamplingActions, completedSamplingActions } = coreSampleManager; - const currentSamplingAction = useMemo(() => { + const currentSamplingAction = useMemo(import.meta.url, () => { const sampleId = props.sampleId || props.preselect?.id; return currentSamplingActions.find((c) => c.action?.sampleId === sampleId) || completedSamplingActions.find((c) => c.action?.sampleId === sampleId); }, [completedSamplingActions, currentSamplingActions, props.sampleId]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/JettisonCargo.js b/src/game/interface/hud/actionDialogs/JettisonCargo.js index b8bae342f..cc57fe06c 100644 --- a/src/game/interface/hud/actionDialogs/JettisonCargo.js +++ b/src/game/interface/hud/actionDialogs/JettisonCargo.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { Asteroid, Crewmate, Entity, Inventory, Lot, Permission, Product, Time } from '@influenceth/sdk'; import styled from 'styled-components'; @@ -65,7 +65,7 @@ const JettisonCargo = ({ const [originSelectorOpen, setOriginSelectorOpen] = useState(false); const [originSelection, setOriginSelection] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { if (!fixedOrigin) return; const availInvs = (fixedOrigin.Inventories || []).filter((i) => i.status === Inventory.STATUSES.AVAILABLE); setOriginSelection({ @@ -80,13 +80,13 @@ const JettisonCargo = ({ }, [currentJettison, fixedOrigin]); const { data: origin } = useEntity(originSelection ? { id: originSelection.id, label: originSelection.label } : undefined); - const originLotId = useMemo(() => origin && locationsArrToObj(origin?.Location?.locations || []).lotId, [origin]); + const originLotId = useMemo(import.meta.url, () => origin && locationsArrToObj(origin?.Location?.locations || []).lotId, [origin]); const { data: originLot } = useLot(originLotId); - const originInventory = useMemo(() => (origin?.Inventories || []).find((i) => i.slot === originSelection?.slot), [origin, originSelection]); - const originInventoryTally = useMemo(() => (origin?.Inventories || []).filter((i) => i.status === Inventory.STATUSES.AVAILABLE).length, [origin]); + const originInventory = useMemo(import.meta.url, () => (origin?.Inventories || []).find((i) => i.slot === originSelection?.slot), [origin, originSelection]); + const originInventoryTally = useMemo(import.meta.url, () => (origin?.Inventories || []).filter((i) => i.status === Inventory.STATUSES.AVAILABLE).length, [origin]); // When a new origin inventory is selected, reset the selected items - const onOriginSelect = useCallback((selection) => { + const onOriginSelect = useCallback(import.meta.url, (selection) => { const { id, label, slot } = originSelection || {}; if (id !== selection.id || label !== selection.label || slot !== selection.slot) { setOriginSelection(selection); @@ -95,13 +95,13 @@ const JettisonCargo = ({ }, [originSelection]); // handle "currentDeliveryAction" state - useEffect(() => { + useEffect(import.meta.url, () => { if (currentJettison) { setSelectedItems(currentJettison.vars.products.reduce((acc, item) => ({ ...acc, [item.product]: item.amount }), {})); } }, [currentJettison]); - const { totalMass, totalVolume } = useMemo(() => { + const { totalMass, totalVolume } = useMemo(import.meta.url, () => { return Object.keys(selectedItems).reduce((acc, resourceId) => { acc.totalMass += selectedItems[resourceId] * Product.TYPES[resourceId].massPerUnit; acc.totalVolume += selectedItems[resourceId] * Product.TYPES[resourceId].volumePerUnit; @@ -109,7 +109,7 @@ const JettisonCargo = ({ }, { totalMass: 0, totalVolume: 0 }) }, [selectedItems]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Deleted Mass', value: `${formatMass(totalMass)}`, @@ -122,7 +122,7 @@ const JettisonCargo = ({ }, ]), [totalMass, totalVolume]); - const onJettison = useCallback(() => { + const onJettison = useCallback(import.meta.url, () => { jettisonCargo( originInventory?.slot, selectedItems, @@ -276,7 +276,7 @@ const Wrapper = (props) => { const { data: originEntity, isLoading: originLoading } = useEntity(jettisonManager.currentJettison?.vars?.origin || props.origin); - useEffect(() => { + useEffect(import.meta.url, () => { if (!props.onClose) return; if (!asteroid && !isLoading) props.onClose(); if (origin && !originEntity && !originLoading) props.onClose(); @@ -284,7 +284,7 @@ const Wrapper = (props) => { // handle auto-closing on any status change const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (lastStatus.current && jettisonManager.actionStage !== lastStatus.current) { if (props.onClose) props.onClose(); } diff --git a/src/game/interface/hud/actionDialogs/LandShip.js b/src/game/interface/hud/actionDialogs/LandShip.js index 0a1637bf6..df15e8258 100644 --- a/src/game/interface/hud/actionDialogs/LandShip.js +++ b/src/game/interface/hud/actionDialogs/LandShip.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { Asteroid, Crewmate, Dock, Entity, Inventory, Lot, Permission, Product, Ship, Time } from '@influenceth/sdk'; import { LandShipIcon, RouteIcon, ShipIcon, WarningOutlineIcon } from '~/components/Icons'; @@ -52,7 +52,7 @@ const LandShip = ({ asteroid, manager, ship, stage, ...props }) => { || undefined; const { data: destinationLot, isLoading: destLotLoading } = useLot(destinationLotId); - const [hopperBonus, distBonus, exhaustBonus] = useMemo(() => { + const [hopperBonus, distBonus, exhaustBonus] = useMemo(import.meta.url, () => { if (!crew) return {}; const bonusIds = [ Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, @@ -64,12 +64,12 @@ const LandShip = ({ asteroid, manager, ship, stage, ...props }) => { return bonusIds.map((id) => abilities[id] || {}); }, [crew]); - const groundDelay = useMemo(() => { + const groundDelay = useMemo(import.meta.url, () => { const delay = destinationLot?.building ? Dock.Entity.getGroundDelay(destinationLot.building) : 0; return Time.toRealDuration(delay, crew?._timeAcceleration); }, [crew?._timeAcceleration, destinationLot?.building]); - const [escapeVelocity, propellantRequirement, poweredTime, tugTime] = useMemo(() => { + const [escapeVelocity, propellantRequirement, poweredTime, tugTime] = useMemo(import.meta.url, () => { const escapeVelocity = Asteroid.Entity.getEscapeVelocity(asteroid) * 1000; const propellantRequired = Ship.Entity.getPropellantRequirement(ship, escapeVelocity, exhaustBonus.totalBonus); const destinationLotIndex = destinationLot ? Lot.toIndex(destinationLot?.id) : 1; @@ -84,7 +84,7 @@ const LandShip = ({ asteroid, manager, ship, stage, ...props }) => { ]; }, [asteroid, destinationLot?.id, distBonus, hopperBonus, powered, exhaustBonus, ship]); - const [propellantLoaded, deltaVLoaded] = useMemo(() => { + const [propellantLoaded, deltaVLoaded] = useMemo(import.meta.url, () => { if (!ship) return 0; const shipConfig = Ship.TYPES[ship.Ship.shipType]; const propellantMass = (ship.Inventories || []).find((inv) => inv.slot === shipConfig.propellantSlot)?.mass || 0; @@ -95,15 +95,15 @@ const LandShip = ({ asteroid, manager, ship, stage, ...props }) => { ]; }, [ship]); - const launchTime = useMemo(() => { + const launchTime = useMemo(import.meta.url, () => { return groundDelay + (powered ? poweredTime : tugTime); }, [groundDelay, powered, poweredTime, tugTime]); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { return [ launchTime, launchTime ]; }, [launchTime]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Time until Docked', value: formatTimer(launchTime), @@ -145,7 +145,7 @@ const LandShip = ({ asteroid, manager, ship, stage, ...props }) => { }, ]), [escapeVelocity, hopperBonus, launchTime, exhaustBonus, propellantRequirement, ship]); - const onLand = useCallback(() => { + const onLand = useCallback(import.meta.url, () => { if (!destinationLot) return; dockShip( destinationLot.building || { label: Entity.IDS.LOT, id: destinationLot.id }, @@ -156,7 +156,7 @@ const LandShip = ({ asteroid, manager, ship, stage, ...props }) => { // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { // (close on status change from) if (lastStatus.current && stage !== lastStatus.current) { props.onClose(); @@ -301,7 +301,7 @@ const Wrapper = (props) => { const isLoading = shipIsLoading || asteroidIsLoading; - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !ship) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/LaunchShip.js b/src/game/interface/hud/actionDialogs/LaunchShip.js index a762ec7ec..36bd3b078 100644 --- a/src/game/interface/hud/actionDialogs/LaunchShip.js +++ b/src/game/interface/hud/actionDialogs/LaunchShip.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { Asteroid, Crewmate, Dock, Inventory, Lot, Product, Ship, Time } from '@influenceth/sdk'; import { LaunchShipIcon, RouteIcon, ShipIcon, WarningOutlineIcon } from '~/components/Icons'; @@ -52,14 +52,14 @@ const LaunchShip = ({ asteroid, originLot, manager, ship, shipCrews, stage, ...p const isForceLaunch = crew?.id !== ship?.Control?.controller?.id; // TODO: in event of self-piloted launch, need to update with cached crew values on flightCrew (just like in other action dialogs while waiting on an action) - const _flightCrew = useMemo(() => shipCrews.find((c) => c.id === ship.Control?.controller?.id), [shipCrews, ship]); + const _flightCrew = useMemo(import.meta.url, () => shipCrews.find((c) => c.id === ship.Control?.controller?.id), [shipCrews, ship]); const { data: flightCrew, ...other } = useHydratedCrew(_flightCrew?.id); // TODO: should this default to hopper-assisted if no propellant? const [powered, setPowered] = useState(isForceLaunch ? false : true); const [tab, setTab] = useState(0); - const [hopperBonus, distBonus, exhaustBonus] = useMemo(() => { + const [hopperBonus, distBonus, exhaustBonus] = useMemo(import.meta.url, () => { const bonusIds = [ Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, @@ -70,12 +70,12 @@ const LaunchShip = ({ asteroid, originLot, manager, ship, shipCrews, stage, ...p return bonusIds.map((id) => abilities[id] || {}); }, [flightCrew]); - const groundDelay = useMemo( + const groundDelay = useMemo(import.meta.url, () => Time.toRealDuration(originLot?.building ? Dock.Entity.getGroundDelay(originLot.building) : 0, crew?._timeAcceleration), [crew?._timeAcceleration, originLot?.building] ); - const [escapeVelocity, propellantRequirement, poweredTime, tugTime] = useMemo(() => { + const [escapeVelocity, propellantRequirement, poweredTime, tugTime] = useMemo(import.meta.url, () => { if (!ship || !asteroid) return [0, 0, 0, 0]; const escapeVelocity = Asteroid.Entity.getEscapeVelocity(asteroid) * 1000; const propellantRequired = Ship.Entity.getPropellantRequirement(ship, escapeVelocity, exhaustBonus.totalBonus); @@ -91,13 +91,13 @@ const LaunchShip = ({ asteroid, originLot, manager, ship, shipCrews, stage, ...p ]; }, [asteroid, distBonus, hopperBonus, originLot?.id, powered, exhaustBonus, ship]); - const isDeliveryPending = useMemo(() => !!(ship?.Inventories || []).find((inv) => inv.reservedMass > 0), [ship]); + const isDeliveryPending = useMemo(import.meta.url, () => !!(ship?.Inventories || []).find((inv) => inv.reservedMass > 0), [ship]); - const isGuestCrewBusy = useMemo(() => { + const isGuestCrewBusy = useMemo(import.meta.url, () => { return shipCrews.some((c) => c.id !== ship?.Control?.controller?.id && c.Crew?.readyAt > blockTime); }, [blockTime, shipCrews]); - const [propellantLoaded, deltaVLoaded] = useMemo(() => { + const [propellantLoaded, deltaVLoaded] = useMemo(import.meta.url, () => { if (!ship) return [0, 0]; const shipConfig = Ship.TYPES[ship.Ship.shipType]; const propellantMass = (ship.Inventories || []).find((inv) => inv.slot === shipConfig.propellantSlot)?.mass || 0; @@ -108,13 +108,13 @@ const LaunchShip = ({ asteroid, originLot, manager, ship, shipCrews, stage, ...p ]; }, [ship]); - const launchTime = useMemo(() => groundDelay + (powered ? poweredTime : tugTime), [groundDelay, powered, poweredTime, tugTime]); + const launchTime = useMemo(import.meta.url, () => groundDelay + (powered ? poweredTime : tugTime), [groundDelay, powered, poweredTime, tugTime]); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { return [ launchTime, launchTime ]; }, [launchTime]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Time until Orbit', value: formatTimer(launchTime), @@ -156,13 +156,13 @@ const LaunchShip = ({ asteroid, originLot, manager, ship, shipCrews, stage, ...p }, ]), [escapeVelocity, hopperBonus, launchTime, exhaustBonus, propellantRequirement, ship]); - const onLaunch = useCallback(() => { + const onLaunch = useCallback(import.meta.url, () => { undockShip(!powered); }, [powered, undockShip]); // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { // (close on status change from) if (lastStatus.current && stage !== lastStatus.current) { props.onClose(); @@ -172,7 +172,7 @@ const LaunchShip = ({ asteroid, originLot, manager, ship, shipCrews, stage, ...p const simulationEnabled = useSimulationEnabled(); const simulationActions = useStore((s) => s.simulationActions); - const simLaunchTypeAllowed = useMemo(() => { + const simLaunchTypeAllowed = useMemo(import.meta.url, () => { if (simulationEnabled) { if (powered) return simulationActions.includes('SelectLaunchType:propulsive'); return simulationActions.includes('SelectLaunchType:tug'); @@ -308,7 +308,7 @@ const Wrapper = (props) => { const isLoading = shipIsLoading || asteroidIsLoading || originLotIsLoading || shipCrewsLoading; - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !originLot || !ship) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/ManageCrew.js b/src/game/interface/hud/actionDialogs/ManageCrew.js index aac4e7e9e..730a16d0b 100644 --- a/src/game/interface/hud/actionDialogs/ManageCrew.js +++ b/src/game/interface/hud/actionDialogs/ManageCrew.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { createPortal } from 'react-dom'; import { useThrottle } from '@react-hook/throttle'; import styled from 'styled-components'; @@ -218,7 +218,7 @@ const ManageCrew = ({ altCrews, crew, isForeignCrew, manager, stage, ...props }) const [dragOffset, setDragOffset] = useState(); const [dragPosition, setDragPosition] = useThrottle(null, 30, true); - const exchangeCrew = useMemo(() => { + const exchangeCrew = useMemo(import.meta.url, () => { if (exchangeCrewId === 0) { return { id: 0, @@ -236,7 +236,7 @@ const ManageCrew = ({ altCrews, crew, isForeignCrew, manager, stage, ...props }) return altCrews.find((c) => c.id === exchangeCrewId); }, [altCrews, exchangeCrewId]) - useEffect(() => { + useEffect(import.meta.url, () => { if (!crew?._crewmates) return; const slots = []; for (let i = 0; i < (exchangeCrew ? 10 : 5); i++) { @@ -246,7 +246,7 @@ const ManageCrew = ({ altCrews, crew, isForeignCrew, manager, stage, ...props }) setPristine(slots.map((c) => c?.id)); }, [crew?._crewmates, exchangeCrew?._crewmates]); - const onSaveChanges = useCallback(() => { + const onSaveChanges = useCallback(import.meta.url, () => { if (!(crew?.id > 0 && orderedCrewmates.length > 0)) return; if (exchangeCrew) { swapCrewmates({ @@ -263,7 +263,7 @@ const ManageCrew = ({ altCrews, crew, isForeignCrew, manager, stage, ...props }) } }, [crew?.id, exchangeCrew, orderedCrewmates, reorderRoster, swapCrewmates]); - const onMouseDown = useCallback((index) => (e) => { + const onMouseDown = useCallback(import.meta.url, (index) => (e) => { e.preventDefault(); setDragOffset({ x: e.nativeEvent?.offsetX, y: e.nativeEvent?.offsetY }); @@ -271,7 +271,7 @@ const ManageCrew = ({ altCrews, crew, isForeignCrew, manager, stage, ...props }) setDragging(index); }, []); - const onMouseUp = useCallback((index) => (e) => { + const onMouseUp = useCallback(import.meta.url, (index) => (e) => { if (dragging >= 0 && index >= 0 && dragging !== index) { // if dropping on a foreign crew (not allowed) if (isForeignCrew && index < 5) { @@ -331,7 +331,7 @@ const ManageCrew = ({ altCrews, crew, isForeignCrew, manager, stage, ...props }) setDragging(); }, [dragging, isForeignCrew]); - useEffect(() => { + useEffect(import.meta.url, () => { const mouseMoveHandler = (e) => setDragPosition({ x: e.clientX, y: e.clientY }); const mouseUpHandler = (e) => onMouseUp(-1); document.addEventListener('mousemove', mouseMoveHandler); @@ -344,7 +344,7 @@ const ManageCrew = ({ altCrews, crew, isForeignCrew, manager, stage, ...props }) // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { // (close on status change from) if (lastStatus.current === actionStages.COMPLETING && stage !== actionStages.COMPLETING) { props.onClose(); @@ -352,7 +352,7 @@ const ManageCrew = ({ altCrews, crew, isForeignCrew, manager, stage, ...props }) lastStatus.current = stage; }, [stage]); - const isPristine = useMemo(() => { + const isPristine = useMemo(import.meta.url, () => { if (!pristine || !orderedCrewmates) return true; return pristine.join(',') === orderedCrewmates.map((c) => c?.id).join(','); }, [pristine, orderedCrewmates]); @@ -483,7 +483,7 @@ const Wrapper = ({ crew, loading, ...props }) => { const crewSwapManager = useCrewSwapManager(); const { actionStage } = crewSwapManager; - const locationCrews = useMemo(() => { + const locationCrews = useMemo(import.meta.url, () => { if (!crew?._location) return []; return crews.filter((c) => ( crew.Location.location.label === c.Location.location.label @@ -493,7 +493,7 @@ const Wrapper = ({ crew, loading, ...props }) => { )); }, [crew?._location]); - useEffect(() => { + useEffect(import.meta.url, () => { // if could not load crew... let shouldClose = !crew && !loading; // or it is a foreign crew without any of my crewmates... diff --git a/src/game/interface/hud/actionDialogs/MarketplaceOrder.js b/src/game/interface/hud/actionDialogs/MarketplaceOrder.js index e0c3283c7..9e21f5ab3 100644 --- a/src/game/interface/hud/actionDialogs/MarketplaceOrder.js +++ b/src/game/interface/hud/actionDialogs/MarketplaceOrder.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid, Crewmate, Inventory, Lot, Order, Permission, Product, Time } from '@influenceth/sdk'; @@ -220,7 +220,7 @@ const MarketplaceOrder = ({ const { crew, crewCan } = useCrewContext(); const { data: orders, refetch } = useOrderList(exchange?.id, resourceId); - const [buyOrders, sellOrders] = useMemo(() => ([ + const [buyOrders, sellOrders] = useMemo(import.meta.url, () => ([ (orders || []).filter((o) => o.orderType === Order.IDS.LIMIT_BUY), (orders || []).filter((o) => o.orderType === Order.IDS.LIMIT_SELL), ]), [orders]); @@ -231,12 +231,12 @@ const MarketplaceOrder = ({ const currentDestinationLot = {}; const currentOriginLot = {}; // const { data: destination } = useEntity(destinationSelection ? { id: destinationSelection.id, label: destinationSelection.label } : undefined); - // const destinationLotId = useMemo(() => destination && locationsArrToObj(destination?.Location?.locations || []).lotId, [destination]); + // const destinationLotId = useMemo(import.meta.url, () => destination && locationsArrToObj(destination?.Location?.locations || []).lotId, [destination]); // const { data: destinationLot } = useLot(destinationLotId); - // const destinationInventory = useMemo(() => (destination?.Inventories || []).find((i) => i.slot === destinationSelection?.slot), [destination, destinationSelection]); + // const destinationInventory = useMemo(import.meta.url, () => (destination?.Inventories || []).find((i) => i.slot === destinationSelection?.slot), [destination, destinationSelection]); // const { data: destinationController } = useCrew(destination?.Control?.controller?.id); - const [hopperTransportBonus, distBonus, feeReductionBonus] = useMemo(() => { + const [hopperTransportBonus, distBonus, feeReductionBonus] = useMemo(import.meta.url, () => { if (!crew) return []; const bonusIds = [ @@ -249,13 +249,13 @@ const MarketplaceOrder = ({ return bonusIds.map((id) => abilities[id] || {}); }, [crew]); - const feeEnforcementBonus = useMemo(() => { + const feeEnforcementBonus = useMemo(import.meta.url, () => { if (!exchangeController) return {}; return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.MARKETPLACE_FEE_ENFORCEMENT, exchangeController) || {}; }, [exchangeController]); - const quantityToUnits = useCallback((quantity) => resource.isAtomic ? quantity : (quantity / 1000 * resource.massPerUnit), [resource]); - const unitsToQuantity = useCallback((units) => resource.isAtomic ? units : (1000 * units / resource.massPerUnit), [resource]); + const quantityToUnits = useCallback(import.meta.url, (quantity) => resource.isAtomic ? quantity : (quantity / 1000 * resource.massPerUnit), [resource]); + const unitsToQuantity = useCallback(import.meta.url, (units) => resource.isAtomic ? units : (1000 * units / resource.massPerUnit), [resource]); const [limitPrice, setLimitPrice] = useState(preselect?.limitPrice); const [quantity, setQuantity] = useState(unitsToQuantity(preselect?.quantity)); @@ -268,11 +268,11 @@ const MarketplaceOrder = ({ }) || undefined ); const { data: storage } = useEntity(storageSelection ? { id: storageSelection.id, label: storageSelection.label } : undefined); - const storageLotId = useMemo(() => storage && locationsArrToObj(storage?.Location?.locations || []).lotId, [storage]); + const storageLotId = useMemo(import.meta.url, () => storage && locationsArrToObj(storage?.Location?.locations || []).lotId, [storage]); const { data: storageLot } = useLot(storageLotId); - const storageInventory = useMemo(() => (storage?.Inventories || []).find((i) => i.slot === storageSelection?.slot), [storage, storageSelection]); + const storageInventory = useMemo(import.meta.url, () => (storage?.Inventories || []).find((i) => i.slot === storageSelection?.slot), [storage, storageSelection]); - const { totalTime: crewTravelTime, tripDetails } = useMemo(() => { + const { totalTime: crewTravelTime, tripDetails } = useMemo(import.meta.url, () => { if (!asteroid?.id || !crew?._location?.lotId || !lot?.id) return {}; return getTripDetails(asteroid.id, hopperTransportBonus, distBonus, crew?._location?.lotIndex, [ { label: 'Travel to Marketplace', lotIndex: Lot.toIndex(lot.id) }, @@ -280,7 +280,7 @@ const MarketplaceOrder = ({ ], crew?._timeAcceleration); }, [asteroid?.id, lot?.id, crew?._location?.lotId, crew?._timeAcceleration, hopperTransportBonus, distBonus]); - const [transportDistance, transportTime] = useMemo(() => { + const [transportDistance, transportTime] = useMemo(import.meta.url, () => { if (!asteroid?.id || !exchange?.id || !storageLot?.id) return [0, 0]; const exchangeLotIndex = Lot.toIndex(exchange?.Location?.location?.id); const storageLotIndex = Lot.toIndex(storageLot?.id); @@ -294,7 +294,7 @@ const MarketplaceOrder = ({ return [transportDistance, transportTime]; }, [asteroid?.id, distBonus, exchange?.id, storageLot?.id, hopperTransportBonus, crew?._timeAcceleration]); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { let crewTime = 0; let taskTime = 0; @@ -324,7 +324,7 @@ const MarketplaceOrder = ({ return [crewTime, taskTime]; }, [transportTime, crewTravelTime, type]); - const [totalMarketPrice, avgMarketPrice, averagedOrderTally, marketFills] = useMemo(() => { + const [totalMarketPrice, avgMarketPrice, averagedOrderTally, marketFills] = useMemo(import.meta.url, () => { const orders = [].concat(mode === 'buy' ? sellOrders : buyOrders); const marketFills = ordersToFills( mode, @@ -344,13 +344,13 @@ const MarketplaceOrder = ({ return [total, total / quantity, totalOrders, marketFills]; }, [buyOrders, exchange, feeEnforcementBonus, feeReductionBonus, mode, quantity, sellOrders, type]); - const totalLimitPrice = useMemo(() => { + const totalLimitPrice = useMemo(import.meta.url, () => { return (limitPrice || 0) * quantity; }, [limitPrice, quantity]); // maker = limit order // taker = market order - const feeRate = useMemo( + const feeRate = useMemo(import.meta.url, () => ( cancellationMakerFee || Order.adjustedFee( exchange?.Exchange?.[type === 'market' ? 'takerFee' : 'makerFee'], @@ -361,11 +361,11 @@ const MarketplaceOrder = ({ [exchange, feeEnforcementBonus, feeReductionBonus, type] ); - const feeTotal = useMemo(() => { + const feeTotal = useMemo(import.meta.url, () => { return Math.floor(1e6 * feeRate * (type === 'market' ? totalMarketPrice : totalLimitPrice)) / 1e6; }, [feeRate, totalLimitPrice, totalMarketPrice, type]); - const stats = useMemo(() => { + const stats = useMemo(import.meta.url, () => { const baseFeeRate = exchange?.Exchange?.[type === 'limit' ? 'makerFee' : 'takerFee'] / Order.FEE_SCALE; return [ (isCancellation @@ -431,7 +431,7 @@ const MarketplaceOrder = ({ }, [feeTotal, quantity, transportTime, crewTravelTime, hopperTransportBonus, resourceId]); // handle "currentOrder" state - useEffect(() => { + useEffect(import.meta.url, () => { if (currentOrder) { // TODO: make selections } @@ -441,15 +441,15 @@ const MarketplaceOrder = ({ const [tooltipVisible, setTooltipVisible] = useState(); - const totalForBuy = useMemo(() => { + const totalForBuy = useMemo(import.meta.url, () => { return (buyOrders || []).reduce((acc, cur) => acc + cur.amount, 0); }, [buyOrders]); - const totalForSale = useMemo(() => { + const totalForSale = useMemo(import.meta.url, () => { return (sellOrders || []).reduce((acc, cur) => acc + cur.amount, 0); }, [sellOrders]); - const onSubmitOrder = useCallback(() => { + const onSubmitOrder = useCallback(import.meta.url, () => { if (isCancellation) { if (mode === 'buy') { cancelBuyOrder({ @@ -513,7 +513,7 @@ const MarketplaceOrder = ({ // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { // (close on status change from) if (lastStatus.current && orderStatus !== lastStatus.current) { props.onClose(); @@ -521,7 +521,7 @@ const MarketplaceOrder = ({ lastStatus.current = orderStatus; }, [orderStatus]); - const handleChangeQuantity = useCallback((e) => { + const handleChangeQuantity = useCallback(import.meta.url, (e) => { let input = parseInt(e.currentTarget.value) || 0; if (input && type === 'market') { if (mode === 'buy') input = Math.max(0, Math.min(input, totalForSale)); @@ -531,11 +531,11 @@ const MarketplaceOrder = ({ setQuantity(input); }, [mode, totalForSale, totalForBuy, type]); - const handleChangeLimitPrice = useCallback((e) => { + const handleChangeLimitPrice = useCallback(import.meta.url, (e) => { setLimitPrice(Number(e.currentTarget.value)); }, []); - const matchBestLimitOrder = useCallback((e) => { + const matchBestLimitOrder = useCallback(import.meta.url, (e) => { if (mode === 'buy') { setLimitPrice(buyOrders[0]?.price || sellOrders[sellOrders.length - 1].price); } else { @@ -543,11 +543,11 @@ const MarketplaceOrder = ({ } }, [mode, buyOrders, sellOrders]); - const handleOrderRefresh = useCallback(() => { + const handleOrderRefresh = useCallback(import.meta.url, () => { refetch(); }, [refetch]); - const [competingOrderTally, betterOrderTally, bestOrderPrice] = useMemo(() => { + const [competingOrderTally, betterOrderTally, bestOrderPrice] = useMemo(import.meta.url, () => { if (mode === 'buy') { return [ buyOrders.length, @@ -562,7 +562,7 @@ const MarketplaceOrder = ({ ]; }, [buyOrders, mode, sellOrders, limitPrice]); - const exceedsOtherSide = useMemo(() => { + const exceedsOtherSide = useMemo(import.meta.url, () => { if (type === 'limit') { if (mode === 'buy') { return limitPrice > sellOrders?.[sellOrders?.length - 1]?.price; @@ -573,12 +573,12 @@ const MarketplaceOrder = ({ return false; }, [mode, type, limitPrice, buyOrders, sellOrders]); - const total = useMemo(() => { + const total = useMemo(import.meta.url, () => { let sum = type === 'limit' ? totalLimitPrice : totalMarketPrice; return sum + (mode === 'buy' ? feeTotal : -feeTotal); }, [feeTotal, mode, totalLimitPrice, totalMarketPrice, type]); - const dialogAction = useMemo(() => { + const dialogAction = useMemo(import.meta.url, () => { let a = {}; if (type === 'market' && mode === 'buy') { a.icon = ; @@ -600,7 +600,7 @@ const MarketplaceOrder = ({ return a; }, [mode, type, isCancellation]); - const goLabel = useMemo(() => { + const goLabel = useMemo(import.meta.url, () => { if (isCancellation) return `Cancel Order`; if (type === 'market' && mode === 'buy') return `Market Buy`; if (type === 'market' && mode === 'sell') return `Market Sell`; @@ -608,11 +608,11 @@ const MarketplaceOrder = ({ if (type === 'limit' && mode === 'sell') return `Limit Sell`; }, [type, isCancellation]); - const amountInInventory = useMemo(() => { + const amountInInventory = useMemo(import.meta.url, () => { return (storageInventory?.contents || []).find((c) => Number(c.product) === Number(resourceId))?.amount || 0; }, [storageInventory, resourceId]); - const insufficientAssets = useMemo(() => { + const insufficientAssets = useMemo(import.meta.url, () => { if (isCancellation) return false; if (mode === 'buy') { return total > safeBigInt(swayBalance) / safeBigInt(TOKEN_SCALE[TOKEN.SWAY]); @@ -621,7 +621,7 @@ const MarketplaceOrder = ({ } }, [isCancellation, mode, quantity, amountInInventory, swayBalance, total]); - const insufficientCapacity = useMemo(() => { + const insufficientCapacity = useMemo(import.meta.url, () => { if (mode === 'buy' && storageInventory) { const buyUnits = quantityToUnits(quantity); const buyMass = buyUnits * resource.massPerUnit; @@ -637,7 +637,7 @@ const MarketplaceOrder = ({ return false; }, [amountInInventory, crew?._inventoryBonuses, mode, quantity, storageInventory]); - const isPermitted = useMemo(() => { + const isPermitted = useMemo(import.meta.url, () => { let perm = 0; if (isCancellation) return true; if (type === 'limit' && mode === 'buy') perm = Permission.IDS.LIMIT_BUY; @@ -905,7 +905,7 @@ const Wrapper = (props) => { const pendingOrder = manager.getPendingOrder(props.mode, props.type, { exchange, product: props.resourceId }); const actionStage = pendingOrder ? actionStages.STARTING : actionStages.NOT_STARTED; - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot) { if (!isLoading) { if (props.onClose) props.onClose(); @@ -914,7 +914,7 @@ const Wrapper = (props) => { }, [asteroid, lot, isLoading]); const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (lastStatus.current && actionStage !== lastStatus.current) { if (props.onClose) props.onClose(); } diff --git a/src/game/interface/hud/actionDialogs/NewCoreSample.js b/src/game/interface/hud/actionDialogs/NewCoreSample.js index 273311b49..cf7cf138b 100644 --- a/src/game/interface/hud/actionDialogs/NewCoreSample.js +++ b/src/game/interface/hud/actionDialogs/NewCoreSample.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { Asteroid, Crewmate, Deposit, Lot, Product, Time } from '@influenceth/sdk'; import { NewCoreSampleIcon, ResourceIcon } from '~/components/Icons'; @@ -42,7 +42,7 @@ const NewCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAction const dispatchResourceMapToggle = useStore(s => s.dispatchResourceMapToggle); const resourceMap = useStore(s => s.asteroids.resourceMap); - const prepop = useMemo(() => ({ + const prepop = useMemo(import.meta.url, () => ({ origin: currentSamplingAction?.origin ? { ...currentSamplingAction.origin } : props.preselect?.origin, resourceId: props.preselect?.resourceId || (resourceMap?.active && resourceMap?.selected || undefined) }), [currentSamplingAction, props.preselect, resourceMap]); @@ -56,7 +56,7 @@ const NewCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAction const [resourceSelectorOpen, setResourceSelectorOpen] = useState(false); const [sourceSelectorOpen, setSourceSelectorOpen] = useState(false); - useEffect(() => { + useEffect(import.meta.url, () => { if (currentSamplingAction) { setSampleId(currentSamplingAction.sampleId); if (currentSamplingAction.resourceId !== resourceId) { @@ -76,7 +76,7 @@ const NewCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAction } }, [currentSamplingAction, originEntity]); - const onSelectResource = useCallback((r) => { + const onSelectResource = useCallback(import.meta.url, (r) => { setResourceId(r); // if open to a different resource map, switch... if a resource map is not open, don't open one @@ -85,7 +85,7 @@ const NewCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAction } }, [resourceMap?.active]); - const [sample, initialYieldTonnage] = useMemo(() => { + const [sample, initialYieldTonnage] = useMemo(import.meta.url, () => { if (lot?.deposits && resourceId && sampleId) { const thisSample = lot.deposits.find((s) => s.id === sampleId); if (thisSample) { @@ -99,7 +99,7 @@ const NewCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAction }, [lot?.deposits, sampleId, resourceId]); // get lot abundance - const lotAbundances = useMemo(() => { + const lotAbundances = useMemo(import.meta.url, () => { if (!asteroid?.Celestial?.abundances || !lot?.id) return {}; // TODO: do this in worker? takes about 200ms on decent cpu @@ -115,7 +115,7 @@ const NewCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAction const lotAbundance = resourceId ? lotAbundances[resourceId] : 0; - const [crewTravelBonus, crewDistBonus, sampleQualityBonus, sampleTimeBonus] = useMemo(() => { + const [crewTravelBonus, crewDistBonus, sampleQualityBonus, sampleTimeBonus] = useMemo(import.meta.url, () => { const bonusIds = [ Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, @@ -127,7 +127,7 @@ const NewCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAction return bonusIds.map((id) => abilities[id] || {}); }, [crew]); - const { totalTime: crewTravelTime, tripDetails } = useMemo(() => { + const { totalTime: crewTravelTime, tripDetails } = useMemo(import.meta.url, () => { if (!asteroid?.id || !crew?._location?.lotId || !lot?.id) return {}; const crewLotIndex = Lot.toIndex(crew?._location?.lotId); return getTripDetails(asteroid.id, crewTravelBonus, crewDistBonus, crewLotIndex, [ @@ -136,14 +136,14 @@ const NewCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAction ], crew?._timeAcceleration); }, [asteroid?.id, lot?.id, crew?._location?.lotId, crew?._timeAcceleration, crewTravelBonus, crewDistBonus]); - const [sampleBounds, sampleTime] = useMemo(() => { + const [sampleBounds, sampleTime] = useMemo(import.meta.url, () => { return [ lotAbundance ? Deposit.getSampleBounds(lotAbundance, 0, sampleQualityBonus.totalBonus) : null, Time.toRealDuration(Deposit.getSampleTime(sampleTimeBonus.totalBonus), crew?._timeAcceleration) ]; }, [lotAbundance, sampleQualityBonus, sampleTimeBonus, crew?._timeAcceleration]); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { if (!asteroid?.id || !crew?._location?.lotId || !lot?.id || !drillSource?.lotIndex) return []; const oneWayCrewTravelTime = crewTravelTime / 2; const drillTravelTime = Time.toRealDuration( @@ -158,7 +158,7 @@ const NewCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAction ]; }, [asteroid?.id, crew?._location?.lotId, crew?._timeAcceleration, drillSource?.lotIndex, lot?.id, crewDistBonus, crewTravelBonus]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Crew Travel', value: formatTimer(crewTravelTime), @@ -213,7 +213,7 @@ const NewCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAction // handle auto-closing const miniStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { let newMiniStatus = 1; if (currentSamplingAction) newMiniStatus = 2; if (currentSamplingAction?.sampleId) newMiniStatus = 3; @@ -226,7 +226,7 @@ const NewCoreSample = ({ asteroid, lot, coreSampleManager, currentSamplingAction miniStatus.current = newMiniStatus; }, [currentSamplingAction]); - const onFinish = useCallback(() => { + const onFinish = useCallback(import.meta.url, () => { finishSampling(currentSamplingAction?.sampleId) }, [finishSampling, currentSamplingAction]); @@ -359,7 +359,7 @@ const Wrapper = (props) => { const coreSampleManager = useCoreSampleManager(lot?.id); const { currentSamplingActions, completedSamplingActions } = coreSampleManager; - const currentSamplingAction = useMemo(() => { + const currentSamplingAction = useMemo(import.meta.url, () => { return props.sampleId ? ( currentSamplingActions.find((c) => c.action?.sampleId === props.sampleId) @@ -368,7 +368,7 @@ const Wrapper = (props) => { : currentSamplingActions.find((c) => !c.action?.sampleId); }, [completedSamplingActions, currentSamplingActions, props.sampleId]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/PlanBuilding.js b/src/game/interface/hud/actionDialogs/PlanBuilding.js index d996d76b1..e82bdd04e 100644 --- a/src/game/interface/hud/actionDialogs/PlanBuilding.js +++ b/src/game/interface/hud/actionDialogs/PlanBuilding.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState } from 'react'; +import { useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Building, Crewmate, Lot, Permission } from '@influenceth/sdk'; @@ -44,19 +44,19 @@ const PlanBuilding = ({ asteroid, lot, constructionManager, stage, ...props }) = const [buildingType, setBuildingType] = useState(); - const crewTravelBonus = useMemo(() => { + const crewTravelBonus = useMemo(import.meta.url, () => { if (!crew) return {}; return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, crew) || {}; }, [crew]); - const crewDistBonus = useMemo(() => { + const crewDistBonus = useMemo(import.meta.url, () => { if (!crew) return {}; return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, crew) || {}; }, [crew]); - const lotIsControlled = useMemo(() => crewCan(Permission.IDS.USE_LOT, lot), [crewCan, lot]); + const lotIsControlled = useMemo(import.meta.url, () => crewCan(Permission.IDS.USE_LOT, lot), [crewCan, lot]); - const { totalTime: crewTravelTime, tripDetails } = useMemo(() => { + const { totalTime: crewTravelTime, tripDetails } = useMemo(import.meta.url, () => { if (!asteroid?.id || !crew?._location?.lotId || !lot?.id) return {}; if (lotIsControlled) return { totalTime: 0, tripDetails: null }; const crewLotIndex = Lot.toIndex(crew?._location?.lotId); @@ -66,12 +66,12 @@ const PlanBuilding = ({ asteroid, lot, constructionManager, stage, ...props }) = ], crew?._timeAcceleration); }, [asteroid?.id, lot, crew?._location?.lotId, crew?._timeAcceleration, crewTravelBonus, crewDistBonus, lotIsControlled]); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { if (!tripDetails) return []; return [crewTravelTime, 0]; }, [crewTravelTime, tripDetails]); - const stats = useMemo(() => { + const stats = useMemo(import.meta.url, () => { if (!asteroid?.id || !lot?.id) return []; const taskTime = 0; return [ @@ -96,7 +96,7 @@ const PlanBuilding = ({ asteroid, lot, constructionManager, stage, ...props }) = ]; }, [crewTravelTime, tripDetails]); - useEffect(() => { + useEffect(import.meta.url, () => { if (currentConstructionAction?.buildingType) setBuildingType(currentConstructionAction.buildingType) }, [currentConstructionAction?.buildingType]); @@ -106,7 +106,7 @@ const PlanBuilding = ({ asteroid, lot, constructionManager, stage, ...props }) = setSiteSelectorOpen(); } - const buildingRequirements = useMemo(() => getBuildingRequirements({ Building: { buildingType } }), [buildingType]); + const buildingRequirements = useMemo(import.meta.url, () => getBuildingRequirements({ Building: { buildingType } }), [buildingType]); return ( <> @@ -209,7 +209,7 @@ const Wrapper = (props) => { const simulationEnabled = useSimulationEnabled(); const simulation = useSimulationState(); - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot) { if (!isLoading) { if (props.onClose) props.onClose(); @@ -218,7 +218,7 @@ const Wrapper = (props) => { }, [asteroid, lot, isLoading]); // stay in this window until PLANNED, then swap to CONSTRUCT - useEffect(() => { + useEffect(import.meta.url, () => { if (!['READY_TO_PLAN', 'PLANNING'].includes(constructionManager.constructionStatus)) { if (simulationEnabled && !simulation?.canFastForward) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/Process.js b/src/game/interface/hud/actionDialogs/Process.js index 685e453cd..6244a14d2 100644 --- a/src/game/interface/hud/actionDialogs/Process.js +++ b/src/game/interface/hud/actionDialogs/Process.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid, Crewmate, Lot, Permission, Process, Processor, Product, Time } from '@influenceth/sdk'; @@ -61,7 +61,7 @@ const SECTION_WIDTH = 1150; const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...props }) => { const { currentProcess, processStatus, startProcess, finishProcess } = processManager; - const processor = useMemo( + const processor = useMemo(import.meta.url, () => (lot?.building?.Processors || []).find((e) => e.slot === processorSlot) || {}, [lot?.building, processorSlot] ); @@ -73,17 +73,17 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro const [selectedOrigin, setSelectedOrigin] = useState(currentProcess ? { ...currentProcess?.origin, slot: currentProcess?.originSlot } : undefined); const { data: origin } = useEntity(selectedOrigin); - const originLotId = useMemo(() => origin && locationsArrToObj(origin?.Location?.locations || []).lotId, [origin]); - const originLotIndex = useMemo(() => Lot.toIndex(originLotId), [originLotId]); + const originLotId = useMemo(import.meta.url, () => origin && locationsArrToObj(origin?.Location?.locations || []).lotId, [origin]); + const originLotIndex = useMemo(import.meta.url, () => Lot.toIndex(originLotId), [originLotId]); const { data: originLot } = useLot(originLotId); - const originInventory = useMemo(() => (origin?.Inventories || []).find((i) => i.slot === selectedOrigin?.slot), [origin, selectedOrigin?.slot]); + const originInventory = useMemo(import.meta.url, () => (origin?.Inventories || []).find((i) => i.slot === selectedOrigin?.slot), [origin, selectedOrigin?.slot]); const [selectedDestination, setSelectedDestination] = useState(currentProcess ? { ...currentProcess?.destination, slot: currentProcess?.destinationSlot } : undefined); const { data: destination } = useEntity(selectedDestination); - const destinationLotId = useMemo(() => destination && locationsArrToObj(destination?.Location?.locations || []).lotId, [destination]); - const destinationLotIndex = useMemo(() => Lot.toIndex(destinationLotId), [destinationLotId]); + const destinationLotId = useMemo(import.meta.url, () => destination && locationsArrToObj(destination?.Location?.locations || []).lotId, [destination]); + const destinationLotIndex = useMemo(import.meta.url, () => Lot.toIndex(destinationLotId), [destinationLotId]); const { data: destinationLot } = useLot(destinationLotId); - const destinationInventory = useMemo(() => (destination?.Inventories || []).find((i) => i.slot === selectedDestination?.slot), [destination, selectedDestination?.slot]); + const destinationInventory = useMemo(import.meta.url, () => (destination?.Inventories || []).find((i) => i.slot === selectedDestination?.slot), [destination, selectedDestination?.slot]); const [amount, setAmount] = useState(currentProcess?.recipeTally || 1); const [processId, setProcessId] = useState(currentProcess?.processId); @@ -94,7 +94,7 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro const process = Process.TYPES[processId]; - const { recipeStepSize } = useMemo(() => { + const { recipeStepSize } = useMemo(import.meta.url, () => { if (process) { const placesAfterDecimal = Math.ceil(Math.log10(Math.max(...Object.values(process.outputs)))); const recipeStepSize = 1 / Math.pow(10, placesAfterDecimal); @@ -104,13 +104,13 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro return { placesAfterDecimal: 3, recipeStepSize: 0.001 }; }, [process]); - useEffect(() => { + useEffect(import.meta.url, () => { if (currentProcess && !selectedOrigin) { setSelectedOrigin({ ...currentProcess?.origin, slot: currentProcess?.originSlot }) } }, [currentProcess]); - const maxAmount = useMemo(() => { + const maxAmount = useMemo(import.meta.url, () => { let maxPossible = 1; if (process) maxPossible = Math.floor((365 * 86400) / process.recipeTime); @@ -125,7 +125,7 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro }, [process, originInventory]); // Ensure amount is within bounds when origin inventory or recipe changes - useEffect(() => { + useEffect(import.meta.url, () => { // For actions that are already in progress etc., just trust the recipeTally for amount. // The maxAmount (which depends on *current* origin inventory stock) is not relevant in that case. if (stage !== actionStages.NOT_STARTED) return; @@ -133,14 +133,14 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro if (amount < recipeStepSize) setAmount(recipeStepSize); }, [recipeStepSize, maxAmount, stage]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!process) return; if (currentProcess) return; setPrimaryOutput(Number(Object.keys(process.outputs)[0])); setAmount(1); }, [currentProcess, process]); - const [crewTravelBonus, crewDistBonus, processingTimeBonus, secondaryOutputsBonus] = useMemo(() => { + const [crewTravelBonus, crewDistBonus, processingTimeBonus, secondaryOutputsBonus] = useMemo(import.meta.url, () => { const bonusIds = [Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE]; if (processor.processorType === Processor.IDS.BIOREACTOR) { bonusIds.push(Crewmate.ABILITY_IDS.REACTION_TIME); @@ -154,7 +154,7 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro return bonusIds.map((id) => abilities[id] || {}); }, [crew]); - const [setupTime, processingTime] = useMemo(() => { + const [setupTime, processingTime] = useMemo(import.meta.url, () => { if (!process) return [0, 0]; return [ Time.toRealDuration(Process.getSetupTime(processId, processingTimeBonus.totalBonus), crew?._timeAcceleration), @@ -162,7 +162,7 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro ]; }, [amount, crew?._timeAcceleration, process, processingTimeBonus]); - const { totalTime: crewTravelTime, tripDetails } = useMemo(() => { + const { totalTime: crewTravelTime, tripDetails } = useMemo(import.meta.url, () => { if (!asteroid?.id || !crew?._location?.lotId || !lot?.id) return {}; const crewLotIndex = Lot.toIndex(crew?._location?.lotId); return getTripDetails(asteroid.id, crewTravelBonus, crewDistBonus, crewLotIndex, [ @@ -171,7 +171,7 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro ], crew?._timeAcceleration); }, [asteroid?.id, lot?.id, crew?._location?.lotId, crew?._timeAcceleration, crewTravelBonus, crewDistBonus]); - const [inputTransportDistance, inputTransportTime] = useMemo(() => { + const [inputTransportDistance, inputTransportTime] = useMemo(import.meta.url, () => { if (!originLot?.id) return []; return [ Asteroid.getLotDistance(asteroid?.id, Lot.toIndex(originLot?.id), Lot.toIndex(lot?.id)) || 0, @@ -188,7 +188,7 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro ]; }, [asteroid?.id, lot?.id, crew?._timeAcceleration, originLot?.id, crewDistBonus, crewTravelBonus]); - const [outputTransportDistance, outputTransportTime] = useMemo(() => { + const [outputTransportDistance, outputTransportTime] = useMemo(import.meta.url, () => { if (!destinationLot?.id) return []; return [ Asteroid.getLotDistance(asteroid?.id, Lot.toIndex(lot?.id), Lot.toIndex(destinationLot?.id)) || 0, @@ -205,7 +205,7 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro ]; }, [asteroid?.id, lot?.id, crew?._timeAcceleration, destinationLot?.id, crewDistBonus, crewTravelBonus]); - const [inputArr, inputMass, inputVolume, outputArr, outputMass, outputVolume] = useMemo(() => { + const [inputArr, inputMass, inputVolume, outputArr, outputMass, outputVolume] = useMemo(import.meta.url, () => { if (!process || !amount) return [[], 0, 0, [], 0, 0]; const inputArr = Object.keys(process.inputs || {}).map(Number); const outputArr = Process.getOutputs(processId, amount, primaryOutput, secondaryOutputsBonus?.totalBonus); @@ -220,7 +220,7 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro ]; }, [process, amount, primaryOutput, secondaryOutputsBonus]); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { const onewayCrewTravelTime = crewTravelTime / 2; return [ Math.max(onewayCrewTravelTime, inputTransportTime) + (setupTime + processingTime) / 8 + onewayCrewTravelTime, @@ -228,7 +228,7 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro ]; }, [crewTravelTime, inputTransportTime, setupTime, processingTime, outputTransportTime]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Crew Travel Time', value: formatTimer(crewTravelTime), @@ -297,11 +297,11 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro setupTime, tripDetails ]); - const prepaidLeaseConfig = useMemo(() => { + const prepaidLeaseConfig = useMemo(import.meta.url, () => { return getProcessorLeaseConfig(lot?.building, Permission.IDS.RUN_PROCESS, crew, blockTime); }, [blockTime, crew, lot?.building]); - const { leasePayment, desiredLeaseTerm, actualLeaseTerm } = useMemo(() => { + const { leasePayment, desiredLeaseTerm, actualLeaseTerm } = useMemo(import.meta.url, () => { return getProcessorLeaseSelections( prepaidLeaseConfig, taskTimeRequirement, @@ -310,11 +310,11 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro ); }, [blockTime, crew?.Crew?.readyAt, prepaidLeaseConfig, taskTimeRequirement]); - const onFinishProcess = useCallback(() => { + const onFinishProcess = useCallback(import.meta.url, () => { finishProcess(); }, [finishProcess]); - const onStartProcess = useCallback(() => { + const onStartProcess = useCallback(import.meta.url, () => { if (leasePayment && !buildingOwner?.Crew?.delegatedTo) return; startProcess({ processId, @@ -343,7 +343,7 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { // (close on status change from) if (['READY', 'READY_TO_FINISH', 'FINISHING'].includes(lastStatus.current)) { if (processStatus !== lastStatus.current) { @@ -353,13 +353,13 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro lastStatus.current = processStatus; }, [processStatus]); - const isOriginSufficient = useMemo(() => { + const isOriginSufficient = useMemo(import.meta.url, () => { if (!originInventory || !process) return false; const sourceContentObj = (originInventory?.contents || []).reduce((acc, cur) => ({ ...acc, [cur.product]: cur.amount }), {}); return !inputArr.find((i) => (sourceContentObj[i] || 0) < process.inputs[i] * amount); }, [amount, inputArr, originInventory?.contents, process]); - const [headerAction, gerund] = useMemo(() => { + const [headerAction, gerund] = useMemo(import.meta.url, () => { if (processor.processorType === Processor.IDS.REFINERY) { return [ { @@ -399,7 +399,7 @@ const ProcessIO = ({ asteroid, lot, processorSlot, processManager, stage, ...pro return [{}, '']; }, [processor.processorType]); - const goLabel = useMemo(() => { + const goLabel = useMemo(import.meta.url, () => { if (leasePayment) { return ( @@ -663,7 +663,7 @@ const Wrapper = (props) => { const processManager = useProcessManager(lot?.id, props.processorSlot); const { actionStage } = processManager; - useEffect(() => { + useEffect(import.meta.url, () => { if (props.onClose) { if (!asteroid || !lot) { if (!isLoading) { diff --git a/src/game/interface/hud/actionDialogs/PurchaseEntity.js b/src/game/interface/hud/actionDialogs/PurchaseEntity.js index 63d76c225..9489276d1 100644 --- a/src/game/interface/hud/actionDialogs/PurchaseEntity.js +++ b/src/game/interface/hud/actionDialogs/PurchaseEntity.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef } from 'react'; +import { useEffect, useMemo, useRef } from '~/lib/react-debug'; import styled from 'styled-components'; import { Entity, Ship } from '@influenceth/sdk'; @@ -41,7 +41,7 @@ const PurchaseEntity = ({ asteroid, lot, entity, actionManager, stage, ...props // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (lastStatus.current && lastStatus.current !== stage) { props.onClose(); } else if (!lastStatus.current) { @@ -49,7 +49,7 @@ const PurchaseEntity = ({ asteroid, lot, entity, actionManager, stage, ...props } }, [stage]); - const insufficientSway = useMemo(() => { + const insufficientSway = useMemo(import.meta.url, () => { return entity?.Nft?.price > swayBalance; }, [entity, swayBalance]); @@ -116,14 +116,14 @@ const PurchaseEntity = ({ asteroid, lot, entity, actionManager, stage, ...props const Wrapper = ({ entity: rawEntity, ...props }) => { const { data: entity, isLoading: entityIsLoading } = useEntity(rawEntity); - const loc = useMemo(() => locationsArrToObj(entity?.Location?.locations || []), [entity]); + const loc = useMemo(import.meta.url, () => locationsArrToObj(entity?.Location?.locations || []), [entity]); const { data: asteroid, isLoading: asteroidIsLoading } = useAsteroid(loc.asteroidId); const { data: lot, isLoading: lotIsLoading } = useEntity({ id: loc.lotId, label: Entity.IDS.LOT }); const saleManager = useNftSaleManager(entity); const stage = saleManager.isPendingPurchase ? actionStages.STARTING : actionStages.NOT_STARTED - useEffect(() => { + useEffect(import.meta.url, () => { if (props.onClose) { if (!entity && !entityIsLoading) { props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/RepoBuilding.js b/src/game/interface/hud/actionDialogs/RepoBuilding.js index 253f12be3..3be03d8ee 100644 --- a/src/game/interface/hud/actionDialogs/RepoBuilding.js +++ b/src/game/interface/hud/actionDialogs/RepoBuilding.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo } from 'react'; +import { useEffect, useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Building } from '@influenceth/sdk'; @@ -63,9 +63,9 @@ const RepoBuilding = ({ asteroid, lot, actionManager, stage, ...props }) => { const { crew } = useCrewContext(); const { data: delinquentController } = useCrew(lot?.building?.Control?.controller?.id); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => ([0, 0]), []); + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => ([0, 0]), []); - const stats = useMemo(() => ([]), []); + const stats = useMemo(import.meta.url, () => ([]), []); // TODO: if repo construction site, go to "construct" dialog after @@ -175,7 +175,7 @@ const Wrapper = (props) => { const repoManager = useRepoManager(lot?.id); const { actionStage } = repoManager; - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/SellingList.js b/src/game/interface/hud/actionDialogs/SellingList.js index fda478ff6..5e76383b6 100644 --- a/src/game/interface/hud/actionDialogs/SellingList.js +++ b/src/game/interface/hud/actionDialogs/SellingList.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useContext, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid, Building, Crew, Crewmate, Entity, Inventory, Lot, Permission, Process, Product, Time } from '@influenceth/sdk'; @@ -242,7 +242,7 @@ export const ProductMarketSummary = ({ const [sort, setSort] = useState(['_dynamicUnitPrice', 'asc']); const [sortField, sortDirection] = sort; - const getRowProps = useCallback((row) => ({ + const getRowProps = useCallback(import.meta.url, (row) => ({ onClick: () => { onSelected(row.buildingId); }, @@ -252,7 +252,7 @@ export const ProductMarketSummary = ({ }), [onSelected, productId, selected]); // NOTE: this augments resourceMarketplaces, but updates less often - const dynamicMarketplaces = useMemo(() => { + const dynamicMarketplaces = useMemo(import.meta.url, () => { return Object.values(resourceMarketplaces).map((m) => { const row = { ...m }; const remainingToSource = selectionSummary.needed || targetAmount; @@ -276,7 +276,7 @@ export const ProductMarketSummary = ({ }); }, [resourceMarketplaces, selectionSummary, targetAmount]); - const handleSort = useCallback((field) => () => { + const handleSort = useCallback(import.meta.url, (field) => () => { if (!field) return; let updatedSortField = sortField; @@ -294,7 +294,7 @@ export const ProductMarketSummary = ({ ]); }, [sortDirection, sortField]); - const sortedMarketplaces = useMemo(() => { + const sortedMarketplaces = useMemo(import.meta.url, () => { return (dynamicMarketplaces || []) .sort((a, b) => (sortDirection === 'asc' ? 1 : -1) * (a[sortField] < b[sortField] ? 1 : -1)); }, [dynamicMarketplaces, sortField, sortDirection]); @@ -322,19 +322,19 @@ const SellingList = ({ asteroid, origin, originSlot, initialSelection, preselect const [selected, setSelected] = useState(initialSelection || {}); const { data: exchanges, dataUpdatedAt: exchangesUpdatedAt } = useAsteroidBuildings(asteroid?.id, 'Exchange', Permission.IDS.SELL); - const exchangesById = useMemo(() => { + const exchangesById = useMemo(import.meta.url, () => { return (exchanges || []).reduce((acc, cur) => { acc[cur.id] = cur; return acc; }, {}); }, [exchangesUpdatedAt]) const { data: originLot } = useLot(locationsArrToObj(origin?.Location?.locations || []).lotId); - const originInventory = useMemo(() => origin?.Inventories.find((i) => i.slot === originSlot), [origin, originSlot]); + const originInventory = useMemo(import.meta.url, () => origin?.Inventories.find((i) => i.slot === originSlot), [origin, originSlot]); const [targets, setTargets] = useState(Object.keys(preselect?.selectedItems || {}).map((k) => ({ productId: k, amount: preselect.selectedItems[k] }))); // derive shopping list from selected site - const [sellingList, productIds] = useMemo(() => { + const [sellingList, productIds] = useMemo(import.meta.url, () => { const list = targets.map(({ productId, amount }) => ({ product: Product.TYPES[productId], amount })); return [list, list.map((p) => p.product.i)]; }, [targets]); @@ -349,7 +349,7 @@ const SellingList = ({ asteroid, origin, originSlot, initialSelection, preselect useInterval(() => { refetchResourceMarketplaces(); }, 60e3); // keep things loosely fresh // crew bonuses related to market buys and transport - const crewBonuses = useMemo(() => { + const crewBonuses = useMemo(import.meta.url, () => { if (!crew) return {}; const abilities = getCrewAbilityBonuses([ @@ -364,7 +364,7 @@ const SellingList = ({ asteroid, origin, originSlot, initialSelection, preselect } }, [crew]); - const selectionSummary = useMemo(() => { + const selectionSummary = useMemo(import.meta.url, () => { return productIds.reduce((acc, productId) => { const targetAmount = sellingList.find((l) => l.product.i === productId)?.amount || 0; @@ -419,7 +419,7 @@ const SellingList = ({ asteroid, origin, originSlot, initialSelection, preselect }, {}); }, [asteroid?.id, crew?._timeAcceleration, crewBonuses, originLot?.id, selected, sellingList]); - const { totalPrice, totalMass, totalVolume, taskTimeRequirement, exchangeTally, allFills } = useMemo(() => { + const { totalPrice, totalMass, totalVolume, taskTimeRequirement, exchangeTally, allFills } = useMemo(import.meta.url, () => { return Object.keys(selectionSummary).reduce((acc, k) => { const s = selectionSummary[k]; return { @@ -440,7 +440,7 @@ const SellingList = ({ asteroid, origin, originSlot, initialSelection, preselect }); }, [selectionSummary]); - const handleSelected = useCallback((productId) => (buildingId) => { + const handleSelected = useCallback(import.meta.url, (productId) => (buildingId) => { setSelected((old) => { const s = { ...old }; if (!s[productId]) s[productId] = []; @@ -461,7 +461,7 @@ const SellingList = ({ asteroid, origin, originSlot, initialSelection, preselect }); }, [selectionSummary]); - useEffect(() => { + useEffect(import.meta.url, () => { Object.keys(selected || {}).forEach((productId) => { selected[productId].forEach((buildingId) => { // deselect building if no longer available due to change in market conditions @@ -478,7 +478,7 @@ const SellingList = ({ asteroid, origin, originSlot, initialSelection, preselect }, [resourceMarketplacesUpdatedAt, selected]) const [selling, setSelling] = useState(); - const handleSell = useCallback(async () => { + const handleSell = useCallback(import.meta.url, async () => { // TODO: do syncronous refetch and return if significant change (i.e. > 2% change in price or anything that was satisfied is now unsatisfied) setSelling(true); try { @@ -534,16 +534,16 @@ const SellingList = ({ asteroid, origin, originSlot, initialSelection, preselect }, [allFills, crew?.id, origin, originLot?.id, originSlot, exchangesUpdatedAt, execute]); - const handleProductClick = useCallback((productId) => () => { + const handleProductClick = useCallback(import.meta.url, (productId) => () => { setOpenProductId((p) => p === productId ? null : productId); }, []); - const sellingListSaleTally = useMemo(() => { + const sellingListSaleTally = useMemo(import.meta.url, () => { return (pendingTransactions || []).filter((tx) => tx.key === 'EscrowWithdrawalAndFillBuyOrders' && tx.meta?.originLotId === originLot?.id); }, [originLot?.id, pendingTransactions]); // if sellingListSaleTally on this lot changes while in `selling` mode, close dialog - useEffect(() => { + useEffect(import.meta.url, () => { if (selling && props.onClose) { props.onClose(); } @@ -697,13 +697,13 @@ const Wrapper = (props) => { const { asteroid, lot, isLoading } = useAsteroidAndLot(props); const actionManager = { actionStage: actionStage.NOT_STARTED }; - const [origin, originSlot] = useMemo(() => { + const [origin, originSlot] = useMemo(import.meta.url, () => { const origin = props.origin || lot?.building; const originSlot = props.originSlot || origin?.Inventories.find((i) => i.status === Inventory.STATUSES.AVAILABLE)?.slot; return [origin, originSlot]; }, [lot?.building, props.origin, props.originSlot]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot || !origin || !originSlot) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/SetCourse.js b/src/game/interface/hud/actionDialogs/SetCourse.js index 57d719244..966c4f799 100644 --- a/src/game/interface/hud/actionDialogs/SetCourse.js +++ b/src/game/interface/hud/actionDialogs/SetCourse.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import cloneDeep from 'lodash/cloneDeep'; import { Crewmate, Product, Ship, Time } from '@influenceth/sdk'; @@ -212,11 +212,11 @@ const SetCourse = ({ origin, destination, manager, ship, stage, travelSolution, const [tab, setTab] = useState(0); - const exhaustBonus = useMemo(() => { + const exhaustBonus = useMemo(import.meta.url, () => { return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.PROPELLANT_EXHAUST_VELOCITY, crew); }, [crew]); - const [shipConfig, cargoInv, propellantInv] = useMemo(() => { + const [shipConfig, cargoInv, propellantInv] = useMemo(import.meta.url, () => { if (!ship) return []; const shipConfig = Ship.TYPES[ship.Ship.shipType]; const cargoInv = ship.Inventories.find((inventory) => inventory.slot === shipConfig.cargoSlot) || { mass: 0 }; @@ -224,22 +224,22 @@ const SetCourse = ({ origin, destination, manager, ship, stage, travelSolution, return [shipConfig, cargoInv, propellantInv]; }, [ship]); - const delay = useMemo(() => { + const delay = useMemo(import.meta.url, () => { return Math.max(0, travelSolution.departureTime - coarseTime) * 86400; }, [coarseTime, travelSolution]); - const arrivingIn = useMemo(() => { + const arrivingIn = useMemo(import.meta.url, () => { return Math.max(0, travelSolution.arrivalTime - coarseTime); }, [coarseTime, travelSolution]); - const propellantMassLoaded = useMemo(() => { + const propellantMassLoaded = useMemo(import.meta.url, () => { if (!propellantInv) return 0; let totalMass = propellantInv.mass; if (currentTravelAction) totalMass += travelSolution.usedPropellantMass || 0; return totalMass; }, [currentTravelAction, propellantInv]); - const deltaVLoaded = useMemo(() => { + const deltaVLoaded = useMemo(import.meta.url, () => { if (!ship || !propellantMassLoaded) return 0; const cloneShip = cloneDeep(ship); @@ -251,14 +251,14 @@ const SetCourse = ({ origin, destination, manager, ship, stage, travelSolution, } }, [propellantMassLoaded, exhaustBonus, ship]); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { const timeRequirement = currentTravelAction ? currentTravelAction.finishTime - currentTravelAction.startTime : Time.toRealDuration(arrivingIn * 86400, crew?._timeAcceleration); return [timeRequirement, timeRequirement]; }, [currentTravelAction, arrivingIn, crew?._timeAcceleration]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Propellant Used', value: formatMass(travelSolution.usedPropellantMass), @@ -310,17 +310,17 @@ const SetCourse = ({ origin, destination, manager, ship, stage, travelSolution, }, ]), [arrivingIn, cargoInv, travelSolution, exhaustBonus, propellantInv, shipConfig]); - const onDepart = useCallback(() => { + const onDepart = useCallback(import.meta.url, () => { depart(); }, []); - const onArrive = useCallback(() => { + const onArrive = useCallback(import.meta.url, () => { arrive(); }, []); // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { // (close on status change) if (lastStatus.current && travelStatus !== lastStatus.current) { // (close travel details) @@ -331,7 +331,7 @@ const SetCourse = ({ origin, destination, manager, ship, stage, travelSolution, lastStatus.current = travelStatus; }, [travelStatus]); - useEffect(() => { + useEffect(import.meta.url, () => { if (travelStatus === 'READY' && delay <= 0) { createAlert({ type: 'GenericAlert', @@ -503,7 +503,7 @@ const Wrapper = (props) => { const { crew } = useCrewContext(); const { data: maybeShip, isLoading: shipIsLoading } = useShip(crew?._location?.shipId); - const ship = useMemo(() => { + const ship = useMemo(import.meta.url, () => { return (!shipIsLoading && !maybeShip && crew?.Ship?.emergencyAt > 0) ? crew : maybeShip; }, [crew]); @@ -514,7 +514,7 @@ const Wrapper = (props) => { const defaultDestination = useStore(s => s.asteroids.destination); const proposedTravelSolution = useStore(s => s.asteroids.travelSolution); - const travelSolution = useMemo( + const travelSolution = useMemo(import.meta.url, () => (solutionIsLoading || currentTravelAction) ? currentTravelSolution : proposedTravelSolution, [currentTravelAction, proposedTravelSolution, solutionIsLoading] ); @@ -523,7 +523,7 @@ const Wrapper = (props) => { const { data: destination, isLoading: destinationIsLoading } = useAsteroid(currentTravelAction?.destinationId || defaultDestination); // close dialog if cannot load both asteroids or if no travel solution - useEffect(() => { + useEffect(import.meta.url, () => { if (!origin || !destination || !ship) { if (!originIsLoading && !destinationIsLoading && !shipIsLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/ShoppingList.js b/src/game/interface/hud/actionDialogs/ShoppingList.js index 04f828970..c7febb1b6 100644 --- a/src/game/interface/hud/actionDialogs/ShoppingList.js +++ b/src/game/interface/hud/actionDialogs/ShoppingList.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useContext, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid, Building, Crew, Crewmate, Entity, Inventory, Lot, Permission, Process, Product, Time } from '@influenceth/sdk'; @@ -241,7 +241,7 @@ export const ProductMarketSummary = ({ const [sort, setSort] = useState(['_dynamicUnitPrice', 'desc']); const [sortField, sortDirection] = sort; - const getRowProps = useCallback((row) => ({ + const getRowProps = useCallback(import.meta.url, (row) => ({ onClick: () => { onSelected(row.buildingId); }, @@ -251,7 +251,7 @@ export const ProductMarketSummary = ({ }), [onSelected, productId, selected]); // NOTE: this augments resourceMarketplaces, but updates less often - const dynamicMarketplaces = useMemo(() => { + const dynamicMarketplaces = useMemo(import.meta.url, () => { return Object.values(resourceMarketplaces).map((m) => { const row = { ...m }; const remainingToSource = selectionSummary.needed || targetAmount; @@ -275,7 +275,7 @@ export const ProductMarketSummary = ({ }); }, [resourceMarketplaces, selectionSummary, targetAmount]); - const handleSort = useCallback((field) => () => { + const handleSort = useCallback(import.meta.url, (field) => () => { if (!field) return; let updatedSortField = sortField; @@ -293,7 +293,7 @@ export const ProductMarketSummary = ({ ]); }, [sortDirection, sortField]); - const sortedMarketplaces = useMemo(() => { + const sortedMarketplaces = useMemo(import.meta.url, () => { return (dynamicMarketplaces || []) .sort((a, b) => (sortDirection === 'asc' ? 1 : -1) * (a[sortField] < b[sortField] ? 1 : -1)); }, [dynamicMarketplaces, sortField, sortDirection]); @@ -324,25 +324,25 @@ const ShoppingList = ({ asteroid, destination, destinationSlot, stage, ...props const [selected, setSelected] = useState({}); const { data: exchanges, dataUpdatedAt: exchangesUpdatedAt } = useAsteroidBuildings(asteroid?.id, 'Exchange', Permission.IDS.BUY); - const exchangesById = useMemo(() => { + const exchangesById = useMemo(import.meta.url, () => { return (exchanges || []).reduce((acc, cur) => { acc[cur.id] = cur; return acc; }, {}); }, [exchangesUpdatedAt]) const { data: destinationLot } = useLot(locationsArrToObj(destination?.Location?.locations || []).lotId); - const destinationInventory = useMemo(() => destination?.Inventories.find((i) => i.slot === destinationSlot), [destination, destinationSlot]); + const destinationInventory = useMemo(import.meta.url, () => destination?.Inventories.find((i) => i.slot === destinationSlot), [destination, destinationSlot]); const { currentDeliveryActions } = useDeliveryManager({ destination, destinationSlot }); const [processId, setProcessId] = useState(); const [processSelectorOpen, setProcessSelectorOpen] = useState(false); - const recipe = useMemo(() => Process.TYPES[processId], [processId]); + const recipe = useMemo(import.meta.url, () => Process.TYPES[processId], [processId]); const [recipeTally, setRecipeTally] = useState(1); const [isAdditive, setIsAdditive] = useState(false); const isInSiteMode = destination?.Building?.status === Building.CONSTRUCTION_STATUSES.PLANNED; - useEffect(() => { + useEffect(import.meta.url, () => { if (isInSiteMode && destination?.Building?.buildingType) { const constructionProcessId = Object.values(Process.IDS).find((id) => Process.TYPES[id].name === `${Building.TYPES[destination.Building.buildingType].name} Construction`); if (constructionProcessId) { @@ -357,13 +357,13 @@ const ShoppingList = ({ asteroid, destination, destinationSlot, stage, ...props }, [isInSiteMode, destination?.Building, props.onClose]) // derive targets from selected recipe - const totalTargets = useMemo(() => { + const totalTargets = useMemo(import.meta.url, () => { if (!recipe) return []; return getRecipeRequirements(recipe.inputs, destinationInventory, recipeTally, currentDeliveryActions); }, [currentDeliveryActions, destinationInventory, recipe, recipeTally]); // convert targets into shopping list - const [shoppingList, productIds] = useMemo(() => { + const [shoppingList, productIds] = useMemo(import.meta.url, () => { const list = totalTargets .filter((req) => (isAdditive ? req.inNeed : req.totalRequired) > 0) .map((req) => ({ @@ -383,7 +383,7 @@ const ShoppingList = ({ asteroid, destination, destinationSlot, stage, ...props useInterval(() => { refetchResourceMarketplaces(); }, 60e3); // keep things loosely fresh // crew bonuses related to market buys and transport - const crewBonuses = useMemo(() => { + const crewBonuses = useMemo(import.meta.url, () => { if (!crew) return {}; const abilities = getCrewAbilityBonuses([ @@ -398,7 +398,7 @@ const ShoppingList = ({ asteroid, destination, destinationSlot, stage, ...props } }, [crew]); - const selectionSummary = useMemo(() => { + const selectionSummary = useMemo(import.meta.url, () => { return productIds.reduce((acc, productId) => { const targetAmount = shoppingList.find((l) => l.product.i === productId)?.amount || 0; @@ -453,7 +453,7 @@ const ShoppingList = ({ asteroid, destination, destinationSlot, stage, ...props }, {}); }, [asteroid?.id, crew?._timeAcceleration, crewBonuses, destinationLot?.id, selected, shoppingList]); - const { totalPrice, totalMass, totalVolume, taskTimeRequirement, exchangeTally, allFills } = useMemo(() => { + const { totalPrice, totalMass, totalVolume, taskTimeRequirement, exchangeTally, allFills } = useMemo(import.meta.url, () => { return Object.keys(selectionSummary).reduce((acc, k) => { const s = selectionSummary[k]; return { @@ -474,16 +474,16 @@ const ShoppingList = ({ asteroid, destination, destinationSlot, stage, ...props }); }, [selectionSummary]); - const insufficientSway = useMemo(() => totalPrice * TOKEN_SCALE[TOKEN.SWAY] > swayBalance, [totalPrice, swayBalance]); + const insufficientSway = useMemo(import.meta.url, () => totalPrice * TOKEN_SCALE[TOKEN.SWAY] > swayBalance, [totalPrice, swayBalance]); - const invConfig = useMemo(() => { + const invConfig = useMemo(import.meta.url, () => { if (destinationInventory) { return Inventory.getType(destinationInventory.inventoryType, crew?._inventoryBonuses); } return null; }, [destinationInventory, crew?._inventoryBonuses]); - const [targetMass, targetVolume] = useMemo(() => { + const [targetMass, targetVolume] = useMemo(import.meta.url, () => { return shoppingList.reduce((acc, { product, amount }) => { acc[0] += amount * product.massPerUnit; acc[1] += amount * product.volumePerUnit; @@ -491,7 +491,7 @@ const ShoppingList = ({ asteroid, destination, destinationSlot, stage, ...props }, [0, 0]); }, [shoppingList]); - const insufficientCapacity = useMemo(() => { + const insufficientCapacity = useMemo(import.meta.url, () => { const massConstraint = invConfig?.massConstraint - (destinationInventory?.mass + destinationInventory?.reservedMass); const volumeConstraint = invConfig?.volumeConstraint - (destinationInventory?.volume + destinationInventory?.reservedVolume); @@ -507,7 +507,7 @@ const ShoppingList = ({ asteroid, destination, destinationSlot, stage, ...props totalVolume ]); - const inventoryConstrained = useMemo(() => { + const inventoryConstrained = useMemo(import.meta.url, () => { if (invConfig.productConstraints) { const allowed = Object.keys(invConfig.productConstraints); if (Object.keys(selectionSummary).find((k) => selectionSummary[k].totalFilled > 0 && !allowed.includes(k))) return 'error'; @@ -522,7 +522,7 @@ const ShoppingList = ({ asteroid, destination, destinationSlot, stage, ...props totalVolume ]); - const handleSelected = useCallback((productId) => (buildingId) => { + const handleSelected = useCallback(import.meta.url, (productId) => (buildingId) => { setSelected((old) => { const s = { ...old }; if (!s[productId]) s[productId] = []; @@ -543,7 +543,7 @@ const ShoppingList = ({ asteroid, destination, destinationSlot, stage, ...props }); }, [selectionSummary]); - useEffect(() => { + useEffect(import.meta.url, () => { Object.keys(selected || {}).forEach((productId) => { selected[productId].forEach((buildingId) => { // deselect building if no longer available due to change in market conditions @@ -560,7 +560,7 @@ const ShoppingList = ({ asteroid, destination, destinationSlot, stage, ...props }, [resourceMarketplacesUpdatedAt, selected]) const [purchasing, setPurchasing] = useState(); - const handlePurchase = useCallback(async () => { + const handlePurchase = useCallback(import.meta.url, async () => { // TODO: do syncronous refetch and return if significant change (i.e. > 2% change in price or anything that was satisfied is now unsatisfied) setPurchasing(true); try { @@ -619,20 +619,20 @@ const ShoppingList = ({ asteroid, destination, destinationSlot, stage, ...props }, [allFills, crew?.id, destination, destinationLot?.id, destinationSlot, exchangesUpdatedAt, execute]); - const handleProductClick = useCallback((productId) => () => { + const handleProductClick = useCallback(import.meta.url, (productId) => () => { setOpenProductId((p) => p === productId ? null : productId); }, []); - const goToSwayStore = useCallback(() => { + const goToSwayStore = useCallback(import.meta.url, () => { dispatchLauncherPage('store', 'sway'); }, []); - const shoppingListPurchaseTally = useMemo(() => { + const shoppingListPurchaseTally = useMemo(import.meta.url, () => { return (pendingTransactions || []).filter((tx) => tx.key === 'BulkFillSellOrder' && tx.meta?.destinationLotId === destinationLot?.id); }, [destinationLot?.id, pendingTransactions]); // if shoppingListPurchaseTally on this lot changes while in `purchasing` mode, close dialog - useEffect(() => { + useEffect(import.meta.url, () => { if (purchasing && props.onClose) { props.onClose(); } @@ -864,13 +864,13 @@ const Wrapper = (props) => { const { asteroid, lot, isLoading } = useAsteroidAndLot(props); const actionManager = { actionStage: actionStage.NOT_STARTED }; - const [destination, destinationSlot] = useMemo(() => { + const [destination, destinationSlot] = useMemo(import.meta.url, () => { const destination = props.destination || lot?.building; const destinationSlot = props.destinationSlot || destination?.Inventories.find((i) => i.status === Inventory.STATUSES.AVAILABLE)?.slot; return [destination, destinationSlot]; }, [lot?.building, props.destination, props.destinationSlot]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot || !destination || !destinationSlot) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/StationCrew.js b/src/game/interface/hud/actionDialogs/StationCrew.js index 46f3b791c..f3b01466b 100644 --- a/src/game/interface/hud/actionDialogs/StationCrew.js +++ b/src/game/interface/hud/actionDialogs/StationCrew.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef } from 'react'; +import { useCallback, useEffect, useMemo, useRef } from '~/lib/react-debug'; import cloneDeep from 'lodash/cloneDeep'; import { Asteroid, Building, Crewmate, Entity, Permission, Station, Time } from '@influenceth/sdk'; @@ -38,17 +38,17 @@ const StationCrew = ({ asteroid, destination: rawDestination, lot, origin: rawOr const { stationCrew } = stationCrewManager; const { crew, crewCan } = useCrewContext(); - const crewTravelBonus = useMemo(() => { + const crewTravelBonus = useMemo(import.meta.url, () => { if (!crew) return {}; return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, crew) || {}; }, [crew]); - const crewDistBonus = useMemo(() => { + const crewDistBonus = useMemo(import.meta.url, () => { if (!crew) return {}; return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, crew) || {}; }, [crew]); - const origin = useMemo(() => { + const origin = useMemo(import.meta.url, () => { if (!rawOrigin) return null; const newOrigin = cloneDeep(rawOrigin); newOrigin._location = locationsArrToObj(newOrigin?.Location?.locations || []); @@ -57,7 +57,7 @@ const StationCrew = ({ asteroid, destination: rawDestination, lot, origin: rawOr return newOrigin; }, [rawOrigin]); - const destination = useMemo(() => { + const destination = useMemo(import.meta.url, () => { if (!rawDestination) return null; const newDestination = cloneDeep(rawDestination); newDestination._location = locationsArrToObj(newDestination?.Location?.locations || []); @@ -72,7 +72,7 @@ const StationCrew = ({ asteroid, destination: rawDestination, lot, origin: rawOr const { data: destinationLot } = useLot(destination?._location?.lotId); const { data: originLot } = useLot(origin?._location?.lotId); - const [travelDistance, travelTime] = useMemo(() => { + const [travelDistance, travelTime] = useMemo(import.meta.url, () => { if (!origin._location || !destination._location) return [0, 0]; return [ Asteroid.getLotDistance(asteroid?.id, origin._location.lotIndex || 0, destination._location.lotIndex || 0), @@ -89,11 +89,11 @@ const StationCrew = ({ asteroid, destination: rawDestination, lot, origin: rawOr ]; }, [asteroid?.id, origin?.id, destination?.id, crewDistBonus, crewTravelBonus, crew?._timeAcceleration]); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { return [ travelTime, 0 ]; }, [travelTime]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Travel Time', value: formatTimer(travelTime), @@ -114,20 +114,20 @@ const StationCrew = ({ asteroid, destination: rawDestination, lot, origin: rawOr }, ]), [crewTravelBonus, travelTime]); - const onStation = useCallback(() => { + const onStation = useCallback(import.meta.url, () => { stationCrew(); }, [stationCrew]); // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (lastStatus.current && stage !== lastStatus.current) { props.onClose(); } lastStatus.current = stage; }, [stage]); - const actionDetails = useMemo(() => { + const actionDetails = useMemo(import.meta.url, () => { const icon = destination?.label === Entity.IDS.SHIP && !crewIsOwner ? : ; @@ -284,7 +284,7 @@ const Wrapper = (props) => { const { data: asteroid, isLoading: asteroidIsLoading } = useAsteroid(asteroidId); const { data: lot, isLoading: lotIsLoading } = useLot(lotId); - const destinationEntityId = useMemo(() => { + const destinationEntityId = useMemo(import.meta.url, () => { if (props.destinationEntityId) return props.destinationEntityId; if (zoomScene?.type === 'SHIP' && zoomScene.shipId) { @@ -310,7 +310,7 @@ const Wrapper = (props) => { const isLoading = asteroidIsLoading || crewIsLoading || destIsLoading || lotIsLoading || originIsLoading; - useEffect(() => { + useEffect(import.meta.url, () => { if (!origin || !destination) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/SurfaceTransfer.js b/src/game/interface/hud/actionDialogs/SurfaceTransfer.js index d67b8ab3f..cb1d5ac06 100644 --- a/src/game/interface/hud/actionDialogs/SurfaceTransfer.js +++ b/src/game/interface/hud/actionDialogs/SurfaceTransfer.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { Asteroid, Crewmate, Entity, Inventory, Lot, Permission, Product, Time } from '@influenceth/sdk'; import styled from 'styled-components'; @@ -72,18 +72,18 @@ const SurfaceTransfer = ({ const createAlert = useStore(s => s.dispatchAlertLogged); const { startDelivery, finishDelivery, packageDelivery, acceptDelivery, cancelDelivery } = deliveryManager; - const currentDelivery = useMemo(() => currentDeliveryAction?.action, [currentDeliveryAction]); + const currentDelivery = useMemo(import.meta.url, () => currentDeliveryAction?.action, [currentDeliveryAction]); const crew = useActionCrew(currentDelivery); const { data: currentDeliveryCallerCrew } = useHydratedCrew(currentDelivery?.callerCrew?.id); const { crewCan } = useCrewContext(); const blockTime = useBlockTime(); - const crewTravelBonus = useMemo(() => { + const crewTravelBonus = useMemo(import.meta.url, () => { if (!crew) return {}; return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, crew) || {}; }, [crew]); - const crewDistBonus = useMemo(() => { + const crewDistBonus = useMemo(import.meta.url, () => { if (!crew) return {}; return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, crew) || {}; }, [crew]); @@ -98,7 +98,7 @@ const SurfaceTransfer = ({ const [destinationSelection, setDestinationSelection] = useState(); const [originSelection, setOriginSelection] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { if (fixedDestination) { const availInvs = (fixedDestination.Inventories || []).filter((i) => i.status === Inventory.STATUSES.AVAILABLE); setDestinationSelection({ @@ -127,30 +127,30 @@ const SurfaceTransfer = ({ }, [currentDelivery, fixedDestination, fixedOrigin]); const { data: origin } = useEntity(originSelection ? { id: originSelection.id, label: originSelection.label } : undefined); - const originLotId = useMemo(() => origin && locationsArrToObj(origin?.Location?.locations || []).lotId, [origin]); + const originLotId = useMemo(import.meta.url, () => origin && locationsArrToObj(origin?.Location?.locations || []).lotId, [origin]); const { data: originLot } = useLot(originLotId); - const originInventory = useMemo(() => (origin?.Inventories || []).find((i) => i.slot === originSelection?.slot), [origin, originSelection]); + const originInventory = useMemo(import.meta.url, () => (origin?.Inventories || []).find((i) => i.slot === originSelection?.slot), [origin, originSelection]); const { data: originController } = useCrew(origin?.Control?.controller?.id); - const originInventoryTally = useMemo(() => (origin?.Inventories || []).filter((i) => i.status === Inventory.STATUSES.AVAILABLE).length, [origin]); - const originProductIds = useMemo(() => { + const originInventoryTally = useMemo(import.meta.url, () => (origin?.Inventories || []).filter((i) => i.status === Inventory.STATUSES.AVAILABLE).length, [origin]); + const originProductIds = useMemo(import.meta.url, () => { const invConfig = Inventory.TYPES[originInventory?.inventoryType] || {}; return invConfig?.productConstraints ? Object.keys(invConfig?.productConstraints) : null; }, [originInventory]); const { data: destination } = useEntity(destinationSelection ? { id: destinationSelection.id, label: destinationSelection.label } : undefined); - const destinationLotId = useMemo(() => destination && locationsArrToObj(destination?.Location?.locations || []).lotId, [destination]); + const destinationLotId = useMemo(import.meta.url, () => destination && locationsArrToObj(destination?.Location?.locations || []).lotId, [destination]); const { data: destinationLot } = useLot(destinationLotId); - const destinationInventory = useMemo(() => (destination?.Inventories || []).find((i) => i.slot === destinationSelection?.slot), [destination, destinationSelection]); + const destinationInventory = useMemo(import.meta.url, () => (destination?.Inventories || []).find((i) => i.slot === destinationSelection?.slot), [destination, destinationSelection]); const { data: destinationController } = useCrew(destination?.Control?.controller?.id); - const destinationInventoryTally = useMemo(() => (destination?.Inventories || []).filter((i) => i.status === Inventory.STATUSES.AVAILABLE).length, [destination]); + const destinationInventoryTally = useMemo(import.meta.url, () => (destination?.Inventories || []).filter((i) => i.status === Inventory.STATUSES.AVAILABLE).length, [destination]); const destDeliveryManager = useDeliveryManager({ destination, destinationSlot: destinationSelection?.slot }); - const destinationProductIds = useMemo(() => { + const destinationProductIds = useMemo(import.meta.url, () => { const invConfig = Inventory.TYPES[destinationInventory?.inventoryType] || {}; return invConfig?.productConstraints ? Object.keys(invConfig?.productConstraints) : null; }, [destinationInventory]); // When a new origin inventory is selected, reset the selected items - const onOriginSelect = useCallback((selection) => { + const onOriginSelect = useCallback(import.meta.url, (selection) => { const { id, label, slot } = originSelection || {}; if (id !== selection.id || label !== selection.label || slot !== selection.slot) { setOriginSelection(selection); @@ -158,25 +158,25 @@ const SurfaceTransfer = ({ } }, [originSelection]); - const onDestinationSelect = useCallback((selection) => { + const onDestinationSelect = useCallback(import.meta.url, (selection) => { const { id, label, slot } = destinationSelection || {}; if (id !== selection.id || label !== selection.label || slot !== selection.slot) { setDestinationSelection(selection); } }, [destinationSelection]); - const onSwayChange = useCallback((value) => { + const onSwayChange = useCallback(import.meta.url, (value) => { setSway(value ? parseInt(value) : ''); }, []); // handle "currentDeliveryAction" state - useEffect(() => { + useEffect(import.meta.url, () => { if (currentDelivery) { setSelectedItems(currentDelivery.contents.reduce((acc, item) => ({ ...acc, [item.product]: item.amount }), {})); } }, [currentDelivery]); - useEffect(() => { + useEffect(import.meta.url, () => { if (stage === actionStage.NOT_STARTED && originInventory) { const destInvConfig = (Inventory.getType(destinationInventory?.inventoryType, crew?._inventoryBonuses) || {}); const destInvConstraints = destInvConfig.productConstraints; @@ -215,7 +215,7 @@ const SurfaceTransfer = ({ } }, [crew?._inventoryBonuses, originInventory, destinationInventory, destDeliveryManager.currentDeliveryActions]); - const [transportDistance, transportTime] = useMemo(() => { + const [transportDistance, transportTime] = useMemo(import.meta.url, () => { if (!asteroid?.id || !originLot?.id || !destinationLot?.id) return [0, 0]; const originLotIndex = Lot.toIndex(originLot?.id); const destinationLotIndex = Lot.toIndex(destinationLot?.id); @@ -229,7 +229,7 @@ const SurfaceTransfer = ({ return [transportDistance, transportTime]; }, [asteroid?.id, originLot?.id, destinationLot?.id, crewDistBonus, crewTravelBonus, crew?._timeAcceleration]); - const { totalMass, totalVolume } = useMemo(() => { + const { totalMass, totalVolume } = useMemo(import.meta.url, () => { return Object.keys(selectedItems).reduce((acc, resourceId) => { acc.totalMass += selectedItems[resourceId] * Product.TYPES[resourceId].massPerUnit; acc.totalVolume += selectedItems[resourceId] * Product.TYPES[resourceId].volumePerUnit; @@ -237,22 +237,22 @@ const SurfaceTransfer = ({ }, { totalMass: 0, totalVolume: 0 }) }, [selectedItems]); - const currentCrewIsSender = useMemo(() => { + const currentCrewIsSender = useMemo(import.meta.url, () => { if (currentDelivery) return currentCrew?.id === currentDelivery.callerCrew?.id; return true; }, [currentCrew, currentDelivery]); - const currentCrewHasOriginPerms = useMemo(() => { + const currentCrewHasOriginPerms = useMemo(import.meta.url, () => { if (origin) return currentCrewCan(Permission.IDS.REMOVE_PRODUCTS, origin); return true; }, [currentCrewCan, origin]); - const currentCrewHasDestinationPerms = useMemo(() => { + const currentCrewHasDestinationPerms = useMemo(import.meta.url, () => { if (destination) return currentCrewCan(Permission.IDS.ADD_PRODUCTS, destination); return true; }, [currentCrewCan, destination]); - const senderHasDestPerm = useMemo(() => { + const senderHasDestPerm = useMemo(import.meta.url, () => { if (!destination) return true; if (currentDelivery) { if (currentDeliveryCallerCrew && destination) { @@ -263,9 +263,9 @@ const SurfaceTransfer = ({ return crewCan(Permission.IDS.ADD_PRODUCTS, destination); }, [blockTime, crew, currentDelivery, currentDeliveryCallerCrew, destination]); - const isP2P = useMemo(() => currentDelivery?.isProposal || !senderHasDestPerm, [currentDelivery?.isProposal, senderHasDestPerm]); + const isP2P = useMemo(import.meta.url, () => currentDelivery?.isProposal || !senderHasDestPerm, [currentDelivery?.isProposal, senderHasDestPerm]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Task Duration', value: formatTimer(transportTime), @@ -296,7 +296,7 @@ const SurfaceTransfer = ({ }, ]), [totalMass, totalVolume, transportDistance, transportTime]); - const willBeOverCapacity = useMemo(() => { + const willBeOverCapacity = useMemo(import.meta.url, () => { if (![actionStage.NOT_STARTED, actionStage.STARTING].includes(stage)) return false; const destInventoryConfig = Inventory.getType(destinationInventory?.inventoryType, crew?._inventoryBonuses) || {}; @@ -307,7 +307,7 @@ const SurfaceTransfer = ({ return (totalMass > destInventoryConfig.massConstraint) || (totalVolume > destInventoryConfig.volumeConstraint); }, [crew?._inventoryBonuses, destinationInventory, stage, totalMass, totalVolume]); - const onStartDelivery = useCallback(() => { + const onStartDelivery = useCallback(import.meta.url, () => { if (willBeOverCapacity) { const destInventoryConfig = Inventory.getType(destinationInventory?.inventoryType, crew?._inventoryBonuses) || {}; createAlert({ @@ -329,28 +329,28 @@ const SurfaceTransfer = ({ }, { asteroidId: asteroid?.id, lotId: originLot?.id }); }, [crew?._inventoryBonuses, packageDelivery, startDelivery, originInventory, destinationInventory, selectedItems, sway, isP2P, senderHasDestPerm, asteroid?.id, originLot?.id, willBeOverCapacity]); - const onFinishDelivery = useCallback(() => { + const onFinishDelivery = useCallback(import.meta.url, () => { finishDelivery(deliveryId, { asteroidId: asteroid?.id, lotId: destinationLot?.id, }); }, [finishDelivery, deliveryId, asteroid?.id, destinationLot?.id]); - const onCancelDelivery = useCallback(() => { + const onCancelDelivery = useCallback(import.meta.url, () => { cancelDelivery(deliveryId, { asteroidId: asteroid?.id, lotId: destinationLot?.id, }); }, [cancelDelivery, deliveryId, asteroid?.id, destinationLot?.id]); - const onAcceptDelivery = useCallback(() => { + const onAcceptDelivery = useCallback(import.meta.url, () => { acceptDelivery(deliveryId, { asteroidId: asteroid?.id, lotId: destinationLot?.id, }); }, [acceptDelivery, deliveryId, asteroid?.id, destinationLot?.id]); - const actionDetails = useMemo(() => { + const actionDetails = useMemo(import.meta.url, () => { let overrideColor = undefined; let status = undefined; if (stage === actionStage.NOT_STARTED || ['READY','PACKAGED'].includes(currentDeliveryAction?.status)) { @@ -370,7 +370,7 @@ const SurfaceTransfer = ({ return { overrideColor, status, stage }; }, [crew, currentCrewHasOriginPerms, currentDeliveryAction?.status, destination, isP2P, stage]); - const finalizeActions = useMemo(() => { + const finalizeActions = useMemo(import.meta.url, () => { if (currentDeliveryAction?.status === 'PACKAGED') { if (currentCrewHasDestinationPerms) { return { @@ -669,7 +669,7 @@ const Wrapper = (props) => { // - origin (from sendFrom button) +- originSlot // - destination (from sendTo button) +- destinationSlot // TODO: test from actionItem, hud action button, inventory menu action button - const deliveryManagerQuery = useMemo(() => { + const deliveryManagerQuery = useMemo(import.meta.url, () => { if (deliveryId) return { deliveryId }; if (txHash) return { txHash }; if (destination) return { destination, destinationSlot }; @@ -678,7 +678,7 @@ const Wrapper = (props) => { }, [deliveryId, destination, destinationSlot, origin, originSlot, txHash]) const deliveryManager = useDeliveryManager(deliveryManagerQuery); - const currentDeliveryAction = useMemo(() => { + const currentDeliveryAction = useMemo(import.meta.url, () => { return (deliveryManager.currentDeliveryActions || []).find((d) => { if (deliveryId) return d.action.deliveryId === deliveryId if (txHash) return d.action.txHash === txHash; @@ -689,7 +689,7 @@ const Wrapper = (props) => { const { data: originEntity, isLoading: originLoading } = useEntity(currentDeliveryAction?.action?.origin || props.origin); const { data: destEntity, isLoading: destLoading } = useEntity(currentDeliveryAction?.action?.dest || props.destination); - useEffect(() => { + useEffect(import.meta.url, () => { if (!props.onClose) return; if (!asteroid && !isLoading) props.onClose(); if (origin && !originEntity && !originLoading) props.onClose(); @@ -700,7 +700,7 @@ const Wrapper = (props) => { // handle auto-closing on any status change const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (stage !== 'READY_TO_FINISH') { if (lastStatus.current && stage !== lastStatus.current) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/TransferToSite.js b/src/game/interface/hud/actionDialogs/TransferToSite.js index e2c043d48..f15c1a306 100644 --- a/src/game/interface/hud/actionDialogs/TransferToSite.js +++ b/src/game/interface/hud/actionDialogs/TransferToSite.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import { Asteroid, Crewmate, Entity, Inventory, Lot, Permission, Product, Time } from '@influenceth/sdk'; import { ForwardIcon, InventoryIcon, TransferToSiteIcon } from '~/components/Icons'; @@ -37,12 +37,12 @@ const TransferToSite = ({ asteroid, lot: destinationLot, deliveryManager, stage, const { currentDeliveryActions, startDelivery } = deliveryManager; const { crew, crewCan } = useCrewContext(); - const crewTravelBonus = useMemo(() => { + const crewTravelBonus = useMemo(import.meta.url, () => { if (!crew) return {}; return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.HOPPER_TRANSPORT_TIME, crew) || {}; }, [crew]); - const crewDistBonus = useMemo(() => { + const crewDistBonus = useMemo(import.meta.url, () => { if (!crew) return {}; return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.FREE_TRANSPORT_DISTANCE, crew) || {}; }, [crew]); @@ -52,31 +52,31 @@ const TransferToSite = ({ asteroid, lot: destinationLot, deliveryManager, stage, const [selectedItems, setSelectedItems] = useState(props.preselect?.selectedItems || {}); // get destination and destinationInventory - const destination = useMemo(() => ({ + const destination = useMemo(import.meta.url, () => ({ id: destinationLot?.building?.id, label: Entity.IDS.BUILDING, lotIndex: Lot.toIndex(destinationLot?.id), slot: destinationLot?.building?.Inventories.find((i) => i.status === Inventory.STATUSES.AVAILABLE)?.slot }), [destinationLot]); - const destinationInventory = useMemo(() => (destinationLot?.building?.Inventories || []).find((i) => i.slot === destination?.slot), [destinationLot, destination?.slot]); + const destinationInventory = useMemo(import.meta.url, () => (destinationLot?.building?.Inventories || []).find((i) => i.slot === destination?.slot), [destinationLot, destination?.slot]); // get originLot and originInventory const [origin, setOrigin] = useState(); - const originLotId = useMemo(() => Lot.toId(asteroid?.id, origin?.lotIndex), [asteroid?.id, origin?.lotIndex]); + const originLotId = useMemo(import.meta.url, () => Lot.toId(asteroid?.id, origin?.lotIndex), [asteroid?.id, origin?.lotIndex]); const { data: originLot } = useLot(originLotId); - const originEntity = useMemo(() => { + const originEntity = useMemo(import.meta.url, () => { if (!originLot || !origin) return null; if (origin.label === Entity.IDS.SHIP) return originLot.ships.find((s) => s.id === origin.id); return originLot.building; }, [originLot, origin]); - const originInventory = useMemo(() => (originEntity?.Inventories || []).find((i) => i.slot === origin?.slot), [originEntity, origin]); + const originInventory = useMemo(import.meta.url, () => (originEntity?.Inventories || []).find((i) => i.slot === origin?.slot), [originEntity, origin]); - const buildingRequirements = useMemo( + const buildingRequirements = useMemo(import.meta.url, () => getBuildingRequirements(destinationLot?.building, currentDeliveryActions), [destinationLot?.building, currentDeliveryActions] ); - useEffect(() => { + useEffect(import.meta.url, () => { if (stage === actionStage.NOT_STARTED) { const validated = Object.keys(selectedItems).reduce((acc, product) => { // cap selectedItems to originInventory contents and adjusted building requirements @@ -91,13 +91,13 @@ const TransferToSite = ({ asteroid, lot: destinationLot, deliveryManager, stage, }, [originInventory, buildingRequirements]); // // handle "currentDeliveryAction" state - // useEffect(() => { + // useEffect(import.meta.url, () => { // if (currentDeliveryAction) { // setSelectedItems(currentDeliveryAction.contents); // } // }, [currentDeliveryAction]); - // useEffect(() => { + // useEffect(import.meta.url, () => { // if (currentDeliveryAction?.originLotId) { // setOriginLotId(currentDeliveryAction?.originLotId); // } @@ -106,18 +106,18 @@ const TransferToSite = ({ asteroid, lot: destinationLot, deliveryManager, stage, // // reset selectedItems if change origin lot before starting // // TODO: in general, could probably remove all currentDeliveryAction stuff // // since we don't follow the course of the delivery in this dialog - // useEffect(() => { + // useEffect(import.meta.url, () => { // if (!currentDeliveryAction) setSelectedItems(props.preselect?.selectedItems || {}); // }, [originLot]); // reset selectedItems if not in a ready state (to avoid double-counting) - useEffect(() => { + useEffect(import.meta.url, () => { if (stage !== actionStage.NOT_STARTED) { setSelectedItems({}); } }, [stage]) - const [transportDistance, transportTime] = useMemo(() => { + const [transportDistance, transportTime] = useMemo(import.meta.url, () => { if (!asteroid?.id || !originLot?.id || !destinationLot?.id) return [0, 0]; const originLotIndex = Lot.toIndex(originLot?.id); const destinationLotIndex = Lot.toIndex(destinationLot?.id); @@ -131,7 +131,7 @@ const TransferToSite = ({ asteroid, lot: destinationLot, deliveryManager, stage, return [transportDistance, transportTime]; }, [asteroid?.id, originLot?.id, destinationLot?.id, crew?._timeAcceleration, crewDistBonus, crewTravelBonus]); - const { totalMass, totalVolume } = useMemo(() => { + const { totalMass, totalVolume } = useMemo(import.meta.url, () => { return Object.keys(selectedItems).reduce((acc, resourceId) => { acc.totalMass += selectedItems[resourceId] * (Product.TYPES[resourceId].massPerUnit || 0); acc.totalVolume += selectedItems[resourceId] * (Product.TYPES[resourceId].volumePerUnit || 0); @@ -139,11 +139,11 @@ const TransferToSite = ({ asteroid, lot: destinationLot, deliveryManager, stage, }, { totalMass: 0, totalVolume: 0 }) }, [selectedItems]); - const [crewTimeRequirement, taskTimeRequirement] = useMemo(() => { + const [crewTimeRequirement, taskTimeRequirement] = useMemo(import.meta.url, () => { return [0, transportTime]; }, [transportTime]); - const stats = useMemo(() => ([ + const stats = useMemo(import.meta.url, () => ([ { label: 'Total Mass', value: `${formatMass(totalMass)}`, @@ -174,7 +174,7 @@ const TransferToSite = ({ asteroid, lot: destinationLot, deliveryManager, stage, }, ]), [totalMass, totalVolume, transportDistance, transportTime]); - const onStartDelivery = useCallback(() => { + const onStartDelivery = useCallback(import.meta.url, () => { const destInventoryConfig = Inventory.getType(destinationInventory?.inventoryType, crew?._inventoryBonuses) || {}; if (destinationInventory) { destInventoryConfig.massConstraint -= ((destinationInventory.mass || 0) + (destinationInventory.reservedMass || 0)); @@ -199,13 +199,13 @@ const TransferToSite = ({ asteroid, lot: destinationLot, deliveryManager, stage, }, { asteroidId: asteroid?.id, lotId: originLot?.id }); }, [crew?._inventoryBonuses, originInventory, destinationInventory, selectedItems, asteroid?.id, originLot?.id]); - useEffect(() => { + useEffect(import.meta.url, () => { if (destinationLot?.building && !buildingRequirements.find((r) => r.inNeed > 0)) { onSetAction('CONSTRUCT'); } }, [buildingRequirements, destinationLot?.building, onSetAction]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!destinationInventory) { createAlert({ type: 'GenericAlert', @@ -339,7 +339,7 @@ const Wrapper = (props) => { const deliveryManager = useDeliveryManager({ destination: lot?.building }); - const [stage, innerKey] = useMemo(() => { + const [stage, innerKey] = useMemo(import.meta.url, () => { if ((deliveryManager.currentDeliveryActions || []).find((d) => d.status === 'DEPARTING')) { return [actionStage.STARTING, deliveryManager.currentDeliveryActions.length - 1]; } @@ -348,7 +348,7 @@ const Wrapper = (props) => { // TODO (nice-to-have): if requirements are all met, close the dialog - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/UnplanBuilding.js b/src/game/interface/hud/actionDialogs/UnplanBuilding.js index 6907d6f4e..a34e4a032 100644 --- a/src/game/interface/hud/actionDialogs/UnplanBuilding.js +++ b/src/game/interface/hud/actionDialogs/UnplanBuilding.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef } from 'react'; +import { useEffect, useMemo, useRef } from '~/lib/react-debug'; import styled from 'styled-components'; import { Building, Inventory } from '@influenceth/sdk'; @@ -40,14 +40,14 @@ const UnplanBuilding = ({ asteroid, lot, constructionManager, stage, ...props }) const { currentConstructionAction, constructionStatus, unplanConstruction } = useConstructionManager(lot?.id); const { crew } = useCrewContext(); - const siteEmpty = useMemo(() => { + const siteEmpty = useMemo(import.meta.url, () => { const inv = (lot?.building?.Inventories || []).find((i) => Inventory.TYPES[i.inventoryType].category === Inventory.CATEGORIES.SITE); return ((inv?.mass + inv?.reservedMass) === 0); }, [lot?.building]); // handle auto-closing const lastStatus = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { // (always close if not in planned or canceling state) if (!['PLANNED', 'CANCELING'].includes(constructionStatus)) { props.onClose(); @@ -116,7 +116,7 @@ const Wrapper = (props) => { const constructionManager = useConstructionManager(lot?.id); const { stageByActivity } = constructionManager; - useEffect(() => { + useEffect(import.meta.url, () => { if (!asteroid || !lot) { if (!isLoading) { if (props.onClose) props.onClose(); diff --git a/src/game/interface/hud/actionDialogs/components.js b/src/game/interface/hud/actionDialogs/components.js index b1783d06c..2f83c8d3d 100644 --- a/src/game/interface/hud/actionDialogs/components.js +++ b/src/game/interface/hud/actionDialogs/components.js @@ -1,4 +1,4 @@ -import React, { Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import React, { Fragment, useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled, { css, keyframes } from 'styled-components'; import { createPortal } from 'react-dom'; import { Tooltip } from 'react-tooltip'; @@ -1489,19 +1489,19 @@ export const CrewSelectionDialog = ({ crews, disabler, onClose, onSelected, open const { height: screenHeight } = useScreenSize(); const [selection, setSelection] = useState(); - const onComplete = useCallback(() => { + const onComplete = useCallback(import.meta.url, () => { onSelected(selection?.id); onClose(); }, [onClose, onSelected, selection]); - const [firstNonEmptyCrew, firstEmptyCrew] = useMemo( + const [firstNonEmptyCrew, firstEmptyCrew] = useMemo(import.meta.url, () => [ crews.find((c) => c.Crew.roster.length > 0), crews.find((c) => c.Crew.roster.length === 0), ], [crews] ); - const firstNonEmptyCrewLocation = useMemo(() => { + const firstNonEmptyCrewLocation = useMemo(import.meta.url, () => { return firstNonEmptyCrew ? locationsArrToObj(firstNonEmptyCrew.Location?.locations || []) : undefined; @@ -1510,11 +1510,11 @@ export const CrewSelectionDialog = ({ crews, disabler, onClose, onSelected, open const listWrapper = useRef(); const [listHeight, setListHeight] = useState(0); - useEffect(() => { + useEffect(import.meta.url, () => { setListHeight(listWrapper.current?.clientHeight || 500); }, [crews?.length, screenHeight]); - const getCrewRowHeight = useCallback(({ index }) => { + const getCrewRowHeight = useCallback(import.meta.url, ({ index }) => { if (!crews?.[index]) return 0; const crew = crews[index]; const isFirstNonEmpty = crew.id === firstNonEmptyCrew?.id; @@ -1522,7 +1522,7 @@ export const CrewSelectionDialog = ({ crews, disabler, onClose, onSelected, open return 152 + ((isFirstNonEmpty || isFirstEmpty) ? 26 : 0); }, [crews, firstNonEmptyCrew?.id, firstEmptyCrew?.id]); - const renderCrewRow = useCallback(({ key, index, style }) => { + const renderCrewRow = useCallback(import.meta.url, ({ key, index, style }) => { if (!crews?.[index]) return null; const crew = crews[index]; const disabled = disabler ? disabler(crew) : false; @@ -1582,12 +1582,12 @@ export const SitePlanSelectionDialog = ({ initialSelection, onClose, onSelected, const [selection, setSelection] = useState(initialSelection); - const onComplete = useCallback(() => { + const onComplete = useCallback(import.meta.url, () => { onSelected(selection); onClose(); }, [onClose, onSelected, selection]); - const isCompletable = useMemo(() => { + const isCompletable = useMemo(import.meta.url, () => { if (simulationEnabled) { return simulationActions.includes(`SelectSitePlan:${selection}`); } @@ -1631,19 +1631,19 @@ export const ResourceSelectionDialog = ({ abundances, lotId, initialSelection, o const [selection, setSelection] = useState(initialSelection); - const onComplete = useCallback(() => { + const onComplete = useCallback(import.meta.url, () => { onSelected(selection); onClose(); }, [onClose, onSelected, selection]); - const isCompletable = useMemo(() => { + const isCompletable = useMemo(import.meta.url, () => { if (simulationEnabled) { return simulationActions.includes(`SelectTargetResource:${selection}`); } return selection > 0; }, [selection, simulationActions, simulationEnabled]); - const nonzeroAbundances = useMemo(() => Object.values(abundances).filter((x) => x > 0).length, [abundances]); + const nonzeroAbundances = useMemo(import.meta.url, () => Object.values(abundances).filter((x) => x > 0).length, [abundances]); return ( { + useEffect(import.meta.url, () => { setSelection(initialSelection); }, [initialSelection]); - const onComplete = useCallback(() => { + const onComplete = useCallback(import.meta.url, () => { onSelected(selection); onClose(); }, [onClose, onSelected, selection]); - const [forSaleExist, usedExist] = useMemo(() => { + const [forSaleExist, usedExist] = useMemo(import.meta.url, () => { return [ !!options.find((s) => s.PrivateSale?.amount > 0), !!options.find((s) => s.Deposit.remainingYield !== s.Deposit.initialYield), ]; }, [options]) - const samples = useMemo(() => { + const samples = useMemo(import.meta.url, () => { return options .filter((s) => (showForSale || !s.PrivateSale?.amount || crew?.id === s.Control?.controller?.id) && (showUsed || (s.Deposit.remainingYield === s.Deposit.initialYield))) .sort((a, b) => { @@ -1829,7 +1829,7 @@ export const TransferSelectionDialog = ({ }) => { const [selection, setSelection] = useState({}); - const pendingContents = useMemo(() => { + const pendingContents = useMemo(import.meta.url, () => { if (!pendingTargetDeliveries) return {}; return (pendingTargetDeliveries || []) .filter((d) => d.status !== 'FINISHED') @@ -1843,19 +1843,19 @@ export const TransferSelectionDialog = ({ }, [pendingTargetDeliveries]); const prevInitialSelection = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (!prevInitialSelection.current || JSON.stringify(prevInitialSelection.current) !== JSON.stringify(initialSelection)) { setSelection({ ...initialSelection }); prevInitialSelection.current = initialSelection; } }, [initialSelection]); - const onComplete = useCallback(() => { + const onComplete = useCallback(import.meta.url, () => { onSelected(selection); onClose(); }, [onClose, onSelected, selection]); - const onSelectItem = useCallback((resourceId) => (selectedAmount) => { + const onSelectItem = useCallback(import.meta.url, (resourceId) => (selectedAmount) => { setSelection((currentlySelected) => { const updated = { ...currentlySelected }; if (selectedAmount > 0) { @@ -1867,13 +1867,13 @@ export const TransferSelectionDialog = ({ }); }, []); - const targetInvConfig = useMemo( + const targetInvConfig = useMemo(import.meta.url, () => targetInventory ? Inventory.getType(targetInventory?.inventoryType, inventoryBonuses) : null, [targetInventory?.inventoryType, inventoryBonuses] ); - const cells = useMemo(() => [...Array(6 * Math.max(2, Math.ceil(Object.keys(sourceContents).length / 6))).keys()], [sourceContents]); - const items = useMemo(() => { + const cells = useMemo(import.meta.url, () => [...Array(6 * Math.max(2, Math.ceil(Object.keys(sourceContents).length / 6))).keys()], [sourceContents]); + const items = useMemo(import.meta.url, () => { const productConstraints = targetInventoryConstraints || (targetInvConfig ? targetInvConfig?.productConstraints : null); return sourceContents.map(({ product, amount }) => { @@ -1908,7 +1908,7 @@ export const TransferSelectionDialog = ({ }); }, [sourceContents, targetInventory, targetInventoryConstraints, targetInvConfig, selection]); - const { tally, totalMass, totalVolume } = useMemo(() => { + const { tally, totalMass, totalVolume } = useMemo(import.meta.url, () => { return items.reduce((acc, { selected, resource }) => { acc.tally += selected > 0 ? 1 : 0; acc.totalMass += (selected || 0) * resource.massPerUnit; @@ -1919,7 +1919,7 @@ export const TransferSelectionDialog = ({ // TODO: should title be inventory type name instead? - const [title, subtitle] = useMemo(() => { + const [title, subtitle] = useMemo(import.meta.url, () => { let title = ''; if (sourceEntity?.Ship) { title = Ship.TYPES[sourceEntity.Ship.shipType || 0]?.name; @@ -1929,7 +1929,7 @@ export const TransferSelectionDialog = ({ return [title, formatters.lotName(locationsArrToObj(sourceEntity?.Location?.locations || []).lotId)]; }, [sourceEntity]); - const overcapacity = useMemo(() => { + const overcapacity = useMemo(import.meta.url, () => { if (targetInvConfig?.massConstraint && totalMass > targetInvConfig.massConstraint) return 'mass'; if (targetInvConfig?.volumeConstraint && totalVolume > targetInvConfig.volumeConstraint) return 'volume'; return false; @@ -1999,7 +1999,7 @@ export const LandingSelectionDialog = ({ asteroid, deliveryMode, initialSelectio const { data: unorderedSpaceports } = useAsteroidBuildings(asteroid?.id, 'Dock', Permission.IDS.DOCK_SHIP); const { crew } = useCrewContext(); - const spaceports = useMemo( + const spaceports = useMemo(import.meta.url, () => unorderedSpaceports .map((a) => { const { lotIndex } = locationsArrToObj(a?.Location?.locations); @@ -2013,12 +2013,12 @@ export const LandingSelectionDialog = ({ asteroid, deliveryMode, initialSelectio [asteroid?.id, originLotIndex, unorderedSpaceports] ); - const onComplete = useCallback(() => { + const onComplete = useCallback(import.meta.url, () => { onSelected(selection); onClose(); }, [onClose, onSelected, selection]); - const handleKeyDown = useCallback((e) => { + const handleKeyDown = useCallback(import.meta.url, (e) => { if (e.key === 'Enter') { const lot = parseInt(e.target.value); if (lot && lotData[lot] !== undefined) { @@ -2153,7 +2153,7 @@ export const ProcessSelectionDialog = ({ initialSelection, onClose, forceProcess const coachmarks = useStore((s) => s.coachmarks); const simulationActions = useStore((s) => s.simulationActions); - const processes = useMemo(() => { + const processes = useMemo(import.meta.url, () => { const unSorted = forceProcesses || Object.values(Process.TYPES).filter((p) => processorType ? p.processorType === processorType : true); return unSorted .sort((a, b) => { @@ -2174,12 +2174,12 @@ export const ProcessSelectionDialog = ({ initialSelection, onClose, forceProcess }) }, [coachmarks, forceProcesses, processorType]) - const onComplete = useCallback(() => { + const onComplete = useCallback(import.meta.url, () => { onSelected(selection); onClose(); }, [onClose, onSelected, selection]); - const applyProcessFilter = useCallback((process) => { + const applyProcessFilter = useCallback(import.meta.url, (process) => { if (!processFilter && !outputFilter) return true; if (processFilter) { @@ -2197,7 +2197,7 @@ export const ProcessSelectionDialog = ({ initialSelection, onClose, forceProcess return true; }, [processFilter, outputFilter]); - const isCompletable = useMemo(() => { + const isCompletable = useMemo(import.meta.url, () => { if (simulationEnabled) { return simulationActions.includes(`SelectProcess:${selection}`); } @@ -2459,7 +2459,7 @@ export const InventorySelectionDialog = ({ const [showPublicInventories, setShowPublicInventories] = useState(false); const [sort, setSort] = useState(['distance', 'asc']); - const otherLocation = useMemo(() => { + const otherLocation = useMemo(import.meta.url, () => { if (!otherEntity) return {}; return locationsArrToObj(otherEntity.Location?.locations || []); }, [otherEntity]); @@ -2471,7 +2471,7 @@ export const InventorySelectionDialog = ({ // ... but can access inventories on their crewed ship (assuming not sending things elsewhere) const { data: crewedShip } = useShip((otherLocation.lotIndex === 0 && crew?._location?.shipId === otherLocation.shipId) ? otherLocation.shipId : null); - const inventories = useMemo(() => { + const inventories = useMemo(import.meta.url, () => { const allInventoryEntities = []; if (limitToPrimary) { @@ -2553,7 +2553,7 @@ export const InventorySelectionDialog = ({ return display; }, [crewedShip, inventoryData, itemIds, otherLocation, sort]); - const onComplete = useCallback(() => { + const onComplete = useCallback(import.meta.url, () => { onSelected(selection ? JSON.parse(selection) : null); onClose(); }, [onClose, onSelected, selection]); @@ -2561,7 +2561,7 @@ export const InventorySelectionDialog = ({ const specifiedItems = !!filterItemIds; const soloItem = itemIds?.length === 1 ? itemIds[0] : null; - const columns = useMemo(() => { + const columns = useMemo(import.meta.url, () => { const useItemAmount = Object.values(filterItemIds || {}).filter((x) => !!x).length === 1 ? Object.keys(filterItemIds).find((k) => filterItemIds[k]) : false; @@ -2635,7 +2635,7 @@ export const InventorySelectionDialog = ({ ].filter((x) => !!x); }, [filterItemIds, isSourcing, limitToPrimary, specifiedItems]); - const handleSort = useCallback((field) => () => { + const handleSort = useCallback(import.meta.url, (field) => () => { if (!field) return; let [updatedSortField, updatedSortDirection] = sort; @@ -2649,7 +2649,7 @@ export const InventorySelectionDialog = ({ setSort([updatedSortField, updatedSortDirection]); }, [sort]); - const getRowProps = useCallback((row) => { + const getRowProps = useCallback(import.meta.url, (row) => { const coachmarked = coachmarks[COACHMARK_IDS.actionDialogTargetInventory] === `${row.entity.label}.${row.entity.id}.${row.slot}`; return { setRef: coachmarked ? setCoachmarkRef(COACHMARK_IDS.actionDialogTargetInventory) : null, @@ -2659,11 +2659,11 @@ export const InventorySelectionDialog = ({ }; }, [selection, coachmarks, setCoachmarkRef]); - const handleFilterChange = useCallback((e) => { + const handleFilterChange = useCallback(import.meta.url, (e) => { setFilterValue(e.target.value); }, []); - useEffect(() => { + useEffect(import.meta.url, () => { setFilterItemIds( itemIds?.length ? itemIds @@ -2673,11 +2673,11 @@ export const InventorySelectionDialog = ({ ); }, [itemIds]); - const toggleFilterItem = useCallback((itemId) => { + const toggleFilterItem = useCallback(import.meta.url, (itemId) => { setFilterItemIds((x) => ({ ...x, [itemId]: !x[itemId] })); }, []); - const filteredInventories = useMemo(() => { + const filteredInventories = useMemo(import.meta.url, () => { const filterProductIds = isSourcing ? Object.keys(filterItemIds || {}).filter((k) => filterItemIds[k]) : []; return inventories .map((inv) => { @@ -2712,7 +2712,7 @@ export const InventorySelectionDialog = ({ .sort((a, b) => (sort[1] === 'desc' ? -1 : 1) * (a[sort[0]] < b[sort[0]] ? -1 : 1)); }, [filterItemIds, filterValue, inventories, isSourcing, showPermittedInventories, showPublicInventories, sort]); - const isCompletable = useMemo(() => { + const isCompletable = useMemo(import.meta.url, () => { if (selection && simulationEnabled) { const selObj = inventories.find((i) => i.key === selection); return simulationActions.includes(`SelectInventory:${selObj?.entity?.label}.${selObj?.entity?.id}.${selObj?.slot}`); @@ -2862,7 +2862,7 @@ const OrderSelectionTable = ({ orders, productId, onSelected, selected }) => { const [sort, setSort] = useState(['_adjUnitPrice', 'desc']); const [sortField, sortDirection] = sort; - const getRowProps = useCallback((row) => ({ + const getRowProps = useCallback(import.meta.url, (row) => ({ onClick: () => { onSelected(row); }, @@ -2871,7 +2871,7 @@ const OrderSelectionTable = ({ orders, productId, onSelected, selected }) => { tableState: { resource: Product.TYPES[productId] } }), [onSelected, productId, selected]); - const handleSort = useCallback((field) => () => { + const handleSort = useCallback(import.meta.url, (field) => () => { if (!field) return; let updatedSortField = sortField; @@ -2889,12 +2889,12 @@ const OrderSelectionTable = ({ orders, productId, onSelected, selected }) => { ]); }, [sortDirection, sortField]); - const sortedOrders = useMemo(() => { + const sortedOrders = useMemo(import.meta.url, () => { return (orders || []) .sort((a, b) => (sortDirection === 'asc' ? 1 : -1) * (a[sortField] < b[sortField] ? 1 : -1)); }, [orders, sortField, sortDirection]); - const columns = useMemo(() => ([ + const columns = useMemo(import.meta.url, () => ([ { key: 'selector', label: , @@ -2983,13 +2983,13 @@ export const OrderSelectionDialog = ({ const [selected, setSelected] = useState(); const [targetAmount, setTargetAmount] = useState(maxAmount || 0); - const destinationLocation = useMemo(() => { + const destinationLocation = useMemo(import.meta.url, () => { if (!otherEntity) return {}; return locationsArrToObj(otherEntity.Location?.locations || []); }, [otherEntity]); const destLotId = destinationLocation?.lotId; - const crewBonuses = useMemo(() => { + const crewBonuses = useMemo(import.meta.url, () => { if (!crew) return {}; const abilities = getCrewAbilityBonuses([ @@ -3010,11 +3010,11 @@ export const OrderSelectionDialog = ({ isLoading: resourceMarketplacesLoading, refetch: refetchResourceMarketplaces } = useShoppingListData(asteroidId, destLotId, [productId]); - const exchanges = useMemo(() => resourceMarketplaces?.[productId] || [], [resourceMarketplacesUpdatedAt]); + const exchanges = useMemo(import.meta.url, () => resourceMarketplaces?.[productId] || [], [resourceMarketplacesUpdatedAt]); useInterval(() => { refetchResourceMarketplaces(); }, 60e3); // keep things loosely fresh - const orders = useMemo(() => { + const orders = useMemo(import.meta.url, () => { return exchanges.reduce((aggOrders, row) => { const exchangeDistance = Asteroid.getLotDistance(asteroidId, Lot.toIndex(row.lotId), Lot.toIndex(destLotId)); const exchangeTravelTime = Time.toRealDuration( @@ -3068,19 +3068,19 @@ export const OrderSelectionDialog = ({ }, []); }, [asteroidId, crew?._timeAcceleration, crewBonuses, destLotId, exchanges, targetAmount]); - useEffect(() => { + useEffect(import.meta.url, () => { setSelected(); }, [targetAmount]); - const insufficientSway = useMemo(() => selected?.fillPaymentTotal > swayBalance, [selected, swayBalance]); + const insufficientSway = useMemo(import.meta.url, () => selected?.fillPaymentTotal > swayBalance, [selected, swayBalance]); - const isCompletable = useMemo(() => selected && !insufficientSway, [insufficientSway, selected]); + const isCompletable = useMemo(import.meta.url, () => selected && !insufficientSway, [insufficientSway, selected]); - const onSelected = useCallback((order) => { + const onSelected = useCallback(import.meta.url, (order) => { setSelected((old) => old?._orderPath === order._orderPath ? undefined : order); }, []); - const onComplete = useCallback(() => { + const onComplete = useCallback(import.meta.url, () => { if (isCompletable) { onCompleted(selected); onClose(); @@ -3171,7 +3171,7 @@ export const ExchangeSelectionDialog = ({ const [selected, setSelected] = useState([]); const [targetAmount, setTargetAmount] = useState(maxAmount || 0); - const destinationLocation = useMemo(() => { + const destinationLocation = useMemo(import.meta.url, () => { if (!otherEntity) return {}; return locationsArrToObj(otherEntity.Location?.locations || []); }, [otherEntity]); @@ -3183,11 +3183,11 @@ export const ExchangeSelectionDialog = ({ isLoading: resourceMarketplacesLoading, refetch: refetchResourceMarketplaces } = useShoppingListData(asteroidId, destLotId, [productId]); - const exchanges = useMemo(() => resourceMarketplaces?.[productId] || [], [resourceMarketplacesUpdatedAt]); + const exchanges = useMemo(import.meta.url, () => resourceMarketplaces?.[productId] || [], [resourceMarketplacesUpdatedAt]); useInterval(() => { refetchResourceMarketplaces(); }, 60e3); // keep things loosely fresh - const crewBonuses = useMemo(() => { + const crewBonuses = useMemo(import.meta.url, () => { if (!crew) return {}; const abilities = getCrewAbilityBonuses([ @@ -3202,7 +3202,7 @@ export const ExchangeSelectionDialog = ({ } }, [crew]); - const selectionSummary = useMemo(() => { + const selectionSummary = useMemo(import.meta.url, () => { let needed = targetAmount; let totalPrice = 0; let maxTravelTime = 0; @@ -3252,11 +3252,11 @@ export const ExchangeSelectionDialog = ({ }; }, [selected, targetAmount]); - const insufficientSway = useMemo(() => selectionSummary.totalPrice * TOKEN_SCALE[TOKEN.SWAY] > swayBalance, [selectionSummary, swayBalance]); + const insufficientSway = useMemo(import.meta.url, () => selectionSummary.totalPrice * TOKEN_SCALE[TOKEN.SWAY] > swayBalance, [selectionSummary, swayBalance]); - const isCompletable = useMemo(() => selectionSummary.totalFilled > 0 && !insufficientSway, [insufficientSway, selectionSummary]); + const isCompletable = useMemo(import.meta.url, () => selectionSummary.totalFilled > 0 && !insufficientSway, [insufficientSway, selectionSummary]); - const onSelected = useCallback((buildingId) => { + const onSelected = useCallback(import.meta.url, (buildingId) => { if (singleSelectionMode) { setSelected((old) => old.includes(buildingId) ? [] : [buildingId]); } else { @@ -3277,7 +3277,7 @@ export const ExchangeSelectionDialog = ({ } }, [selectionSummary, singleSelectionMode]); - const onComplete = useCallback(() => { + const onComplete = useCallback(import.meta.url, () => { if (isCompletable) { onCompleted(selectionSummary); onClose(); @@ -3560,13 +3560,13 @@ export const MiniBarChart = ({ color, deltaColor, deltaValue, label, valueLabel, export const SwayInput = ({ inputLabel = "SWAY", onChange, value: defaultValue, ...props }) => { const [value, setValue] = useState(0); - const internalOnChange = useCallback((e) => { + const internalOnChange = useCallback(import.meta.url, (e) => { let cleanValue = e.target?.value ? parseInt(e.target.value) : ''; setValue(cleanValue); if (onChange) onChange(cleanValue); }, [onChange]); - useEffect(() => { + useEffect(import.meta.url, () => { setValue(defaultValue || 0); }, [defaultValue]); @@ -3852,7 +3852,7 @@ export const LotControlWarning = ({ lot }) => { const { crew } = useCrewContext(); const { isAtRisk } = useConstructionManager(lot?.id); - const warning = useMemo(() => { + const warning = useMemo(import.meta.url, () => { if (!(crew && lot)) return null; if (isAtRisk) { return <>Construction Site is vulnerable to any crew.; @@ -3887,7 +3887,7 @@ export const ResourceGridSectionInner = ({ style, theming = 'default' }) => { - const { totalItems, totalMass, totalVolume } = useMemo(() => { + const { totalItems, totalMass, totalVolume } = useMemo(import.meta.url, () => { return items.reduce((acc, { i, numerator, denominator, selected }) => { if (!Product.TYPES[i]) { console.error(`Product #${i} invalid`) @@ -3969,7 +3969,7 @@ const ResourceGridSection = ({ label, sectionProps = {}, ...props }) => ( ); export const BuildingRequirementsSection = ({ mode, label, requirements, requirementsMet }) => { - const items = useMemo(() => { + const items = useMemo(import.meta.url, () => { return requirements.map((item) => ({ i: item.i, numerator: item.inInventory + item.inTransit, @@ -3996,7 +3996,7 @@ export const BuildingRequirementsSection = ({ mode, label, requirements, require }; export const TransferBuildingRequirementsSection = ({ label, onClick, requirements, selectedItems }) => { - const items = useMemo(() => requirements.map((item) => ({ + const items = useMemo(import.meta.url, () => requirements.map((item) => ({ i: item.i, numerator: item.inInventory + item.inTransit + (selectedItems[item.i] || 0), denominator: item.totalRequired, @@ -4022,7 +4022,7 @@ export const TransferBuildingRequirementsSection = ({ label, onClick, requiremen }; export const DeconstructionMaterialsSection = ({ label, itemsReturned }) => { - const items = useMemo(() => { + const items = useMemo(import.meta.url, () => { return itemsReturned.map((item) => ({ i: item.i, customIcon: { icon: }, @@ -4038,7 +4038,7 @@ export const DeconstructionMaterialsSection = ({ label, itemsReturned }) => { }; export const ItemSelectionSection = ({ columns = 7, label, items, onClick, stage, unwrapped, ...props }) => { - const formattedItems = useMemo(() => { + const formattedItems = useMemo(import.meta.url, () => { return Object.keys(items || {}).map((resourceId) => ({ i: resourceId, numerator: items[resourceId] @@ -4110,7 +4110,7 @@ export const ProgressBarSection = ({ const refEl = useRef(); const [hovered, setHovered] = useState(); - const { animating, barWidth, color, left, reverseAnimation, right, center } = useMemo(() => { + const { animating, barWidth, color, left, reverseAnimation, right, center } = useMemo(import.meta.url, () => { const r = { animating: false, reverseAnimation: false, @@ -4175,7 +4175,7 @@ export const ProgressBarSection = ({ return r; }, [finishTime, stage, startTime, syncedTime]); - const totalTimeNote = useMemo(() => { + const totalTimeNote = useMemo(import.meta.url, () => { if (!totalTime) return ''; if ([actionStage.NOT_STARTED, actionStage.COMPLETING, actionStage.COMPLETED].includes(stage)) return ''; return `TOTAL: ${formatTimer(totalTime, 2)}`; @@ -4215,7 +4215,7 @@ export const ProgressBarSection = ({ export const ResourceAmountSlider = ({ amount, extractionTime, min, max, resource, setAmount }) => { const setCoachmarkRef = useCoachmarkRefSetter(); - const [grams, tonnageValue] = useMemo(() => { + const [grams, tonnageValue] = useMemo(import.meta.url, () => { const grams = amount * resource?.massPerUnit || 0; const tonnage = grams / 1e6; const tonnageValue = Math.round(1e3 * tonnage) / 1e3; @@ -4225,7 +4225,7 @@ export const ResourceAmountSlider = ({ amount, extractionTime, min, max, resourc const [focusOn, setFocusOn] = useState(); const [mouseIn, setMouseIn] = useState(false); - const onFocusEvent = useCallback((e) => { + const onFocusEvent = useCallback(import.meta.url, (e) => { if (e.type === 'focus') { setFocusOn(true); e.target.select(); @@ -4234,7 +4234,7 @@ export const ResourceAmountSlider = ({ amount, extractionTime, min, max, resourc } }, []); - const onMouseEvent = useCallback((e) => { + const onMouseEvent = useCallback(import.meta.url, (e) => { setMouseIn(e.type === 'mouseenter') }, []); @@ -4287,14 +4287,14 @@ export const RecipeSlider = ({ amount, disabled, increment = 0.001, processingTi const setCoachmarkRef = useCoachmarkRefSetter(); - const [min, max] = useMemo(() => { + const [min, max] = useMemo(import.meta.url, () => { return [ Math.ceil(rawMin / increment) * increment, Math.floor(rawMax / increment) * increment ]; }, [increment, rawMin, rawMax]); - const onFocusEvent = useCallback((e) => { + const onFocusEvent = useCallback(import.meta.url, (e) => { if (e.type === 'focus') { setFocusOn(true); e.target.select(); @@ -4303,11 +4303,11 @@ export const RecipeSlider = ({ amount, disabled, increment = 0.001, processingTi } }, []); - const onMouseEvent = useCallback((e) => { + const onMouseEvent = useCallback(import.meta.url, (e) => { setMouseIn(e.type === 'mouseenter') }, []); - const onSetAmount = useCallback((value) => { + const onSetAmount = useCallback(import.meta.url, (value) => { let cleansed = numeral(value); if (cleansed.value() === null) cleansed = numeral(min); @@ -4323,11 +4323,11 @@ export const RecipeSlider = ({ amount, disabled, increment = 0.001, processingTi setAmount(Number(cleansed.format(`${increment}`))); }, [increment, min, max]); - const onChangeInput = useCallback((e) => { + const onChangeInput = useCallback(import.meta.url, (e) => { onSetAmount(e.currentTarget.value); }, [onSetAmount]); - const onRound = useCallback(() => { + const onRound = useCallback(import.meta.url, () => { onSetAmount(Math.round(amount)); }, [amount, onSetAmount]); @@ -4386,7 +4386,7 @@ export const RecipeSlider = ({ amount, disabled, increment = 0.001, processingTi }; export const ProcessInputOutputSection = ({ title, products, input, output, primaryOutput, secondaryOutputsBonus, setPrimaryOutput, source, stage, ...props }) => { - const sourceContents = useMemo(() => (source?.contents || []).reduce((acc, cur) => ({ ...acc, [cur.product]: cur.amount }), {}), [source]); + const sourceContents = useMemo(import.meta.url, () => (source?.contents || []).reduce((acc, cur) => ({ ...acc, [cur.product]: cur.amount }), {}), [source]); return ( @@ -4446,7 +4446,7 @@ export const ProcessInputOutputSection = ({ title, products, input, output, prim }; export const ProcessInputSquareSection = ({ title, products, input, output, primaryOutput, setPrimaryOutput, source, stage, ...props }) => { - const sourceContents = useMemo(() => (source?.contents || []).reduce((acc, cur) => ({ ...acc, [cur.product]: cur.amount }), {}), [source]); + const sourceContents = useMemo(import.meta.url, () => (source?.contents || []).reduce((acc, cur) => ({ ...acc, [cur.product]: cur.amount }), {}), [source]); return ( @@ -4844,21 +4844,21 @@ export const InventoryInputBlock = ({ sublabel, ...props }) => { - const inventory = useMemo(() => { + const inventory = useMemo(import.meta.url, () => { if (entity?.Inventories && inventorySlot) { return entity.Inventories.find((i) => i.slot === inventorySlot); } return null; }, [entity, inventorySlot]); - const invConfig = useMemo(() => { + const invConfig = useMemo(import.meta.url, () => { if (inventory) { return Inventory.getType(inventory.inventoryType, inventoryBonuses); } return null; }, [inventory, inventoryBonuses]); - const destinationOverloaded = useMemo(() => { + const destinationOverloaded = useMemo(import.meta.url, () => { const changeAlreadyApplied = (stage && ![actionStage.NOT_STARTED, actionStage.STARTING].includes(stage)); if (inventory && !isSourcing) { @@ -4875,7 +4875,7 @@ export const InventoryInputBlock = ({ return false; }, [transferMass, transferVolume, inventory, inventoryBonuses, stage]); - const params = useMemo(() => { + const params = useMemo(import.meta.url, () => { const fullImageProps = { ...imageProps, error: destinationOverloaded, @@ -4973,7 +4973,7 @@ export const ShipInputBlock = ({ ship, ...props }) => { export const ShipTab = ({ pilotCrew, inventoryBonuses, ship, stage, deltas = {}, statWarnings = {}, warnings = [] }) => { // TODO: if want to include "reserved", it would probably make sense to use getCapacityUsage helper instead - const inventory = useMemo(() => { + const inventory = useMemo(import.meta.url, () => { if (!ship?.Ship?.shipType || !ship?.Inventories) return {}; const shipConfig = Ship.TYPES[ship.Ship.shipType] || {}; const propellantInventory = ship.Inventories.find((i) => i.slot === shipConfig.propellantSlot); @@ -4992,7 +4992,7 @@ export const ShipTab = ({ pilotCrew, inventoryBonuses, ship, stage, deltas = {}, }; }, [ship?.shipType, ship?.Inventories, inventoryBonuses]); - const charts = useMemo(() => { + const charts = useMemo(import.meta.url, () => { const result = { propellantMass: { color: '#8cc63f', @@ -5179,12 +5179,12 @@ const ActionDialogStat = ({ stat: { isTimeStat, label, value, direction, tooltip export const ActionDialogStats = ({ stage, stats: rawStats, wide }) => { const [open, setOpen] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { setOpen(stage === actionStage.NOT_STARTED); }, [stage]); // remove any conditionally omitted stats - const stats = useMemo(() => rawStats.filter((s) => !!s), [rawStats]); + const stats = useMemo(import.meta.url, () => rawStats.filter((s) => !!s), [rawStats]); if (!stats?.length) return null; return ( @@ -5247,13 +5247,13 @@ export const ActionDialogFooter = ({ // (we'll also need the ability to cancel those timers) // show unless already enabled - const enableNotifications = useCallback(async () => { + const enableNotifications = useCallback(import.meta.url, async () => { setNotificationsEnabled((x) => !x); }, []); - const allowedOrLaunched = useMemo(() => requireLaunched ? isLaunched : true, [isLaunched, requireLaunched]); + const allowedOrLaunched = useMemo(import.meta.url, () => requireLaunched ? isLaunched : true, [isLaunched, requireLaunched]); - const finalizeActions = useMemo(() => { + const finalizeActions = useMemo(import.meta.url, () => { if (Array.isArray(onFinalize)) { return onFinalize.map((onAction, i) => ({ finalizeLabel: finalizeLabel?.[i], @@ -5468,7 +5468,7 @@ const extractBonuses = (bonusObj, isTimeStat) => { export const BonusTooltip = ({ bonus = {}, details, title, titleValue, isTimeStat }) => { const timeMult = isTimeStat ? -1 : 1; const titleDirection = getBonusDirection({ totalBonus: bonus.totalBonus }); - const bonuses = useMemo(() => extractBonuses(bonus, isTimeStat), [bonus, isTimeStat]); + const bonuses = useMemo(import.meta.url, () => extractBonuses(bonus, isTimeStat), [bonus, isTimeStat]); return ( {(bonus.totalBonus !== 1 || !details) && ( @@ -5532,7 +5532,7 @@ export const BonusTooltip = ({ bonus = {}, details, title, titleValue, isTimeSta export const FeeBonusTooltip = ({ baseFeeRate, bonusedFeeRate, feeEnforcementBonus, feeReductionBonus, ...props }) => { const flip = false; const timeMult = 1; - const reductionBonuses = useMemo(() => extractBonuses(feeReductionBonus, true), [feeReductionBonus]); + const reductionBonuses = useMemo(import.meta.url, () => extractBonuses(feeReductionBonus, true), [feeReductionBonus]); return ( {feeEnforcementBonus.totalBonus !== 1 && ( diff --git a/src/game/interface/hud/actionForms/RouteSelection.js b/src/game/interface/hud/actionForms/RouteSelection.js index 17111255c..74a5c9fc8 100644 --- a/src/game/interface/hud/actionForms/RouteSelection.js +++ b/src/game/interface/hud/actionForms/RouteSelection.js @@ -1,4 +1,4 @@ -import { useCallback } from 'react'; +import { useCallback } from '~/lib/react-debug'; import styled from 'styled-components'; import { TiMediaRecord as OriginIcon } from 'react-icons/ti'; import { TbSwitch2 as SwapIcon } from 'react-icons/tb'; @@ -61,22 +61,22 @@ const RouteSelection = () => { const { data: destination } = useAsteroid(destinationId); const setCoachmarkRef = useCoachmarkRefSetter(); - const handleSwap = useCallback(() => { + const handleSwap = useCallback(import.meta.url, () => { if (originId && destinationId) dispatchSwapOriginDestination(); }, [destinationId, dispatchSwapOriginDestination, originId]); - const handleClose = useCallback(() => { + const handleClose = useCallback(import.meta.url, () => { dispatchDestinationSelected(); dispatchHudMenuOpened(); }, [dispatchDestinationSelected, dispatchHudMenuOpened]); - const handleFocus = useCallback(() => { + const handleFocus = useCallback(import.meta.url, () => { if (simulationActions.includes('PlanFlight')) { dispatchDestinationSelected(SIMULATION_CONFIG.destinationAsteroidId); } }, [simulationActions]); - const handleSelect = useCallback((dest) => { + const handleSelect = useCallback(import.meta.url, (dest) => { if (Number(dest?.id) !== Number(originId)) dispatchDestinationSelected(dest?.id) }, [dispatchDestinationSelected, originId]); diff --git a/src/game/interface/hud/hudBanners/SearchAsteroidsBanner.js b/src/game/interface/hud/hudBanners/SearchAsteroidsBanner.js index e294e4dac..846f85084 100644 --- a/src/game/interface/hud/hudBanners/SearchAsteroidsBanner.js +++ b/src/game/interface/hud/hudBanners/SearchAsteroidsBanner.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import Dropdown from '~/components/Dropdown'; @@ -66,21 +66,21 @@ const SearchAsteroidsBanner = ({ visible }) => { const sort = useStore(s => s.assetSearch[assetType].sort); const updateSort = useStore(s => s.dispatchSortUpdated(assetType)); - const toggleSortOrder = useCallback(() => { + const toggleSortOrder = useCallback(import.meta.url, () => { updateSort([sort[0], sort[1] === 'asc' ? 'desc' : 'asc']); }, [sort]); - const updateSortOrder = useCallback((option) => { + const updateSortOrder = useCallback(import.meta.url, (option) => { updateSort([option.value || 'Celestial.radius', 'desc']); }, [sort]); - const sortOptions = useMemo(() => { + const sortOptions = useMemo(import.meta.url, () => { return columns .filter((c) => c.sortField && !['owner','spectralType'].includes(c.sortField)) // TODO: ecs refactor .map((c) => ({ label: c.label, value: c.sortField, icon: c.icon })); }, [columns]); - const data = useMemo(() => { + const data = useMemo(import.meta.url, () => { const total = assetSearch?.total; const showing = assetSearch?.hits?.length || 0; return { total, showing }; diff --git a/src/game/interface/hud/hudBanners/SearchLotsBanner.js b/src/game/interface/hud/hudBanners/SearchLotsBanner.js index bb4799155..9d1f6a57d 100644 --- a/src/game/interface/hud/hudBanners/SearchLotsBanner.js +++ b/src/game/interface/hud/hudBanners/SearchLotsBanner.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid } from '@influenceth/sdk'; @@ -39,9 +39,9 @@ const SearchLotsBanner = ({ visible }) => { const { total, isLoading } = useStore(s => s.lotsMappedAssetSearchResults); const asteroidId = useStore(s => s.asteroids.origin); - const maxResults = useMemo(() => Asteroid.getSurfaceArea(asteroidId), [asteroidId]); + const maxResults = useMemo(import.meta.url, () => Asteroid.getSurfaceArea(asteroidId), [asteroidId]); - const activeFilters = useMemo(() => { + const activeFilters = useMemo(import.meta.url, () => { return Object.keys(filters || {}) .reduce((acc, fieldName) => acc + (isAssetSearchFilterMatchingDefault(assetType, fieldName) ? 0 : 1), 0) }, [assetType, filters]); diff --git a/src/game/interface/hud/hudBanners/TravelBanner.js b/src/game/interface/hud/hudBanners/TravelBanner.js index 08a2ea4b3..a8d8de519 100644 --- a/src/game/interface/hud/hudBanners/TravelBanner.js +++ b/src/game/interface/hud/hudBanners/TravelBanner.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { GasIcon, ShipMarkerIcon, TimerIcon, WarningIcon } from '~/components/Icons'; @@ -65,7 +65,7 @@ const TravelBanner = ({ visible }) => { const travelSolutionIsValid = useTravelSolutionIsValid(); - const { headline, bannerColor } = useMemo(() => { + const { headline, bannerColor } = useMemo(import.meta.url, () => { let h, c; if (travelSolution) { if (!travelSolutionIsValid) { diff --git a/src/game/interface/hud/hudMenus/AdminAsteroid.js b/src/game/interface/hud/hudMenus/AdminAsteroid.js index 2f7f66368..07a835647 100644 --- a/src/game/interface/hud/hudMenus/AdminAsteroid.js +++ b/src/game/interface/hud/hudMenus/AdminAsteroid.js @@ -14,7 +14,7 @@ import { renderDummyAsteroid } from '~/game/scene/asteroid/helpers/utils'; import constants from '~/lib/constants'; import exportGLTF from '~/lib/graphics/exportGLTF'; import useWebWorker from '~/hooks/useWebWorker'; -import { useCallback, useState } from 'react'; +import { useCallback, useState } from '~/lib/react-debug'; import { nativeBool, reactBool } from '~/lib/utils'; import styled from 'styled-components'; import CrewIndicator from '~/components/CrewIndicator'; @@ -40,7 +40,7 @@ const AdminAsteroid = ({}) => { const [exportingModel, setExportingModel] = useState(false); - const download3dModel = useCallback(() => { + const download3dModel = useCallback(import.meta.url, () => { if (exportingModel || !asteroid) return; setExportingModel(true); renderDummyAsteroid(asteroid, constants.MODEL_EXPORT_RESOLUTION, webWorkerPool, (asteroidModel, dispose) => { diff --git a/src/game/interface/hud/hudMenus/AdminShip.js b/src/game/interface/hud/hudMenus/AdminShip.js index 96384d7f8..954c1d9c9 100644 --- a/src/game/interface/hud/hudMenus/AdminShip.js +++ b/src/game/interface/hud/hudMenus/AdminShip.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Entity, Permission } from '@influenceth/sdk'; @@ -22,7 +22,7 @@ const AdminShip = ({}) => { const { data: zoomShip } = useShip(zoomShipId); const { data: lot } = useLot(lotId); - const ship = useMemo(() => zoomShipId ? zoomShip : lot?.surfaceShip, [lot, zoomShip, zoomShipId]); + const ship = useMemo(import.meta.url, () => zoomShipId ? zoomShip : lot?.surfaceShip, [lot, zoomShip, zoomShipId]); const { data: controller } = useCrew(ship?.Control?.controller?.id); return ( diff --git a/src/game/interface/hud/hudMenus/AsteroidChat.js b/src/game/interface/hud/hudMenus/AsteroidChat.js index c0051f885..4fae2a7bf 100644 --- a/src/game/interface/hud/hudMenus/AsteroidChat.js +++ b/src/game/interface/hud/hudMenus/AsteroidChat.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Entity } from '@influenceth/sdk'; import moment from 'moment'; @@ -105,7 +105,7 @@ const isValidChatMessage = (content) => { const maxChatInputHeight = 95; const ChatItem = ({ chat, showTimestamp }) => { - const ago = useMemo(() => { + const ago = useMemo(import.meta.url, () => { if (!chat.timestamp) return 'a long time ago'; const m = moment(new Date(chat.timestamp)); return m.fromNow(); @@ -139,12 +139,12 @@ const AsteroidChat = () => { const [newChat, setNewChat] = useState(); - const scrollToBottom = useCallback(() => { + const scrollToBottom = useCallback(import.meta.url, () => { if (chatScrollRef.current) chatScrollRef.current.scrollTop = chatScrollRef.current.scrollHeight; }, []); const [submitting, setSubmitting] = useState(); - const submitNewChat = useCallback(async () => { + const submitNewChat = useCallback(import.meta.url, async () => { if (asteroidId && crew?.id && isValidChatMessage(newChat)) { setSubmitting(true); const ack = await emitMessage('send-message', { @@ -175,21 +175,21 @@ const AsteroidChat = () => { } }, [asteroidId, crew?.id, emitMessage, newChat, createAlert]); - const handleNewChatChange = useCallback(async (e) => { + const handleNewChatChange = useCallback(import.meta.url, async (e) => { setNewChat(e.currentTarget.value || ''); resizeOnKeydown(maxChatInputHeight)(e); scrollToBottom(); }, [scrollToBottom]); - const handleKeyDown = useCallback((e) => { + const handleKeyDown = useCallback(import.meta.url, (e) => { if (e.key === 'Enter' && !e.shiftKey) { submitNewChat(); } }, [submitNewChat]); - const remaining = useMemo(() => maxChatMessageLength - (newChat?.length || 0), [newChat?.length]); + const remaining = useMemo(import.meta.url, () => maxChatMessageLength - (newChat?.length || 0), [newChat?.length]); - const asteroidChats = useMemo( + const asteroidChats = useMemo(import.meta.url, () => (chatHistory || []) // filter to asteroid (and connection breaks) .filter((c) => c.isConnectionBreak || c.asteroidId === asteroidId) @@ -201,13 +201,13 @@ const AsteroidChat = () => { ); const lastChat = asteroidChats?.[asteroidChats?.length - 1]; - useEffect(() => { + useEffect(import.meta.url, () => { if (asteroidId && lastChat?.unread) { dispatchChatRoomView(asteroidId); } }, [asteroidId, lastChat?.timestamp]); - useEffect(() => { + useEffect(import.meta.url, () => { scrollToBottom(); }, [asteroidChats, scrollToBottom]); diff --git a/src/game/interface/hud/hudMenus/AsteroidInfo.js b/src/game/interface/hud/hudMenus/AsteroidInfo.js index 8a8214d7e..8b770b729 100644 --- a/src/game/interface/hud/hudMenus/AsteroidInfo.js +++ b/src/game/interface/hud/hudMenus/AsteroidInfo.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid, Entity, Ship } from '@influenceth/sdk'; @@ -72,13 +72,13 @@ const AsteroidInfo = ({ onClose }) => { const { data: administrator } = useCrew(asteroid?.Control?.controller?.id); const { data: priceConstants } = usePriceConstants(); - const shipsInOrbitTally = useMemo(() => { + const shipsInOrbitTally = useMemo(import.meta.url, () => { return (ships || []).filter((ship) => { return ship.Location.location.label === Entity.IDS.ASTEROID && ship.Ship.status === Ship.STATUSES.AVAILABLE; }).length; }, [ships]); - const structuresTally = useMemo(() => { + const structuresTally = useMemo(import.meta.url, () => { let structures = 0; if (lotData) { for (let i = 1; i < lotData.length; i++) { @@ -88,7 +88,7 @@ const AsteroidInfo = ({ onClose }) => { return structures; }, [lotData]); - const zoomIn = useCallback(() => { + const zoomIn = useCallback(import.meta.url, () => { dispatchZoomStatus('zooming-in'); }, []); diff --git a/src/game/interface/hud/hudMenus/DevTools.js b/src/game/interface/hud/hudMenus/DevTools.js index 2d97609cc..d839a9937 100644 --- a/src/game/interface/hud/hudMenus/DevTools.js +++ b/src/game/interface/hud/hudMenus/DevTools.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useContext, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { NoToneMapping } from 'three'; import { Building, Product, Ship } from '@influenceth/sdk'; @@ -77,7 +77,7 @@ const reader = new FileReader(); const DevTools = () => { const { assetType, overrides, ...setters } = useContext(DevToolContext); - const [defaultSettings, settings] = useMemo(() => { + const [defaultSettings, settings] = useMemo(import.meta.url, () => { if (!assetType) return [{}, {}]; const defaults = assetType === 'scene' ? visualConfigs.scene : visualConfigs.modelViewer[assetType]; @@ -100,13 +100,13 @@ const DevTools = () => { const [modelSelection, setModelSelection] = useState(); const [modelOverride, setModelOverride] = useState(); - const assets = useMemo(() => { + const assets = useMemo(import.meta.url, () => { if (assetType === 'building') return Object.keys(Building.TYPES).map((i) => ({ ...Building.TYPES[i], modelUrl: getBuildingModel(i) })); if (assetType === 'resource') return Object.keys(Product.TYPES).map((i) => ({ ...Product.TYPES[i], modelUrl: getProductModel(i) })); if (assetType === 'ship') return Object.keys(Ship.TYPES).map((i) => ({ ...Ship.TYPES[i], modelUrl: getShipModel(i) })); }, [assetType]); - useEffect(() => { + useEffect(import.meta.url, () => { setCategories(); setCategory(); if (assets) { @@ -119,7 +119,7 @@ const DevTools = () => { } }, [assetType]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!!assets) { const bAssets = assets .filter((a) => (a.category || '') === category) @@ -131,20 +131,20 @@ const DevTools = () => { } }, [assetType, category]); // eslint-disable-line react-hooks/exhaustive-deps - useEffect(() => { + useEffect(import.meta.url, () => { setters.setModelUrl(modelOverride?.url || modelSelection?.modelUrl); }, [modelOverride, modelSelection]); - const selectModel = useCallback((m) => { + const selectModel = useCallback(import.meta.url, (m) => { setModelSelection(m); }, []); - const handleUploadClick = useCallback((which) => () => { + const handleUploadClick = useCallback(import.meta.url, (which) => () => { uploadType.current = which; fileInput.current.click(); }, []); - const handleFile = useCallback((e) => { + const handleFile = useCallback(import.meta.url, (e) => { const file = e.target.files[0]; if (uploadType.current === 'model' && file.name.match(/\.(gltf|glb)$/i)) { setIsLoading(true); @@ -174,7 +174,7 @@ const DevTools = () => { } }, []); - const removeOverride = useCallback((which) => () => { + const removeOverride = useCallback(import.meta.url, (which) => () => { if (which === 'model') { setModelOverride(); } else if (which === 'bg') { @@ -186,11 +186,11 @@ const DevTools = () => { } }, []); - const toggleSetting = useCallback((setter) => { + const toggleSetting = useCallback(import.meta.url, (setter) => { setter((s) => !s); }, []); - const onChangeToneMapping = useCallback((selection) => { + const onChangeToneMapping = useCallback(import.meta.url, (selection) => { setters.setToneMapping(selection?.value); // if (selection?.value === NoToneMapping) { // setters.setToneMappingExposure(); @@ -199,7 +199,7 @@ const DevTools = () => { // (make sure form values all get reset on asset change) const [resetting, setResetting] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { setResetting(true); setTimeout(() => { setResetting(false); diff --git a/src/game/interface/hud/hudMenus/DockDetails.js b/src/game/interface/hud/hudMenus/DockDetails.js index 493c678f8..38fbf1839 100644 --- a/src/game/interface/hud/hudMenus/DockDetails.js +++ b/src/game/interface/hud/hudMenus/DockDetails.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Dock, Ship } from '@influenceth/sdk'; @@ -155,17 +155,17 @@ const DockDetails = ({ onClose }) => { const [nameFilter, setNameFilter] = useState(''); const [selectedShipId, setSelectedShipId] = useState(); - const selectedShip = useMemo(() => lot?.ships?.find((s) => s.id === selectedShipId), [lot?.ships, selectedShipId]); + const selectedShip = useMemo(import.meta.url, () => lot?.ships?.find((s) => s.id === selectedShipId), [lot?.ships, selectedShipId]); - const onFilterChange = useCallback((e) => { + const onFilterChange = useCallback(import.meta.url, (e) => { setNameFilter(e.target.value || ''); }, []); - const zoomIn = useCallback(() => { + const zoomIn = useCallback(import.meta.url, () => { dispatchZoomScene({ type: 'SHIP', shipId: selectedShipId }); }, [selectedShipId]); - const filteredShips = useMemo(() => { + const filteredShips = useMemo(import.meta.url, () => { return (lot?.ships || []).filter((s) => { return formatters.shipName(s).toLowerCase().includes(nameFilter.toLowerCase()) }) diff --git a/src/game/interface/hud/hudMenus/Favorites.js b/src/game/interface/hud/hudMenus/Favorites.js index d093a3352..3d603c7e0 100644 --- a/src/game/interface/hud/hudMenus/Favorites.js +++ b/src/game/interface/hud/hudMenus/Favorites.js @@ -1,4 +1,4 @@ -import { useCallback } from 'react'; +import { useCallback } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid } from '@influenceth/sdk'; @@ -75,7 +75,7 @@ const Favorites = ({ onClose }) => { const updateZoomStatus = useStore(s => s.dispatchZoomStatusChanged); const { watchlist: { data: watchlist } } = useWatchlist(); - const onClick = useCallback((id) => () => { + const onClick = useCallback(import.meta.url, (id) => () => { if (asteroidId === id) { updateZoomStatus('zooming-in'); onClose(); diff --git a/src/game/interface/hud/hudMenus/Inventory.js b/src/game/interface/hud/hudMenus/Inventory.js index 9e870c0f2..2d6545840 100644 --- a/src/game/interface/hud/hudMenus/Inventory.js +++ b/src/game/interface/hud/hudMenus/Inventory.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { createPortal } from 'react-dom'; import styled, { css } from 'styled-components'; import { usePopper } from 'react-popper'; @@ -292,13 +292,13 @@ const LotInventory = () => { const zoomShipId = zoomScene?.type === 'SHIP' ? zoomScene.shipId : null; const { data: zoomShip } = useShip(zoomShipId); - const ship = useMemo(() => zoomShipId ? zoomShip : lot?.surfaceShip, [lot?.surfaceShip, zoomShip, zoomShipId]); + const ship = useMemo(import.meta.url, () => zoomShipId ? zoomShip : lot?.surfaceShip, [lot?.surfaceShip, zoomShip, zoomShipId]); - const entity = useMemo(() => ship || lot?.building, [lot, ship]); + const entity = useMemo(import.meta.url, () => ship || lot?.building, [lot, ship]); const { crew, crewCan } = useCrewContext(); - const inventories = useMemo(() => { + const inventories = useMemo(import.meta.url, () => { return (entity?.Inventories || []) .filter((i) => i.status === Inventory.STATUSES.AVAILABLE) .map((i) => ({ @@ -319,7 +319,7 @@ const LotInventory = () => { const resourceItemRefs = useRef([]); - const [canAddProducts, canRemoveProducts] = useMemo( + const [canAddProducts, canRemoveProducts] = useMemo(import.meta.url, () => ([ crewCan(Permission.IDS.ADD_PRODUCTS, entity), crewCan(Permission.IDS.REMOVE_PRODUCTS, entity), @@ -328,13 +328,13 @@ const LotInventory = () => { ); // default slot - useEffect(() => { + useEffect(import.meta.url, () => { if (inventorySlot === null) { setInventorySlot(inventories?.[0]?.slot || null); } }, [inventories]); - useEffect(() => { + useEffect(import.meta.url, () => { setSelectedItems({}); // clear selected items when switching inventories }, [entity?.uuid, inventorySlot]) @@ -345,7 +345,7 @@ const LotInventory = () => { ); // get selected inventory - const inventory = useMemo( + const inventory = useMemo(import.meta.url, () => inventories.find((i) => i.slot === inventorySlot), [inventories, inventorySlot] ); @@ -363,7 +363,7 @@ const LotInventory = () => { maxVolume, pctVolume, pctOrReservedVolume - } = useMemo(() => { + } = useMemo(import.meta.url, () => { if (!inventory) { return { usedMass: 0, @@ -414,11 +414,11 @@ const LotInventory = () => { }; }, [crew?._inventoryBonuses, inventory]); - const toggleVolumeDisplay = useCallback(() => { + const toggleVolumeDisplay = useCallback(import.meta.url, () => { setDisplayVolumes((d) => !d); }, []); - const sortedResources = useMemo(() => { + const sortedResources = useMemo(import.meta.url, () => { if (!inventory?.contentsObj) return []; return Object.keys(inventory.contentsObj).sort((a, b) => { if (order === 'Mass') return inventory.contentsObj[a] * Product.TYPES[a].massPerUnit > inventory.contentsObj[b] * Product.TYPES[b].massPerUnit ? -1 : 1; @@ -427,9 +427,9 @@ const LotInventory = () => { }); }, [inventory?.contentsObj, order]); - const isIncomingDelivery = useMemo(() => incomingDeliveries?.length > 0, [incomingDeliveries]); + const isIncomingDelivery = useMemo(import.meta.url, () => incomingDeliveries?.length > 0, [incomingDeliveries]); - const handleSelected = useCallback((resourceId, newTotal) => { + const handleSelected = useCallback(import.meta.url, (resourceId, newTotal) => { setSelectedItems((s) => { const newS = { ...s }; if (newTotal === 0) { @@ -441,20 +441,20 @@ const LotInventory = () => { }); }, []); - const splitStack = useCallback((resourceId) => (e) => { + const splitStack = useCallback(import.meta.url, (resourceId) => (e) => { e.stopPropagation(); setSplittingResourceId(resourceId); setAmount(selectedItems[resourceId] || inventory?.contentsObj[resourceId] || 0); }, [selectedItems, inventory?.contentsObj]); - const onChangeAmount = useCallback((e) => { + const onChangeAmount = useCallback(import.meta.url, (e) => { let newValue = parseInt(e.target.value.replace(/^0+/g, '').replace(/[^0-9]/g, '')); if (!(newValue > -1)) newValue = 0; if (newValue > e.target.max) newValue = e.target.max; setAmount(newValue); }, []); - const onKeyDown = useCallback((e) => { + const onKeyDown = useCallback(import.meta.url, (e) => { if (['Enter', 'Tab'].includes(e.key) && e.currentTarget.value) { handleSelected(splittingResourceId, amount); setFocused(false); @@ -462,17 +462,17 @@ const LotInventory = () => { } }, [amount, splittingResourceId]); - const onInventoryScroll = useCallback(() => { + const onInventoryScroll = useCallback(import.meta.url, () => { setSplittingResourceId(); }, []); - const onMouseLeave = useCallback(() => { + const onMouseLeave = useCallback(import.meta.url, () => { if (!focused) { setSplittingResourceId(); } }, [focused]); - const onFocusAmount = useCallback((e) => { + const onFocusAmount = useCallback(import.meta.url, (e) => { if (e.type === 'focus') { setFocused(true); } else { @@ -481,11 +481,11 @@ const LotInventory = () => { } }, []); - const isAllSelected = useMemo(() => { + const isAllSelected = useMemo(import.meta.url, () => { return Object.keys(selectedItems).length === sortedResources.length; }, [selectedItems, sortedResources]); - const toggleAll = useCallback(() => { + const toggleAll = useCallback(import.meta.url, () => { setSelectedItems((s) => { if (isAllSelected) return {}; return sortedResources.reduce((acc, resourceId) => { @@ -499,11 +499,11 @@ const LotInventory = () => { // TODO: maybe should deselect all whenever sendfrom, sellfrom, or jettison dialogs opened // TODO: probably should optimistically update item amounts from pending txs // of sendfrom, sellfrom, or jettison... - useEffect(() => { + useEffect(import.meta.url, () => { setSelectedItems({}); }, [inventory?.contentsObj]) - const trayLabel = useMemo(() => { + const trayLabel = useMemo(import.meta.url, () => { const selectedTally = Object.keys(selectedItems).length; if (selectedTally > 0) { const [totalMass, totalVolume] = Object.keys(selectedItems).reduce((acc, resourceId) => { @@ -516,7 +516,7 @@ const LotInventory = () => { return null; }, [selectedItems]); - const removalDisabledReason = useMemo(() => { + const removalDisabledReason = useMemo(import.meta.url, () => { if (!canRemoveProducts) return 'access restricted'; if (Object.keys(selectedItems).length === 0) return 'nothing selected'; return ''; diff --git a/src/game/interface/hud/hudMenus/LotInfo.js b/src/game/interface/hud/hudMenus/LotInfo.js index 78ece35b9..f3b23856c 100644 --- a/src/game/interface/hud/hudMenus/LotInfo.js +++ b/src/game/interface/hud/hudMenus/LotInfo.js @@ -3,7 +3,7 @@ import ResourceRequirement from '~/components/ResourceRequirement'; import { getBuildingRequirements } from '../actionDialogs/components'; import useDeliveryManager from '~/hooks/actionManagers/useDeliveryManager'; -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Building, Ship, Product } from '@influenceth/sdk'; import moment from 'moment'; @@ -53,7 +53,7 @@ const ItemsList = styled.div` `; const ConstructionMaterialsGrid = ({ building }) => { - const items = useMemo(() => { + const items = useMemo(import.meta.url, () => { return getBuildingRequirements(building).map((item) => ({ i: Number(item.i), numerator: item.totalRequired, @@ -90,13 +90,13 @@ const LotInfo = () => { const dispatchZoomScene = useStore(s => s.dispatchZoomScene); const zoomScene = useStore(s => s.asteroids.zoomScene); - const gracePeriodPretty = useMemo(() => { + const gracePeriodPretty = useMemo(import.meta.url, () => { return moment(Date.now() - Building.GRACE_PERIOD * 1e3).fromNow(true) }, []); const isZoomedToLot = zoomScene?.type === 'LOT'; - const toggleZoomScene = useCallback(() => { + const toggleZoomScene = useCallback(import.meta.url, () => { dispatchZoomScene(isZoomedToLot ? null : { type: 'LOT', lotId: lot?.id }); }, [isZoomedToLot, lot?.id]); diff --git a/src/game/interface/hud/hudMenus/MyAssets.js b/src/game/interface/hud/hudMenus/MyAssets.js index e2c89a1d7..27ba8d7d8 100644 --- a/src/game/interface/hud/hudMenus/MyAssets.js +++ b/src/game/interface/hud/hudMenus/MyAssets.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Building, Entity, Permission, Ship } from '@influenceth/sdk'; import Loader from 'react-spinners/PuffLoader'; @@ -103,11 +103,11 @@ const AsteroidBlocks = ({ asteroids, onSelectCrew, selectedCrew }) => { const [rendersReady, setRendersReady] = useState(0); - const onRenderReady = useCallback(() => { + const onRenderReady = useCallback(import.meta.url, () => { setRendersReady((r) => r + 1); }, []); - const onClick = useCallback((asteroid) => () => { + const onClick = useCallback(import.meta.url, (asteroid) => () => { if (origin === asteroid?.id) { updateZoomStatus('zooming-in'); } else { @@ -191,7 +191,7 @@ const MyAssets = () => { const [autoselectMode, setAutoselectMode] = useState(!!launcherPage); const [allCrewsMode, setAllCrewsMode] = useState(!!launcherPage); - const onClickCrewAsset = useCallback((crewId, fallbackCrewId) => { + const onClickCrewAsset = useCallback(import.meta.url, (crewId, fallbackCrewId) => { // if in autoselect mode, switch to crewId (IF it is my crew) if (autoselectMode) { const autoselectCrew = crews.find((c) => c.id === crewId) @@ -205,7 +205,7 @@ const MyAssets = () => { dispatchLauncherPage(); }, [autoselectMode, crew, crews]); - const [agreements, agreementTally] = useMemo(() => { + const [agreements, agreementTally] = useMemo(import.meta.url, () => { const paths = []; const deduped = (walletAgreementsWithDupes || []).filter((a) => { if (paths.includes(a._agreement._path)) return false; @@ -245,7 +245,7 @@ const MyAssets = () => { return [groups, ungrouped.length]; }, [walletAgreementsWithDupes, allAsteroidsMode, allCrewsMode]); - const [asteroids, asteroidTally] = useMemo(() => { + const [asteroids, asteroidTally] = useMemo(import.meta.url, () => { const a = (walletAsteroids || []) .filter((a) => { if (allAsteroidsMode || a.id === origin) { @@ -268,7 +268,7 @@ const MyAssets = () => { return [a, a.length, 1]; }, [walletAsteroids, allAsteroidsMode, allCrewsMode]); - const [buildings, buildingTally] = useMemo(() => { + const [buildings, buildingTally] = useMemo(import.meta.url, () => { const ungrouped = (walletBuildings || []) .filter((a) => { const asteroidId = (a.Location?.locations || []).find((l) => l.label === Entity.IDS.ASTEROID)?.id; @@ -294,7 +294,7 @@ const MyAssets = () => { return [groups, ungrouped.length]; }, [walletBuildings, allAsteroidsMode, allCrewsMode]); - const [ships, shipTally] = useMemo(() => { + const [ships, shipTally] = useMemo(import.meta.url, () => { const ungrouped = (walletShips || []) .filter((a) => { const asteroidId = (a.Location?.locations || []).find((l) => l.label === Entity.IDS.ASTEROID)?.id diff --git a/src/game/interface/hud/hudMenus/MyCrews.js b/src/game/interface/hud/hudMenus/MyCrews.js index fc20b88a7..89d0c7a50 100644 --- a/src/game/interface/hud/hudMenus/MyCrews.js +++ b/src/game/interface/hud/hudMenus/MyCrews.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import styled, { keyframes } from 'styled-components'; import { useHistory } from 'react-router-dom'; import { Entity } from '@influenceth/sdk'; @@ -38,7 +38,7 @@ const UncontrolledCrewBlock = ({ crewId, crewmateIds }) => { const { data: crew } = useHydratedCrew(crewId); const history = useHistory(); - const onClick = useCallback(() => { + const onClick = useCallback(import.meta.url, () => { history.push(`/crew/${crewId}`); dispatchLauncherPage(); }, [crewId]); @@ -64,15 +64,15 @@ const MyCrews = () => { const { crew, crews, crewmateMap, selectCrew } = useCrewContext(); const [searchFilter, setSearchFilter] = useState(''); - const filteredCrews = useMemo(() => { + const filteredCrews = useMemo(import.meta.url, () => { if (!searchFilter) return crews; return crews.filter((c) => (c.Name?.name || '').toLowerCase().includes(searchFilter.toLowerCase())); }, [crews, searchFilter]); - const nonEmptyCrews = useMemo(() => filteredCrews.filter((c) => c.Crew.roster.length > 0), [filteredCrews]); - const emptyCrews = useMemo(() => filteredCrews.filter((c) => c.Crew.roster.length === 0), [filteredCrews]); + const nonEmptyCrews = useMemo(import.meta.url, () => filteredCrews.filter((c) => c.Crew.roster.length > 0), [filteredCrews]); + const emptyCrews = useMemo(import.meta.url, () => filteredCrews.filter((c) => c.Crew.roster.length === 0), [filteredCrews]); - const nonEmptyCrewsByLocation = useMemo(() => { + const nonEmptyCrewsByLocation = useMemo(import.meta.url, () => { return nonEmptyCrews.reduce((acc, cur) => { const asteroidId = locationsArrToObj(cur.Location.locations)?.asteroidId || '_'; const locationKey = JSON.stringify(locationsArrToObj(cur.Location.locations)); @@ -84,7 +84,7 @@ const MyCrews = () => { }, {}); }, [nonEmptyCrews]); - const uncontrolledCrewIds = useMemo(() => { + const uncontrolledCrewIds = useMemo(import.meta.url, () => { return Object.keys(crewmateMap || {}) .filter((id) => !crews.find((c) => c.id === crewmateMap[id].Control?.controller?.id)) .reduce((acc, crewmateId) => { @@ -96,7 +96,7 @@ const MyCrews = () => { }, {}); }, [crewmateMap]); - const asteroidContainerHeights = useMemo(() => { + const asteroidContainerHeights = useMemo(import.meta.url, () => { return Object.keys(nonEmptyCrewsByLocation || {}).reduce((acc, asteroidId) => { const asteroidCrewTally = nonEmptyCrewsByLocation[asteroidId].tally; const asteroidLocationTally = Object.keys(nonEmptyCrewsByLocation[asteroidId].locations).length; diff --git a/src/game/interface/hud/hudMenus/OrbitDetails.js b/src/game/interface/hud/hudMenus/OrbitDetails.js index 16c4d6d04..d680662ae 100644 --- a/src/game/interface/hud/hudMenus/OrbitDetails.js +++ b/src/game/interface/hud/hudMenus/OrbitDetails.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Entity, Ship } from '@influenceth/sdk'; @@ -151,23 +151,23 @@ const DockDetails = ({ onClose }) => { const { data: asteroidShips } = useAsteroidShips(asteroidId); - const ships = useMemo(() => { + const ships = useMemo(import.meta.url, () => { return (asteroidShips || []).filter((s) => (s.Location?.location?.label === Entity.IDS.ASTEROID) && !s.Ship.transitDestination); }, [asteroidShips]); const [nameFilter, setNameFilter] = useState(''); const [selectedShipId, setSelectedShipId] = useState(); - const selectedShip = useMemo(() => ships?.find((s) => s.id === selectedShipId), [ships, selectedShipId]); + const selectedShip = useMemo(import.meta.url, () => ships?.find((s) => s.id === selectedShipId), [ships, selectedShipId]); - const onFilterChange = useCallback((e) => { + const onFilterChange = useCallback(import.meta.url, (e) => { setNameFilter(e.target.value || ''); }, []); - const zoomIn = useCallback(() => { + const zoomIn = useCallback(import.meta.url, () => { dispatchZoomScene({ type: 'SHIP', shipId: selectedShipId }); }, [selectedShipId]); - const filteredShips = useMemo(() => { + const filteredShips = useMemo(import.meta.url, () => { return (ships || []).filter((s) => { return formatters.shipName(s).toLowerCase().includes(nameFilter.toLowerCase()) }) diff --git a/src/game/interface/hud/hudMenus/Resources.js b/src/game/interface/hud/hudMenus/Resources.js index 8a75524c0..d5c36f5d9 100644 --- a/src/game/interface/hud/hudMenus/Resources.js +++ b/src/game/interface/hud/hudMenus/Resources.js @@ -1,4 +1,4 @@ -import { useEffect } from 'react'; +import { useEffect } from '~/lib/react-debug'; import useStore from '~/hooks/useStore'; import LotResources from './components/LotResources'; @@ -9,7 +9,7 @@ const Resources = (props) => { const lotId = useStore(s => s.asteroids.lot); const dispatchResourceMapToggle = useStore(s => s.dispatchResourceMapToggle); - useEffect(() => { + useEffect(import.meta.url, () => { return () => { dispatchResourceMapToggle(false); }; diff --git a/src/game/interface/hud/hudMenus/RoutePlanner.js b/src/game/interface/hud/hudMenus/RoutePlanner.js index c2196e9a1..dacf87476 100644 --- a/src/game/interface/hud/hudMenus/RoutePlanner.js +++ b/src/game/interface/hud/hudMenus/RoutePlanner.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Crew, Crewmate, Entity, Inventory, Ship, Time } from '@influenceth/sdk'; @@ -233,14 +233,14 @@ const RoutePlanner = () => { const [ship, setShip] = useState(); // TODO: should this use baseTime instead? - const crewFoodSupplies = useMemo(() => { + const crewFoodSupplies = useMemo(import.meta.url, () => { if (!crew) return 100; const realTime = Time.fromOrbitADays(coarseTime, TIME_ACCELERATION).toDate().getTime() / 1000; const lastFedAgo = Time.toGameDuration(realTime - (crew?.Crew?.lastFed || 0), parseInt(TIME_ACCELERATION)); return lastFedAgo > 0 ? Math.round(100 * Crew.getCurrentFoodRatio(lastFedAgo, crew._foodBonuses?.consumption)) : 100; }, [coarseTime, crew?.Crew?.lastFed]); - const shipList = useMemo(() => { + const shipList = useMemo(import.meta.url, () => { const escapeModule = crew?.Ship?.emergencyAt > 0 ? [ Object.assign({ _simulated: false }, crew ) ] : []; if (crewIsLoading || myShipsLoading) return []; @@ -282,7 +282,7 @@ const RoutePlanner = () => { }, [crewIsLoading, crew?._location?.shipId, myShips, myShipsLoading, originId]); // select default - useEffect(() => { + useEffect(import.meta.url, () => { if (shipList.length > 0 && !ship) { if (!!crew) { setShip(shipList[0]); @@ -292,11 +292,11 @@ const RoutePlanner = () => { } }, [!!crew, crewIsLoading, shipList, ship]); - const toggleEmode = useCallback(() => { + const toggleEmode = useCallback(import.meta.url, () => { setEmode((e) => !e); }, []); - const shipConfig = useMemo(() => { + const shipConfig = useMemo(import.meta.url, () => { if (!ship) return null; const shipTypeConfig = Ship.TYPES[ship.Ship.shipType]; @@ -320,21 +320,21 @@ const RoutePlanner = () => { return config; }, [crew?._inventoryBonuses, emode, ship]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!shipConfig) return; setCargoMass(shipConfig.initialCargoMass); setPropellantMass(shipConfig.initialPropellantMass); setFoodSupplies((shipConfig.emode || ship?._simulated) ? 100 : crewFoodSupplies); }, [shipConfig, ship]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!ship?._simulated) { setFoodSupplies(crewFoodSupplies); } }, [crewFoodSupplies, ship]); // if no crew, assume this is tutorial simulation (so minimize cargo, maximize propellant and food) - useEffect(() => { + useEffect(import.meta.url, () => { if (!crew && !crewIsLoading && !!shipConfig) { setCargoMass(0); setPropellantMass(shipConfig.maxPropellantMass); @@ -342,23 +342,23 @@ const RoutePlanner = () => { } }, [crew, crewIsLoading, shipConfig]); - const onSetCargoMass = useCallback((amount) => { + const onSetCargoMass = useCallback(import.meta.url, (amount) => { const parsed = parseInt(amount * 1_000_000) || 0; setCargoMass(Math.max(0, Math.min(shipConfig?.maxCargoMass, Math.floor(parsed)))); }, [shipConfig]); - const onSetPropellantMass = useCallback((amount) => { + const onSetPropellantMass = useCallback(import.meta.url, (amount) => { const parsed = parseInt(amount * 1_000_000) || 0; setPropellantMass(Math.max(0, Math.min(shipConfig?.maxPropellantMass, Math.floor(parsed)))); }, [shipConfig]); - const onSetFoodSupplies = useCallback((amount) => { + const onSetFoodSupplies = useCallback(import.meta.url, (amount) => { const parsed = parseInt(amount) || 0; setFoodSupplies(Math.max(0, Math.min(100, Math.floor(parsed)))); }, [shipConfig]); - const exhaustBonus = useMemo(() => getCrewAbilityBonuses(Crewmate.ABILITY_IDS.PROPELLANT_EXHAUST_VELOCITY, crew), [crew]); - const shipParams = useMemo(() => { + const exhaustBonus = useMemo(import.meta.url, () => getCrewAbilityBonuses(Crewmate.ABILITY_IDS.PROPELLANT_EXHAUST_VELOCITY, crew), [crew]); + const shipParams = useMemo(import.meta.url, () => { if (!ship) return 0; const variantMod = 1 + (Ship.Entity.getVariant(ship)?.exhaustVelocityModifier || 0); const exhaustVelocity = (Ship.TYPES[ship.Ship.shipType]?.exhaustVelocity * exhaustBonus?.totalBonus) * variantMod || 0; @@ -376,7 +376,7 @@ const RoutePlanner = () => { }; }, [ship, cargoMass, propellantMass, exhaustBonus]); - useEffect(() => { + useEffect(import.meta.url, () => { dispatchReorientCamera(true); return () => { @@ -389,21 +389,21 @@ const RoutePlanner = () => { // - use was fast-forwarding and is no longer // - travel-solution was just cleared because no longer valid const isFastForwarding = (Math.abs(timeOverride?.speed) > 1); - useEffect(() => { + useEffect(import.meta.url, () => { if (!baseTime || ((coarseTime - baseTime) / baseTime > 0.05)) { setBaseTime(coarseTime); } }, [coarseTime, TIME_ACCELERATION]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!isFastForwarding) setBaseTime(coarseTime); }, [isFastForwarding]); - useEffect(() => { + useEffect(import.meta.url, () => { if (travelSolution?.departureTime && travelSolution?.departureTime < coarseTime) { setBaseTime(coarseTime); } }, [coarseTime, travelSolution?.departureTime]); - const { originPath, destinationPath } = useMemo(() => { + const { originPath, destinationPath } = useMemo(import.meta.url, () => { if (!origin || !destination || !baseTime) return {}; // TODO: could do each of these in a worker as well // (might as well move to porkchop at that point) @@ -429,7 +429,7 @@ const RoutePlanner = () => { return paths; }, [baseTime, origin, destination]); - const lastFedAt = useMemo(() => { + const lastFedAt = useMemo(import.meta.url, () => { return baseTime - Crew.getTimeSinceFed(foodSupplies / 100, crew?._foodBonuses?.consumption) / 86400; }, [baseTime, crew, foodSupplies]); diff --git a/src/game/interface/hud/hudMenus/SearchMap.js b/src/game/interface/hud/hudMenus/SearchMap.js index e9ad4de4b..5df9edad3 100644 --- a/src/game/interface/hud/hudMenus/SearchMap.js +++ b/src/game/interface/hud/hudMenus/SearchMap.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; // import styled from 'styled-components'; import useStore from '~/hooks/useStore'; @@ -9,7 +9,7 @@ import SearchFilters from '~/components/SearchFilters'; const SearchMap = ({ assetType }) => { const assetSearch = useStore(s => s.assetSearch[assetType]); const isAssetSearchMatchingDefault = useStore(s => s.isAssetSearchMatchingDefault); - const isDefaultSearch = useMemo(() => isAssetSearchMatchingDefault(assetType), [assetType, assetSearch]); + const isDefaultSearch = useMemo(import.meta.url, () => isAssetSearchMatchingDefault(assetType), [assetType, assetSearch]); return ( <> diff --git a/src/game/interface/hud/hudMenus/StationManifest.js b/src/game/interface/hud/hudMenus/StationManifest.js index 3fc8fadac..687a81274 100644 --- a/src/game/interface/hud/hudMenus/StationManifest.js +++ b/src/game/interface/hud/hudMenus/StationManifest.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { useHistory } from 'react-router-dom'; import styled from 'styled-components'; import { Permission, Station } from '@influenceth/sdk'; @@ -61,25 +61,25 @@ const StationManifest = () => { const zoomShipId = zoomScene?.type === 'SHIP' ? zoomScene.shipId : null; const { data: zoomShip } = useShip(zoomShipId); - const [shipId, ship] = useMemo(() => zoomShipId ? [zoomShipId, zoomShip] : [lot?.surfaceShip?.id, lot?.surfaceShip], [lot, zoomShip, zoomShipId]); + const [shipId, ship] = useMemo(import.meta.url, () => zoomShipId ? [zoomShipId, zoomShip] : [lot?.surfaceShip?.id, lot?.surfaceShip], [lot, zoomShip, zoomShipId]); - const station = useMemo(() => ship || lot?.building, [lot, ship]); + const station = useMemo(import.meta.url, () => ship || lot?.building, [lot, ship]); const { data: unfilteredCrews } = useStationedCrews(station); const [nameFilter, setNameFilter] = useState(''); const [selectedCrewId, setSelectedCrewId] = useState(); - const onFilterChange = useCallback((e) => { + const onFilterChange = useCallback(import.meta.url, (e) => { setNameFilter(e.target.value || ''); }, []); - const canStation = useMemo( + const canStation = useMemo(import.meta.url, () => crewCan(Permission.IDS.STATION_CREW, station), [crewCan, station] ); - const crews = useMemo(() => { + const crews = useMemo(import.meta.url, () => { return (unfilteredCrews || []) .filter((c) => formatters.crewName(c).toLowerCase().includes(nameFilter.toLowerCase())) .map((c) => ({ ...c, _crewmates: c.Crew.roster.map((id) => ({ id })) })) @@ -89,17 +89,17 @@ const StationManifest = () => { const crewIsStationed = shipId ? (crew?._location?.shipId === ship?.id) : (crew?._location?.buildingId === lot?.building?.id); const hasTray = !crewIsStationed || selectedCrewId; - const [flightCrew, passengerCrews, population] = useMemo(() => ([ + const [flightCrew, passengerCrews, population] = useMemo(import.meta.url, () => ([ crews?.find(c => c.id === ship?.Control?.controller?.id), crews?.filter(c => c.id !== ship?.Control?.controller?.id), unfilteredCrews?.reduce((acc, cur) => acc + cur.Crew.roster.length, 0) ]), [crews, ship, unfilteredCrews]); - const handleInspect = useCallback(() => { + const handleInspect = useCallback(import.meta.url, () => { history.push(`/crew/${selectedCrewId}`); }, [selectedCrewId]); - const renderCrewRow = useCallback(({ key, index, style }) => ( + const renderCrewRow = useCallback(import.meta.url, ({ key, index, style }) => (
{ const listWrapper = useRef(); const [listHeight, setListHeight] = useState(0); - useEffect(() => { + useEffect(import.meta.url, () => { setListHeight(listWrapper.current?.clientHeight || 500); }, [screenHeight]); diff --git a/src/game/interface/hud/hudMenus/components/AssetBlocks.js b/src/game/interface/hud/hudMenus/components/AssetBlocks.js index 2d9468ea3..bd25b3730 100644 --- a/src/game/interface/hud/hudMenus/components/AssetBlocks.js +++ b/src/game/interface/hud/hudMenus/components/AssetBlocks.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import styled, { keyframes } from 'styled-components'; import { Asteroid, Building, Dock, Entity, Inventory, Permission, Station } from '@influenceth/sdk'; @@ -202,7 +202,7 @@ const getBuildingIcon = (buildingType) => { export const AgreementBlock = ({ agreement, onSelectCrew, selectedCrew, setRef }) => { const blockTime = useBlockTime(); - const location = useMemo(() => locationsArrToObj(agreement.Location?.locations || [agreement.Location?.locations]), []); + const location = useMemo(import.meta.url, () => locationsArrToObj(agreement.Location?.locations || [agreement.Location?.locations]), []); const onLotLink = useLotLink(( agreement.label === Entity.IDS.LOT @@ -219,7 +219,7 @@ export const AgreementBlock = ({ agreement, onSelectCrew, selectedCrew, setRef } : {} ); - const [icon, name, onLink] = useMemo(() => { + const [icon, name, onLink] = useMemo(import.meta.url, () => { if (agreement.label === Entity.IDS.BUILDING) { return [ getBuildingIcon(agreement.Building?.buildingType), @@ -243,7 +243,7 @@ export const AgreementBlock = ({ agreement, onSelectCrew, selectedCrew, setRef } } }, [agreement, onLotLink, onShipLink]); - const [status, progress, progressColor] = useMemo(() => { + const [status, progress, progressColor] = useMemo(import.meta.url, () => { if (agreement._agreement._type === Permission.POLICY_IDS.PREPAID) { // TODO: factor in noticeTime? const timeRemaining = agreement._agreement.endTime - blockTime; if (timeRemaining > 0) { @@ -262,7 +262,7 @@ export const AgreementBlock = ({ agreement, onSelectCrew, selectedCrew, setRef } ]; }, [blockTime]); - const onClick = useCallback(() => { + const onClick = useCallback(import.meta.url, () => { onLink(); onSelectCrew(agreement.Control?.controller?.id, agreement._agreement.permitted?.id); }, [onLink, onSelectCrew, agreement]); @@ -291,7 +291,7 @@ export const AgreementBlock = ({ agreement, onSelectCrew, selectedCrew, setRef } }; export const AsteroidBlock = ({ asteroid, onClick, onRenderReady, selectedCrew, showRender }) => { - const rarity = useMemo(() => { + const rarity = useMemo(import.meta.url, () => { if ([Asteroid.SCAN_STATUSES.SURFACE_SCANNED, Asteroid.SCAN_STATUSES.RESOURCE_SCANNED].includes(asteroid.Celestial.scanStatus)) { return Asteroid.Entity.getRarity(asteroid); } @@ -329,7 +329,7 @@ export const BuildingBlock = ({ building, onSelectCrew, selectedCrew, setRef }) const { currentProcess } = useProcessManager(buildingLoc?.lotId, building.Processors?.[0]?.slot); const { currentConstructionAction } = useConstructionManager(buildingLoc?.lotId); - const [progress, progressColor] = useMemo(() => { + const [progress, progressColor] = useMemo(import.meta.url, () => { if (building?.Building?.status === Building.CONSTRUCTION_STATUSES.OPERATIONAL) { if (Building.TYPES[building?.Building?.buildingType]?.category === Building.CATEGORIES.STORAGE) { const inventory = (building.Inventories || []).find((i) => i.status === Inventory.STATUSES.AVAILABLE); @@ -389,7 +389,7 @@ export const BuildingBlock = ({ building, onSelectCrew, selectedCrew, setRef }) return [0]; }, [building, selectedCrew?._inventoryBonuses, syncedTime]); - const status = useMemo(() => { + const status = useMemo(import.meta.url, () => { if (building?.Building?.status === Building.CONSTRUCTION_STATUSES.OPERATIONAL) { if (building?.Building?.buildingType === Building.IDS.EXTRACTOR && building?.Extractors?.[0]?.status > 0) { return 'Extracting'; @@ -414,7 +414,7 @@ export const BuildingBlock = ({ building, onSelectCrew, selectedCrew, setRef }) return `${Building.CONSTRUCTION_STATUS_LABELS[building?.Building?.status || 0]}`; }, [building, progress, syncedTime]); - const onClick = useCallback(() => { + const onClick = useCallback(import.meta.url, () => { onClickBuilding(); onSelectCrew(building.Control?.controller?.id); }, [onClickBuilding, onSelectCrew, building?.Control?.controller?.id, buildingLoc?.lotId]); @@ -444,9 +444,9 @@ export const BuildingBlock = ({ building, onSelectCrew, selectedCrew, setRef }) export const ShipBlock = ({ ship, onSelectCrew, selectedCrew, setRef }) => { const onClickShip = useShipLink({ shipId: ship.id, zoomToShip: true }); - const location = useMemo(() => locationsArrToObj(ship.Location?.locations || [])); + const location = useMemo(import.meta.url, () => locationsArrToObj(ship.Location?.locations || [])); - const status = useMemo(() => { + const status = useMemo(import.meta.url, () => { if (location?.buildingId) return 'Docked'; if (location?.lotIndex) return 'Landed'; if (!location?.lotIndex && ship.Ship?.transitDestination) return 'In Flight'; @@ -454,7 +454,7 @@ export const ShipBlock = ({ ship, onSelectCrew, selectedCrew, setRef }) => { return ''; }, [location, ship.Ship?.transitDestination]); - const onClick = useCallback(() => { + const onClick = useCallback(import.meta.url, () => { onClickShip(); onSelectCrew(ship.Control?.controller?.id); }, [onClickShip, onSelectCrew, ship?.Control?.controller?.id]); diff --git a/src/game/interface/hud/hudMenus/components/AsteroidResources.js b/src/game/interface/hud/hudMenus/components/AsteroidResources.js index 7f0813d79..648e91ae1 100644 --- a/src/game/interface/hud/hudMenus/components/AsteroidResources.js +++ b/src/game/interface/hud/hudMenus/components/AsteroidResources.js @@ -1,4 +1,4 @@ -import { Fragment, useCallback, useEffect, useMemo, useState } from 'react'; +import { Fragment, useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid } from '@influenceth/sdk'; @@ -106,7 +106,7 @@ const AsteroidResources = ({ onClose }) => { const resourceMap = useStore(s => s.asteroids.resourceMap); const coachmarks = useStore(s => s.coachmarks); - const onClick = useCallback((i) => () => { + const onClick = useCallback(import.meta.url, (i) => () => { if (resourceMap.active && resourceMap.selected === Number(i)) { dispatchResourceMapSelect(); } else { @@ -116,7 +116,7 @@ const AsteroidResources = ({ onClose }) => { }, [resourceMap]); // default to most abundant emissive map when panel is opened... - useEffect(() => { + useEffect(import.meta.url, () => { if (!resourceMap.active && groupAbundances.length > 0) { if (!resourceMap.selected) { dispatchResourceMapSelect(groupAbundances[0].resources[0].id); @@ -125,8 +125,8 @@ const AsteroidResources = ({ onClose }) => { } }, []); - const unpackedBonuses = useMemo(() => (asteroid && Asteroid.Entity.getBonuses(asteroid)) || [], [asteroid]); - const nonzeroBonuses = useMemo(() => unpackedBonuses.filter((b) => b.level > 0), [unpackedBonuses]); + const unpackedBonuses = useMemo(import.meta.url, () => (asteroid && Asteroid.Entity.getBonuses(asteroid)) || [], [asteroid]); + const nonzeroBonuses = useMemo(import.meta.url, () => unpackedBonuses.filter((b) => b.level > 0), [unpackedBonuses]); return ( diff --git a/src/game/interface/hud/hudMenus/components/AsteroidTitleArea.js b/src/game/interface/hud/hudMenus/components/AsteroidTitleArea.js index 9c8326da3..b13fcbfe1 100644 --- a/src/game/interface/hud/hudMenus/components/AsteroidTitleArea.js +++ b/src/game/interface/hud/hudMenus/components/AsteroidTitleArea.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid, Product } from '@influenceth/sdk'; @@ -52,7 +52,7 @@ const SubtitleRow = styled.div` `; const AsteroidTitleArea = ({ asteroid }) => { - const resourceCategories = useMemo(() => { + const resourceCategories = useMemo(import.meta.url, () => { return (Asteroid.SPECTRAL_TYPES[asteroid?.Celestial?.celestialType]?.resources || []).reduce((acc, productId) => { const category = Product.TYPES[productId]?.category; if (category && !acc.includes(category)) { diff --git a/src/game/interface/hud/hudMenus/components/EntityDescriptionForm.js b/src/game/interface/hud/hudMenus/components/EntityDescriptionForm.js index 52bed47bd..478198773 100644 --- a/src/game/interface/hud/hudMenus/components/EntityDescriptionForm.js +++ b/src/game/interface/hud/hudMenus/components/EntityDescriptionForm.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import Button from '~/components/ButtonAlt'; @@ -28,32 +28,32 @@ const EntityDescriptionForm = ({ buttonSize = 'small', buttonText = 'Update', en const isLoading = annotationLoading || contentLoading; const [desc, setDesc] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { if (!desc) setDesc(originalDesc) }, [originalDesc]) - const handleDescChange = useCallback(async (e) => { + const handleDescChange = useCallback(import.meta.url, async (e) => { setDesc(e.currentTarget.value || ''); }, []); - const saveDescChange = useCallback(async () => { + const saveDescChange = useCallback(import.meta.url, async () => { if (isValidAnnotation(desc)) { saveAnnotation(desc); } }, [entity?.id, desc]); - const handleCancel = useCallback(async () => { + const handleCancel = useCallback(import.meta.url, async () => { setDesc(originalDesc); if (onCancel) onCancel(); }, [onCancel, originalDesc]); - useEffect(() => { + useEffect(import.meta.url, () => { if (txPending && onSave) { onSave(); } }, [txPending]); - const remaining = useMemo(() => maxAnnotationLength - (desc?.length || 0), [desc?.length]); + const remaining = useMemo(import.meta.url, () => maxAnnotationLength - (desc?.length || 0), [desc?.length]); return ( diff --git a/src/game/interface/hud/hudMenus/components/EntityNameForm.js b/src/game/interface/hud/hudMenus/components/EntityNameForm.js index 1b7e38c89..ae5470f41 100644 --- a/src/game/interface/hud/hudMenus/components/EntityNameForm.js +++ b/src/game/interface/hud/hudMenus/components/EntityNameForm.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import UncontrolledTextInput from '~/components/TextInputUncontrolled'; @@ -20,18 +20,18 @@ const EntityNameForm = ({ entity, label, originalName, skipCollisionCheck = fals const [error, setError] = useState(); const [name, setName] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { if (!name) setName(originalName) }, [originalName]) - const handleNameChange = useCallback(async (e) => { + const handleNameChange = useCallback(import.meta.url, async (e) => { const val = e.currentTarget.value || ''; setName(val); const err = await isNameValid(val, entity.id, skipCollisionCheck, 'string'); setError(typeof err === 'string' ? err : false); }, [entity?.id]); - const saveNameChange = useCallback(async () => { + const saveNameChange = useCallback(import.meta.url, async () => { if (await isNameValid(name, entity?.id)) { changeName(name); diff --git a/src/game/interface/hud/hudMenus/components/ListForSalePanel.js b/src/game/interface/hud/hudMenus/components/ListForSalePanel.js index 8de90ca75..88cbd7a87 100644 --- a/src/game/interface/hud/hudMenus/components/ListForSalePanel.js +++ b/src/game/interface/hud/hudMenus/components/ListForSalePanel.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { RadioCheckedIcon, RadioUncheckedIcon, WarningIcon } from '~/components/Icons'; @@ -39,21 +39,21 @@ export const ListForSaleInner = ({ forSaleWarning, isSaving, onCancel, onSave, o const [forSale, setForSale] = useState(originalPrice > 0); const [price, setPrice] = useState(originalPrice || 0); - const isDirty = useMemo(() => (originalPrice !== (forSale ? price : 0)), [forSale, originalPrice, price]); + const isDirty = useMemo(import.meta.url, () => (originalPrice !== (forSale ? price : 0)), [forSale, originalPrice, price]); - const isIncomplete = useMemo(() => (forSale && !(price > 0)), [forSale, price]); + const isIncomplete = useMemo(import.meta.url, () => (forSale && !(price > 0)), [forSale, price]); - const onUpdatePrice = useCallback((e) => { + const onUpdatePrice = useCallback(import.meta.url, (e) => { setPrice((e.currentTarget.value ? parseInt(e.currentTarget.value) : '') || ''); }, []); - const cancelForSale = useCallback(() => { + const cancelForSale = useCallback(import.meta.url, () => { setForSale(originalPrice > 0); setPrice(originalPrice); if (onCancel) onCancel(); }, [originalPrice]); - const saveForSale = useCallback(() => { + const saveForSale = useCallback(import.meta.url, () => { onSave(forSale ? price : 0); }, [onSave, forSale, price]); @@ -109,9 +109,9 @@ export const ListForSaleInner = ({ forSaleWarning, isSaving, onCancel, onSave, o const ListForSalePanel = ({ entity, forSaleWarning }) => { const { updateListing, isPendingUpdate } = useNftSaleManager(entity); - const originalPrice = useMemo(() => (entity?.Nft?.price || 0) / 1e6, [entity?.Nft?.price]); + const originalPrice = useMemo(import.meta.url, () => (entity?.Nft?.price || 0) / 1e6, [entity?.Nft?.price]); - const config = useMemo(() => { + const config = useMemo(import.meta.url, () => { return { color: originalPrice ? theme.colors.brightMain : theme.colors.red }; diff --git a/src/game/interface/hud/hudMenus/components/LotResources.js b/src/game/interface/hud/hudMenus/components/LotResources.js index 6e62e35b0..34fd58b31 100644 --- a/src/game/interface/hud/hudMenus/components/LotResources.js +++ b/src/game/interface/hud/hudMenus/components/LotResources.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Asteroid, Building, Deposit, Lot, Product } from '@influenceth/sdk'; @@ -230,9 +230,9 @@ const SaleDetails = ({ isMine, sample }) => { const { updateListing, isPendingUpdate } = useDepositSaleManager(sample); const [editing, setEditing] = useState(); - const originalPrice = useMemo(() => (sample?.PrivateSale?.amount || 0) / 1e6, [sample?.PrivateSale?.amount]); + const originalPrice = useMemo(import.meta.url, () => (sample?.PrivateSale?.amount || 0) / 1e6, [sample?.PrivateSale?.amount]); - useEffect(() => { + useEffect(import.meta.url, () => { setEditing(false); }, [originalPrice]) @@ -275,16 +275,16 @@ const DepositSection = ({ deposits = [], selected, onSelect, title, type }) => { const [showAll, setShowAll] = useState(true); - const onClickSample = useCallback((id) => () => { + const onClickSample = useCallback(import.meta.url, (id) => () => { onSelect({ type, id }); dispatchResourceMapToggle(false); // TODO: instead of turning off the resource map, should this change it the resource of the selected sample? }, [onSelect, type]); - const usedDepositsExist = useMemo(() => { + const usedDepositsExist = useMemo(import.meta.url, () => { return !!deposits.find((d) => d.Deposit.remainingYield !== d.Deposit.initialYield); }, [deposits]); - const samples = useMemo(() => { + const samples = useMemo(import.meta.url, () => { if (showAll) return deposits; return deposits.filter((d) => d.Deposit.remainingYield === d.Deposit.initialYield); }, [deposits, showAll]); @@ -360,7 +360,7 @@ const LotResources = () => { const { props: actionProps } = useActionButtons(); const { crew } = useCrewContext(); const lotId = useStore(s => s.asteroids.lot); - const asteroidId = useMemo(() => Lot.toPosition(lotId)?.asteroidId, [lotId]); + const asteroidId = useMemo(import.meta.url, () => Lot.toPosition(lotId)?.asteroidId, [lotId]); const { data: asteroid } = useAsteroid(asteroidId); const { data: lot } = useLot(lotId); @@ -374,14 +374,14 @@ const LotResources = () => { const [showAllAbundances, setShowAllAbundances] = useState(); // if there is an active resource map, select that resource - useEffect(() => { + useEffect(import.meta.url, () => { if (resourceMap.active && resourceMap.selected) { setSelected({ type: 'resource', id: resourceMap.selected }); } }, []); // get lot abundance - const lotAbundances = useMemo(() => { + const lotAbundances = useMemo(import.meta.url, () => { if (!(asteroid && lotId)) return []; // TODO: do this in worker? takes about 200ms on decent cpu @@ -400,14 +400,14 @@ const LotResources = () => { .sort((a, b) => b.abundance - a.abundance); }, [asteroid, lotId]); - const onClickResource = useCallback((id) => () => { + const onClickResource = useCallback(import.meta.url, (id) => () => { setSelected({ type: 'resource', id }); dispatchResourceMapSelect(id); dispatchResourceMapToggle(true); }, []); - const [showAbundances, abundancesTruncated] = useMemo(() => { + const [showAbundances, abundancesTruncated] = useMemo(import.meta.url, () => { if (showAllAbundances || lotAbundances.length < 8) { return [lotAbundances, false]; } else { @@ -415,21 +415,21 @@ const LotResources = () => { } }, [lotAbundances, showAllAbundances]); - const selectedResource = useMemo(() => { + const selectedResource = useMemo(import.meta.url, () => { if (selected && selected.type === 'resource') { return Product.TYPES[selected.id]; } return null; }, [selected]); - const selectedSample = useMemo(() => { + const selectedSample = useMemo(import.meta.url, () => { if (selected && selected.type !== 'resource') { return (lot?.deposits || []).find((s) => selected.id === s.id); } return null; }, [lot?.deposits, selected]); - const extraSampleParams = useMemo(() => { + const extraSampleParams = useMemo(import.meta.url, () => { const params = {}; if (selectedSample?.id) { params.improveSample = { ...selectedSample }; @@ -439,7 +439,7 @@ const LotResources = () => { return params; }, [currentSamplingActions, selectedResource, selectedSample]); - const extraExtractParams = useMemo(() => { + const extraExtractParams = useMemo(import.meta.url, () => { const params = {}; if (!currentExtraction) { if (selectedSample) { @@ -452,7 +452,7 @@ const LotResources = () => { return params; }, [currentExtraction, selectedSample]); - const [ownedSamples, forSaleSamples] = useMemo(() => ([ + const [ownedSamples, forSaleSamples] = useMemo(import.meta.url, () => ([ (lot?.deposits || []).filter((s) => s.Control.controller.id === crew?.id && (!s.Deposit.initialYield || s.Deposit.remainingYield > 0)).sort(sampleSort), (lot?.deposits || []).filter((s) => s.PrivateSale?.amount > 0 && (!s.Deposit.initialYield || s.Deposit.remainingYield > 0)).sort(sampleSort), ]), [crew?.id, lot?.deposits]); diff --git a/src/game/interface/hud/hudMenus/components/LotTitleArea.js b/src/game/interface/hud/hudMenus/components/LotTitleArea.js index b78902e8d..676b36ba1 100644 --- a/src/game/interface/hud/hudMenus/components/LotTitleArea.js +++ b/src/game/interface/hud/hudMenus/components/LotTitleArea.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { Building, Lot } from '@influenceth/sdk'; @@ -21,7 +21,7 @@ const Abandoned = styled.div` const LotTitleArea = ({ lot }) => { const { isAtRisk } = useConstructionManager(lot?.id); - const [title, subtitle, background] = useMemo(() => { + const [title, subtitle, background] = useMemo(import.meta.url, () => { if (!lot) return []; if (lot.building) { if (lot.building.Building?.status < Building.CONSTRUCTION_STATUSES.OPERATIONAL) { diff --git a/src/game/interface/hud/hudMenus/components/MarketplaceSettings.js b/src/game/interface/hud/hudMenus/components/MarketplaceSettings.js index 6b8804ed5..358cd06d0 100644 --- a/src/game/interface/hud/hudMenus/components/MarketplaceSettings.js +++ b/src/game/interface/hud/hudMenus/components/MarketplaceSettings.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Exchange, Product } from '@influenceth/sdk'; import { PuffLoader as Loader } from 'react-spinners'; @@ -91,7 +91,7 @@ const MarketplaceSettings = ({ marketplace }) => { const [ makerFee, setMakerFee ] = useState(exchange.makerFee / 100); const [ takerFee, setTakerFee ] = useState(exchange.takerFee / 100); - const handleChange = useCallback((setter, defaultValue) => (e) => { + const handleChange = useCallback(import.meta.url, (setter, defaultValue) => (e) => { setter( Math.max( e.currentTarget.min, @@ -103,7 +103,7 @@ const MarketplaceSettings = ({ marketplace }) => { ); }, []); - const handleRevert = useCallback(() => { + const handleRevert = useCallback(import.meta.url, () => { setProducts(exchange.allowedProducts || []); setMakerFee(exchange.makerFee / 100); setTakerFee(exchange.takerFee / 100); @@ -112,22 +112,22 @@ const MarketplaceSettings = ({ marketplace }) => { // revert if exchange is updated (handleRevert will be changed) // (these are intended to maintain a "loading" state until the updated exchange has been fetched) - useEffect(() => { + useEffect(import.meta.url, () => { if (changingSettings) setLoading(true); }, [changingSettings]); - useEffect(() => { + useEffect(import.meta.url, () => { setLoading(false); }, [handleRevert]); - const handleBlur = useCallback((index) => (e) => { + const handleBlur = useCallback(import.meta.url, (index) => (e) => { setFocused(); }, []); - const handleFocus = useCallback((index) => (e) => { + const handleFocus = useCallback(import.meta.url, (index) => (e) => { setFocused(index); }, []); - const saveChanges = useCallback(() => { + const saveChanges = useCallback(import.meta.url, () => { changeSettings({ makerFee: makerFee * 100, takerFee: takerFee * 100, @@ -136,7 +136,7 @@ const MarketplaceSettings = ({ marketplace }) => { setFocused(); }, [makerFee, takerFee, products, changeSettings]); - const updateProductList = useCallback((index, value) => { + const updateProductList = useCallback(import.meta.url, (index, value) => { let s = new Set(); // create a set of the remaining products + this one @@ -149,7 +149,7 @@ const MarketplaceSettings = ({ marketplace }) => { setProducts(final); }, [products]); - const [productList, productListLength] = useMemo(() => { + const [productList, productListLength] = useMemo(import.meta.url, () => { const l = []; let len = 0; for (let i = 0; i < Exchange.TYPES[exchange.exchangeType].productCap; i++) { @@ -159,7 +159,7 @@ const MarketplaceSettings = ({ marketplace }) => { return [l, len]; }, [exchange.exchangeType, products]); - const isDirty = useMemo(() => ( + const isDirty = useMemo(import.meta.url, () => ( makerFee !== exchange.makerFee / 100 || takerFee !== exchange.takerFee / 100 || products.length !== exchange.allowedProducts.length diff --git a/src/game/interface/hud/hudMenus/components/PolicyPanels.js b/src/game/interface/hud/hudMenus/components/PolicyPanels.js index 401d60e63..16a06fb3c 100644 --- a/src/game/interface/hud/hudMenus/components/PolicyPanels.js +++ b/src/game/interface/hud/hudMenus/components/PolicyPanels.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Address, Building, Entity, Permission } from '@influenceth/sdk'; @@ -237,31 +237,31 @@ const PolicyPanel = ({ editable = false, entity, permission }) => { const saving = editing === 'allowlist' ? allowlistChangePending : policyChangePending; // reset if object is changed - useEffect(() => { + useEffect(import.meta.url, () => { setPolicyType(Number(originalPolicyType)); setDetails(originalPolicyDetails); }, [editing, originalPolicyType, originalPolicyDetails]); - useEffect(() => { + useEffect(import.meta.url, () => { setAllowlist(originalAllowlist || []); setAccountAllowlist(originalAccountAllowlist || []); setAllowlistDirty(false); }, [editing, originalAllowlist, originalAccountAllowlist]); - const handleChange = useCallback((key) => (e) => { + const handleChange = useCallback(import.meta.url, (key) => (e) => { let newVal = e.currentTarget.value; if (key === 'rate') newVal /= 24; setDetails((v) => ({ ...v, [key]: newVal })); }, []); - const isDirty = useMemo(() => { + const isDirty = useMemo(import.meta.url, () => { return policyType !== originalPolicyType || Object.keys(details).reduce((acc, k) => acc || details[k] !== originalPolicyDetails[k], false) || Object.keys(originalPolicyDetails).reduce((acc, k) => acc || details[k] !== originalPolicyDetails[k], false) || allowlistDirty; }, [allowlistDirty, policyType, originalPolicyType, originalPolicyDetails, details]); - const isIncomplete = useMemo(() => { + const isIncomplete = useMemo(import.meta.url, () => { if (policyType === Permission.POLICY_IDS.PREPAID) { if (!details.rate || details.rate < 0) return true; if (details.initialTerm < 0 || details.noticePeriod < 0) return true; @@ -273,7 +273,7 @@ const PolicyPanel = ({ editable = false, entity, permission }) => { return false; }, [policyType, details]); - const allowlistAdd = useCallback((crew) => { + const allowlistAdd = useCallback(import.meta.url, (crew) => { if (!crew) return; if (typeof crew === 'object') { setAllowlist((a) => [...a, crew].sort((a, b) => formatters.crewName(a).localeCompare(formatters.crewName(b)))); @@ -285,7 +285,7 @@ const PolicyPanel = ({ editable = false, entity, permission }) => { setAllowlistDirty(true); }, []); - const allowlistRemove = useCallback((crew) => { + const allowlistRemove = useCallback(import.meta.url, (crew) => { if (typeof crew === 'object') { setAllowlist((a) => a.filter((c) => c.id !== crew.id)); } else { @@ -294,15 +294,15 @@ const PolicyPanel = ({ editable = false, entity, permission }) => { setAllowlistDirty(true); }, []); - const allowlistExclude = useCallback((c) => { + const allowlistExclude = useCallback(import.meta.url, (c) => { return allowlist.find((a) => a.id === c.id || crew?.id === c.id); }, [allowlist]) - const cancelEdits = useCallback(() => { + const cancelEdits = useCallback(import.meta.url, () => { setEditing(); }, []); - const saveEdits = useCallback(() => { + const saveEdits = useCallback(import.meta.url, () => { if (editing === 'allowlist') { updateAllowlists(allowlist, accountAllowlist); } else { @@ -310,7 +310,7 @@ const PolicyPanel = ({ editable = false, entity, permission }) => { } }, [accountAllowlist, allowlist, editing, policyType, details]); - const toggleEditing = useCallback((which) => { + const toggleEditing = useCallback(import.meta.url, (which) => { setEditing(which); }, []); @@ -318,7 +318,7 @@ const PolicyPanel = ({ editable = false, entity, permission }) => { * Viewing */ - const onAllowlist = useMemo( + const onAllowlist = useMemo(import.meta.url, () => ( currentPolicy?.allowlist?.find((c) => c.id === crew?.id) || currentPolicy?.accountAllowlist?.find((c) => Address.areEqual(accountAddress, c)) @@ -326,7 +326,7 @@ const PolicyPanel = ({ editable = false, entity, permission }) => { [accountAddress, crew, currentPolicy] ); - const jitStatus = useMemo(() => { + const jitStatus = useMemo(import.meta.url, () => { // if exclusive, everyone cares if under notice if (Permission.TYPES[permission].isExclusive) { if (currentPolicy?.agreements?.[0]?.noticeTime > 0) return 'under notice'; @@ -348,7 +348,7 @@ const PolicyPanel = ({ editable = false, entity, permission }) => { return null; }, [currentPolicy?.crewStatus, entity]); - const config = useMemo(() => { + const config = useMemo(import.meta.url, () => { if (editing === 'allowlist') { return { name: 'Allowlist', @@ -369,7 +369,7 @@ const PolicyPanel = ({ editable = false, entity, permission }) => { originalPolicyDetails?.initialTerm === 0 && originalPolicyDetails?.noticePeriod === 0 ) )); - const toggleIsPayAsYouGo = useCallback(() => { + const toggleIsPayAsYouGo = useCallback(import.meta.url, () => { setIsPayAsYouGo((v) => { const newVal = !v; if (newVal) { @@ -686,13 +686,13 @@ const PolicyPanels = ({ editable, entity }) => { const { isAtRisk } = useConstructionManager(lot?.id); const { data: entityController } = useHydratedCrew(entity?.Control?.controller?.id); - const permPolicies = useMemo( + const permPolicies = useMemo(import.meta.url, () => entity ? Permission.getPolicyDetails(entity, crew, blockTime) : {}, [accountAddress, blockTime, crew, entity] ); // show lot warning if building controller does not have lot permission - const showLotWarning = useMemo(() => { + const showLotWarning = useMemo(import.meta.url, () => { if (!lot || !entityController) return false; const lotPerm = Permission.getPolicyDetails(lot, entityController, blockTime)[Permission.IDS.USE_LOT]; return !( @@ -702,9 +702,9 @@ const PolicyPanels = ({ editable, entity }) => { ); }, [blockTime, entity, entityController, lot]); - const buildingOrSite = useMemo(() => lot?.building?.Building?.status < Building.CONSTRUCTION_STATUSES.OPERATIONAL ? 'Construction Site' : 'Building', [lot]); + const buildingOrSite = useMemo(import.meta.url, () => lot?.building?.Building?.status < Building.CONSTRUCTION_STATUSES.OPERATIONAL ? 'Construction Site' : 'Building', [lot]); - const showStagingWarning = useMemo(() => { + const showStagingWarning = useMemo(import.meta.url, () => { if (isAtRisk) { return 2; } else if (lot && lot.building && lot.building.Building?.status < Building.CONSTRUCTION_STATUSES.UNDER_CONSTRUCTION) { @@ -714,7 +714,7 @@ const PolicyPanels = ({ editable, entity }) => { }, [lot]); // find out if any others have access to this asset via any perm - const othersHaveAgreementsOnThisAsset = useMemo(() => { + const othersHaveAgreementsOnThisAsset = useMemo(import.meta.url, () => { return !!Object.keys(permPolicies).find((permission) => { const { agreements, allowlist, accountAllowlist } = permPolicies[permission]; if ((agreements || []).find((a) => a?.permitted?.id !== crew?.id)) return true; diff --git a/src/game/interface/hud/hudMenus/components/ShipTitleArea.js b/src/game/interface/hud/hudMenus/components/ShipTitleArea.js index 1d989d2cd..b6cce71a8 100644 --- a/src/game/interface/hud/hudMenus/components/ShipTitleArea.js +++ b/src/game/interface/hud/hudMenus/components/ShipTitleArea.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Entity, Ship } from '@influenceth/sdk'; import { LocationIcon } from '~/components/Icons'; @@ -7,7 +7,7 @@ import EntityName from '~/components/EntityName'; import TitleArea from '../components/TitleArea'; const ShipTitleArea = ({ ship }) => { - const locations = useMemo(() => { + const locations = useMemo(import.meta.url, () => { if (!ship?.Location?.locations) return []; const asteroidEntity = ship.Location.locations.find((l) => l.label === Entity.IDS.ASTEROID); if (asteroidEntity) { diff --git a/src/game/interface/mainMenu/TimeControls.js b/src/game/interface/mainMenu/TimeControls.js index 390598940..e0c3f2c59 100644 --- a/src/game/interface/mainMenu/TimeControls.js +++ b/src/game/interface/mainMenu/TimeControls.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Time } from '@influenceth/sdk'; @@ -91,19 +91,19 @@ const TimeController = ({ open }) => { const [ isPaused, setIsPaused ] = useState(false); const [ speedSetting, setSpeedSetting ] = useState(0); - const pause = useCallback(() => { + const pause = useCallback(import.meta.url, () => { setIsPaused(true); setSpeedSetting(0); dispatchTimeOverride(getTime(), 0); }, [dispatchTimeOverride, getTime]); - const reset = useCallback(() => { + const reset = useCallback(import.meta.url, () => { setIsPaused(false); setSpeedSetting(0); dispatchTimeOverride(); }, [dispatchTimeOverride]); - const changeSpeed = useCallback((direction) => { + const changeSpeed = useCallback(import.meta.url, (direction) => { const newSpeed = speeds[Math.abs(speedSetting + direction)]; if (Number.isFinite(newSpeed)) { setIsPaused(false); @@ -111,7 +111,7 @@ const TimeController = ({ open }) => { } }, [speedSetting]); - useEffect(() => { + useEffect(import.meta.url, () => { // if speedSetting is zero and timeOverride is already non-set, don't override // otherwise (there is a timeOverride and speedSetting changes), update override if (speedSetting !== 0 || timeOverride) { @@ -121,12 +121,12 @@ const TimeController = ({ open }) => { } }, [ speedSetting ]); // eslint-disable-line react-hooks/exhaustive-deps - const displaySpeed = useMemo(() => { + const displaySpeed = useMemo(import.meta.url, () => { if (isPaused) return '0'; return speeds[Math.abs(speedSetting)].toLocaleString(); }, [isPaused, speedSetting]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!open && timeOverride) { reset(); } @@ -190,11 +190,11 @@ const TimeControls = () => { const timeOverride = useStore(s => s.timeOverride); const [open, setOpen] = useState(false); - const toggleOpen = useCallback((e) => { + const toggleOpen = useCallback(import.meta.url, (e) => { setOpen((o) => !o); }, []); - const displayTime = useMemo(() => { + const displayTime = useMemo(import.meta.url, () => { if (!coarseTime || isLoading) return ''; return Time.fromOrbitADays(coarseTime, TIME_ACCELERATION || Time.DEFAULT_TIME_ACCELERATION) .toGameClockADays() diff --git a/src/game/interface/modelViewer/DevToolsViewer.js b/src/game/interface/modelViewer/DevToolsViewer.js index f7b6ff015..4d983da9b 100644 --- a/src/game/interface/modelViewer/DevToolsViewer.js +++ b/src/game/interface/modelViewer/DevToolsViewer.js @@ -1,4 +1,4 @@ -import { useContext, useEffect } from 'react'; +import { useContext, useEffect } from '~/lib/react-debug'; import DevToolContext from '~/contexts/DevToolContext'; import ModelViewer from '../ModelViewer'; @@ -6,7 +6,7 @@ import ModelViewer from '../ModelViewer'; const DevToolsViewer = () => { const { assetType, overrides, ...setters } = useContext(DevToolContext); - useEffect(() => { + useEffect(import.meta.url, () => { if (!assetType) { setters.setAssetType('scene'); } diff --git a/src/game/interface/modelViewer/LinkedViewer.js b/src/game/interface/modelViewer/LinkedViewer.js index 2a3eb022e..997fc0c0b 100644 --- a/src/game/interface/modelViewer/LinkedViewer.js +++ b/src/game/interface/modelViewer/LinkedViewer.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { useParams } from 'react-router-dom'; import { Building, Product, Ship } from '@influenceth/sdk'; @@ -8,7 +8,7 @@ import ModelViewer from '../ModelViewer'; const LinkedViewer = () => { const { assetType, assetName } = useParams(); - const modelUrl = useMemo(() => { + const modelUrl = useMemo(import.meta.url, () => { if (assetType === 'building') { return getBuildingModel(Object.keys(Building.TYPES).find((i) => Building.TYPES[i].name === assetName)); } else if (assetType === 'resource') { diff --git a/src/game/interface/modelViewer/LotViewer.js b/src/game/interface/modelViewer/LotViewer.js index e1dfd3969..e07b2c4de 100644 --- a/src/game/interface/modelViewer/LotViewer.js +++ b/src/game/interface/modelViewer/LotViewer.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState } from 'react'; +import { useEffect, useMemo, useState } from '~/lib/react-debug'; import { Building } from '@influenceth/sdk'; import useLot from '~/hooks/useLot'; @@ -16,7 +16,7 @@ const LotViewer = () => { const [pendingSound, setPendingSound] = useState(null); // Play chatter after a delay, clear timeout if scene changes - useEffect(() => { + useEffect(import.meta.url, () => { if (zoomScene?.type === 'LOT' && lot?.building?.Building?.buildingType > 0) { const id = setTimeout(() => playSound(`buildingChatter.${lot?.building?.Building?.buildingType}`), 5000); setPendingSound(id); @@ -27,7 +27,7 @@ const LotViewer = () => { } }, [zoomScene, lot]); - const modelUrl = useMemo(() => { + const modelUrl = useMemo(import.meta.url, () => { if (zoomScene?.overrides?.buildingType) { return getBuildingModel(zoomScene.overrides.buildingType); } diff --git a/src/game/interface/modelViewer/ShipViewer.js b/src/game/interface/modelViewer/ShipViewer.js index 620491a56..34cc57c1f 100644 --- a/src/game/interface/modelViewer/ShipViewer.js +++ b/src/game/interface/modelViewer/ShipViewer.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState } from 'react'; +import { useEffect, useMemo, useState } from '~/lib/react-debug'; import { Ship } from '@influenceth/sdk'; import useShip from '~/hooks/useShip'; @@ -16,7 +16,7 @@ const ShipViewer = () => { const [pendingSound, setPendingSound] = useState(null); // Play ship thruster loop - useEffect(() => { + useEffect(import.meta.url, () => { if (zoomScene?.type === 'SHIP') { const id = setTimeout(() => playSound('ship')); setPendingSound(id); @@ -29,7 +29,7 @@ const ShipViewer = () => { } }, [zoomScene]); - const modelUrl = useMemo(() => { + const modelUrl = useMemo(import.meta.url, () => { return getShipModel( zoomScene?.shipId ? ship?.Ship?.shipType : Ship.IDS.ESCAPE_MODULE, ship?.Ship?.variant diff --git a/src/game/launcher/Help.js b/src/game/launcher/Help.js index 638fd99f3..cdc331d11 100644 --- a/src/game/launcher/Help.js +++ b/src/game/launcher/Help.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import Loader from 'react-spinners/PuffLoader'; @@ -118,7 +118,7 @@ const YoutubeFeed = ({ playlistId, title }) => { const [loading, setLoading] = useState(); const [videos, setVideos] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { setVideos(); if (playlistId) { @@ -137,13 +137,13 @@ const YoutubeFeed = ({ playlistId, title }) => { } }, [playlistId]); - const onClickOwner = useCallback((v) => { + const onClickOwner = useCallback(import.meta.url, (v) => { if (v.snippet?.videoOwnerChannelId) { window.open(`https://www.youtube.com/channel/${v.snippet?.videoOwnerChannelId}`); } }, []); - const onClickVideo = useCallback((v) => { + const onClickVideo = useCallback(import.meta.url, (v) => { if (v.snippet?.resourceId?.videoId) { window.open(`http://youtube.com/watch?v=${v.snippet?.resourceId?.videoId}&list=${playlistId}`) } diff --git a/src/game/launcher/Play.js b/src/game/launcher/Play.js index 42eaca180..f45acc4a5 100644 --- a/src/game/launcher/Play.js +++ b/src/game/launcher/Play.js @@ -1,4 +1,4 @@ -import { useEffect } from 'react'; +import { useEffect } from '~/lib/react-debug'; import useSession from '~/hooks/useSession' import { useControlledAlert } from '~/game/interface/Alerts'; @@ -67,7 +67,7 @@ const Play = () => { const simulation = useSimulationEnabled(); const dispatchHudMenuOpened = useStore(s => s.dispatchHudMenuOpened); - useEffect(() => { + useEffect(import.meta.url, () => { if (crews?.length) { dispatchHudMenuOpened('MY_CREWS'); } diff --git a/src/game/launcher/Settings.js b/src/game/launcher/Settings.js index c858321ee..14df2c1b0 100644 --- a/src/game/launcher/Settings.js +++ b/src/game/launcher/Settings.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import screenfull from 'screenfull'; import { FiCheckSquare as CheckedIcon, FiSquare as UncheckedIcon } from 'react-icons/fi'; @@ -144,7 +144,7 @@ const GraphicsPane = () => { const [ localFOV, setLocalFOV ] = useState(graphics.fov); const [ fullscreen, setFullscreen ] = useState(screenfull.isEnabled && screenfull.isFullscreen); - useEffect(() => { + useEffect(import.meta.url, () => { if (screenfull.isEnabled) { screenfull.on('change', () => { setFullscreen(screenfull.isEnabled && screenfull.isFullscreen); @@ -156,7 +156,7 @@ const GraphicsPane = () => { setAutodetect(!graphics.autodetect, gpuInfo); }; - const pixelRatioOptions = useMemo(() => { + const pixelRatioOptions = useMemo(import.meta.url, () => { const options = new Set(); // add device settings and current selection always @@ -358,7 +358,7 @@ const GameplayPane = () => { const dispatchUseSessionsSet = useStore(s => s.dispatchUseSessionsSet); const dispatchFeeTokenSet = useStore(s => s.dispatchFeeTokenSet); - const tutorialIsDisabled = useMemo(() => { + const tutorialIsDisabled = useMemo(import.meta.url, () => { if (gameplay.dismissTutorial) { return true; } else if (crewTutorials?.[crew?.id]?.dismissed) { @@ -367,7 +367,7 @@ const GameplayPane = () => { return false; }, [crew, crewTutorials, gameplay.dismissTutorial]); - const toggleTutorialDisabled = useCallback((which) => { + const toggleTutorialDisabled = useCallback(import.meta.url, (which) => { // disable setting only (i.e. not crew-specific) if (which) { dispatchTutorialDisabled(true); @@ -381,7 +381,7 @@ const GameplayPane = () => { } }, [crew, crewTutorials, gameplay.dismissTutorial]); - const toggleSessionKeys = useCallback(async (which) => { + const toggleSessionKeys = useCallback(import.meta.url, async (which) => { dispatchUseSessionsSet(which); if (which !== false && !starknetSession && await shouldUseSessionKeys(true)) upgradeToSessionKey(); }, [starknetSession, upgradeToSessionKey]); diff --git a/src/game/launcher/Store.js b/src/game/launcher/Store.js index d7dbfc8d6..40884bcf1 100644 --- a/src/game/launcher/Store.js +++ b/src/game/launcher/Store.js @@ -1,4 +1,4 @@ -import { useMemo, useState } from 'react'; +import { useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import AsteroidsImage from '~/assets/images/sales/asteroids.png'; @@ -162,7 +162,7 @@ const SkuSelector = ({ onSelect }) => { const { data: priceConstants } = usePriceConstants(); const packs = useStarterPackPricing(); - const paneMeta = useMemo(() => { + const paneMeta = useMemo(import.meta.url, () => { const asteroidExtra = {}; const remaining = asteroidSale ? (Number(asteroidSale.limit) - Number(asteroidSale.volume)) : 0; @@ -226,7 +226,7 @@ const Store = () => { const initialSubpage = useStore(s => s.launcherSubpage); - const initialSelection = useMemo(() => { + const initialSelection = useMemo(import.meta.url, () => { const linkedSelectionIndex = Object.keys(storeAssets).indexOf(initialSubpage); return linkedSelectionIndex >= 0 ? linkedSelectionIndex : undefined; }, [initialSubpage]); @@ -234,7 +234,7 @@ const Store = () => { const [selection, setSelection] = useState(initialSelection); const isSelected = selection !== undefined; - const panes = useMemo(() => { + const panes = useMemo(import.meta.url, () => { return Object.keys(storeAssets).map((k) => ({ label: storeAssets[k], pane: setSelection()} />, diff --git a/src/game/launcher/components/EthFaucetButton.js b/src/game/launcher/components/EthFaucetButton.js index e345d4ea6..c0b92729e 100644 --- a/src/game/launcher/components/EthFaucetButton.js +++ b/src/game/launcher/components/EthFaucetButton.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import { useQueryClient } from 'react-query'; import { TOKEN, TOKEN_SCALE } from '~/lib/priceUtils'; @@ -17,13 +17,13 @@ const EthFaucetButton = ({ onError, onProcessing, onSuccess }) => { const [requestingEth, setRequestingEth] = useState(); - const ethEnabled = useMemo(() => { + const ethEnabled = useMemo(import.meta.url, () => { if (!faucetInfo) return false; const lastClaimed = faucetInfo.ETH.lastClaimed || 0; return Date.now() > (Date.parse(lastClaimed) + 23.5 * 3600e3); }, [faucetInfo]); - const requestEth = useCallback(async () => { + const requestEth = useCallback(import.meta.url, async () => { setRequestingEth(true); try { @@ -44,7 +44,7 @@ const EthFaucetButton = ({ onError, onProcessing, onSuccess }) => { queryClient.invalidateQueries({ queryKey: ['walletBalance', 'eth'] }); }, [provider]); - useEffect(() => { + useEffect(import.meta.url, () => { if (onProcessing) onProcessing(requestingEth); }, [onProcessing, requestingEth]); diff --git a/src/game/launcher/components/FundingFlow.js b/src/game/launcher/components/FundingFlow.js index 4d5f5d372..36317d8be 100644 --- a/src/game/launcher/components/FundingFlow.js +++ b/src/game/launcher/components/FundingFlow.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled, { css } from 'styled-components'; import { createPortal } from 'react-dom'; import { PropagateLoader as Loader } from 'react-spinners'; @@ -315,7 +315,7 @@ export const FundingFlow = ({ totalPrice, onClose, onFunded }) => { const [debug, setDebug] = useState(0); // TODO: technically could wait to start polling until page is focused again - useEffect(() => { + useEffect(import.meta.url, () => { // if (waiting && !debug) { // setTimeout(() => { // console.log('hack', startingBalance.current, wallet.tokenBalances); // tokenBalances @@ -335,7 +335,7 @@ export const FundingFlow = ({ totalPrice, onClose, onFunded }) => { } }, [waiting, !!wallet, debug]); - useEffect(() => { + useEffect(import.meta.url, () => { // if there is an actual increase in currency of a token (i.e. not just an // increase in value b/c we don't want a trigger on exchange rate changes) if (waiting && startingBalance.current) { @@ -368,7 +368,7 @@ export const FundingFlow = ({ totalPrice, onClose, onFunded }) => { } }, [debug, waiting, wallet?.tokenBalances]) - const [walletBalance, fundsNeeded] = useMemo( + const [walletBalance, fundsNeeded] = useMemo(import.meta.url, () => { if (!wallet) return []; const balance = wallet.combinedBalance; @@ -382,7 +382,7 @@ export const FundingFlow = ({ totalPrice, onClose, onFunded }) => { [priceHelper, totalPrice, wallet] ); - const suggestedAmounts = useMemo(() => { + const suggestedAmounts = useMemo(import.meta.url, () => { if (!fundsNeeded) return [10e6, 25e6, 50e6]; const needed = Math.ceil(fundsNeeded.to(TOKEN.USDC)); @@ -394,7 +394,7 @@ export const FundingFlow = ({ totalPrice, onClose, onFunded }) => { }, [fundsNeeded]); const to = useRef(); - const onRampHover = useCallback((which) => (e) => { + const onRampHover = useCallback(import.meta.url, (which) => (e) => { if (to.current) clearTimeout(to.current); if (which) { setHoveredRampButton(e.target); @@ -406,7 +406,7 @@ export const FundingFlow = ({ totalPrice, onClose, onFunded }) => { }, []); const [rampPurchase, setRampPurchase] = useState(); - const checkRampPurchase = useCallback(async (purchase) => { + const checkRampPurchase = useCallback(import.meta.url, async (purchase) => { try { const response = await fetch( `https://api.${RAMP_PREPEND}ramp.network/api/host-api/purchase/${purchase.id}?secret=${purchase.purchaseViewToken}`, @@ -433,14 +433,14 @@ export const FundingFlow = ({ totalPrice, onClose, onFunded }) => { console.error('Error fetching purchase info:', error); } }, []); - useEffect(() => { + useEffect(import.meta.url, () => { if (rampPurchase) { const i = setInterval(() => { checkRampPurchase(rampPurchase); }, 5000); return () => clearInterval(i); } }, [checkRampPurchase, rampPurchase]) - const onClickCC = useCallback((amount) => () => { + const onClickCC = useCallback(import.meta.url, (amount) => () => { fireTrackingEvent('funding_start', { externalId: accountAddress }); setRamping(true); setRampPurchase(); @@ -472,7 +472,7 @@ export const FundingFlow = ({ totalPrice, onClose, onFunded }) => { }, [accountAddress]); const [layerswapUrl, setLayerswapUrl] = useState(); - const onClickLayerswap = useCallback(() => { + const onClickLayerswap = useCallback(import.meta.url, () => { let amount; if (fundsNeeded) { const swapAmount = fundsNeeded.clone(); @@ -497,14 +497,14 @@ export const FundingFlow = ({ totalPrice, onClose, onFunded }) => { ); }, [accountAddress, fundsNeeded]); - const onClickStarkgate = useCallback(() => { + const onClickStarkgate = useCallback(import.meta.url, () => { const url = `https://${areChainsEqual('SN_SEPOLIA', chainId) ? 'sepolia.' : ''}starkgate.starknet.io/`; window.open(url, '_blank'); setWaiting(true); }, []); - const onFaucetError = useCallback(() => { + const onFaucetError = useCallback(import.meta.url, () => { createAlert({ type: 'GenericAlert', data: { content: 'Faucet request failed, please try again later.' }, @@ -514,7 +514,7 @@ export const FundingFlow = ({ totalPrice, onClose, onFunded }) => { onClose(); }, [onClose]); - useEffect(() => { + useEffect(import.meta.url, () => { // error: clear ramp purchase + close funding dialog if (RAMP_PURCHASE_STATUS[rampPurchase?.status]?.isError) { // fire error diff --git a/src/game/launcher/components/FundingMenu.js b/src/game/launcher/components/FundingMenu.js index 06ad769e0..1543a5b1a 100644 --- a/src/game/launcher/components/FundingMenu.js +++ b/src/game/launcher/components/FundingMenu.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import ReactDOMServer from 'react-dom/server'; import styled from 'styled-components'; @@ -149,16 +149,16 @@ const FundingMenu = () => { const [isFunding, setIsFunding] = useState(); - const handleFunding = useCallback(() => { + const handleFunding = useCallback(import.meta.url, () => { if (!accountAddress) return login(); setIsFunding(true); }, [accountAddress, login]); - const reloadBalance = useCallback(() => { + const reloadBalance = useCallback(import.meta.url, () => { refetch(); }, [refetch]); - const tooltipContent = useMemo(() => ReactDOMServer.renderToStaticMarkup( + const tooltipContent = useMemo(import.meta.url, () => ReactDOMServer.renderToStaticMarkup( {Object.keys(wallet?.tokenBalances || {}).map((tokenAddress) => { const balance = priceHelper.from(wallet.tokenBalances[tokenAddress], tokenAddress); diff --git a/src/game/launcher/components/LauncherDialog.js b/src/game/launcher/components/LauncherDialog.js index 7c099cafd..659ef5b32 100644 --- a/src/game/launcher/components/LauncherDialog.js +++ b/src/game/launcher/components/LauncherDialog.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import ClipCorner from '~/components/ClipCorner'; @@ -100,13 +100,13 @@ const BottomLeft = styled.div``; const LauncherDialog = ({ panes = [], preselect, singlePane, bottomLeftMenu }) => { const [selected, setSelected] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { if (!!panes) { setSelected(panes[preselect || 0]); } }, [!!panes, preselect]); - const handleClick = useCallback((pane) => { + const handleClick = useCallback(import.meta.url, (pane) => { if (pane.link) { window.open(pane.link); } else { diff --git a/src/game/launcher/components/RecruitmentMenu.js b/src/game/launcher/components/RecruitmentMenu.js index 13d52abf0..99f848b2b 100644 --- a/src/game/launcher/components/RecruitmentMenu.js +++ b/src/game/launcher/components/RecruitmentMenu.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { SwayIcon } from '~/components/Icons'; @@ -28,7 +28,7 @@ const Wrapper = styled.div` const RecruitmentMenu = () => { const { data: referrals, isLoading } = useReferrals(); - const [referralsCount, referralsTotal] = useMemo(() => { + const [referralsCount, referralsTotal] = useMemo(import.meta.url, () => { const referred = new Set(); let total = 0; (referrals || []).forEach((r) => { diff --git a/src/game/launcher/components/RewardMissions.js b/src/game/launcher/components/RewardMissions.js index 5e7be0978..353b91ca5 100644 --- a/src/game/launcher/components/RewardMissions.js +++ b/src/game/launcher/components/RewardMissions.js @@ -1,4 +1,4 @@ -import { useCallback, useState } from 'react'; +import { useCallback, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import Loader from 'react-spinners/PuffLoader'; @@ -326,7 +326,7 @@ const MissionWrapper = styled.div` `; const Mission = ({ mission, mode }) => { const createAlert = useStore(s => s.dispatchAlertLogged); - const onClick = useCallback(() => { + const onClick = useCallback(import.meta.url, () => { const targetUrl = mode === 'community' ? process.env.REACT_APP_COMMUNITY_MISSIONS_URL : process.env.REACT_APP_COLONIZATION_MISSIONS_URL; if (targetUrl) { window.open(targetUrl); diff --git a/src/game/launcher/components/RewardQuests.js b/src/game/launcher/components/RewardQuests.js index a91f9f604..c9a3a83a2 100644 --- a/src/game/launcher/components/RewardQuests.js +++ b/src/game/launcher/components/RewardQuests.js @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useState } from '~/lib/react-debug'; import styled from 'styled-components'; import Loader from 'react-spinners/PuffLoader'; diff --git a/src/game/launcher/components/RewardReferrals.js b/src/game/launcher/components/RewardReferrals.js index 1e6cb582c..3e851dac0 100644 --- a/src/game/launcher/components/RewardReferrals.js +++ b/src/game/launcher/components/RewardReferrals.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Entity } from '@influenceth/sdk'; import moment from 'moment'; @@ -216,7 +216,7 @@ const RewardReferrals = () => { const [sort, setSort] = useState(['createdAt', 'asc']); - const handleCopyLink = useCallback(() => { + const handleCopyLink = useCallback(import.meta.url, () => { if (!accountAddress) return login(); navigator.clipboard.writeText(`${document.location.origin}/play?r=${accountAddress}`); @@ -227,7 +227,7 @@ const RewardReferrals = () => { }); }, [accountAddress, createAlert, login]); - const handleSort = useCallback((field) => () => { + const handleSort = useCallback(import.meta.url, (field) => () => { if (!field) return; let updatedSortField = sort[0]; @@ -242,14 +242,14 @@ const RewardReferrals = () => { setSort([updatedSortField, updatedSortDirection]); }, [sort]); - const transformedData = useMemo(() => { + const transformedData = useMemo(import.meta.url, () => { return (referrals || []).map((r) => ({ uuid: Entity.packEntity(r.entity), ...r })) }, [referrals]); - const filteredData = useMemo(() => { + const filteredData = useMemo(import.meta.url, () => { return transformedData.sort((a, b) => { return (sort[1] === 'asc' ? -1 : 1) * (a[sort[0]] < b[sort[0]] ? -1 : 1); }); diff --git a/src/game/launcher/components/SKU.js b/src/game/launcher/components/SKU.js index 5cfbadb18..0c74d53d1 100644 --- a/src/game/launcher/components/SKU.js +++ b/src/game/launcher/components/SKU.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useMemo, useState } from 'react'; +import { useCallback, useContext, useEffect, useMemo, useState } from '~/lib/react-debug'; import { useQueryClient } from 'react-query'; import styled from 'styled-components'; @@ -257,7 +257,7 @@ const FilterAsteroidButton = ({ price, sizeFilter }) => { const dispatchZoomScene = useStore(s => s.dispatchZoomScene); const updateZoomStatus = useStore(s => s.dispatchZoomStatusChanged); - const filterUnownedAsteroidsAndClose = useCallback(() => { + const filterUnownedAsteroidsAndClose = useCallback(import.meta.url, () => { updateFilters(Object.assign({}, filters, { ownedBy: 'unowned', ...sizeFilter })); dispatchZoomScene(); let hudTimeout = 0; @@ -285,7 +285,7 @@ const largeMaxPrice = 10000 * TOKEN_SCALE[TOKEN.USDC]; const AsteroidSKU = () => { const { data: priceConstants } = usePriceConstants(); const priceHelper = usePriceHelper(); - const [smallMaxLots, mediumMaxLots, largeMaxLots] = useMemo(() => { + const [smallMaxLots, mediumMaxLots, largeMaxLots] = useMemo(import.meta.url, () => { return [ asteroidPriceToLots(priceHelper.from(smallMaxPrice, TOKEN.USDC).to(TOKEN.ETH), priceConstants), asteroidPriceToLots(priceHelper.from(mediumMaxPrice, TOKEN.USDC).to(TOKEN.ETH), priceConstants), @@ -360,11 +360,11 @@ const CrewmateSKU = ({ onUpdatePurchase, onPurchasing }) => { const priceHelper = usePriceHelper(); const [quantity, setQuantity] = useState(1); - useEffect(() => { + useEffect(import.meta.url, () => { onPurchasing(getPendingCreditPurchase()) }, [getPendingCreditPurchase, onPurchasing]); - useEffect(() => { + useEffect(import.meta.url, () => { const cleanQuantity = cleanseCrewmates(quantity) || 1; const totalPrice = priceHelper.from( safeBigInt(cleanQuantity) * priceConstants?.ADALIAN_PURCHASE_PRICE, @@ -455,7 +455,7 @@ const SwaySKU = ({ onUpdatePurchase, onPurchasing }) => { const [usdc, setUSDC] = useState(); const [isProcessing, setIsProcessing] = useState(); - const handleEthChange = useCallback((newValue) => { + const handleEthChange = useCallback(import.meta.url, (newValue) => { setETH(newValue); const value = priceHelper.from(newValue * TOKEN_SCALE[TOKEN.ETH], TOKEN.ETH); @@ -463,7 +463,7 @@ const SwaySKU = ({ onUpdatePurchase, onPurchasing }) => { setSway(roundToPlaces(value.to(TOKEN.SWAY) / TOKEN_SCALE[TOKEN.SWAY], 0)); }, [priceHelper]); - const handleSwayChange = useCallback((newValue) => { + const handleSwayChange = useCallback(import.meta.url, (newValue) => { setSway(newValue); const value = priceHelper.from(newValue * TOKEN_SCALE[TOKEN.SWAY], TOKEN.SWAY); @@ -471,7 +471,7 @@ const SwaySKU = ({ onUpdatePurchase, onPurchasing }) => { setUSDC(roundToPlaces(value.to(TOKEN.USDC) / TOKEN_SCALE[TOKEN.USDC], 2)); }, [priceHelper]); - const handleUsdcChange = useCallback((newValue) => { + const handleUsdcChange = useCallback(import.meta.url, (newValue) => { setUSDC(newValue); const value = priceHelper.from(newValue * TOKEN_SCALE[TOKEN.USDC], TOKEN.USDC); @@ -479,7 +479,7 @@ const SwaySKU = ({ onUpdatePurchase, onPurchasing }) => { setSway(roundToPlaces(value.to(TOKEN.SWAY) / TOKEN_SCALE[TOKEN.SWAY], 0)); }, [priceHelper]); - useEffect(() => { + useEffect(import.meta.url, () => { if (preferredUiCurrency === TOKEN.ETH) { handleEthChange(0.001); } else { @@ -487,7 +487,7 @@ const SwaySKU = ({ onUpdatePurchase, onPurchasing }) => { } }, []); - useEffect(() => { + useEffect(import.meta.url, () => { const unscaledUSDC = (usdc || 0) * TOKEN_SCALE[TOKEN.USDC]; onUpdatePurchase({ totalPrice: priceHelper.from(unscaledUSDC, TOKEN.USDC), @@ -548,7 +548,7 @@ const SwaySKU = ({ onUpdatePurchase, onPurchasing }) => { wallet ]); - useEffect(() => { + useEffect(import.meta.url, () => { onPurchasing(isProcessing); }, [isProcessing, onPurchasing]) @@ -635,13 +635,13 @@ const SwayFaucetButton = () => { const [requestingSway, setRequestingSway] = useState(); - const swayEnabled = useMemo(() => { + const swayEnabled = useMemo(import.meta.url, () => { if (!faucetInfo) return false; const lastClaimed = faucetInfo.SWAY.lastClaimed || 0; return Date.now() > (Date.parse(lastClaimed) + 23.5 * 3600e3); }, [faucetInfo]); - const requestSway = useCallback(async () => { + const requestSway = useCallback(import.meta.url, async () => { if (!accountAddress) return login(); setRequestingSway(true); @@ -706,7 +706,7 @@ const SKU = ({ asset, onBack }) => { const [fundingPurchase, setFundingPurchase] = useState(); const [isPurchasing, setIsPurchasing] = useState(); - const handlePurchase = useCallback((overridePurchase) => { + const handlePurchase = useCallback(import.meta.url, (overridePurchase) => { if (!accountAddress) return login(); const purch = (overridePurchase || purchase); @@ -719,7 +719,7 @@ const SKU = ({ asset, onBack }) => { } }, [accountAddress, login, purchase, wallet]); - const [asteroidsRemaining, nextAsteroidSale] = useMemo(() => { + const [asteroidsRemaining, nextAsteroidSale] = useMemo(import.meta.url, () => { if (!asteroidSale) return [0, 0, false]; const remaining = asteroidSale ? (Number(asteroidSale.limit) - Number(asteroidSale.volume)) : 0; @@ -730,7 +730,7 @@ const SKU = ({ asset, onBack }) => { ]; }, [asteroidSale, blockTime]); - const { content, ...props } = useMemo(() => { + const { content, ...props } = useMemo(import.meta.url, () => { if (asset === 'asteroids') { return { coverImage: AsteroidsHeroImage, diff --git a/src/game/launcher/components/StarterPack.js b/src/game/launcher/components/StarterPack.js index c5e13fd17..a5c59298b 100644 --- a/src/game/launcher/components/StarterPack.js +++ b/src/game/launcher/components/StarterPack.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useMemo, useState } from 'react'; +import { useCallback, useContext, useEffect, useMemo, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { Building, Crewmate, Process } from '@influenceth/sdk'; import cloneDeep from 'lodash/cloneDeep'; @@ -155,7 +155,7 @@ export const useStarterPackPricing = () => { const priceHelper = usePriceHelper(); const { data: wallet } = useWalletPurchasableBalances(); - const adalianPrice = useMemo(() => { + const adalianPrice = useMemo(import.meta.url, () => { if (!priceConstants) return priceHelper.from(0); return priceHelper.from(priceConstants?.ADALIAN_PURCHASE_PRICE, priceConstants?.ADALIAN_PURCHASE_TOKEN); }, [priceConstants]); @@ -166,7 +166,7 @@ export const useStarterPackPricing = () => { } = useShoppingListData(1, 0, uniqueProductIds); // TODO: could just add adv building difference to basic to avoid repeating all those calcs for shared buildings - const getMarketCostForBuildingList = useCallback((buildingIds) => { + const getMarketCostForBuildingList = useCallback(import.meta.url, (buildingIds) => { if (!resourceMarketplaces) return 0; // get instance of resourceMarketplaces that we can be destructive with @@ -239,22 +239,22 @@ export const useStarterPackPricing = () => { return allOrders.reduce((acc, o) => acc + o.cost, 0); }, [resourceMarketplacesUpdatedAt]); - const introPackSwayMin = useMemo(() => { + const introPackSwayMin = useMemo(import.meta.url, () => { const marketCost = getMarketCostForBuildingList(introBuildings); return (1 + MARKET_BUFFER) * marketCost; }, [getMarketCostForBuildingList]); - const basicPackSwayMin = useMemo(() => { + const basicPackSwayMin = useMemo(import.meta.url, () => { const marketCost = getMarketCostForBuildingList(basicBuildings); return (1 + MARKET_BUFFER) * marketCost; }, [getMarketCostForBuildingList]); - const advPackSwayMin = useMemo(() => { + const advPackSwayMin = useMemo(import.meta.url, () => { const marketCost = getMarketCostForBuildingList(advBuildings); return (1 + MARKET_BUFFER) * marketCost; }, [getMarketCostForBuildingList]); - return useMemo(() => { + return useMemo(import.meta.url, () => { const introMinPrice = priceHelper.from(introPackPriceUSD * TOKEN_SCALE[TOKEN.USDC], TOKEN.USDC); const introMinSwayValue = priceHelper.from(introPackSwayMin * TOKEN_SCALE[TOKEN.SWAY], TOKEN.SWAY); const introCrewmatesValue = priceHelper.from(introPackCrewmates * adalianPrice.usdcValue, TOKEN.USDC); @@ -339,7 +339,7 @@ export const useStarterPacks = () => { const createAlert = useStore(s => s.dispatchAlertLogged); - return useMemo(() => { + return useMemo(import.meta.url, () => { const onPurchase = (which) => async (onIsPurchasing) => { const pack = starterPacks[which]; const totalPrice = pack.price; @@ -414,11 +414,11 @@ const PurchasePackButton = ({ pack }) => { const [isPurchasing, setIsPurchasing] = useState(); - const isPurchasingStarterPack = useMemo(() => { + const isPurchasingStarterPack = useMemo(import.meta.url, () => { return isPurchasing || (pendingTransactions || []).find(tx => tx.key === 'PurchaseStarterPack'); }, [pendingTransactions]); - const onPurchase = useCallback(() => { + const onPurchase = useCallback(import.meta.url, () => { pack.onPurchase((which) => setIsPurchasing(which)); }, [pack]); @@ -444,7 +444,7 @@ const StarterPackWrapper = ({ children, pack, ...props }) => { const [isFunding, setIsFunding] = useState(); const [isFunded, setIsFunded] = useState(); - const onClick = useCallback(() => { + const onClick = useCallback(import.meta.url, () => { if (props.asButton) { if (pack.price.usdcValue > wallet?.combinedBalance?.to(TOKEN.USDC)) { setIsFunding({ @@ -459,7 +459,7 @@ const StarterPackWrapper = ({ children, pack, ...props }) => { }, [props.asButton, pack.price, wallet?.combinedBalance]); // pull pack.onPurchase out of onClick (so can be re-memoized after wallet balance updates before called) - useEffect(() => { + useEffect(import.meta.url, () => { if (isFunded) { pack.onPurchase(props.onIsPurchasing); setIsFunded(); diff --git a/src/game/launcher/components/SupportMenu.js b/src/game/launcher/components/SupportMenu.js index 128ca4c61..25371881d 100644 --- a/src/game/launcher/components/SupportMenu.js +++ b/src/game/launcher/components/SupportMenu.js @@ -1,4 +1,4 @@ -import { useCallback } from 'react'; +import { useCallback } from '~/lib/react-debug'; import styled from 'styled-components'; import { ChevronDoubleRightIcon, InfluenceIcon } from '~/components/Icons'; @@ -75,7 +75,7 @@ const SupportWrapper = styled.div` `; const SupportMenu = () => { - const goToDiscord = useCallback(() => { + const goToDiscord = useCallback(import.meta.url, () => { window.open(process.env.REACT_APP_HELP_URL); }, []); return ( diff --git a/src/game/scene/Asteroid.js b/src/game/scene/Asteroid.js index 260e657a9..bd257f920 100644 --- a/src/game/scene/Asteroid.js +++ b/src/game/scene/Asteroid.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useContext, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { useFrame, useThree } from '@react-three/fiber'; import { ACESFilmicToneMapping, AxesHelper, CameraHelper, Color, DirectionalLight, DirectionalLightHelper, Quaternion, Vector3 } from 'three'; import gsap from 'gsap'; @@ -161,7 +161,7 @@ const AsteroidComponent = () => { const { assetType, overrides } = useContext(DevToolContext); - const [STAR_COLOR, STAR_INTENSITY_ADJ, DARKLIGHT_COLOR, DARKLIGHT_INTENSITY] = useMemo(() => { + const [STAR_COLOR, STAR_INTENSITY_ADJ, DARKLIGHT_COLOR, DARKLIGHT_INTENSITY] = useMemo(import.meta.url, () => { const defaults = visualConfigs.scene; const o = assetType === 'scene' ? overrides : {}; return [ @@ -172,12 +172,12 @@ const AsteroidComponent = () => { ]; }, [assetType, overrides]); - const selectedLot = useMemo(() => Lot.toPosition(lotId), [lotId]); + const selectedLot = useMemo(import.meta.url, () => Lot.toPosition(lotId), [lotId]); const { data: asteroidData } = useAsteroid(origin); const { data: ships } = useAsteroidShips(origin); - const shipsInOrbitTally = useMemo(() => { + const shipsInOrbitTally = useMemo(import.meta.url, () => { return (ships || []).filter((ship) => { return ship.Location.location.label === Entity.IDS.ASTEROID && !ship.Ship.transitDestination && ship.Ship.status === Ship.STATUSES.AVAILABLE; }).length; @@ -213,26 +213,26 @@ const AsteroidComponent = () => { const forceUpdate = useRef(0); const lastUpdateStart = useRef(0); - const maxStretch = useMemo( + const maxStretch = useMemo(import.meta.url, () => config?.stretch ? Math.max(config.stretch.x, config.stretch.y, config.stretch.z) : 1, [config?.stretch] ); - // const minStretch = useMemo( + // const minStretch = useMemo(import.meta.url, // () => config?.stretch ? Math.min(config.stretch.x, config.stretch.y, config.stretch.z) : 1, // [config?.stretch] // ); // scaleHelper helps define outmost telemetry lines and initial zoom // to help convey relative scale of asteroids - const SCALE_HELPER = useMemo(() => { + const SCALE_HELPER = useMemo(import.meta.url, () => { return 360000 * Math.sqrt(config?.radius / 376000) / config?.radius; }, [config?.radius]); - const INITIAL_ZOOM = useMemo(() => { + const INITIAL_ZOOM = useMemo(import.meta.url, () => { return Math.max(INITIAL_ZOOM_MIN, 1.5 * SCALE_HELPER * config?.radius); }, [config?.radius, SCALE_HELPER]); - const initialOrientation = useMemo(() => { + const initialOrientation = useMemo(import.meta.url, () => { if (!(controls && config?.radius && zoomedFrom?.position)) return null; // zoom to the point on the equator closest to the camera @@ -273,15 +273,15 @@ const AsteroidComponent = () => { }; }, [cinematicInitialPosition, !controls, config?.radius, prevAsteroidPosition, zoomedFrom?.position]); - const ringsPresent = useMemo(() => !!config?.ringsPresent, [config?.ringsPresent]); - const surfaceDistance = useMemo( + const ringsPresent = useMemo(import.meta.url, () => !!config?.ringsPresent, [config?.ringsPresent]); + const surfaceDistance = useMemo(import.meta.url, () => (MIN_FRUSTUM_AT_SURFACE / 2) / Math.tan((controls?.object?.fov / 2) * (Math.PI / 180)), [controls?.object?.fov] ); - const frustumHeightMult = useMemo(() => 2 * Math.tan((controls?.object?.fov / 2) * (Math.PI / 180)), [controls?.object?.fov]); + const frustumHeightMult = useMemo(import.meta.url, () => 2 * Math.tan((controls?.object?.fov / 2) * (Math.PI / 180)), [controls?.object?.fov]); - const disposeGeometry = useCallback(() => { + const disposeGeometry = useCallback(import.meta.url, () => { if (geometry.current && quadtreeRef.current) { geometry.current.groups.forEach((g) => { quadtreeRef.current.remove(g); @@ -293,7 +293,7 @@ const AsteroidComponent = () => { } }, []); - const disposeLight = useCallback(() => { + const disposeLight = useCallback(import.meta.url, () => { if (group.current && light.current) { group.current.remove(light.current); } @@ -311,7 +311,7 @@ const AsteroidComponent = () => { } }, []); - const onUnload = useCallback(() => { + const onUnload = useCallback(import.meta.url, () => { setConfig(); setTerrainInitialized(); asteroidOrbit.current = null; @@ -324,7 +324,7 @@ const AsteroidComponent = () => { disposeGeometry(); }, [disposeLight, disposeGeometry]); - useEffect(() => { + useEffect(import.meta.url, () => { // if origin changed, zoom into new asteroid if (asteroidId.current && asteroidId.current !== origin) { if (zoomStatus === 'in') { @@ -339,14 +339,14 @@ const AsteroidComponent = () => { dispatchLotsLoading(origin); // initialize lot loader }, [origin]); // eslint-disable-line react-hooks/exhaustive-deps - useEffect(() => { + useEffect(import.meta.url, () => { if (zoomStatus !== 'in') { setZoomedIntoAsteroidId(); } }, [zoomStatus]); // Update texture generation config when new asteroid data is available - useEffect(() => { + useEffect(import.meta.url, () => { // when asteroidData is loaded for selected asteroid... if (asteroidData && asteroidData.id === origin) { @@ -375,24 +375,24 @@ const AsteroidComponent = () => { // eslint-disable-next-line react-hooks/exhaustive-deps }, [ asteroidData ]); - const defaultLightIntensity = useMemo(() => { + const defaultLightIntensity = useMemo(import.meta.url, () => { if (!position.current || !config?.radius) return 0; return Math.max(0.175, STAR_INTENSITY_ADJ * constants.STAR_INTENSITY / (new Vector3(...position.current).length() / constants.AU)); }, [config?.radius, STAR_INTENSITY_ADJ]); // turn down the sun while in resource mode - const currentLightIntensity = useMemo(() => { + const currentLightIntensity = useMemo(import.meta.url, () => { return (resourceMap?.active && resourceMap?.selected) ? Math.min(0.175, defaultLightIntensity) : defaultLightIntensity; }, [defaultLightIntensity, resourceMap]); - useEffect(() => { + useEffect(import.meta.url, () => { if (light.current && light.current.intensity !== currentLightIntensity) { gsap.timeline().to(light.current, { intensity: currentLightIntensity, ease: 'power4.out', duration: LIGHT_ANIMATION_TIME / 1e3 }); } }, [currentLightIntensity]); // Configures the light component once the geometry is created - useEffect(() => { + useEffect(import.meta.url, () => { if (!(config?.radius && config?.stretch && geometry.current && quadtreeRef.current && position.current)) return; // calculate intended shadow mode @@ -463,16 +463,16 @@ const AsteroidComponent = () => { // eslint-disable-next-line react-hooks/exhaustive-deps }, [config, ringsPresent, shadowMode, shadowSize, textureSize, surfaceDistance]); - useEffect(() => { + useEffect(import.meta.url, () => { if (light.current) light.current.color = new Color().setStyle(STAR_COLOR); }, [STAR_COLOR]); - useEffect(() => { + useEffect(import.meta.url, () => { if (darkLight.current) darkLight.current.color = new Color().setStyle(DARKLIGHT_COLOR); }, [DARKLIGHT_COLOR]); // Zooms the camera to the correct location - useEffect(() => { + useEffect(import.meta.url, () => { if (zoomStatus === 'zooming-in' && !prevAsteroidPosition && controls) { // console.log('set zoomedfrom'); setZoomedFrom({ @@ -484,7 +484,7 @@ const AsteroidComponent = () => { }, [zoomStatus]); const shouldZoomIn = zoomStatus === 'zooming-in' && controls && config?.radius; - useEffect(() => { + useEffect(import.meta.url, () => { if (!shouldZoomIn || !initialOrientation || !config) return; if (!group.current || !position.current) return; @@ -529,7 +529,7 @@ const AsteroidComponent = () => { }, [ shouldZoomIn, !initialOrientation ]); const shouldFinishZoomIn = zoomStatus === 'in' && controls && config?.radius; - useEffect(() => { + useEffect(import.meta.url, () => { if (!shouldFinishZoomIn || !initialOrientation) return; const panTo = new Vector3(...position.current); @@ -561,7 +561,7 @@ const AsteroidComponent = () => { // Handle zooming back out const shouldZoomOut = zoomStatus === 'zooming-out' && zoomedFrom && controls; - useEffect(() => { + useEffect(import.meta.url, () => { if (!shouldZoomOut) return; controls.minDistance = 0; @@ -589,14 +589,14 @@ const AsteroidComponent = () => { // eslint-disable-next-line react-hooks/exhaustive-deps }, [ shouldZoomOut ]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!cameraAltitude || !frustumHeightMult) return; const frustumWidth = cameraAltitude * frustumHeightMult * window.innerWidth / window.innerHeight; const thetaAcrossScreen = frustumWidth / controls.object.position.length(); controls.rotateSpeed = Math.min(1.5, 1.5 * thetaAcrossScreen / 2); }, [cameraAltitude, frustumHeightMult]); // eslint-disable-line react-hooks/exhaustive-deps - const getClosestChunk = useCallback((cameraPosition) => { + const getClosestChunk = useCallback(import.meta.url, (cameraPosition) => { if (!geometry.current?.chunks) return null; const [closestChunk] = Object.values(geometry.current.chunks).reduce((acc, c) => { const distance = c.sphereCenter.distanceTo(cameraPosition); @@ -605,7 +605,7 @@ const AsteroidComponent = () => { return closestChunk; }, []); - const getMinDistance = useCallback((closestChunk) => { + const getMinDistance = useCallback(import.meta.url, (closestChunk) => { return Math.min( config?.radius * MIN_ZOOM_DEFAULT, // for smallest asteroids to match legacy (where this > min surface distance) closestChunk.sphereCenterHeight + surfaceDistance @@ -619,7 +619,7 @@ const AsteroidComponent = () => { // NOTE: raycasting technically *might* be more accurate here, but it's way less performant // (3ms+ for just closest mesh... if all quadtree children, closer to 20ms) const applyingZoomLimits = useRef(0); - const applyZoomLimits = useCallback((cameraPosition) => { + const applyZoomLimits = useCallback(import.meta.url, (cameraPosition) => { if (!config?.radius) return; applyingZoomLimits.current = true; setTimeout(() => { @@ -646,12 +646,12 @@ const AsteroidComponent = () => { } // adjust rotation speed - setCameraAltitude(cameraPosition.length() - closestChunk.sphereCenterHeight); + setCameraAltitude(Math.round(cameraPosition.length() - closestChunk.sphereCenterHeight)); }, 0); // eslint-disable-next-line react-hooks/exhaustive-deps }, [surfaceDistance, config?.radius, controls?.minDistance]); - useEffect(() => { + useEffect(import.meta.url, () => { const resourceMapActive = resourceMap?.active; const resourceMapId = resourceMap?.selected; @@ -687,7 +687,7 @@ const AsteroidComponent = () => { } }, [resourceMap, terrainInitialized, !asteroidData?.Celestial?.abundances]); - useEffect(() => { + useEffect(import.meta.url, () => { if (geometry.current && terrainUpdateNeeded) { // vvv BENCHMARK 2ms (zoomed-out), 4-20ms+ (zoomed-in) lastUpdateStart.current = Date.now(); @@ -701,7 +701,7 @@ const AsteroidComponent = () => { // NOTE: to stop / start chunk splitting with shift+space, can // uncomment below and the "disableChunks" line above // const disableChunks = useRef(); - // useEffect(() => { + // useEffect(import.meta.url, () => { // const onKeydown = (e) => { // if (e.shiftKey && e.which === 32) { // disableChunks.current = !disableChunks.current; @@ -714,7 +714,7 @@ const AsteroidComponent = () => { // }, []); // const ddd = useRef(); - // useEffect(() => { + // useEffect(import.meta.url, () => { // if (!config?.radius) return; // const onKeydown = (e) => { // if (e.shiftKey && e.which === 32) { @@ -761,19 +761,19 @@ const AsteroidComponent = () => { // }, [controls, config?.radius]); const [dramaticZoom, setDramaticZoom] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { setDramaticZoom(true); }, [origin]); const [cameraRecenterTimestamp, setCameraRecenterTimestamp] = useState(0); - useEffect(() => { + useEffect(import.meta.url, () => { if (cameraNeedsRecenter) { dispatchRecenterCamera(); setCameraRecenterTimestamp(Date.now()) } }, [cameraNeedsRecenter]); - useEffect(() => { + useEffect(import.meta.url, () => { if (cameraNeedsHighAltitude && config?.radius && zoomStatus === 'in' && !automatingCamera.current) { const newPosition = new Vector3(...controls.object.position); newPosition.setLength(config.radius * 1.5); @@ -796,7 +796,7 @@ const AsteroidComponent = () => { const [debugTrajectory, setDebugTrajectory] = useState([]); const automatingCamera = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (selectedLot?.lotIndex > 0 && zoomedIntoAsteroidId === selectedLot?.asteroidId && config?.radiusNominal && zoomStatus === 'in') { const lotTally = Asteroid.getSurfaceArea(selectedLot?.asteroidId); if (lotTally < selectedLot.lotIndex) { dispatchLotSelected(); return; } @@ -953,7 +953,7 @@ const AsteroidComponent = () => { } }, [cameraRecenterTimestamp, zoomedIntoAsteroidId, origin, selectedLot, config?.radiusNominal, zoomStatus]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!cameraNeedsReorientation || zoomStatus !== 'in') return; dispatchReorientCamera(); gsap.timeline().to(controls.object.up, { ...rotationAxis.current.clone(), ease: 'slow.out' }); diff --git a/src/game/scene/Asteroids.js b/src/game/scene/Asteroids.js index b9181e50a..0a4c7dcd9 100644 --- a/src/game/scene/Asteroids.js +++ b/src/game/scene/Asteroids.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState, useMemo } from 'react'; +import { useCallback, useEffect, useRef, useState, useMemo } from '~/lib/react-debug'; import styled from 'styled-components'; import { AxesHelper, Color, Vector3 } from 'three'; import { useThrottleCallback } from '@react-hook/throttle'; @@ -86,7 +86,7 @@ const Asteroids = () => { const selectDestination = useStore(s => s.dispatchDestinationSelected); const dispatchSwapOriginDestination = useStore(s => s.dispatchSwapOriginDestination); - const isDefaultSearch = useMemo(() => isAssetSearchMatchingDefault('asteroidsMapped'), [filters]); + const isDefaultSearch = useMemo(import.meta.url, () => isAssetSearchMatchingDefault('asteroidsMapped'), [filters]); const { processInBackground } = useWebWorker(); @@ -111,11 +111,11 @@ const Asteroids = () => { const isUpdating = useRef(false); const asteroidsGeom = useRef(); - const asteroids = useMemo(() => { + const asteroids = useMemo(import.meta.url, () => { return asteroidSearch?.hits?.length > 0 ? asteroidSearch.hits : []; }, [asteroidSearch?.hits]); - const assetedAsteroids = useMemo(() => { + const assetedAsteroids = useMemo(import.meta.url, () => { const asseted = {}; (controlledAsteroids || []).forEach((a) => { if (!asseted[a.id]) asseted[a.id] = { asteroid: a }; @@ -146,7 +146,7 @@ const Asteroids = () => { // Update state when asteroids from server, origin, or destination change const isZoomedIn = zoomStatus === 'in'; - useEffect(() => { + useEffect(import.meta.url, () => { const newMappedAsteroids = asteroids ? cloneDeep(asteroids) : []; // in default search, append watchlist and owned as needed @@ -186,7 +186,7 @@ const Asteroids = () => { }, [ asteroids, origin, destination, assetedAsteroids, watchlist, isZoomedIn ]); // Responds to hover changes in the store which could be fired from the HUD - useEffect(() => { + useEffect(import.meta.url, () => { if (!hovered || hovered === originId || hovered === destinationId) { setHoveredPos(null); return; @@ -209,7 +209,7 @@ const Asteroids = () => { // managing trigger for this in a useFrame loop (rather than listening for coarseTime update), // and setting geometry attributes directly, rather than through state... could potentially do // fewer updates / only update on coarseTime when zoomed in - useEffect(() => { + useEffect(import.meta.url, () => { if (coarseTime && asteroidsWorkerPayload && !isUpdating.current) { isUpdating.current = true; processInBackground( @@ -228,7 +228,7 @@ const Asteroids = () => { // eslint-disable-next-line react-hooks/exhaustive-deps }, [coarseTime, asteroidsWorkerPayload]) - useEffect(() => { + useEffect(import.meta.url, () => { // Check that we have data, positions are processed, and they're in sync if (mappedAsteroids.length * 3 === positions.length) { if (originId) { @@ -248,7 +248,7 @@ const Asteroids = () => { }, [ mappedAsteroids, positions, originId, destinationId ]); // Update colors - useEffect(() => { + useEffect(import.meta.url, () => { const newColors = mappedAsteroids.map(a => { if (highlightConfig) return highlighters[highlightConfig.field](a, highlightConfig); return [ 1, 1, 1 ]; @@ -258,13 +258,13 @@ const Asteroids = () => { }, [ mappedAsteroids, highlightConfig ]); // re-computeBoundingSphere on geometry change - useEffect(() => { + useEffect(import.meta.url, () => { if (asteroidsGeom.current) { asteroidsGeom.current.computeBoundingSphere(); } }, [positions]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!cameraNeedsReorientation || zoomStatus !== 'out' || !controls?.object?.position) return; dispatchReorientCamera(); @@ -290,7 +290,7 @@ const Asteroids = () => { }, [cameraNeedsReorientation]); // mouse event handlers - const onClick = useCallback((e) => { + const onClick = useCallback(import.meta.url, (e) => { e.stopPropagation(); const index = e.intersections.sort((a, b) => a.distanceToRay - b.distanceToRay)[0].index; if (mappedAsteroids[index]) { @@ -305,7 +305,7 @@ const Asteroids = () => { } }, [mappedAsteroids, destinationId, travelMode]); // eslint-disable-line react-hooks/exhaustive-deps - const onContextClick = useCallback((e) => { + const onContextClick = useCallback(import.meta.url, (e) => { e.stopPropagation(); const index = e.intersections.sort((a, b) => a.distanceToRay - b.distanceToRay)[0].index; @@ -326,7 +326,7 @@ const Asteroids = () => { unhoverAsteroid(); }, 30); // eslint-disable-line react-hooks/exhaustive-deps - const { assetPositions, assetPositionsById, watchlistPositions } = useMemo(() => { + const { assetPositions, assetPositionsById, watchlistPositions } = useMemo(import.meta.url, () => { const assetPositions = []; const assetPositionsById = {}; const watchlistPositions = []; @@ -349,7 +349,7 @@ const Asteroids = () => { } }, [origin, positions, watchlist]); // don't update when mappedAsteroids updated (wait for positions update) - const [originToDestination, originToDestinationDistance, originToDestinationHalfway] = useMemo(() => { + const [originToDestination, originToDestinationDistance, originToDestinationHalfway] = useMemo(import.meta.url, () => { if (originPos && destinationPos) { const o = new Vector3(originPos[0], originPos[1], originPos[2]); const d = new Vector3(destinationPos[0], destinationPos[1], destinationPos[2]); @@ -371,7 +371,7 @@ const Asteroids = () => { const diamondMarker = useTexture(`${process.env.PUBLIC_URL}/textures/asteroids/solid_diamond.png`); - const billboardedAsteroids = useMemo(() => { + const billboardedAsteroids = useMemo(import.meta.url, () => { const b = {}; if (origin && originPos) { b[origin.id] = { diff --git a/src/game/scene/Planets.js b/src/game/scene/Planets.js index ac74cc8dc..b3166cebd 100644 --- a/src/game/scene/Planets.js +++ b/src/game/scene/Planets.js @@ -1,4 +1,4 @@ -import { useEffect, useRef } from 'react'; +import { useEffect, useRef } from '~/lib/react-debug'; import { AdditiveBlending, Float32BufferAttribute } from 'three'; import { useTexture } from '@react-three/drei'; import { Planet } from '@influenceth/sdk'; @@ -21,7 +21,7 @@ const Planets = () => { const geometry = useRef(); // Listen for changes to planets data or global time and update planet positions - useEffect(() => { + useEffect(import.meta.url, () => { if (planets && coarseTime && !isUpdating.current) { isUpdating.current = true; processInBackground( diff --git a/src/game/scene/SettingsManager.js b/src/game/scene/SettingsManager.js index c3ee047b0..1744dabed 100644 --- a/src/game/scene/SettingsManager.js +++ b/src/game/scene/SettingsManager.js @@ -1,4 +1,4 @@ -import { useContext, useEffect, useMemo, useState } from 'react'; +import { useContext, useEffect, useMemo, useState } from '~/lib/react-debug'; import { useThree } from '@react-three/fiber'; import { useCubeTexture } from '@react-three/drei'; import { Color, EquirectangularReflectionMapping, TextureLoader } from 'three'; @@ -18,7 +18,7 @@ const SettingsManager = () => { const [overrideTexture, setOverrideTexture] = useState(); - const [backgroundOverride, backgroundOverrideName, backgroundIntensity] = useMemo(() => { + const [backgroundOverride, backgroundOverrideName, backgroundIntensity] = useMemo(import.meta.url, () => { const defaults = visualConfigs.scene; const o = assetType === 'scene' ? overrides : {}; return [ @@ -33,7 +33,7 @@ const SettingsManager = () => { 'sky_pos_x.jpg', 'sky_neg_x.jpg', 'sky_pos_y.jpg', 'sky_neg_y.jpg', 'sky_pos_z.jpg', 'sky_neg_z.jpg' ], { path: `${process.env.PUBLIC_URL}/textures/skybox/`}); - useEffect(() => { + useEffect(import.meta.url, () => { if (backgroundOverride && backgroundOverrideName) { const cleanupTextures = []; const resolve = function (texture) { @@ -56,12 +56,12 @@ const SettingsManager = () => { } }, [backgroundOverride, backgroundOverrideName]); - useEffect(() => { + useEffect(import.meta.url, () => { gl.setPixelRatio(pixelRatio || 1); }, [pixelRatio]); // toggle background on / off per settings - useEffect(() => { + useEffect(import.meta.url, () => { if (skyboxVisible && skybox) { scene.background = overrideTexture || skybox; } else if (!skyboxVisible) { @@ -69,12 +69,12 @@ const SettingsManager = () => { } }, [ overrideTexture, skyboxVisible, skybox ]); - useEffect(() => { + useEffect(import.meta.url, () => { scene.backgroundIntensity = backgroundIntensity; }, [backgroundIntensity]); // toggle fov as needed - useEffect(() => { + useEffect(import.meta.url, () => { if (fov && camera && camera.fov !== fov) { camera.fov = fov; camera.updateProjectionMatrix(); diff --git a/src/game/scene/Star.js b/src/game/scene/Star.js index 976ec9f2e..8302958bb 100644 --- a/src/game/scene/Star.js +++ b/src/game/scene/Star.js @@ -1,4 +1,4 @@ -import { useEffect, useRef } from 'react'; +import { useEffect, useRef } from '~/lib/react-debug'; import { Color, Vector3 } from 'three'; import { useThree, useFrame } from '@react-three/fiber'; import { useTexture } from '@react-three/drei'; @@ -32,7 +32,7 @@ const Star = () => { const { camera } = useThree(); // Update lensflare elements with textures after loaded - useEffect(() => { + useEffect(import.meta.url, () => { config.forEach((c, i) => { lensflareElements[i].texture = textures[c[0]]; }); diff --git a/src/game/scene/asteroid/Lots.js b/src/game/scene/asteroid/Lots.js index 399941f83..d6039a674 100644 --- a/src/game/scene/asteroid/Lots.js +++ b/src/game/scene/asteroid/Lots.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { useFrame, useThree } from '@react-three/fiber'; import { useTexture } from '@react-three/drei'; import { @@ -92,7 +92,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca const { registerMessageHandler, unregisterMessageHandler, wsReady } = useWebsocket(); const { processInBackground } = useWebWorker(); - const attachTo = useMemo(() => overrideAttachTo || scene, [overrideAttachTo, scene]); + const attachTo = useMemo(import.meta.url, () => overrideAttachTo || scene, [overrideAttachTo, scene]); const textureQuality = useStore(s => s.graphics.textureQuality); const lotId = useStore(s => s.asteroids.lot); @@ -100,9 +100,9 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca const dispatchLotSelected = useStore(s => s.dispatchLotSelected); const dispatchSearchResults = useStore(s => s.dispatchLotsMappedSearchResults); - const selectedLotIndex = useMemo(() => Lot.toIndex(lotId), [lotId]); + const selectedLotIndex = useMemo(import.meta.url, () => Lot.toIndex(lotId), [lotId]); const { data: lotDetails } = useLot(lotId); - const deliveryEndpoint = useMemo(() => lotDetails?.building || lotDetails?.surfaceShip, [lotDetails]); + const deliveryEndpoint = useMemo(import.meta.url, () => lotDetails?.building || lotDetails?.surfaceShip, [lotDetails]); const { data: outboundDeliveries } = useDeliveries({ origin: deliveryEndpoint, status: Delivery.STATUSES.SENT }); const { data: inboundDeliveries } = useDeliveries({ destination: deliveryEndpoint, status: Delivery.STATUSES.SENT }); @@ -122,7 +122,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca const textures = useTexture(lotUseTextures); - const texturesLoaded = useMemo(() => { + const texturesLoaded = useMemo(import.meta.url, () => { return Object.keys(textures) > 0; }, [textures]); @@ -146,12 +146,12 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca const mouseIsOut = useRef(false); const clickStatus = useRef(); - const PLOT_WIDTH = useMemo(() => Math.min(125, config?.radius / 25), [config?.radius]); - const BUILDING_RADIUS = useMemo(() => 0.375 * PLOT_WIDTH, [PLOT_WIDTH]); - const PIP_RADIUS = useMemo(() => 0.25 * PLOT_WIDTH, [PLOT_WIDTH]); + const PLOT_WIDTH = useMemo(import.meta.url, () => Math.min(125, config?.radius / 25), [config?.radius]); + const BUILDING_RADIUS = useMemo(import.meta.url, () => 0.375 * PLOT_WIDTH, [PLOT_WIDTH]); + const PIP_RADIUS = useMemo(import.meta.url, () => 0.25 * PLOT_WIDTH, [PLOT_WIDTH]); const RETICULE_WIDTH = 5 * PLOT_WIDTH; - const chunkyAltitude = useMemo(() => Math.round(cameraAltitude / 500) * 500, [cameraAltitude]); + const chunkyAltitude = useMemo(import.meta.url, () => Math.round(cameraAltitude / 500) * 500, [cameraAltitude]); // NOTE: for every dependency on `lotDataMap`, should also include `lastLotUpdate` so react triggers it // (it seems react does not handle sparse arrays very well for equality checks) @@ -174,27 +174,27 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca refetch: refetchLots } = useMappedAsteroidLots(asteroidId); - useEffect(() => { + useEffect(import.meta.url, () => { dispatchSearchResults({ total: resultTally, isLoading }); }, [resultTally, isLoading]) - const lotTally = useMemo(() => Asteroid.getSurfaceArea(asteroidId), [asteroidId]); - const regionTally = useMemo(() => lotTally <= MAX_LOTS_RENDERED ? 1 : Asteroid.getLotRegionTally(lotTally), [lotTally]); - const visibleLotTally = useMemo(() => Math.min(MAX_MESH_INSTANCES, lotTally), [lotTally]); - const visibleLeasedTally = useMemo(() => Math.min(MAX_LEASE_INSTANCES, leasedTally), [leasedTally]); - const visibleResultTally = useMemo(() => Math.min(MAX_MESH_INSTANCES, resultTally), [resultTally]); + const lotTally = useMemo(import.meta.url, () => Asteroid.getSurfaceArea(asteroidId), [asteroidId]); + const regionTally = useMemo(import.meta.url, () => lotTally <= MAX_LOTS_RENDERED ? 1 : Asteroid.getLotRegionTally(lotTally), [lotTally]); + const visibleLotTally = useMemo(import.meta.url, () => Math.min(MAX_MESH_INSTANCES, lotTally), [lotTally]); + const visibleLeasedTally = useMemo(import.meta.url, () => Math.min(MAX_LEASE_INSTANCES, leasedTally), [leasedTally]); + const visibleResultTally = useMemo(import.meta.url, () => Math.min(MAX_MESH_INSTANCES, resultTally), [resultTally]); // if just navigated to asteroid and lots already loaded, refetch // (b/c might have missed ws updates while on a different asteroid) // TODO: probably technically need to capture allLotsReloading alongside lastLotUpdate in dependency arrays - useEffect(() => { + useEffect(import.meta.url, () => { if (Object.values(lotResultMap).length > 0) refetchLots(); }, []); // position lots and bucket into regions (as needed) // BATCHED region bucketing is really only helpful for largest couple asteroids // NOTE: this just runs once when lots is initial populated - useEffect(() => { + useEffect(import.meta.url, () => { const { ringsMinMax, ringsPresent, ringsVariation, rotationSpeed, ...prunedConfig @@ -274,7 +274,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca // before declaring the lots "loaded" initially // run this when lots changes (after its initial run through the effect that follows this one) - useEffect(() => { + useEffect(import.meta.url, () => { if (lotResultMap && lotsByRegion.current?.length && positionsReady) { const results = []; Object.keys(lotsByRegion.current).forEach((region) => { @@ -285,7 +285,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca } }, [lotResultMap, lastLotUpdate, positionsReady]); - const handleWSMessage = useCallback((message) => { + const handleWSMessage = useCallback(import.meta.url, (message) => { if (process.env.NODE_ENV !== 'production') console.log('onWSMessage (lots)', message); const { type: eventType, body } = message; @@ -337,7 +337,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca }, [processEvent]); - useEffect(() => { + useEffect(import.meta.url, () => { if (token && wsReady) { const regId = registerMessageHandler(handleWSMessage, `Asteroid::${asteroidId}`); return () => { @@ -360,7 +360,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca // listen for click events // NOTE: if just use onclick, then fires on drag events too :( - useEffect(() => { + useEffect(import.meta.url, () => { const onMouseEvent = function (e) { if (e.type === 'pointerdown') { clickStatus.current = new Vector2(e.clientX, e.clientY); @@ -389,7 +389,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca }, []); // Instantiate (invisible) mouseable mesh (behind all pips) - useEffect(() => { + useEffect(import.meta.url, () => { if (!visibleLotTally) return; const mouseableGeometry = new CircleGeometry(MOUSEABLE_WIDTH, 6); @@ -413,7 +413,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca }, [attachTo, visibleLotTally]); // eslint-disable-line react-hooks/exhaustive-deps // Lot meshes - useEffect(() => { + useEffect(import.meta.url, () => { if (!visibleResultTally && texturesLoaded) return; const materialOpts = { @@ -454,7 +454,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca }, [attachTo, visibleResultTally, texturesLoaded, lotUseTallies]); // eslint-disable-line react-hooks/exhaustive-deps // Create mesh for my leases - useEffect(() => { + useEffect(import.meta.url, () => { if (!visibleLeasedTally) return; const leasedLotGeometry = new CircleGeometry(PLOT_WIDTH * 2.6, 32); @@ -480,7 +480,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca }, [attachTo, visibleLeasedTally, PLOT_WIDTH]); // instantiate mouse mesh - useEffect(() => { + useEffect(import.meta.url, () => { mouseHoverMesh.current = new Mesh( new PlaneGeometry(RETICULE_WIDTH, RETICULE_WIDTH), new MeshBasicMaterial({ @@ -503,7 +503,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca }, [attachTo]); // eslint-disable-line react-hooks/exhaustive-deps // Instantiate selection mesh - useEffect(() => { + useEffect(import.meta.url, () => { selectionMesh.current = new Mesh( new PlaneGeometry(RETICULE_WIDTH, RETICULE_WIDTH), new MeshBasicMaterial({ @@ -524,8 +524,8 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca }; }, [attachTo]); // eslint-disable-line react-hooks/exhaustive-deps - const lotScale = useMemo(() => Math.max(1, Math.sqrt(cameraAltitude / 10000)), [cameraAltitude]); - const lotsReady = useMemo(() => { + const lotScale = useMemo(import.meta.url, () => Math.max(1, Math.sqrt(cameraAltitude / 10000)), [cameraAltitude]); + const lotsReady = useMemo(import.meta.url, () => { return !isLoading && !!lotResultMap && meshesInitialized && @@ -541,7 +541,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca resultsByRegion ]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!lotsReady) return; try { @@ -694,7 +694,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca resultsByRegion ]); - const highlightLot = useCallback((lotIndex) => { + const highlightLot = useCallback(import.meta.url, (lotIndex) => { if (!attachTo) return; highlighted.current = null; @@ -725,13 +725,13 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca }, [attachTo?.quaternion, selectedLotIndex]); // Calculates the control point for the delivery bezier curve - const calculateControlPoint = useCallback((origin, dest, distance, frac = 0.5) => { + const calculateControlPoint = useCallback(import.meta.url, (origin, dest, distance, frac = 0.5) => { const ratio = 1 + Math.pow(distance / config.radius, 2); return origin.clone().lerp(dest, frac).multiplyScalar(Math.min(ratio, 3.5)); }, [config]); // Handle turning on and off delivery arcs when a lot is selected - useEffect(() => { + useEffect(import.meta.url, () => { const newDeliveries = []; const material = new ShaderMaterial({ uniforms: deliveryUniforms.current, @@ -808,7 +808,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca }, [attachTo, selectedLotIndex, deliveryEndpoint, inboundDeliveries, outboundDeliveries]); const selectionAnimationTime = useRef(0); - useEffect(() => { + useEffect(import.meta.url, () => { if (!attachTo) return; if (selectionMesh.current && positions.current && positionsReady && selectedLotIndex) { @@ -839,7 +839,7 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca // when camera angle changes, sort all regions by closest, then display // up to max lots (ordered by region proximity) // NOTE: attempted to throttle this and wasn't catching any calculations even on huge, so pulled it out - useEffect(() => { + useEffect(import.meta.url, () => { if (cameraNormalized?.string && regionTally > 1) { processInBackground( { @@ -859,12 +859,12 @@ const Lots = ({ attachTo: overrideAttachTo, asteroidId, axis, cameraAltitude, ca // eslint-disable-next-line react-hooks/exhaustive-deps }, [cameraNormalized?.string, regionsByDistance?.length, regionTally]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!lastClick) return; dispatchLotSelected(Lot.toId(asteroidId, highlighted.current)); }, [lastClick]); - const mouseThrottleTime = useMemo(() => MOUSE_THROTTLE_TIME / (TIME_ACCELERATION / 24), [TIME_ACCELERATION]); + const mouseThrottleTime = useMemo(import.meta.url, () => MOUSE_THROTTLE_TIME / (TIME_ACCELERATION / 24), [TIME_ACCELERATION]); useFrame((state, delta) => { selectionAnimationTime.current = (selectionAnimationTime.current || 0) + delta; diff --git a/src/game/scene/asteroid/Rings.js b/src/game/scene/asteroid/Rings.js index 9ac5bdfd3..81e377451 100644 --- a/src/game/scene/asteroid/Rings.js +++ b/src/game/scene/asteroid/Rings.js @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useState } from '~/lib/react-debug'; import { Color, Vector3, @@ -15,7 +15,7 @@ const Rings = (props) => { const [ geometry, setGeometry ] = useState(); const [ texture, setTexture ] = useState(); - useEffect(() => { + useEffect(import.meta.url, () => { const size = 512; const data = new Uint8Array(size * size * 4); // 1 by 256 pixels const variation = config.ringsVariation; diff --git a/src/game/scene/asteroid/Telemetry.js b/src/game/scene/asteroid/Telemetry.js index 1786bff6d..5ef2a43f6 100644 --- a/src/game/scene/asteroid/Telemetry.js +++ b/src/game/scene/asteroid/Telemetry.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef } from 'react'; +import { useEffect, useMemo, useRef } from '~/lib/react-debug'; import { // AxesHelper, // BoxHelper, @@ -208,16 +208,16 @@ const Telemetry = ({ const helper = useRef(); const shipTime = useRef(); - const circleRadius = useMemo(() => TELEMETRY_SCALE * radius, [radius]); - const circleAttenuation = useMemo(() => Math.max(1.4, 0.75 * scaleHelper) * radius, [radius]); - const trajectoryAttenuation = useMemo(() => Math.max(10, 2 * scaleHelper) * radius, [radius]); - const shipAngularVelocity = useMemo(() => { + const circleRadius = useMemo(import.meta.url, () => TELEMETRY_SCALE * radius, [radius]); + const circleAttenuation = useMemo(import.meta.url, () => Math.max(1.4, 0.75 * scaleHelper) * radius, [radius]); + const trajectoryAttenuation = useMemo(import.meta.url, () => Math.max(10, 2 * scaleHelper) * radius, [radius]); + const shipAngularVelocity = useMemo(import.meta.url, () => { const shipHeight = TELEMETRY_SCALE * config.shipCircle.scale; const period = Math.sqrt(3 * Math.PI * shipHeight ** 3 / (densityByType[spectralType] * GRAV)); return 2 * Math.PI / period; }, [spectralType]); - useEffect(() => { + useEffect(import.meta.url, () => { const circleSegments = 360; const material = getLineMaterial(BLUE_GLSL, circleAttenuation, 0.7); @@ -524,7 +524,7 @@ const Telemetry = ({ if (trajectory.current) group.current.add(trajectory.current); }, [radius]); // eslint-disable-line react-hooks/exhaustive-deps - useEffect(() => { + useEffect(import.meta.url, () => { // TODO: update the number of ships on the ship circle (or dash if empty) }, [shipTally]); diff --git a/src/game/scene/asteroids/Marker.js b/src/game/scene/asteroids/Marker.js index 407672834..7153f44da 100644 --- a/src/game/scene/asteroids/Marker.js +++ b/src/game/scene/asteroids/Marker.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef, useState } from 'react'; +import { useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { useTexture } from '@react-three/drei'; import { AdditiveBlending, Color, DoubleSide, Vector2 } from 'three'; import { useFrame } from '@react-three/fiber'; @@ -39,11 +39,11 @@ const Marker = (props) => { `${process.env.PUBLIC_URL}/textures/marker.png` ]); - useEffect(() => { + useEffect(import.meta.url, () => { reticuleTexture.center = new Vector2(0.5, 0.5); }, [reticuleTexture]); - const { outerProps, innerProps, showInner, showReticule } = useMemo(() => { + const { outerProps, innerProps, showInner, showReticule } = useMemo(import.meta.url, () => { const x = { outerProps: { size: 35 }, innerProps: { color: orbitColors.white, size: 10 }, @@ -114,7 +114,7 @@ const Marker = (props) => { return x; }, [travelSolution]); - useEffect(() => { + useEffect(import.meta.url, () => { if (asteroidPos && asteroidPos.length > 0) { const newPoints = new Float32Array(2 * 3); newPoints.set(asteroidPos); diff --git a/src/game/scene/asteroids/Orbit.js b/src/game/scene/asteroids/Orbit.js index 653e0ed11..f49d7f41d 100644 --- a/src/game/scene/asteroids/Orbit.js +++ b/src/game/scene/asteroids/Orbit.js @@ -1,4 +1,4 @@ -import { useRef, useEffect, useState } from 'react'; +import { useRef, useEffect, useState } from '~/lib/react-debug'; import { useFrame } from '@react-three/fiber'; import { AdalianOrbit } from '@influenceth/sdk'; import { cloneDeep } from 'lodash'; @@ -24,7 +24,7 @@ const Orbit = ({ asteroid, color, opacityMult = 1, staticOpacity }) => { uCol: { type: 'c', value: orbitColors.main }, }); - useEffect(() => { + useEffect(import.meta.url, () => { const orbit = new AdalianOrbit(asteroid.Orbit, { units: 'km' }); let newPositions = []; orbit.getSmoothOrbit(360).forEach(p => { @@ -34,11 +34,11 @@ const Orbit = ({ asteroid, color, opacityMult = 1, staticOpacity }) => { setPositions(new Float32Array(newPositions)); }, [ asteroid ]); - useEffect(() => { + useEffect(import.meta.url, () => { uniforms.current.uCol.value = (color && orbitColors[color]) || orbitColors.main; }, [color]); - useEffect(() => { + useEffect(import.meta.url, () => { uniforms.current.uAlpha.value = Math.min(1, initialUniforms.uAlpha.value * opacityMult); uniforms.current.uAlphaMin.value = Math.min(1, initialUniforms.uAlphaMin.value * opacityMult); }, [opacityMult]); diff --git a/src/game/scene/asteroids/TravelSolution.js b/src/game/scene/asteroids/TravelSolution.js index b370a6027..7533d9b53 100644 --- a/src/game/scene/asteroids/TravelSolution.js +++ b/src/game/scene/asteroids/TravelSolution.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef, useState } from 'react'; +import { useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import styled from 'styled-components'; import { useFrame } from '@react-three/fiber'; import { Html } from '@react-three/drei'; @@ -79,13 +79,13 @@ const TravelSolution = ({}) => { const travelSolution = useStore(s => s.asteroids.travelSolution); const dispatchTravelSolution = useStore(s => s.dispatchTravelSolution); - useEffect(() => { + useEffect(import.meta.url, () => { if (!baseTime || !timeOverride?.speed || Math.abs(timeOverride.speed) <= 1) { setBaseTime(coarseTime); } }, [coarseTime, timeOverride?.speed]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!travelSolution) return; const exhaustBonus = getCrewAbilityBonuses(Crewmate.ABILITY_IDS.PROPELLANT_EXHAUST_VELOCITY, crew); @@ -113,7 +113,7 @@ const TravelSolution = ({}) => { } }, [baseTime, crew, destinationId, originId, timeOverride, travelSolution]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!travelSolution || !destination || !origin) { setPrearrival(); setPredeparture(); @@ -202,7 +202,7 @@ const TravelSolution = ({}) => { uniforms.current.uDash.value = true; }, [baseTime, travelSolution]); - const formattedTrajectoryLength = useMemo(() => { + const formattedTrajectoryLength = useMemo(import.meta.url, () => { if (!trajectoryLength) return ''; return formatBeltDistance(trajectoryLength); }, [trajectoryLength]); diff --git a/src/game/scene/planets/Orbit.js b/src/game/scene/planets/Orbit.js index f9d61d660..e21d8687a 100644 --- a/src/game/scene/planets/Orbit.js +++ b/src/game/scene/planets/Orbit.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef } from 'react'; +import { useEffect, useMemo, useRef } from '~/lib/react-debug'; import { AdalianOrbit } from '@influenceth/sdk'; import theme from '~/theme'; @@ -8,7 +8,7 @@ const Orbit = (props) => { const zoomStatus = useStore(s => s.asteroids.zoomStatus); const geometry = useRef(); - const positions = useMemo(() => { + const positions = useMemo(import.meta.url, () => { const vertices = []; const orbit = new AdalianOrbit(props.planet, { units: 'km' }); orbit.getSmoothOrbit(360).forEach(p => { @@ -19,7 +19,7 @@ const Orbit = (props) => { }, [props.planet]); // re-computeBoundingSphere on geometry change - useEffect(() => { + useEffect(import.meta.url, () => { if (geometry.current) { geometry.current.computeBoundingSphere(); } diff --git a/src/hooks/actionManagers/useAgreementManager.js b/src/hooks/actionManagers/useAgreementManager.js index 47c99b437..f8914baa1 100644 --- a/src/hooks/actionManagers/useAgreementManager.js +++ b/src/hooks/actionManagers/useAgreementManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity, Permission } from '@influenceth/sdk'; import { cloneDeep } from 'lodash'; @@ -13,7 +13,7 @@ const useAgreementManager = (target, permission, agreementPath) => { const { execute, getPendingTx } = useContext(ChainTransactionContext); const { currentPolicy } = usePolicyManager(target, permission); - const currentAgreement = useMemo(() => { + const currentAgreement = useMemo(import.meta.url, () => { const agreement = (currentPolicy?.agreements || []).find((a) => { if (agreementPath) return getAgreementPath(target, permission, a.permitted) === agreementPath; return ( @@ -36,7 +36,7 @@ const useAgreementManager = (target, permission, agreementPath) => { return null; }, [agreementPath, crew?.id, currentPolicy, target, permission]); - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ target: { id: target?.id, label: target?.label }, permission, // NOTE: this does not currently support account-level `permitted` values because that is @@ -45,12 +45,12 @@ const useAgreementManager = (target, permission, agreementPath) => { caller_crew: { id: crew?.id, label: Entity.IDS.CREW }, }), [crew?.id, currentAgreement, target, permission]); - const meta = useMemo(() => ({ + const meta = useMemo(import.meta.url, () => ({ lotId: target?.Location?.locations?.find((l) => l.label === Entity.IDS.LOT)?.id, shipId: target?.label === Entity.IDS.SHIP ? target?.id : undefined, }), [target]); - const enterAgreement = useCallback((details = {}) => { + const enterAgreement = useCallback(import.meta.url, (details = {}) => { const agreementSystem = currentPolicy.policyType === Permission.POLICY_IDS.PREPAID ? 'AcceptPrepaidAgreement' : 'AcceptContractAgreement'; @@ -62,7 +62,7 @@ const useAgreementManager = (target, permission, agreementPath) => { ); }, [currentPolicy, meta, payload]); - const extendAgreement = useCallback((details = {}) => { + const extendAgreement = useCallback(import.meta.url, (details = {}) => { const { term, ...params } = details; execute( 'ExtendPrepaidAgreement', @@ -71,7 +71,7 @@ const useAgreementManager = (target, permission, agreementPath) => { ); }, [meta, payload]); - const cancelAgreement = useCallback((params = {}) => { + const cancelAgreement = useCallback(import.meta.url, (params = {}) => { execute( 'CancelPrepaidAgreement', { agreementPath, ...params, ...payload }, @@ -79,7 +79,7 @@ const useAgreementManager = (target, permission, agreementPath) => { ); }, [agreementPath]); - const pendingChange = useMemo( + const pendingChange = useMemo(import.meta.url, () => { if (getPendingTx) { return getPendingTx('AcceptPrepaidAgreement', { ...payload }) diff --git a/src/hooks/actionManagers/useAnnotationManager.js b/src/hooks/actionManagers/useAnnotationManager.js index fc14e82b3..a1b909c94 100644 --- a/src/hooks/actionManagers/useAnnotationManager.js +++ b/src/hooks/actionManagers/useAnnotationManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo, useState } from 'react'; +import { useCallback, useContext, useMemo, useState } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -20,13 +20,13 @@ const useAnnotationManager = (activity, metaEntity) => { const [saving, setSaving] = useState(); - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ transaction_hash: activity?.event?.transactionHash, log_index: activity?.event?.logIndex, caller_crew: { id: crewId, label: Entity.IDS.CREW } }), [activity]); - const saveAnnotation = useCallback( + const saveAnnotation = useCallback(import.meta.url, async (content) => { setSaving(true); @@ -50,7 +50,7 @@ const useAnnotationManager = (activity, metaEntity) => { [execute, metaEntity, payload] ); - const status = useMemo( + const status = useMemo(import.meta.url, () => getStatus('AnnotateEvent', { ...payload }), [getStatus, payload] ); diff --git a/src/hooks/actionManagers/useBuyAsteroid.js b/src/hooks/actionManagers/useBuyAsteroid.js index 1166a4512..0d40d5b6d 100644 --- a/src/hooks/actionManagers/useBuyAsteroid.js +++ b/src/hooks/actionManagers/useBuyAsteroid.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -17,7 +17,7 @@ const useBuyAsteroid = (id) => { const system = asteroid?.AsteroidProof?.used ? 'PurchaseAsteroid' : 'InitializeAndPurchaseAsteroid'; - const buyAsteroid = useCallback(() => { + const buyAsteroid = useCallback(import.meta.url, () => { // caller_crew is optional here b/c may not exist yet return execute( system, @@ -28,7 +28,7 @@ const useBuyAsteroid = (id) => { ); }, [execute, system, asteroid, crew]); - const checkForLimit = useCallback(async () => { + const checkForLimit = useCallback(import.meta.url, async () => { const saleData = (await api.getAsteroidSale()) || {}; // jit check const currentPeriod = Math.floor(blockTime / 1000 / 1000000); const volume = Number(saleData.volume) || 0; @@ -61,7 +61,7 @@ const useBuyAsteroid = (id) => { return false; }, []); - const status = useMemo( + const status = useMemo(import.meta.url, () => getStatus(system, { asteroid }), [getStatus, system, asteroid] ); diff --git a/src/hooks/actionManagers/useChangeName.js b/src/hooks/actionManagers/useChangeName.js index 1871ce67e..19ef9baf9 100644 --- a/src/hooks/actionManagers/useChangeName.js +++ b/src/hooks/actionManagers/useChangeName.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -8,14 +8,14 @@ const useChangeName = (entity) => { const { crew } = useCrewContext(); const { execute, getStatus } = useContext(ChainTransactionContext); - const caller_crew = useMemo(() => ({ id: crew?.id, label: Entity.IDS.CREW }), [crew?.id]); + const caller_crew = useMemo(import.meta.url, () => ({ id: crew?.id, label: Entity.IDS.CREW }), [crew?.id]); - const changeName = useCallback( + const changeName = useCallback(import.meta.url, (name) => execute('ChangeName', { entity, name, caller_crew }), [execute, entity, caller_crew] ); - const status = useMemo( + const status = useMemo(import.meta.url, () => getStatus('ChangeName', { entity }), [getStatus, entity] ); diff --git a/src/hooks/actionManagers/useConstructionManager.js b/src/hooks/actionManagers/useConstructionManager.js index 058695824..ea2ff28a7 100644 --- a/src/hooks/actionManagers/useConstructionManager.js +++ b/src/hooks/actionManagers/useConstructionManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Asteroid, Building, Entity, Lot } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -16,16 +16,16 @@ const useConstructionManager = (lotId) => { const { crew } = useCrewContext(); const { data: lot } = useLot(lotId); - const asteroidId = useMemo(() => Lot.toPosition(lotId)?.asteroidId, [lotId]); + const asteroidId = useMemo(import.meta.url, () => Lot.toPosition(lotId)?.asteroidId, [lotId]); const { data: asteroid } = useAsteroid(asteroidId); const buildingId = lot?.building?.id; - const planPayload = useMemo(() => ({ + const planPayload = useMemo(import.meta.url, () => ({ lot: { id: lotId, label: Entity.IDS.LOT }, caller_crew: { id: crew?.id, label: Entity.IDS.CREW } }), [lotId, crew?.id]); - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ building: { id: buildingId, label: Entity.IDS.BUILDING }, caller_crew: { id: crew?.id, label: Entity.IDS.CREW } }), [buildingId, crew?.id]); @@ -33,7 +33,7 @@ const useConstructionManager = (lotId) => { // UNBUILDABLE (before asteroid is scanned) // READY_TO_PLAN > PLANNING > PLANNED > UNDER_CONSTRUCTION > READY_TO_FINISH > FINISHING > OPERATIONAL // < CANCELING < < DECONSTRUCTING < - const [currentConstructionAction, constructionStatus, isAtRisk, stageByActivity] = useMemo(() => { + const [currentConstructionAction, constructionStatus, isAtRisk, stageByActivity] = useMemo(import.meta.url, () => { let current = { _cachedData: null, _isAccessible: true, @@ -141,9 +141,9 @@ const useConstructionManager = (lotId) => { ]; }, [actionItems, asteroid, readyItems, getPendingTx, getStatus, payload, planPayload, lot?.building]); - const txMeta = useMemo(() => ({ asteroidId, lotId }), [asteroidId, lotId]); + const txMeta = useMemo(import.meta.url, () => ({ asteroidId, lotId }), [asteroidId, lotId]); - const planConstruction = useCallback((buildingType) => { + const planConstruction = useCallback(import.meta.url, (buildingType) => { execute( 'ConstructionPlan', { @@ -153,7 +153,7 @@ const useConstructionManager = (lotId) => { ) }, [planPayload]); - const unplanConstruction = useCallback(() => { + const unplanConstruction = useCallback(import.meta.url, () => { execute( 'ConstructionAbandon', payload, @@ -161,15 +161,15 @@ const useConstructionManager = (lotId) => { ) }, [payload]); - const startConstruction = useCallback(() => { + const startConstruction = useCallback(import.meta.url, () => { execute('ConstructionStart', payload, txMeta) }, [payload]); - const finishConstruction = useCallback(() => { + const finishConstruction = useCallback(import.meta.url, () => { execute('ConstructionFinish', payload, txMeta) }, [payload]); - const deconstruct = useCallback(() => { + const deconstruct = useCallback(import.meta.url, () => { execute( 'ConstructionDeconstruct', payload, diff --git a/src/hooks/actionManagers/useControlAsteroid.js b/src/hooks/actionManagers/useControlAsteroid.js index ef4b880bc..0830540ba 100644 --- a/src/hooks/actionManagers/useControlAsteroid.js +++ b/src/hooks/actionManagers/useControlAsteroid.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; import useAsteroid from '~/hooks/useAsteroid'; @@ -11,12 +11,12 @@ const useControlAsteroid = (id) => { const system = asteroid?.AsteroidProof?.used ? 'ManageAsteroid' : 'InitializeAndManageAsteroid'; - const controlAsteroid = useCallback( + const controlAsteroid = useCallback(import.meta.url, () => execute(system, { asteroid, caller_crew }), [execute, asteroid, caller_crew, system] ); - const status = useMemo( + const status = useMemo(import.meta.url, () => getStatus(system, { asteroid, caller_crew }), [getStatus, asteroid, caller_crew, system] ); diff --git a/src/hooks/actionManagers/useControlShip.js b/src/hooks/actionManagers/useControlShip.js index daef2c828..d5a56609d 100644 --- a/src/hooks/actionManagers/useControlShip.js +++ b/src/hooks/actionManagers/useControlShip.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; import useShip from '~/hooks/useShip'; @@ -10,12 +10,12 @@ const useControlShip = (id) => { const { data: ship } = useShip(id); const { crew: caller_crew } = useCrewContext(); - const controlShip = useCallback( + const controlShip = useCallback(import.meta.url, () => execute('CommandeerShip', { ship, caller_crew }), [execute, ship, caller_crew] ); - const status = useMemo( + const status = useMemo(import.meta.url, () => getStatus('CommandeerShip', { ship, caller_crew }), [getStatus, ship, caller_crew] ); diff --git a/src/hooks/actionManagers/useCoreSampleManager.js b/src/hooks/actionManagers/useCoreSampleManager.js index 5fdce8f2a..df9dcf97c 100644 --- a/src/hooks/actionManagers/useCoreSampleManager.js +++ b/src/hooks/actionManagers/useCoreSampleManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useMemo, useState } from 'react'; +import { useCallback, useContext, useEffect, useMemo, useState } from '~/lib/react-debug'; import { Deposit, Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -16,14 +16,14 @@ const useCoreSampleManager = (lotId) => { const { data: lot } = useLot(lotId); // * only used by SampleDepositStart contract, but used for equality check on others - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ lot: { id: lotId, label: Entity.IDS.LOT }, caller_crew: { id: crew?.id, label: Entity.IDS.CREW } }), [lotId]); const [completingSamples, setCompletingSamples] = useState([]); - const [currentSamplings, completedSamplings, currentSamplingsVersion] = useMemo(() => { + const [currentSamplings, completedSamplings, currentSamplingsVersion] = useMemo(import.meta.url, () => { const template = { _cachedData: null, finishTime: null, @@ -157,7 +157,7 @@ const useCoreSampleManager = (lotId) => { ]; }, [actionItems, blockTime, completingSamples, pendingTransactions, readyItems, getPendingTx, getStatus, payload, lot?.deposits]); - const startSampling = useCallback((resourceId, coreDrillSource) => { + const startSampling = useCallback(import.meta.url, (resourceId, coreDrillSource) => { // console.log('coreDrillSource', coreDrillSource); return; execute('SampleDepositStart', { resource: resourceId, @@ -167,7 +167,7 @@ const useCoreSampleManager = (lotId) => { }) }, [payload]); - const startImproving = useCallback((depositId, coreDrillSource, depositOwnerCrew) => { + const startImproving = useCallback(import.meta.url, (depositId, coreDrillSource, depositOwnerCrew) => { const sample = (lot?.deposits || []).find((c) => c.id === depositId); execute( depositOwnerCrew ? 'PurchaseDepositAndImprove' : 'SampleDepositImprove', @@ -186,7 +186,7 @@ const useCoreSampleManager = (lotId) => { ) }, [lotId, payload]); - const finishSampling = useCallback((sampleId) => { + const finishSampling = useCallback(import.meta.url, (sampleId) => { const selectedAction = currentSamplings.find((c) => c.action?.sampleId === sampleId); if (!selectedAction) return; execute( diff --git a/src/hooks/actionManagers/useCrewManager.js b/src/hooks/actionManagers/useCrewManager.js index a774eaa1b..edc953c37 100644 --- a/src/hooks/actionManagers/useCrewManager.js +++ b/src/hooks/actionManagers/useCrewManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext } from 'react'; +import { useCallback, useContext } from '~/lib/react-debug'; import { Crewmate, Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -9,16 +9,16 @@ const useCrewManager = () => { const { accountAddress } = useSession(); const { execute, getPendingTx } = useContext(ChainTransactionContext); - const changeActiveCrew = useCallback( + const changeActiveCrew = useCallback(import.meta.url, (params) => execute('SET_ACTIVE_CREW', params), [execute] ); - const getPendingActiveCrewChange = useCallback( + const getPendingActiveCrewChange = useCallback(import.meta.url, (params) => getPendingTx('SET_ACTIVE_CREW', params), [getPendingTx] ); - const purchaseCredits = useCallback((tally) => { + const purchaseCredits = useCallback(import.meta.url, (tally) => { for (let i = 0; i < tally; i++) fireTrackingEvent('purchase', { category: 'purchase', currency: 'USD', @@ -32,11 +32,11 @@ const useCrewManager = () => { execute('BulkPurchaseAdalians', { collection: Crewmate.COLLECTION_IDS.ADALIAN, tally }); }, [accountAddress, execute]); - const getPendingCreditPurchase = useCallback(() => { + const getPendingCreditPurchase = useCallback(import.meta.url, () => { return getPendingTx('BulkPurchaseAdalians', {}); }, [getPendingTx]); - const purchaseAndOrInitializeCrewmate = useCallback( + const purchaseAndOrInitializeCrewmate = useCallback(import.meta.url, ({ crewmate }) => { if (crewmate.Crewmate.coll !== Crewmate.COLLECTION_IDS.ADALIAN) { execute('InitializeArvadian', { @@ -80,7 +80,7 @@ const useCrewManager = () => { [accountAddress, execute] ); - const getPendingCrewmate = useCallback( + const getPendingCrewmate = useCallback(import.meta.url, () => getPendingTx('InitializeArvadian', {}) || getPendingTx('RecruitAdalian', {}), [getPendingTx] ); diff --git a/src/hooks/actionManagers/useCrewSwapManager.js b/src/hooks/actionManagers/useCrewSwapManager.js index 655865e3e..3d89f7a14 100644 --- a/src/hooks/actionManagers/useCrewSwapManager.js +++ b/src/hooks/actionManagers/useCrewSwapManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -9,14 +9,14 @@ const useCrewSwapManager = (props) => { const { crew } = useCrewContext(); const { execute, getPendingTx } = useContext(ChainTransactionContext); - const reorderRoster = useCallback(({ crewId, newRoster }) => { + const reorderRoster = useCallback(import.meta.url, ({ crewId, newRoster }) => { execute('ArrangeCrew', { composition: newRoster, caller_crew: { id: crewId, label: Entity.IDS.CREW }, }) }, []); - const swapCrewmates = useCallback(({ crewId1, newRoster1, crewId2, newRoster2 }) => { + const swapCrewmates = useCallback(import.meta.url, ({ crewId1, newRoster1, crewId2, newRoster2 }) => { execute('ExchangeCrew', { crew1: { id: crewId1, label: Entity.IDS.CREW }, comp1: newRoster1, @@ -25,7 +25,7 @@ const useCrewSwapManager = (props) => { }) }, []); - const getPendingChange = useCallback( + const getPendingChange = useCallback(import.meta.url, () => { return getPendingTx('ArrangeCrew', { caller_crew: { id: crew?.id, label: Entity.IDS.CREW } }) || getPendingTx('ExchangeCrew', {}); @@ -33,7 +33,7 @@ const useCrewSwapManager = (props) => { [crew?.id, getPendingTx] ); - const actionStage = useMemo(() => { + const actionStage = useMemo(import.meta.url, () => { return getPendingChange() ? actionStages.COMPLETING : actionStages.NOT_STARTED }, [getPendingChange]); diff --git a/src/hooks/actionManagers/useDeliveryManager.js b/src/hooks/actionManagers/useDeliveryManager.js index b61f38602..d08c0b089 100644 --- a/src/hooks/actionManagers/useDeliveryManager.js +++ b/src/hooks/actionManagers/useDeliveryManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Delivery, Entity, Permission } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -34,7 +34,7 @@ const useDeliveryManager = ({ destination, destinationSlot, origin, originSlot, const { data: destActionItems } = useUnresolvedActivities(destination || deliveryById?.Delivery?.destination); const { data: origActionItems } = useUnresolvedActivities(origin || deliveryById?.Delivery?.origin); - const actionItems = useMemo(() => { + const actionItems = useMemo(import.meta.url, () => { const deliveryIds = []; return [ ...(destActionItems || []), @@ -49,7 +49,7 @@ const useDeliveryManager = ({ destination, destinationSlot, origin, originSlot, }, []) }, [destActionItems, origActionItems]); - const [deliveries, isLoading] = useMemo(() => { + const [deliveries, isLoading] = useMemo(import.meta.url, () => { if (deliveryId) { return [ deliveryIsLoading @@ -64,11 +64,11 @@ const useDeliveryManager = ({ destination, destinationSlot, origin, originSlot, ]; }, [deliveryId, deliveryById, deliveryIsLoading, deliveriesByLoc, deliveriesIsLoading]); - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ caller_crew: { id: crew?.id, label: Entity.IDS.CREW } }), [crew?.id]); - const pendingDeliveries = useMemo(() => { + const pendingDeliveries = useMemo(import.meta.url, () => { return pendingTransactions.filter(({ key, vars, ...pendingProps }) => (txHash && txHash === pendingProps.txHash) || ( (key === 'SendDelivery' || key === 'PackageDelivery') && ( @@ -80,7 +80,7 @@ const useDeliveryManager = ({ destination, destinationSlot, origin, originSlot, )); }, [destination, destinationSlot, origin, originSlot, pendingTransactions, txHash]); - const [currentDeliveries, currentDeliveriesVersion] = useMemo(() => { + const [currentDeliveries, currentDeliveriesVersion] = useMemo(import.meta.url, () => { const active = [...(deliveries || [])]; // TODO: filter by crew // TODO: filter by incomplete @@ -202,7 +202,7 @@ const useDeliveryManager = ({ destination, destinationSlot, origin, originSlot, return [allDeliveries, Date.now()]; }, [actionItems, blockTime, crew?.id, crewCan, deliveries, pendingDeliveries, getStatus, payload]); - const acceptDelivery = useCallback((selectedDeliveryId, meta) => { + const acceptDelivery = useCallback(import.meta.url, (selectedDeliveryId, meta) => { const delivery = currentDeliveries.find((d) => d.action.deliveryId === (selectedDeliveryId || deliveryId)); if (!delivery?.action) return; execute( @@ -217,7 +217,7 @@ const useDeliveryManager = ({ destination, destinationSlot, origin, originSlot, ); }, [currentDeliveries, payload]); - const cancelDelivery = useCallback((selectedDeliveryId, meta) => { + const cancelDelivery = useCallback(import.meta.url, (selectedDeliveryId, meta) => { execute( 'CancelDelivery', { @@ -228,7 +228,7 @@ const useDeliveryManager = ({ destination, destinationSlot, origin, originSlot, ); }, [payload]); - const packageDelivery = useCallback(({ origin, originSlot, destination, destinationSlot, contents, price }, meta) => { + const packageDelivery = useCallback(import.meta.url, ({ origin, originSlot, destination, destinationSlot, contents, price }, meta) => { execute( 'PackageDelivery', { @@ -244,7 +244,7 @@ const useDeliveryManager = ({ destination, destinationSlot, origin, originSlot, ); }, [payload]); - const startDelivery = useCallback(({ origin, originSlot, destination, destinationSlot, contents }, meta) => { + const startDelivery = useCallback(import.meta.url, ({ origin, originSlot, destination, destinationSlot, contents }, meta) => { execute( 'SendDelivery', { @@ -259,7 +259,7 @@ const useDeliveryManager = ({ destination, destinationSlot, origin, originSlot, ); }, [payload]); - const finishDelivery = useCallback((selectedDeliveryId, meta) => { + const finishDelivery = useCallback(import.meta.url, (selectedDeliveryId, meta) => { execute( 'ReceiveDelivery', { diff --git a/src/hooks/actionManagers/useDepositSaleManager.js b/src/hooks/actionManagers/useDepositSaleManager.js index be0c1a091..0c70a6983 100644 --- a/src/hooks/actionManagers/useDepositSaleManager.js +++ b/src/hooks/actionManagers/useDepositSaleManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; import useCrewContext from '~/hooks/useCrewContext'; @@ -7,16 +7,16 @@ const useDepositSaleManager = (deposit) => { const { crew } = useCrewContext(); const { execute, getStatus } = useContext(ChainTransactionContext); - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ deposit: { id: deposit?.id, label: deposit?.label }, caller_crew: { id: crew?.id, label: crew?.label }, }), [crew, deposit]); - const meta = useMemo(() => ({ + const meta = useMemo(import.meta.url, () => ({ deposit }), [deposit]); - const purchaseListing = useCallback(() => { + const purchaseListing = useCallback(import.meta.url, () => { execute( 'PurchaseDeposit', payload, @@ -24,7 +24,7 @@ const useDepositSaleManager = (deposit) => { ) }, [execute, meta, payload]); - const updateListing = useCallback( + const updateListing = useCallback(import.meta.url, (price) => { if (price > 0) { execute( @@ -43,8 +43,8 @@ const useDepositSaleManager = (deposit) => { [execute, meta, payload] ); - const isPendingPurchase = useMemo(() => getStatus('PurchaseDeposit', payload) === 'pending', [getStatus, payload]); - const isPendingUpdate = useMemo(() => ( + const isPendingPurchase = useMemo(import.meta.url, () => getStatus('PurchaseDeposit', payload) === 'pending', [getStatus, payload]); + const isPendingUpdate = useMemo(import.meta.url, () => ( getStatus('ListDepositForSale', payload) === 'pending' || getStatus('UnlistDepositForSale', payload) === 'pending' ), [getStatus, payload]); diff --git a/src/hooks/actionManagers/useDryDockManager.js b/src/hooks/actionManagers/useDryDockManager.js index c3aebf456..6bc1a5f3b 100644 --- a/src/hooks/actionManagers/useDryDockManager.js +++ b/src/hooks/actionManagers/useDryDockManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { DryDock, Entity, Permission } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -15,17 +15,17 @@ const useDryDockManager = (lotId, slot = 1) => { const { data: lot } = useLot(lotId); const { data: actionItems } = useUnresolvedActivities(lot?.building); - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ dry_dock: { id: lot?.building?.id, label: Entity.IDS.BUILDING }, dry_dock_slot: slot, caller_crew: { id: crew?.id, label: Entity.IDS.CREW } }), [lot?.building, crew?.id, slot]); - const slotDryDock = useMemo(() => lot?.building?.DryDocks?.find((e) => e.slot === slot), [lot?.building, slot]); + const slotDryDock = useMemo(import.meta.url, () => lot?.building?.DryDocks?.find((e) => e.slot === slot), [lot?.building, slot]); // status flow // READY > ASSEMBLING > READY_TO_FINISH > FINISHING - const [currentAssembly, assemblyStatus, actionStage] = useMemo(() => { + const [currentAssembly, assemblyStatus, actionStage] = useMemo(import.meta.url, () => { let current = { _cachedData: null, _isAccessible: false, @@ -87,7 +87,7 @@ const useDryDockManager = (lotId, slot = 1) => { ]; }, [actionItems, blockTime, getPendingTx, getStatus, payload, slotDryDock?.status]); - const startShipAssembly = useCallback((shipType, origin, originSlot, leaseDetails) => { + const startShipAssembly = useCallback(import.meta.url, (shipType, origin, originSlot, leaseDetails) => { execute( leaseDetails ? 'LeaseAssembleShipStart' : 'AssembleShipStart', { @@ -103,7 +103,7 @@ const useDryDockManager = (lotId, slot = 1) => { ) }, [payload]); - const finishShipAssembly = useCallback((destination) => { + const finishShipAssembly = useCallback(import.meta.url, (destination) => { execute( 'AssembleShipFinish', { diff --git a/src/hooks/actionManagers/useEjectCrewManager.js b/src/hooks/actionManagers/useEjectCrewManager.js index 94e82956e..38c6e5d5c 100644 --- a/src/hooks/actionManagers/useEjectCrewManager.js +++ b/src/hooks/actionManagers/useEjectCrewManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -16,7 +16,7 @@ const useEjectCrewManager = (originEntity) => { const { data: origin } = useEntity(originEntity); const { data: originCrews } = useStationedCrews(origin); - const currentEjections = useMemo(() => { + const currentEjections = useMemo(import.meta.url, () => { return pendingTransactions .filter((tx) => { if (tx.key === 'EjectCrew') { @@ -25,7 +25,7 @@ const useEjectCrewManager = (originEntity) => { }); }, [originCrews, pendingTransactions]); - const ejectCrew = useCallback( + const ejectCrew = useCallback(import.meta.url, (id) => { return execute( 'EjectCrew', diff --git a/src/hooks/actionManagers/useExtractionManager.js b/src/hooks/actionManagers/useExtractionManager.js index 8dce0d955..df1d0ce90 100644 --- a/src/hooks/actionManagers/useExtractionManager.js +++ b/src/hooks/actionManagers/useExtractionManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity, Extractor, Permission } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -17,17 +17,17 @@ const useExtractionManager = (lotId, slot = 1) => { const { data: lot } = useLot(lotId); const { data: actionItems } = useUnresolvedActivities(lot?.building); - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ extractor: { id: lot?.building?.id, label: Entity.IDS.BUILDING }, extractor_slot: slot, caller_crew: { id: crew?.id, label: Entity.IDS.CREW } }), [lot?.building, crew?.id, slot]); - const slotExtractor = useMemo(() => lot?.building?.Extractors?.find((e) => e.slot === slot), [lot?.building, slot]); + const slotExtractor = useMemo(import.meta.url, () => lot?.building?.Extractors?.find((e) => e.slot === slot), [lot?.building, slot]); // status flow // READY > EXTRACTING > READY_TO_FINISH > FINISHING - const [currentExtraction, extractionStatus, actionStage] = useMemo(() => { + const [currentExtraction, extractionStatus, actionStage] = useMemo(import.meta.url, () => { let current = { _cachedData: null, _isAccessible: false, @@ -98,7 +98,7 @@ const useExtractionManager = (lotId, slot = 1) => { ]; }, [actionItems, blockTime, crew?.id, crewCan, getPendingTx, getStatus, payload, slotExtractor?.status]); - const startExtraction = useCallback((amount, deposit, destination, destinationSlot, depositRecipient, lease) => { + const startExtraction = useCallback(import.meta.url, (amount, deposit, destination, destinationSlot, depositRecipient, lease) => { execute( 'FlexibleExtractResourceStart', { @@ -120,7 +120,7 @@ const useExtractionManager = (lotId, slot = 1) => { ) }, [payload]); - const finishExtraction = useCallback(() => { + const finishExtraction = useCallback(import.meta.url, () => { execute('ExtractResourceFinish', payload, { lotId }); }, [payload]); diff --git a/src/hooks/actionManagers/useFeedCrewManager.js b/src/hooks/actionManagers/useFeedCrewManager.js index dd4ab2c69..2dd18adad 100644 --- a/src/hooks/actionManagers/useFeedCrewManager.js +++ b/src/hooks/actionManagers/useFeedCrewManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -9,9 +9,9 @@ const useFeedCrewManager = () => { const { crew, isLoading } = useCrewContext(); const { execute, getPendingTx } = useContext(ChainTransactionContext); - const caller_crew = useMemo(() => ({ id: crew?.id, label: Entity.IDS.CREW }), [crew?.id]); + const caller_crew = useMemo(import.meta.url, () => ({ id: crew?.id, label: Entity.IDS.CREW }), [crew?.id]); - const feedCrew = useCallback( + const feedCrew = useCallback(import.meta.url, ({ origin, originSlot, amount, _orderPath, ...fillProps }) => { if (_orderPath) { execute('ResupplyFoodFromExchange', { @@ -39,7 +39,7 @@ const useFeedCrewManager = () => { [execute, caller_crew] ); - const currentFeeding = useMemo( + const currentFeeding = useMemo(import.meta.url, () => { if (getPendingTx) { return getPendingTx('ResupplyFood', { caller_crew }) diff --git a/src/hooks/actionManagers/useJettisonCargoManager.js b/src/hooks/actionManagers/useJettisonCargoManager.js index 82bc03532..89a60ab31 100644 --- a/src/hooks/actionManagers/useJettisonCargoManager.js +++ b/src/hooks/actionManagers/useJettisonCargoManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -9,12 +9,12 @@ const useJettisonCargoManager = (origin) => { const { crew, isLoading } = useCrewContext(); const { execute, getPendingTx } = useContext(ChainTransactionContext); - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ origin: { id: origin?.id, label: origin?.label }, caller_crew: { id: crew?.id, label: Entity.IDS.CREW } }), [crew?.id, origin]) - const jettisonCargo = useCallback( + const jettisonCargo = useCallback(import.meta.url, (originSlot, products, meta) => { if (payload.origin?.id && payload.caller_crew?.id) { execute('DumpDelivery', { @@ -27,7 +27,7 @@ const useJettisonCargoManager = (origin) => { [payload] ); - const currentJettison = useMemo( + const currentJettison = useMemo(import.meta.url, () => getPendingTx ? getPendingTx('DumpDelivery', { ...payload }) : null, [getPendingTx, payload] ); diff --git a/src/hooks/actionManagers/useMarketplaceAdmin.js b/src/hooks/actionManagers/useMarketplaceAdmin.js index e677fe038..c5d5c32e4 100644 --- a/src/hooks/actionManagers/useMarketplaceAdmin.js +++ b/src/hooks/actionManagers/useMarketplaceAdmin.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -10,12 +10,12 @@ const useMarketplaceAdmin = (buildingId) => { const { execute, getStatus } = useContext(ChainTransactionContext); const { data: building } = useEntity({ id: buildingId, label: Entity.IDS.BUILDING }); - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ exchange: { id: buildingId, label: Entity.IDS.BUILDING }, caller_crew: { id: crew?.id, label: Entity.IDS.CREW } }), [crew?.id, buildingId]); - const changeSettings = useCallback( + const changeSettings = useCallback(import.meta.url, ({ makerFee, takerFee, allowedProducts }) => execute( 'ConfigureExchange', { @@ -31,7 +31,7 @@ const useMarketplaceAdmin = (buildingId) => { [building, execute, payload] ); - const status = useMemo( + const status = useMemo(import.meta.url, () => getStatus('ConfigureExchange', { ...payload }), [getStatus, payload] ); diff --git a/src/hooks/actionManagers/useMarketplaceManager.js b/src/hooks/actionManagers/useMarketplaceManager.js index 88e487a00..a8c6e4a04 100644 --- a/src/hooks/actionManagers/useMarketplaceManager.js +++ b/src/hooks/actionManagers/useMarketplaceManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity, Order } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -15,12 +15,12 @@ const useMarketplaceManager = (buildingId) => { const { data: exchange } = useEntity({ id: buildingId, label: Entity.IDS.BUILDING }); const { data: exchangeController } = useHydratedCrew(exchange?.Control?.controller?.id); - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ exchange: { id: buildingId, label: Entity.IDS.BUILDING }, caller_crew: { id: crew?.id, label: Entity.IDS.CREW } }), [crew?.id, buildingId]); - const getPendingOrder = useCallback((mode, type, details) => { + const getPendingOrder = useCallback(import.meta.url, (mode, type, details) => { const keys = []; let locTest = () => true; if (mode === 'buy' && type === 'limit') { @@ -47,7 +47,7 @@ const useMarketplaceManager = (buildingId) => { )); }, [pendingTransactions]); - const createBuyOrder = useCallback( + const createBuyOrder = useCallback(import.meta.url, ({ product, amount, price, destination, destinationSlot, feeTotal }) => execute( 'EscrowDepositAndCreateBuyOrder', { @@ -66,7 +66,7 @@ const useMarketplaceManager = (buildingId) => { ), [crew, payload] ); - const createSellOrder = useCallback( + const createSellOrder = useCallback(import.meta.url, ({ product, amount, price, origin, originSlot }) => execute( 'CreateSellOrder', { @@ -84,7 +84,7 @@ const useMarketplaceManager = (buildingId) => { [exchange, payload] ); - const fillBuyOrders = useCallback( + const fillBuyOrders = useCallback(import.meta.url, ({ isCancellation, origin, originSlot, fillOrders }) => { if (!fillOrders?.length) return; @@ -120,7 +120,7 @@ const useMarketplaceManager = (buildingId) => { [exchangeController, payload] ); - const fillSellOrders = useCallback( + const fillSellOrders = useCallback(import.meta.url, async ({ destination, destinationSlot, fillOrders }) => { if (!fillOrders?.length) return; const sellerCrewIds = fillOrders.map((order) => order.crew?.id); @@ -155,7 +155,7 @@ const useMarketplaceManager = (buildingId) => { [exchangeController, payload] ); - const cancelBuyOrder = useCallback( + const cancelBuyOrder = useCallback(import.meta.url, ({ amount, buyer, price, product, destination, destinationSlot, initialCaller, makerFee }) => { fillBuyOrders({ isCancellation: true, @@ -181,7 +181,7 @@ const useMarketplaceManager = (buildingId) => { }, [fillBuyOrders] ); - const cancelSellOrder = useCallback( + const cancelSellOrder = useCallback(import.meta.url, ({ amount, seller, product, price, origin, originSlot }) => execute( 'CancelSellOrder', { diff --git a/src/hooks/actionManagers/useNftSaleManager.js b/src/hooks/actionManagers/useNftSaleManager.js index 169b81738..c75ee3e4b 100644 --- a/src/hooks/actionManagers/useNftSaleManager.js +++ b/src/hooks/actionManagers/useNftSaleManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -13,12 +13,12 @@ const useNftSaleManager = (entity) => { const { crew } = useCrewContext(); const { execute, getStatus } = useContext(ChainTransactionContext); - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ tokenAddress: tokens[entity?.label], tokenId: entity?.id }), [entity]); - const purchaseListing = useCallback(() => { + const purchaseListing = useCallback(import.meta.url, () => { execute( 'FillNftSellOrder', { @@ -31,7 +31,7 @@ const useNftSaleManager = (entity) => { ) }, [crew, execute, payload]); - const updateListing = useCallback( + const updateListing = useCallback(import.meta.url, (price) => { execute( 'SetNftSellOrder', @@ -44,8 +44,8 @@ const useNftSaleManager = (entity) => { [execute, payload, entity] ); - const isPendingPurchase = useMemo(() => getStatus('FillNftSellOrder', payload) === 'pending', [getStatus, payload]); - const isPendingUpdate = useMemo(() => getStatus('SetNftSellOrder', payload) === 'pending', [getStatus, payload]); + const isPendingPurchase = useMemo(import.meta.url, () => getStatus('FillNftSellOrder', payload) === 'pending', [getStatus, payload]); + const isPendingUpdate = useMemo(import.meta.url, () => getStatus('SetNftSellOrder', payload) === 'pending', [getStatus, payload]); return { isPendingPurchase, diff --git a/src/hooks/actionManagers/usePolicyManager.js b/src/hooks/actionManagers/usePolicyManager.js index 0544627ba..a9cc94db6 100644 --- a/src/hooks/actionManagers/usePolicyManager.js +++ b/src/hooks/actionManagers/usePolicyManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Address, Entity, Permission } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -11,24 +11,24 @@ const usePolicyManager = (target, permission) => { const { crew } = useCrewContext(); const { execute, getStatus } = useContext(ChainTransactionContext); - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ target: { id: target?.id, label: target?.label }, permission, caller_crew: { id: crew?.id, label: Entity.IDS.CREW }, }), [crew?.id, target, permission]); - const meta = useMemo(() => ({ + const meta = useMemo(import.meta.url, () => ({ asteroidId: target?.label === Entity.IDS.ASTEROID ? target?.id : undefined, lotId: (target?.Location?.locations || []).find((l) => l?.label === Entity.IDS.LOT)?.id, shipId: target?.label === Entity.IDS.SHIP ? target?.id : undefined, }), [target]); // using json to avoid unnecessary re-renders - const policyJSON = useMemo(() => { + const policyJSON = useMemo(import.meta.url, () => { return JSON.stringify(Permission.getPolicyDetails(target, crew, blockTime)[permission]); }, [blockTime, crew, target, permission]); - const currentPolicy = useMemo(() => { + const currentPolicy = useMemo(import.meta.url, () => { if (!target) return undefined; if (!policyJSON) return undefined; const pol = JSON.parse(policyJSON); @@ -46,7 +46,7 @@ const usePolicyManager = (target, permission) => { return pol; }, [policyJSON]); - const updateAllowlists = useCallback((newAllowlist, newAccountAllowlist) => { + const updateAllowlists = useCallback(import.meta.url, (newAllowlist, newAccountAllowlist) => { execute( 'UpdateAllowlists', { @@ -60,7 +60,7 @@ const usePolicyManager = (target, permission) => { ); }, [currentPolicy?.allowlist, currentPolicy?.accountAllowlist, meta, payload]); - const updatePolicy = useCallback( + const updatePolicy = useCallback(import.meta.url, (newPolicyType, newPolicyDetails) => { const params = { ...payload, @@ -86,11 +86,11 @@ const usePolicyManager = (target, permission) => { [currentPolicy, meta, payload] ); - const allowlistChangePending = useMemo( + const allowlistChangePending = useMemo(import.meta.url, () => (getStatus ? getStatus('updateAllowlists', { ...payload }) : 'ready') === 'pending', [payload, getStatus] ); - const policyChangePending = useMemo( + const policyChangePending = useMemo(import.meta.url, () => (getStatus ? getStatus('UpdatePolicy', { ...payload }) : 'ready') === 'pending', [payload, getStatus] ); diff --git a/src/hooks/actionManagers/useProcessManager.js b/src/hooks/actionManagers/useProcessManager.js index 781cd6ffd..d072fe5b4 100644 --- a/src/hooks/actionManagers/useProcessManager.js +++ b/src/hooks/actionManagers/useProcessManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity, Permission, Processor } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -15,17 +15,17 @@ const useProcessManager = (lotId, slot) => { const { data: lot } = useLot(lotId); const { data: actionItems } = useUnresolvedActivities(lot?.building); - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ processor: { id: lot?.building?.id, label: Entity.IDS.BUILDING }, processor_slot: slot, caller_crew: { id: crew?.id, label: Entity.IDS.CREW } }), [lot?.building, crew?.id, slot]); - const processor = useMemo(() => lot?.building?.Processors?.find((e) => e.slot === slot), [lot?.building, slot]); + const processor = useMemo(import.meta.url, () => lot?.building?.Processors?.find((e) => e.slot === slot), [lot?.building, slot]); // status flow // READY > PROCESSING > READY_TO_FINISH > FINISHING - const [currentProcess, processStatus, actionStage] = useMemo(() => { + const [currentProcess, processStatus, actionStage] = useMemo(import.meta.url, () => { let current = { _cachedData: null, _isAccessible: false, @@ -98,7 +98,7 @@ const useProcessManager = (lotId, slot) => { ]; }, [actionItems, blockTime, crew?.id, crewCan, getPendingTx, getStatus, payload, processor?.status]); - const startProcess = useCallback(({ processId, primaryOutputId, recipeTally, origin, originSlot, destination, destinationSlot, leaseDetails }) => { + const startProcess = useCallback(import.meta.url, ({ processId, primaryOutputId, recipeTally, origin, originSlot, destination, destinationSlot, leaseDetails }) => { execute( leaseDetails ? 'LeaseAndProcessProductsStart' : 'ProcessProductsStart', { @@ -118,7 +118,7 @@ const useProcessManager = (lotId, slot) => { ) }, [lotId, payload, processor?.processorType]); - const finishProcess = useCallback(() => { + const finishProcess = useCallback(import.meta.url, () => { execute('ProcessProductsFinish', payload, { lotId, process: processor?.runningProcess }); }, [lotId, payload, processor?.runningProcess]); diff --git a/src/hooks/actionManagers/useRepoManager.js b/src/hooks/actionManagers/useRepoManager.js index 4cf585e9f..e8c2ba5b6 100644 --- a/src/hooks/actionManagers/useRepoManager.js +++ b/src/hooks/actionManagers/useRepoManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -13,7 +13,7 @@ const useRepoManager = (lotId) => { const { isAtRisk } = useConstructionManager(lotId); const { data: lot } = useLot(lotId); - const takeoverType = useMemo(() => { + const takeoverType = useMemo(import.meta.url, () => { // if i'm not in control of the building... if (crew?.id !== lot?.building?.Control?.controller?.id) { // ... but i am in control of the lot, then i can takeover from squatter @@ -24,17 +24,17 @@ const useRepoManager = (lotId) => { return null; }, [crew?.id, isAtRisk, lot?.building?.Control?.controller?.id, lot?.Control?.controller?.id]); - const payload = useMemo(() => ({ + const payload = useMemo(import.meta.url, () => ({ building: { id: lot?.building?.id, label: Entity.IDS.BUILDING }, caller_crew: { id: crew?.id, label: Entity.IDS.CREW } }), [crew?.id, lot?.building?.id]); - const repoBuilding = useCallback( + const repoBuilding = useCallback(import.meta.url, () => execute('RepossessBuilding', payload, { lotId }), [execute, lotId, payload] ); - const currentRepo = useMemo( + const currentRepo = useMemo(import.meta.url, () => getPendingTx ? getPendingTx('RepossessBuilding', payload) : null, [getPendingTx, payload] ); diff --git a/src/hooks/actionManagers/useScanManager.js b/src/hooks/actionManagers/useScanManager.js index 9a7225765..a56b5c0ce 100644 --- a/src/hooks/actionManagers/useScanManager.js +++ b/src/hooks/actionManagers/useScanManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Asteroid } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -12,7 +12,7 @@ const useScanManager = (asteroid) => { const { execute, getStatus } = useContext(ChainTransactionContext); const { crew } = useCrewContext(); - const { scanType, startSystem, finishSystem, payload } = useMemo(() => { + const { scanType, startSystem, finishSystem, payload } = useMemo(import.meta.url, () => { const scanType = asteroid?.Celestial?.scanStatus < Asteroid.SCAN_STATUSES.SURFACE_SCANNED ? 'SURFACE' : 'RESOURCE'; const startSystem = scanType === 'RESOURCE' ? 'ScanResourcesStart' : (asteroid?.AsteroidProof?.used ? 'ScanSurfaceStart' : 'InitializeAndStartSurfaceScan'); return { @@ -26,7 +26,7 @@ const useScanManager = (asteroid) => { }; }, [asteroid, crew]); - const scanStatus = useMemo(() => { + const scanStatus = useMemo(import.meta.url, () => { if (asteroid?.Celestial) { if (scanType === 'SURFACE' && asteroid.Celestial?.scanStatus === Asteroid.SCAN_STATUSES.SURFACE_SCANNED) { return 'FINISHED'; @@ -51,12 +51,12 @@ const useScanManager = (asteroid) => { // eslint-disable-next-line react-hooks/exhaustive-deps }, [ asteroid, blockTime, getStatus, startSystem, finishSystem, payload, readyItems, scanType ]); - const startAsteroidScan = useCallback( + const startAsteroidScan = useCallback(import.meta.url, () => execute(startSystem, payload), [execute, startSystem, payload] ); - const finalizeAsteroidScan = useCallback( + const finalizeAsteroidScan = useCallback(import.meta.url, () => execute(finishSystem, payload), [execute, finishSystem, payload] ); diff --git a/src/hooks/actionManagers/useShipDockingManager.js b/src/hooks/actionManagers/useShipDockingManager.js index e40dc422d..f73e867c5 100644 --- a/src/hooks/actionManagers/useShipDockingManager.js +++ b/src/hooks/actionManagers/useShipDockingManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -11,9 +11,9 @@ const useShipDockingManager = (shipId) => { const { crew } = useCrewContext(); const { data: ship } = useShip(shipId); - const caller_crew = useMemo(() => ({ id: crew?.id, label: Entity.IDS.CREW }), [crew?.id]); + const caller_crew = useMemo(import.meta.url, () => ({ id: crew?.id, label: Entity.IDS.CREW }), [crew?.id]); - const undockShip = useCallback((hopperAssisted) => { + const undockShip = useCallback(import.meta.url, (hopperAssisted) => { execute( 'UndockShip', { @@ -28,7 +28,7 @@ const useShipDockingManager = (shipId) => { ); }, [caller_crew, ship]); - const dockShip = useCallback((destination, hopperAssisted, destLotId) => { + const dockShip = useCallback(import.meta.url, (destination, hopperAssisted, destLotId) => { execute( 'DockShip', { @@ -44,12 +44,12 @@ const useShipDockingManager = (shipId) => { ); }, [caller_crew]); - const currentDockingAction = useMemo( + const currentDockingAction = useMemo(import.meta.url, () => getPendingTx ? getPendingTx('DockShip', { caller_crew }) : null [caller_crew, getPendingTx] ); - const currentUndockingAction = useMemo( + const currentUndockingAction = useMemo(import.meta.url, () => getPendingTx ? getPendingTx('UndockShip', { caller_crew }) : null, [caller_crew, getPendingTx] ); diff --git a/src/hooks/actionManagers/useShipEmergencyManager.js b/src/hooks/actionManagers/useShipEmergencyManager.js index 4bc17889d..f888ab84b 100644 --- a/src/hooks/actionManagers/useShipEmergencyManager.js +++ b/src/hooks/actionManagers/useShipEmergencyManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -9,9 +9,9 @@ const useShipEmergencyManager = () => { const { execute, getStatus } = useContext(ChainTransactionContext); const { crew } = useCrewContext(); - const caller_crew = useMemo(() => ({ id: crew?.id, label: Entity.IDS.CREW }), [crew?.id]); + const caller_crew = useMemo(import.meta.url, () => ({ id: crew?.id, label: Entity.IDS.CREW }), [crew?.id]); - const activateEmergencyMode = useCallback(() => { + const activateEmergencyMode = useCallback(import.meta.url, () => { execute( 'ActivateEmergency', { caller_crew }, @@ -19,7 +19,7 @@ const useShipEmergencyManager = () => { ); }, [caller_crew]); - const deactivateEmergencyMode = useCallback(() => { + const deactivateEmergencyMode = useCallback(import.meta.url, () => { execute( 'DeactivateEmergency', { caller_crew }, @@ -27,7 +27,7 @@ const useShipEmergencyManager = () => { ); }, []); - const collectEmergencyPropellant = useCallback(() => { + const collectEmergencyPropellant = useCallback(import.meta.url, () => { execute( 'CollectEmergencyPropellant', { caller_crew }, @@ -35,15 +35,15 @@ const useShipEmergencyManager = () => { ); }, []); - const isActivating = useMemo( + const isActivating = useMemo(import.meta.url, () => getStatus('ActivateEmergency', { caller_crew }) === 'pending', [getStatus, caller_crew] ); - const isDeactivating = useMemo( + const isDeactivating = useMemo(import.meta.url, () => getStatus('DeactivateEmergency', { caller_crew }) === 'pending', [getStatus, caller_crew] ); - const isCollecting = useMemo( + const isCollecting = useMemo(import.meta.url, () => getStatus('CollectEmergencyPropellant', { caller_crew }) === 'pending', [getStatus, caller_crew] ); diff --git a/src/hooks/actionManagers/useShipTravelManager.js b/src/hooks/actionManagers/useShipTravelManager.js index 22f7e5876..909dba80c 100644 --- a/src/hooks/actionManagers/useShipTravelManager.js +++ b/src/hooks/actionManagers/useShipTravelManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useMemo, useState } from 'react'; +import { useCallback, useContext, useEffect, useMemo, useState } from '~/lib/react-debug'; import { lambert } from '@influenceth/astro'; import { GM_ADALIA, AdalianOrbit, Crewmate, Entity, Ship, Time } from '@influenceth/sdk'; import { Vector3 } from 'three'; @@ -26,12 +26,12 @@ const useShipTravelManager = (shipId) => { const [currentTravelSolution, setCurrentTravelSolution] = useState(); - const caller_crew = useMemo(() => { + const caller_crew = useMemo(import.meta.url, () => { return ship?.label === Entity.IDS.CREW ? ship : ship?.Control?.controller; }, [ship?.Control?.controller?.id]); // READY > DEPARTING > IN_FLIGHT > READY_TO_ARRIVE > ARRIVING - const [currentTravelAction, status, stage] = useMemo(() => { + const [currentTravelAction, status, stage] = useMemo(import.meta.url, () => { let current = { _cachedData: null, _isAccessible: true, @@ -96,15 +96,15 @@ const useShipTravelManager = (shipId) => { const shipConfig = Ship.TYPES[ship?.Ship?.shipType]; - const cargoInv = useMemo(() => { + const cargoInv = useMemo(import.meta.url, () => { return (ship?.Inventories || []).find(i => i.slot === shipConfig?.cargoSlot); }, [ship, shipConfig?.cargoSlot]); - const propellantInv = useMemo(() => { + const propellantInv = useMemo(import.meta.url, () => { return (ship?.Inventories || []).find(i => i.slot === shipConfig?.propellantSlot); }, [ship, shipConfig?.propellantSlot]); - useEffect(() => { + useEffect(import.meta.url, () => { setCurrentTravelSolution(); if (!origin || !destination || !propellantInv || !currentTravelAction) return; @@ -187,7 +187,7 @@ const useShipTravelManager = (shipId) => { shipUpdatedAt ]); - const depart = useCallback(() => { + const depart = useCallback(import.meta.url, () => { const { v1, v2, @@ -256,7 +256,7 @@ const useShipTravelManager = (shipId) => { ); }, [caller_crew, destination, proposedTravelSolution, shipId]); - const arrive = useCallback(() => { + const arrive = useCallback(import.meta.url, () => { execute( 'TransitBetweenFinish', { diff --git a/src/hooks/actionManagers/useStationCrewManager.js b/src/hooks/actionManagers/useStationCrewManager.js index 291b4ca4b..dc5f33c0f 100644 --- a/src/hooks/actionManagers/useStationCrewManager.js +++ b/src/hooks/actionManagers/useStationCrewManager.js @@ -1,4 +1,4 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; @@ -12,18 +12,18 @@ const useStationCrewManager = (destination) => { const { execute, getPendingTx } = useContext(ChainTransactionContext); const { data: destEntity } = useEntity(destination); - const destLotId = useMemo(() => { + const destLotId = useMemo(import.meta.url, () => { return locationsArrToObj(destEntity?.Location?.locations || [])?.lotId; }, [destEntity?.Location?.locations]); - const caller_crew = useMemo(() => ({ id: crew?.id, label: Entity.IDS.CREW }), [crew?.id]); + const caller_crew = useMemo(import.meta.url, () => ({ id: crew?.id, label: Entity.IDS.CREW }), [crew?.id]); - const stationCrew = useCallback( + const stationCrew = useCallback(import.meta.url, () => execute('StationCrew', { destination, caller_crew }, { destLotId }), [caller_crew, destination, destLotId, execute] ); - const currentStationing = useMemo( + const currentStationing = useMemo(import.meta.url, () => getPendingTx ? getPendingTx('StationCrew', { caller_crew }) : null, [caller_crew, getPendingTx] ); diff --git a/src/hooks/useAccessibleAsteroidInventories.js b/src/hooks/useAccessibleAsteroidInventories.js index 2fbbf999b..8e8aabe55 100644 --- a/src/hooks/useAccessibleAsteroidInventories.js +++ b/src/hooks/useAccessibleAsteroidInventories.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { useQuery } from 'react-query'; import { Entity, Permission, Ship } from '@influenceth/sdk'; @@ -25,7 +25,7 @@ const useAccessibleAsteroidInventories = (asteroidId, isSourcing) => { { enabled: !!(asteroidId && permission && permissionCrewId && permissionAccount) } ); - return useMemo(() => ({ + return useMemo(import.meta.url, () => ({ data: buildingsLoading || shipsLoading ? undefined : [...(buildings || []), ...(ships || [])], diff --git a/src/hooks/useAccountFormatted.js b/src/hooks/useAccountFormatted.js index 8d353dc8a..a707f69ef 100644 --- a/src/hooks/useAccountFormatted.js +++ b/src/hooks/useAccountFormatted.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { useQuery } from 'react-query'; import useSession from '~/hooks/useSession'; @@ -15,7 +15,7 @@ const useAccountFormatted = (props) => { // { enabled: !!address } // ); - const label = useMemo(() => { + const label = useMemo(import.meta.url, () => { return (accountAddress && accountAddress === address && !doNotReplaceYou) ? 'you' : ( @@ -25,7 +25,7 @@ const useAccountFormatted = (props) => { ); }, [accountAddress, address, doNotReplaceYou, truncate, provider]); - return useMemo(() => { + return useMemo(import.meta.url, () => { if (!address) return null; return label; }, [label, doNotUseName]); diff --git a/src/hooks/useActionButtons.js b/src/hooks/useActionButtons.js index 6b9e7b721..08c795e85 100644 --- a/src/hooks/useActionButtons.js +++ b/src/hooks/useActionButtons.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Ship } from '@influenceth/sdk'; import cloneDeep from 'lodash/cloneDeep'; @@ -138,7 +138,7 @@ const useActionButtons = () => { // actionable ship // NOTE: this does not handle escape pod... these are only for real ships, and that is // expected for the action buttons in their current state - const targetShip = useMemo(() => { + const targetShip = useMemo(import.meta.url, () => { let ship = null; // if zoomed to ship @@ -166,7 +166,7 @@ const useActionButtons = () => { }, [zoomedToShip, crewedShip, lot, crew?.id]); // TODO: should this be useMemo? - const actions = useMemo(() => { + const actions = useMemo(import.meta.url, () => { if (asteroidIsLoading || lotIsLoading || crewedShipIsLoading || zoomedShipIsLoading) return []; return Object.keys(actionButtons) .filter((k) => !actionButtons[k].isVisible || actionButtons[k].isVisible({ diff --git a/src/hooks/useActionCrew.js b/src/hooks/useActionCrew.js index 7b5482a36..14da2de5d 100644 --- a/src/hooks/useActionCrew.js +++ b/src/hooks/useActionCrew.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Crewmate } from '@influenceth/sdk'; import useCrewContext from '~/hooks/useCrewContext'; @@ -14,7 +14,7 @@ const useActionCrew = (currentAction) => { // best-effort fallback (so we'll only load if crew.Location is not set) const { data: liveStation } = useEntity(_cachedData?.crew?.Location ? null : _cachedData?.station?.entity); - return useMemo(() => { + return useMemo(import.meta.url, () => { if (_cachedData) { // rebuild pseudo-crew from cached data const c = { diff --git a/src/hooks/useActionItems.js b/src/hooks/useActionItems.js index 6ae6568c0..0e9f9c7f7 100644 --- a/src/hooks/useActionItems.js +++ b/src/hooks/useActionItems.js @@ -1,4 +1,4 @@ -import { useContext } from 'react'; +import { useContext } from '~/lib/react-debug'; import ActionItemContext from '~/contexts/ActionItemContext'; diff --git a/src/hooks/useActivitiesContext.js b/src/hooks/useActivitiesContext.js index 3ea6db6dd..18271684c 100644 --- a/src/hooks/useActivitiesContext.js +++ b/src/hooks/useActivitiesContext.js @@ -1,4 +1,4 @@ -import { useContext } from 'react'; +import { useContext } from '~/lib/react-debug'; import ActivitiesContext from '~/contexts/ActivitiesContext'; diff --git a/src/hooks/useActivityAnnotations.js b/src/hooks/useActivityAnnotations.js index 0816f9996..a59a09388 100644 --- a/src/hooks/useActivityAnnotations.js +++ b/src/hooks/useActivityAnnotations.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { useQuery } from 'react-query'; import api from '~/lib/api'; @@ -7,7 +7,7 @@ import { cleanseTxHash } from '~/lib/utils'; // note: deprecated at-the-moment, but could be relevant in the future const useActivityAnnotations = (activity) => { - const query = useMemo( + const query = useMemo(import.meta.url, () => activity?.event ? { transactionHash: activity?.event?.transactionHash, logIndex: activity?.event?.logIndex } : null, [activity] ); diff --git a/src/hooks/useAssetSearch.js b/src/hooks/useAssetSearch.js index 8403eb9a2..0d01e5b96 100644 --- a/src/hooks/useAssetSearch.js +++ b/src/hooks/useAssetSearch.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo } from 'react'; +import { useEffect, useMemo } from '~/lib/react-debug'; import { useThrottle } from '@react-hook/throttle'; import { useQuery } from 'react-query'; import esb from 'elastic-builder'; @@ -223,7 +223,7 @@ const useAssetSearch = (assetType, { from = 0, size = 2000 } = {}) => { const [throttledFilters, setThrottledFilters] = useThrottle(filters || {}, 2, true); - useEffect(() => setThrottledFilters(filters || {}), [filters, setThrottledFilters]); + useEffect(import.meta.url, () => setThrottledFilters(filters || {}), [filters, setThrottledFilters]); // asteroidsMapped use the exact same indices as asteroids (for now) // lotsMapped, actionitems, eventlog does not need to query ES @@ -233,7 +233,7 @@ const useAssetSearch = (assetType, { from = 0, size = 2000 } = {}) => { if (esAssetType === 'actionitems') esAssetType = ''; if (esAssetType === 'eventlog') esAssetType = ''; - const query = useMemo(() => { + const query = useMemo(import.meta.url, () => { if (esAssetType) { try { const q = esb.requestBodySearch(); diff --git a/src/hooks/useAsteroidAbundances.js b/src/hooks/useAsteroidAbundances.js index 948a192eb..fa2c92ad6 100644 --- a/src/hooks/useAsteroidAbundances.js +++ b/src/hooks/useAsteroidAbundances.js @@ -1,10 +1,10 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Asteroid, Product } from '@influenceth/sdk'; import { keyify } from '~/lib/utils'; const useAsteroidAbundances = (asteroid) => { - const data = useMemo(() => { + const data = useMemo(import.meta.url, () => { if (asteroid?.Celestial?.scanStatus === Asteroid.SCAN_STATUSES.RESOURCE_SCANNED) { const categories = {}; const abundances = Asteroid.Entity.getAbundances(asteroid); diff --git a/src/hooks/useAsteroidBuildings.js b/src/hooks/useAsteroidBuildings.js index 60d555b4e..3f8cb8f9a 100644 --- a/src/hooks/useAsteroidBuildings.js +++ b/src/hooks/useAsteroidBuildings.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { useQuery } from 'react-query'; import { Building, Entity, Permission } from '@influenceth/sdk'; @@ -15,12 +15,12 @@ const useAsteroidBuildings = (asteroidId, reqComponent = 'Building', reqOneOfPer { enabled: !!asteroidId && !!reqComponent } ); - const perms = useMemo(() => + const perms = useMemo(import.meta.url, () => Array.isArray(reqOneOfPermissions) ? reqOneOfPermissions : (reqOneOfPermissions ? [reqOneOfPermissions] : []), [reqOneOfPermissions] ); - return useMemo(() => { + return useMemo(import.meta.url, () => { let data = allData; // if perms check, filter diff --git a/src/hooks/useAsteroidCrewBuildings.js b/src/hooks/useAsteroidCrewBuildings.js index 84675bb51..57f59f97c 100644 --- a/src/hooks/useAsteroidCrewBuildings.js +++ b/src/hooks/useAsteroidCrewBuildings.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import useCrewBuildings from '~/hooks/useCrewBuildings'; @@ -6,7 +6,7 @@ import useCrewBuildings from '~/hooks/useCrewBuildings'; const useAsteroidCrewBuildings = (asteroidId) => { const { data, isLoading } = useCrewBuildings(); - return useMemo(() => { + return useMemo(import.meta.url, () => { return { data: asteroidId && !isLoading && data ? (data || []).filter((a) => ( diff --git a/src/hooks/useAutocomplete.js b/src/hooks/useAutocomplete.js index 5ac848cfb..2a7857ae8 100644 --- a/src/hooks/useAutocomplete.js +++ b/src/hooks/useAutocomplete.js @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useState } from '~/lib/react-debug'; import { useQuery } from 'react-query'; import { useThrottle } from '@react-hook/throttle'; import esb from 'elastic-builder'; @@ -32,7 +32,7 @@ const useAutocomplete = (assetType, meta) => { const [ searchTerm, setSearchTerm ] = useState(''); const [ query, setQuery ] = useThrottle({}, 2, true); - useEffect(() => { + useEffect(import.meta.url, () => { if (!assetType) return; if (searchTerm) { const q = esb.requestBodySearch(); diff --git a/src/hooks/useBookSession.js b/src/hooks/useBookSession.js index 1e01f1352..5c55b4384 100644 --- a/src/hooks/useBookSession.js +++ b/src/hooks/useBookSession.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import cloneDeep from 'lodash/cloneDeep' import useBookTokens from '~/hooks/useBookTokens'; @@ -66,7 +66,7 @@ const useBookSession = (crewId, crewmateId) => { const [book, setBook] = useState(); - const [bookId, crewmate] = useMemo(() => { + const [bookId, crewmate] = useMemo(import.meta.url, () => { // if creating a completely new crewmate, will be an adalian const adalianRecruit = adalianRecruits.find((a) => a.id === crewmateId); if (adalianRecruit || crewmateId === 0) return [bookIds.ADALIAN_RECRUITMENT, adalianRecruit || null]; @@ -86,7 +86,7 @@ const useBookSession = (crewId, crewmateId) => { const { bookTokens, isLoading: bookTokensLoading } = useBookTokens(bookId); - const error = useMemo(() => { + const error = useMemo(import.meta.url, () => { // validate crewmate (must have crewmate if non-zero id, crewmate must be uninitialized if present) if ((crewmateId > 0 && !crewmate) || (crewmate && crewmate.Crewmate?.status > 0)) return 'Invalid params!'; return null; @@ -97,11 +97,11 @@ const useBookSession = (crewId, crewmateId) => { const dispatchCrewAssignmentPathUndo = useStore(s => s.dispatchCrewAssignmentPathUndo); const dispatchCrewAssignmentRestart = useStore(s => s.dispatchCrewAssignmentRestart); - useEffect(() => { + useEffect(import.meta.url, () => { fetchBook(bookId).then(setBook); }, [bookId]); - const { bookSession, storySession } = useMemo(() => { + const { bookSession, storySession } = useMemo(import.meta.url, () => { // console.log({ book, crewIsLoading, crewmateId, crewmate }); if (!book) return {}; if (bookTokensLoading) return {}; @@ -225,11 +225,11 @@ const useBookSession = (crewId, crewmateId) => { }; }, [book, bookTokens, crewmate, crewmateId, crewIsLoading, sessionData]); - const choosePath = useCallback((pathId) => { + const choosePath = useCallback(import.meta.url, (pathId) => { dispatchCrewAssignmentPathSelection(crewId, crewmateId, bookSession?.currentStoryId, pathId); }, [crewId, crewmateId, bookSession?.currentStoryId]); - const undoPath = useCallback(() => { + const undoPath = useCallback(import.meta.url, () => { if (bookSession.currentStoryIndex > 0 && storySession.history.length === 0) { const previousStoryIndex = book.findIndex((s) => s.id === bookSession?.currentStoryId) - 1; if (previousStoryIndex >= 0) { @@ -240,11 +240,11 @@ const useBookSession = (crewId, crewmateId) => { } }, [crewId, crewmateId, book, bookSession, storySession]); - const restart = useCallback(() => { + const restart = useCallback(import.meta.url, () => { dispatchCrewAssignmentRestart(crewId, crewmateId); }, [crewId, crewmateId]); - return useMemo(() => ({ + return useMemo(import.meta.url, () => ({ book, bookError: error, bookSession, diff --git a/src/hooks/useBookTokens.js b/src/hooks/useBookTokens.js index 17e434f9f..c7766e2b4 100644 --- a/src/hooks/useBookTokens.js +++ b/src/hooks/useBookTokens.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import useCrewContext from '~/hooks/useCrewContext'; import { useSwayBalance } from '~/hooks/useWalletTokenBalance'; @@ -10,14 +10,14 @@ const useBookTokens = (bookId) => { const { captain, isLoading: crewIsLoading } = useCrewContext(); const { data: dispatcherBalance, isLoading: swayIsLoading } = useSwayBalance(process.env.REACT_APP_STARKNET_DISPATCHER); - const swayAmount = useMemo(() => { + const swayAmount = useMemo(import.meta.url, () => { if (swayIsLoading) return null; const scaledSwayBalance = (dispatcherBalance || 0n) / safeBigInt(TOKEN_SCALE[TOKEN.SWAY]); const SWAY_AMOUNT = 30000; // TODO: find better way to get the sway amount (it will change every so often) return parseInt(Math.min(SWAY_AMOUNT, Math.floor(Number(scaledSwayBalance) / 1000))); }, [dispatcherBalance, swayIsLoading]); - const bookTokens = useMemo(() => { + const bookTokens = useMemo(import.meta.url, () => { switch (bookId) { case 'random-1.json': { return { @@ -72,7 +72,7 @@ const useBookTokens = (bookId) => { } }, [bookId, captain, swayAmount]); - return useMemo(() => ({ + return useMemo(import.meta.url, () => ({ bookTokens, isLoading: crewIsLoading || (dispatcherBalance === null) }), [bookTokens, crewIsLoading, dispatcherBalance]); diff --git a/src/hooks/useBusyActivity.js b/src/hooks/useBusyActivity.js index 2da7b05f5..5f53405b5 100644 --- a/src/hooks/useBusyActivity.js +++ b/src/hooks/useBusyActivity.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState } from 'react'; +import { useEffect, useMemo, useState } from '~/lib/react-debug'; import { useQuery, useQueryClient } from 'react-query'; import cloneDeep from 'lodash/cloneDeep'; @@ -26,7 +26,7 @@ const useBusyActivity = (entity) => { // if crew is busy AND there is no unready finishable action (i.e. this activity will be shown) // then it must be because of an unfinishable unready action (where !!getBusyItem) OR because of // a *ready* finishable action where the crew time was > task time (i.e. core sample >1h away)... - const busyItem = useMemo(() => { + const busyItem = useMemo(import.meta.url, () => { // walk backwards until find first of those conditions... return (recentItems || []).find((i) => { if (!activities[i.event?.name]) return false; @@ -36,7 +36,7 @@ const useBusyActivity = (entity) => { }); }, [blockTime, dataUpdatedAt]); - useEffect(() => { + useEffect(import.meta.url, () => { if (busyItem) { setIsHydrating(true); const items = [busyItem]; @@ -48,7 +48,7 @@ const useBusyActivity = (entity) => { } }, [busyItem]); - return useMemo(() => ({ + return useMemo(import.meta.url, () => ({ data: cloneDeep(hydratedBusyItem), isLoading: isLoading || isHydrating, dataUpdatedAt: Date.now(), diff --git a/src/hooks/useCoachmarkRefSetter.js b/src/hooks/useCoachmarkRefSetter.js index 869427114..cf6fbf8fe 100644 --- a/src/hooks/useCoachmarkRefSetter.js +++ b/src/hooks/useCoachmarkRefSetter.js @@ -1,4 +1,4 @@ -import { useContext } from 'react'; +import { useContext } from '~/lib/react-debug'; import CoachmarkContext from '~/contexts/CoachmarkContext'; const useCoachmarkRefSetter = () => { diff --git a/src/hooks/useCoarseTime.js b/src/hooks/useCoarseTime.js index 3035c28eb..fbe53b030 100644 --- a/src/hooks/useCoarseTime.js +++ b/src/hooks/useCoarseTime.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState } from 'react'; +import { useEffect, useMemo, useState } from '~/lib/react-debug'; import { Time } from '@influenceth/sdk'; import useConstants from '~/hooks/useConstants'; @@ -24,7 +24,7 @@ const useCoarseTime = (denom = defaultDenom) => { const [syncing, setSyncing] = useState(true); // this only needs to run as often as 0.01 adays in real time (0.01 * 86400e3 == 864e3) - const tickLength = useMemo( + const tickLength = useMemo(import.meta.url, () => { if (timeOverride?.speed === 0) return null; // (tells useInterval to not run if clock paused) @@ -37,7 +37,7 @@ const useCoarseTime = (denom = defaultDenom) => { ); // sync to nearest coarseness (so any consumers all match each other in display) - useEffect(() => { + useEffect(import.meta.url, () => { const currentTime = getTime(); const currentCoarseTime = formatAsCoarseTime(currentTime, denom); setCoarseTime(currentCoarseTime); diff --git a/src/hooks/useCrew.js b/src/hooks/useCrew.js index 7959a4469..4400af475 100644 --- a/src/hooks/useCrew.js +++ b/src/hooks/useCrew.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Entity } from '@influenceth/sdk'; import useEntity from '~/hooks/useEntity'; @@ -11,7 +11,7 @@ const useCrew = (id) => { const blockTime = useBlockTime(); const response = useEntity({ label: Entity.IDS.CREW, id }); - return useMemo(() => { + return useMemo(import.meta.url, () => { if (response?.data) { // lastFed to launch if (openAccessJSTime) { diff --git a/src/hooks/useCrewAgreements.js b/src/hooks/useCrewAgreements.js index f43eefa6b..68dbef592 100644 --- a/src/hooks/useCrewAgreements.js +++ b/src/hooks/useCrewAgreements.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import useCrewContext from '~/hooks/useCrewContext'; import useWalletAgreements from '~/hooks/useWalletAgreements'; @@ -7,7 +7,7 @@ const useCrewAgreements = (enabled = true, includeWhereLessor = true, includeWhe const { crew } = useCrewContext(); const { data, isLoading } = useWalletAgreements(); - return useMemo(() => { + return useMemo(import.meta.url, () => { return { data: crew?.id && enabled && data ? data?.filter((a) => ( diff --git a/src/hooks/useCrewAsteroids.js b/src/hooks/useCrewAsteroids.js index 26b6a8d07..6e74e3666 100644 --- a/src/hooks/useCrewAsteroids.js +++ b/src/hooks/useCrewAsteroids.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import useCrewContext from '~/hooks/useCrewContext'; import useWalletAsteroids from '~/hooks/useWalletAsteroids'; @@ -7,7 +7,7 @@ const useCrewAsteroids = () => { const { crew } = useCrewContext(); const { data, isLoading } = useWalletAsteroids(); - return useMemo(() => { + return useMemo(import.meta.url, () => { return { data: crew?.id && !isLoading && Array.isArray(data) ? data.filter((a) => (a.Control?.controller?.id === crew?.id)) diff --git a/src/hooks/useCrewBuildings.js b/src/hooks/useCrewBuildings.js index 59df4c748..5998732cd 100644 --- a/src/hooks/useCrewBuildings.js +++ b/src/hooks/useCrewBuildings.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import useCrewContext from '~/hooks/useCrewContext'; import useWalletBuildings from '~/hooks/useWalletBuildings'; @@ -7,7 +7,7 @@ const useCrewBuildings = () => { const { crew } = useCrewContext(); const { data, isLoading } = useWalletBuildings(); - return useMemo(() => { + return useMemo(import.meta.url, () => { return { data: crew?.id && !isLoading && data ? data?.filter((a) => (a.Control?.controller?.id === crew?.id)) diff --git a/src/hooks/useCrewContext.js b/src/hooks/useCrewContext.js index d8f1a3c53..91b905d87 100644 --- a/src/hooks/useCrewContext.js +++ b/src/hooks/useCrewContext.js @@ -1,4 +1,4 @@ -import { useContext } from 'react'; +import { useContext } from '~/lib/react-debug'; import CrewContext from '~/contexts/CrewContext'; diff --git a/src/hooks/useCrewOrders.js b/src/hooks/useCrewOrders.js index 70650b973..182955921 100644 --- a/src/hooks/useCrewOrders.js +++ b/src/hooks/useCrewOrders.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { useQuery } from 'react-query'; import { Entity } from '@influenceth/sdk'; @@ -12,13 +12,13 @@ const useCrewOrders = (controllerId) => { { enabled: !!controllerId } ); - const exchangeIds = useMemo(() => Array.from(new Set((orders || []).map((o) => o.entity.id))), [orders]); + const exchangeIds = useMemo(import.meta.url, () => Array.from(new Set((orders || []).map((o) => o.entity.id))), [orders]); const { data: exchanges, isLoading: exchangesLoading, dataUpdatedAt } = useEntities({ ids: exchangeIds, label: Entity.IDS.BUILDING }); - return useMemo(() => { + return useMemo(import.meta.url, () => { const isLoading = ordersLoading || exchangesLoading; return { data: isLoading diff --git a/src/hooks/useCrewShips.js b/src/hooks/useCrewShips.js index 32eed0d1a..896f61f34 100644 --- a/src/hooks/useCrewShips.js +++ b/src/hooks/useCrewShips.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import useCrewContext from '~/hooks/useCrewContext'; import useWalletShips from '~/hooks/useWalletShips'; @@ -7,7 +7,7 @@ const useCrewShips = () => { const { crew } = useCrewContext(); const { data, isLoading } = useWalletShips(); - return useMemo(() => { + return useMemo(import.meta.url, () => { return { data: crew?.id && !isLoading && Array.isArray(data) ? data.filter((a) => (a.Control?.controller?.id === crew?.id)) diff --git a/src/hooks/useDeliveries.js b/src/hooks/useDeliveries.js index f63631672..b4eee1246 100644 --- a/src/hooks/useDeliveries.js +++ b/src/hooks/useDeliveries.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { useQuery } from 'react-query'; import { Entity } from '@influenceth/sdk'; @@ -11,7 +11,7 @@ import { entitiesCacheKey } from '~/lib/cacheKey'; // (to avoid redundant cache data) const useDeliveries = ({ destination, destinationSlot, origin, originSlot, status } = {}) => { - const cacheKey = useMemo(() => { + const cacheKey = useMemo(import.meta.url, () => { const k = {}; if (destination) k.destination = safeEntityId(destination); if (origin) k.origin = safeEntityId(origin); @@ -25,7 +25,7 @@ const useDeliveries = ({ destination, destinationSlot, origin, originSlot, statu { enabled: !!(destination || origin) } ); - return useMemo(() => ({ + return useMemo(import.meta.url, () => ({ data: isLoading ? undefined : (rawData || []).filter((d) => { if (destinationSlot && d.Delivery?.destSlot !== destinationSlot) return false; if (originSlot && d.Delivery.originSlot !== originSlot) return false; diff --git a/src/hooks/useDescriptionAnnotation.js b/src/hooks/useDescriptionAnnotation.js index 27079f603..2a413b75e 100644 --- a/src/hooks/useDescriptionAnnotation.js +++ b/src/hooks/useDescriptionAnnotation.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import useEarliestActivity from '~/hooks/useEarliestActivity'; import useEntity from '~/hooks/useEntity'; @@ -11,7 +11,7 @@ const useDescriptionAnnotation = (entityId) => { const { data: earliest, isLoading: activityIsLoading } = useEarliestActivity(entityId); const { data: entity, isLoading: entityIsLoading } = useEntity(entityId); - return useMemo(() => { + return useMemo(import.meta.url, () => { if (activityIsLoading || entityIsLoading) return { data: undefined, isLoading: true }; const annotations = earliest?._virtuals?.eventAnnotations || []; const preferred = annotations?.filter((a) => a.crew === entity?.Control?.controller?.id); diff --git a/src/hooks/useGetActivityConfig.js b/src/hooks/useGetActivityConfig.js index 9361c7afc..edf0e939c 100644 --- a/src/hooks/useGetActivityConfig.js +++ b/src/hooks/useGetActivityConfig.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { useQueryClient } from 'react-query'; import useCrewContext from '~/hooks/useCrewContext'; @@ -66,7 +66,7 @@ const getActivityConfig = (queryClient, defaultViewingAs) => (activity, override const useGetActivityConfig = () => { const queryClient = useQueryClient(); const { crew } = useCrewContext(); - return useMemo(() => getActivityConfig(queryClient, { id: crew?.id, label: crew?.label, uuid: crew?.uuid }), [crew?.id, queryClient]); + return useMemo(import.meta.url, () => getActivityConfig(queryClient, { id: crew?.id, label: crew?.label, uuid: crew?.uuid }), [crew?.id, queryClient]); } export default useGetActivityConfig; \ No newline at end of file diff --git a/src/hooks/useGetTime.js b/src/hooks/useGetTime.js index 2cf104c42..a27ac5867 100644 --- a/src/hooks/useGetTime.js +++ b/src/hooks/useGetTime.js @@ -1,4 +1,4 @@ -import { useCallback } from 'react'; +import { useCallback } from '~/lib/react-debug'; import { Time } from '@influenceth/sdk'; import useConstants from '~/hooks/useConstants'; @@ -8,7 +8,7 @@ const useGetTime = () => { const timeOverride = useStore(s => s.timeOverride); const { data: TIME_ACCELERATION } = useConstants('TIME_ACCELERATION'); - return useCallback((overrideNow) => { + return useCallback(import.meta.url, (overrideNow) => { const now = overrideNow || Date.now(); let preciseTime = timeOverride?.anchor || Time.fromUnixMilliseconds(now, TIME_ACCELERATION).toOrbitADays(); diff --git a/src/hooks/useHydratedCrew.js b/src/hooks/useHydratedCrew.js index a49f3f4af..8272e5ee9 100644 --- a/src/hooks/useHydratedCrew.js +++ b/src/hooks/useHydratedCrew.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { cloneDeep } from 'lodash'; import { Crewmate } from '@influenceth/sdk'; @@ -14,7 +14,7 @@ const useHydratedCrew = (id) => { const { data: CREW_SCHEDULE_BUFFER, isLoading: constantsLoading } = useConstants('CREW_SCHEDULE_BUFFER'); const blockTime = useBlockTime(); - return useMemo(() => { + return useMemo(import.meta.url, () => { let data = null; let isLoading = true; if (crew && !crewLoading && !crewmatesLoading && !constantsLoading) { diff --git a/src/hooks/useHydratedLocation.js b/src/hooks/useHydratedLocation.js index 083c17968..b8ae0640f 100644 --- a/src/hooks/useHydratedLocation.js +++ b/src/hooks/useHydratedLocation.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Lot } from '@influenceth/sdk'; import { useLotLink } from '~/components/LotLink'; @@ -15,7 +15,7 @@ const useHydratedLocation = (location = {}, escapeModuleCrewId) => { const { data: building } = useBuilding(location?.buildingId); const { data: ship } = useShip(location?.shipId); - return useMemo(() => { + return useMemo(import.meta.url, () => { return { asteroid, building, diff --git a/src/hooks/useInterval.js b/src/hooks/useInterval.js index 0b94fe157..f5da64b12 100644 --- a/src/hooks/useInterval.js +++ b/src/hooks/useInterval.js @@ -1,16 +1,16 @@ // From https://overreacted.io/making-setinterval-declarative-with-react-hooks/ -import { useEffect, useRef } from 'react'; +import { useEffect, useRef } from '~/lib/react-debug'; const useInterval = (callback, delay) => { const savedCallback = useRef(); // Remember the latest callback. - useEffect(() => { + useEffect(import.meta.url, () => { savedCallback.current = callback; }, [callback]); // Set up the interval. - useEffect(() => { + useEffect(import.meta.url, () => { function tick() { savedCallback.current(); } diff --git a/src/hooks/useLot.js b/src/hooks/useLot.js index 4d8fcebe6..7cc94e313 100644 --- a/src/hooks/useLot.js +++ b/src/hooks/useLot.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo } from 'react'; +import { useEffect, useMemo } from '~/lib/react-debug'; import { useQuery, useQueryClient, } from 'react-query'; import { Entity, Lot, Permission, Ship } from '@influenceth/sdk'; @@ -25,7 +25,7 @@ const useLot = (rawLotId) => { const queryClient = useQueryClient(); // console.log('lotId', typeof lotId, lotId, lotId ? Entity.formatEntity({ id: lotId, label: Entity.IDS.LOT }) : null) - const lotEntity = useMemo(() => lotId ? Entity.formatEntity({ id: lotId, label: Entity.IDS.LOT }) : null, [lotId]); + const lotEntity = useMemo(import.meta.url, () => lotId ? Entity.formatEntity({ id: lotId, label: Entity.IDS.LOT }) : null, [lotId]); // console.log('lotId', { lotId, lotEntity }); const { data: lot, isLoading: lotIsLoading, dataUpdatedAt: lUpdatedAt } = useEntity(lotId ? { id: lotId, label: Entity.IDS.LOT } : undefined); @@ -72,7 +72,7 @@ const useLot = (rawLotId) => { const isLoading = lotEntity?.uuid && (lotIsLoading || lotDataIsLoading || asteroidLoading || buildingsLoading || depositsLoading || shipsLoading); const objArrDataUpdatedAt = Math.max(bUpdatedAt, dUpdatedAt, lUpdatedAt, sUpdatedAt); - const data = useMemo(() => { + const data = useMemo(import.meta.url, () => { if (isLoading || !lotEntity?.uuid) return undefined; const { asteroidId, lotIndex } = Lot.toPosition(lotId) || {}; @@ -125,7 +125,7 @@ const useLot = (rawLotId) => { }; }, [lotEntity?.uuid, isLoading, asteroid, blockTime, buildings, deposits, ships, objArrDataUpdatedAt]); - return useMemo(() => ({ data, isLoading }), [data, isLoading]); + return useMemo(import.meta.url, () => ({ data, isLoading }), [data, isLoading]); }; export default useLot; diff --git a/src/hooks/useMappedAsteroidLots.js b/src/hooks/useMappedAsteroidLots.js index f06b11635..ec44ae2bf 100644 --- a/src/hooks/useMappedAsteroidLots.js +++ b/src/hooks/useMappedAsteroidLots.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from '~/lib/react-debug'; import { useQueryClient } from 'react-query'; import { Building, Entity, Lot } from '@influenceth/sdk'; @@ -30,14 +30,14 @@ const useMappedAsteroidLots = (i) => { // get all leased lots from the server const { data: leasedLots, isLoading: leasedLotsLoading, dataUpdatedAt: dataUpdatedAt1 } = useWalletLeasedLots(i); - const [lotLeasedMap, leasedTally] = useMemo(() => ([ + const [lotLeasedMap, leasedTally] = useMemo(import.meta.url, () => ([ (leasedLots || []).reduce((acc, d) => ({ ...acc, [Lot.toIndex(d.id)]: true }), {}), leasedLots?.length || 0 ]), [leasedLots, dataUpdatedAt1]); // get all occupied-by-me buildings from the server const { data: crewLots, isLoading: crewLotsLoading, dataUpdatedAt: dataUpdatedAt2 } = useAsteroidCrewBuildings(i); - const myOccupationMap = useMemo(() => { + const myOccupationMap = useMemo(import.meta.url, () => { if (crewLotsLoading) return null; return (crewLots || []).reduce((acc, p) => { const _locations = locationsArrToObj(p?.Location?.locations || []); @@ -50,7 +50,7 @@ const useMappedAsteroidLots = (i) => { // get all occupied-by-me ships from the server const { data: crewShips, isLoading: crewShipsLoading, dataUpdatedAt: dataUpdatedAt3 } = useCrewShips(); - const myShipMap = useMemo(() => { + const myShipMap = useMemo(import.meta.url, () => { if (crewShipsLoading) return null; return (crewShips || []).reduce((acc, p) => { const _locations = locationsArrToObj(p?.Location?.locations || []); @@ -62,12 +62,12 @@ const useMappedAsteroidLots = (i) => { }, [crewShips, crewShipsLoading, dataUpdatedAt3]); // determine if search is on or not - const searchIsOn = useMemo(() => { + const searchIsOn = useMemo(import.meta.url, () => { return openHudMenu === 'ASTEROID_MAP_SEARCH' || !isAssetSearchMatchingDefault('lotsMapped'); }, [openHudMenu, mappedLotSearch]); // init highlight config helpers - const { highlightValueMap, highlightColorMap } = useMemo(() => { + const { highlightValueMap, highlightColorMap } = useMemo(import.meta.url, () => { let colorMap; let valueMap = {}; if (highlightConfig) { @@ -88,7 +88,7 @@ const useMappedAsteroidLots = (i) => { }, [highlightConfig, searchIsOn]); // create "search results" test function - const isFilterMatch = useCallback((unpacked) => { + const isFilterMatch = useCallback(import.meta.url, (unpacked) => { const filters = mappedLotSearch?.filters || {}; if (searchIsOn) { if (filters.category && !filters.category.includes(unpacked.category.toString())) return false; @@ -104,7 +104,7 @@ const useMappedAsteroidLots = (i) => { // build sparse array of search results // TODO (enhancement): should send this to a worker if possible - const [lotResultMap, lotUseMap, lotColorMap, lotUseTallies, resultTally] = useMemo(() => { + const [lotResultMap, lotUseMap, lotColorMap, lotUseTallies, resultTally] = useMemo(import.meta.url, () => { const lotResult = {}; const lotColor = {}; const lotUse = {}; @@ -168,11 +168,11 @@ const useMappedAsteroidLots = (i) => { return [lotResult, lotUse, lotColor, lotUseTallies, resultTally]; }, [lotData, lotDataUpdatedAt, myOccupationMap, myShipMap, isFilterMatch, highlightValueMap, rebuildTally]); - const refetch = useCallback(() => { + const refetch = useCallback(import.meta.url, () => { setRebuildTally((t) => t + 1); }, []) - const processEvent = useCallback(async (eventType, body) => { + const processEvent = useCallback(import.meta.url, async (eventType, body) => { console.log('processEvent', eventType, body); let asteroidId, lotIndex, buildingCategory; @@ -245,7 +245,7 @@ const useMappedAsteroidLots = (i) => { const isLoading = lotDataLoading || leasedLotsLoading || crewLotsLoading; - return useMemo(() => { + return useMemo(import.meta.url, () => { return { data: { lotUseTallies, diff --git a/src/hooks/useNameAvailability.js b/src/hooks/useNameAvailability.js index b0249ba5d..96d33b450 100644 --- a/src/hooks/useNameAvailability.js +++ b/src/hooks/useNameAvailability.js @@ -1,4 +1,4 @@ -import { useCallback } from 'react'; +import { useCallback } from '~/lib/react-debug'; import { Entity, Name } from '@influenceth/sdk'; import api from '~/lib/api'; @@ -7,7 +7,7 @@ import useStore from './useStore'; const useNameAvailability = (entity) => { const createAlert = useStore(s => s.dispatchAlertLogged); - const getNameAvailability = useCallback(async (name, entityId, skipCollisionCheck = false, returnType = 'alert') => { + const getNameAvailability = useCallback(import.meta.url, async (name, entityId, skipCollisionCheck = false, returnType = 'alert') => { try { let nameError = null; diff --git a/src/hooks/useOrderSummaryByMarket.js b/src/hooks/useOrderSummaryByMarket.js index 53d0b5ada..078c255cb 100644 --- a/src/hooks/useOrderSummaryByMarket.js +++ b/src/hooks/useOrderSummaryByMarket.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { useQuery } from 'react-query'; import useAsteroidBuildings from '~/hooks/useAsteroidBuildings'; @@ -14,7 +14,7 @@ const useOrderSummaryByExchange = (asteroidId, product) => { ); const isLoading = isLoadingBuildings || isLoadingOrders; - return useMemo(() => { + return useMemo(import.meta.url, () => { if (isLoading) return { data: undefined, isLoading: true }; return { data: exchanges diff --git a/src/hooks/usePagedActionItems.js b/src/hooks/usePagedActionItems.js index 461dc1cc1..ce295651e 100644 --- a/src/hooks/usePagedActionItems.js +++ b/src/hooks/usePagedActionItems.js @@ -1,4 +1,4 @@ -import { useContext, useEffect, useMemo, useState } from 'react'; +import { useContext, useEffect, useMemo, useState } from '~/lib/react-debug'; import ActionItemContext from '~/contexts/ActionItemContext'; import { formatActionItem } from '~/lib/actionItem'; @@ -24,11 +24,11 @@ const usePagedActionItems = () => { const sort = useStore(s => s.assetSearch[assetType].sort || []); const setSort = useStore(s => s.dispatchSortUpdated(assetType)); - useEffect(() => { + useEffect(import.meta.url, () => { setPage(1); }, [filters, sort]); - const { hits, total } = useMemo(() => { + const { hits, total } = useMemo(import.meta.url, () => { const filteredItems = allItems .map((item) => formatActionItem(item, getActivityConfig(item)?.actionItem)) .filter((item) => { diff --git a/src/hooks/usePagedAgreements.js b/src/hooks/usePagedAgreements.js index bccf0870a..0111073e4 100644 --- a/src/hooks/usePagedAgreements.js +++ b/src/hooks/usePagedAgreements.js @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef, useState } from 'react'; +import { useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import get from 'lodash/get'; import { Entity, Lot } from '@influenceth/sdk'; @@ -23,13 +23,13 @@ const usePagedAgreements = (params) => { const updateFilters = useStore(s => s.dispatchFiltersUpdated(assetType)); const setSort = useStore(s => s.dispatchSortUpdated(assetType)); - useEffect(() => { + useEffect(import.meta.url, () => { setPage(1); }, [filters, sort]); // override perm filter from url, but reset to pre-existing on unmount const previousPermFilter = useRef(); - useEffect(() => { + useEffect(import.meta.url, () => { if (params.permission) { previousPermFilter.current = filters.permission; @@ -52,7 +52,7 @@ const usePagedAgreements = (params) => { const isLoading = params.uuid ? entityLoading : crewAgreementsLoading; - const data = useMemo(() => { + const data = useMemo(import.meta.url, () => { if (isLoading) return undefined; if (!params.uuid && crewAgreements) return crewAgreements; if (params.uuid && entity) { @@ -64,7 +64,7 @@ const usePagedAgreements = (params) => { }, [asteroid, crewAgreements, dataUpdatedAt, entity, isLoading, params.permission, params.uuid]); // TODO: should almost certainly move filter application into elasticsearch instead of loading all upfront - const filteredData = useMemo(() => { + const filteredData = useMemo(import.meta.url, () => { return (data || []) .filter((a) => { if (filters.permission) { @@ -88,7 +88,7 @@ const usePagedAgreements = (params) => { .sort((a, b) => (sort[1] === 'asc' ? 1 : -1) * (get(a, sort[0]) < get(b, sort[0]) ? -1 : 1)); }, [blockTime, crew, data, sort, filters]); - const dataPage = useMemo(() => filteredData.slice(pageSize * (page - 1), pageSize * page), [filteredData, page]) + const dataPage = useMemo(import.meta.url, () => filteredData.slice(pageSize * (page - 1), pageSize * page), [filteredData, page]) return { page, diff --git a/src/hooks/usePagedAssets.js b/src/hooks/usePagedAssets.js index 1e4f7688e..a63ce20d8 100644 --- a/src/hooks/usePagedAssets.js +++ b/src/hooks/usePagedAssets.js @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useState } from '~/lib/react-debug'; import useStore from '~/hooks/useStore'; import useAssetSearch from './useAssetSearch'; @@ -12,7 +12,7 @@ const usePagedAssets = (assetType) => { const sort = useStore(s => s.assetSearch[assetType].sort || []); const setSort = useStore(s => s.dispatchSortUpdated(assetType)); - useEffect(() => { + useEffect(import.meta.url, () => { setPage(1); }, [filters, sort]); diff --git a/src/hooks/usePagedEvents.js b/src/hooks/usePagedEvents.js index e335dc603..f7c2d2847 100644 --- a/src/hooks/usePagedEvents.js +++ b/src/hooks/usePagedEvents.js @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useState } from '~/lib/react-debug'; import { useQueryClient } from 'react-query'; import { hydrateActivities, typesWithLogContent } from '~/lib/activities'; @@ -22,11 +22,11 @@ const usePagedEvents = () => { const sort = useStore(s => s.assetSearch[assetType].sort || []); const setSort = useStore(s => s.dispatchSortUpdated(assetType)); - useEffect(() => { + useEffect(import.meta.url, () => { setPage(1); }, [filters, sort]); - useEffect(() => { + useEffect(import.meta.url, () => { setLoading(true); // TODO (enhancement): if not using any filters, should probably use react-query here... diff --git a/src/hooks/usePriceHelper.js b/src/hooks/usePriceHelper.js index abbd37e90..a3f937bb9 100644 --- a/src/hooks/usePriceHelper.js +++ b/src/hooks/usePriceHelper.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { useSwayPerUsdc, useUsdcPerEth } from '~/hooks/useSwapQuote'; import { TOKEN, TOKEN_FORMATTER, TOKEN_SCALE } from '~/lib/priceUtils'; @@ -41,7 +41,7 @@ const usePriceHelper = () => { const { data: swayPerUsdc } = useSwayPerUsdc(); const { data: usdcPerEth } = useUsdcPerEth(); - const from = useCallback((value, originToken) => { + const from = useCallback(import.meta.url, (value, originToken) => { return Price.from( value, originToken, @@ -52,7 +52,7 @@ const usePriceHelper = () => { ); }, [swayPerUsdc, usdcPerEth]); - return useMemo(() => ({ from }), [from]); + return useMemo(import.meta.url, () => ({ from }), [from]); }; export default usePriceHelper; \ No newline at end of file diff --git a/src/hooks/useReadyAtWatcher.js b/src/hooks/useReadyAtWatcher.js index e0eca7b6a..4a5c13b77 100644 --- a/src/hooks/useReadyAtWatcher.js +++ b/src/hooks/useReadyAtWatcher.js @@ -1,9 +1,9 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useState } from '~/lib/react-debug'; const useReadyAtWatcher = (readyAt) => { const [ready, setReady] = useState(true); - useEffect(() => { + useEffect(import.meta.url, () => { let to; if (readyAt > 0) { const now = Date.now(); diff --git a/src/hooks/useScreenSize.js b/src/hooks/useScreenSize.js index 5c55a50ac..be2e2b2a1 100644 --- a/src/hooks/useScreenSize.js +++ b/src/hooks/useScreenSize.js @@ -1,4 +1,4 @@ -import { useContext } from 'react'; +import { useContext } from '~/lib/react-debug'; import ScreensizeContext from '~/contexts/ScreensizeContext'; diff --git a/src/hooks/useServiceWorker.js b/src/hooks/useServiceWorker.js index 6058c4aff..16bb7aafd 100644 --- a/src/hooks/useServiceWorker.js +++ b/src/hooks/useServiceWorker.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from '~/lib/react-debug'; const useServiceWorker = () => { // no service worker in dev mode, so don't default to "installing" in that case @@ -6,7 +6,7 @@ const useServiceWorker = () => { const [updateNeeded, setUpdateNeeded] = useState(false); const refreshing = useRef(false); - useEffect(() => { + useEffect(import.meta.url, () => { if ('serviceWorker' in navigator) { // if there is a controller change (i.e. if new serviceworker becomes active), @@ -75,7 +75,7 @@ const useServiceWorker = () => { return { isInstalling, updateNeeded, - onUpdateVersion: useCallback(() => { + onUpdateVersion: useCallback(import.meta.url, () => { if ('serviceWorker' in navigator) { navigator.serviceWorker.getRegistration().then((registration) => { if (registration && registration.waiting) { diff --git a/src/hooks/useSession.js b/src/hooks/useSession.js index 69ba53176..9bc863c12 100644 --- a/src/hooks/useSession.js +++ b/src/hooks/useSession.js @@ -1,4 +1,4 @@ -import { useContext, useMemo } from 'react'; +import { useContext, useMemo } from '~/lib/react-debug'; import SessionContext from '~/contexts/SessionContext'; import SIMULATION_CONFIG from '~/simulation/simulationConfig'; @@ -12,7 +12,7 @@ const useSession = (includeSimulationOverrides = true) => { const simulationEnabled = useStore(s => s.simulationEnabled); const simulationState = useStore(s => s.simulation); - const [simulationOverrides, overrideBlockTime] = useMemo(() => { + const [simulationOverrides, overrideBlockTime] = useMemo(import.meta.url, () => { if (includeSimulationOverrides && simulationEnabled && !context?.accountAddress) { return [ simulationState, @@ -22,7 +22,7 @@ const useSession = (includeSimulationOverrides = true) => { return [null, null]; }, [context?.accountAddress, includeSimulationOverrides, simulationEnabled, simulationState]); - return useMemo(() => { + return useMemo(import.meta.url, () => { if (simulationOverrides) { return { ...context, diff --git a/src/hooks/useSettleCrew.js b/src/hooks/useSettleCrew.js index 90d89512b..70a89e0f5 100644 --- a/src/hooks/useSettleCrew.js +++ b/src/hooks/useSettleCrew.js @@ -1,16 +1,16 @@ -import { useCallback, useContext, useMemo } from 'react'; +import { useCallback, useContext, useMemo } from '~/lib/react-debug'; import ChainTransactionContext from '~/contexts/ChainTransactionContext'; const useSettleCrew = (i) => { const { execute, getStatus } = useContext(ChainTransactionContext); - const settleCrew = useCallback( + const settleCrew = useCallback(import.meta.url, () => execute('SETTLE_CREW', { i }), [execute, i] ); - const status = useMemo( + const status = useMemo(import.meta.url, () => getStatus('SETTLE_CREW', { i }), [getStatus, i] ); diff --git a/src/hooks/useShip.js b/src/hooks/useShip.js index 5b7557e0f..144de26ff 100644 --- a/src/hooks/useShip.js +++ b/src/hooks/useShip.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { cloneDeep } from 'lodash'; import { Entity } from '@influenceth/sdk'; @@ -6,7 +6,7 @@ import useEntity from '~/hooks/useEntity'; import { locationsArrToObj } from '~/lib/utils'; const useShip = (id) => { - const entity = useMemo(() => { + const entity = useMemo(import.meta.url, () => { if (id) { if (id.label && id.id) return { label: id.label, id: Number(id.id) }; return { label: Entity.IDS.SHIP, id }; @@ -15,7 +15,7 @@ const useShip = (id) => { }, [id]); const { data, dataUpdatedAt, isLoading, refetch } = useEntity(entity); - return useMemo(() => { + return useMemo(import.meta.url, () => { let ship = null; if (data && !isLoading) { ship = cloneDeep(data); diff --git a/src/hooks/useShoppingListData.js b/src/hooks/useShoppingListData.js index 221f9221e..fe20737cf 100644 --- a/src/hooks/useShoppingListData.js +++ b/src/hooks/useShoppingListData.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { Asteroid, Crew, Crewmate, Lot, Permission } from '@influenceth/sdk'; import useAsteroidBuildings from '~/hooks/useAsteroidBuildings'; @@ -18,7 +18,7 @@ const useShoppingListData = (asteroidId, lotId, productIds, mode = 'buy') => { // TODO: how much effort would it be to include feeEnforcement in elasticsearch on exchanges const [feeEnforcements, setFeeEnforcements] = useState(); const [feesLoading, setFeesLoading] = useState(true); - const loadFees = useCallback(async () => { + const loadFees = useCallback(import.meta.url, async () => { const ids = (exchanges || []).map((e) => e.Control?.controller?.id); if (ids?.length > 0) { setFeesLoading(true); @@ -50,14 +50,14 @@ const useShoppingListData = (asteroidId, lotId, productIds, mode = 'buy') => { } setFeesLoading(false); }, [exchangesUpdatedAt]); - useEffect(() => { + useEffect(import.meta.url, () => { loadFees(); }, [loadFees]); const { data: orders, isLoading: ordersLoading, refetch: refetchOrders } = useShoppingListOrders(asteroidId, productIds, mode); const isLoading = exchangesLoading || feesLoading || ordersLoading; - return useMemo(() => { + return useMemo(import.meta.url, () => { const refetch = () => { refetchExchanges(); refetchOrders(); diff --git a/src/hooks/useSimulationState.js b/src/hooks/useSimulationState.js index aad7bd804..c74af6908 100644 --- a/src/hooks/useSimulationState.js +++ b/src/hooks/useSimulationState.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import useSession from '~/hooks/useSession'; import useStore from '~/hooks/useStore'; @@ -7,7 +7,7 @@ const useSimulationState = () => { const simulationEnabled = useStore(s => s.simulationEnabled); const simulationState = useStore(s => s.simulation); - return useMemo( + return useMemo(import.meta.url, () => !accountAddress && simulationEnabled ? simulationState : null, [accountAddress, simulationEnabled, simulationState] ); diff --git a/src/hooks/useStationedCrews.js b/src/hooks/useStationedCrews.js index df150ff99..0c729977f 100644 --- a/src/hooks/useStationedCrews.js +++ b/src/hooks/useStationedCrews.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { useQuery } from 'react-query'; import { Entity } from '@influenceth/sdk'; @@ -7,14 +7,14 @@ import { entitiesCacheKey } from '~/lib/cacheKey'; import { locationsArrToObj } from '~/lib/utils'; const useStationedCrews = (entityId) => { - const entityUuid = useMemo(() => entityId ? Entity.packEntity(entityId) : undefined, [entityId]); + const entityUuid = useMemo(import.meta.url, () => entityId ? Entity.packEntity(entityId) : undefined, [entityId]); const { data: stationedCrews, isLoading: crewsLoading, dataUpdatedAt: crewsUpdatedAt } = useQuery( entitiesCacheKey(Entity.IDS.CREW, { stationUuid: entityUuid }), () => api.getEntities({ match: { 'Location.location.uuid': entityUuid }, label: Entity.IDS.CREW }), { enabled: !!entityUuid } ); - return useMemo(() => { + return useMemo(import.meta.url, () => { if (crewsLoading) { return { data: undefined, isLoading: true }; } diff --git a/src/hooks/useSwapHelper.js b/src/hooks/useSwapHelper.js index f0a31b7c7..2c7fa6e39 100644 --- a/src/hooks/useSwapHelper.js +++ b/src/hooks/useSwapHelper.js @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from '~/lib/react-debug'; import { fetchBuildExecuteTransaction } from '@avnu/avnu-sdk'; import useStore from '~/hooks/useStore'; @@ -17,7 +17,7 @@ const useSwapHelper = () => { const priceHelper = usePriceHelper(); const preferredUiCurrency = useStore(s => s.getPreferredUiCurrency()); - const buildMultiswapFromSellAmount = useCallback(async (sellAmountUSDC, targetToken, allowableSlippage = 0.1) => { + const buildMultiswapFromSellAmount = useCallback(import.meta.url, async (sellAmountUSDC, targetToken, allowableSlippage = 0.1) => { const swappableTokens = Object.keys(wallet?.tokenBalances).filter((t) => t !== targetToken); swappableTokens.sort((a) => a === preferredUiCurrency ? -1 : 1); @@ -59,7 +59,7 @@ const useSwapHelper = () => { return calls; }, [wallet]); - return useMemo( + return useMemo(import.meta.url, () => ({ buildMultiswapFromSellAmount }), [buildMultiswapFromSellAmount] ); diff --git a/src/hooks/useSyncedTime.js b/src/hooks/useSyncedTime.js index 466597473..800d84523 100644 --- a/src/hooks/useSyncedTime.js +++ b/src/hooks/useSyncedTime.js @@ -1,4 +1,4 @@ -import { useContext } from 'react'; +import { useContext } from '~/lib/react-debug'; import SyncedTimeContext from '~/contexts/SyncedTimeContext'; @@ -6,7 +6,7 @@ const useSyncedTime = () => { return useContext(SyncedTimeContext); // const [time, setTime] = useState(getSeconds()); - // useEffect(() => { + // useEffect(import.meta.url, () => { // // on nearest second, start the interval // let to, int; // to = setTimeout(() => { diff --git a/src/hooks/useTravelSolutionIsValid.js b/src/hooks/useTravelSolutionIsValid.js index 5a9408a15..b01cf3e09 100644 --- a/src/hooks/useTravelSolutionIsValid.js +++ b/src/hooks/useTravelSolutionIsValid.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Crewmate, Ship, Time } from '@influenceth/sdk'; import useCrewContext from './useCrewContext'; @@ -14,11 +14,11 @@ const useTravelSolutionIsValid = () => { const { data: ship } = useShip(shipId); const travelSolution = useStore(s => s.asteroids.travelSolution); - const exhaustBonus = useMemo(() => { + const exhaustBonus = useMemo(import.meta.url, () => { return getCrewAbilityBonuses(Crewmate.ABILITY_IDS.PROPELLANT_EXHAUST_VELOCITY, crew); }, [crew]); - return useMemo(() => { + return useMemo(import.meta.url, () => { if (!travelSolution) return false; if (travelSolution._isSimulation) return !travelSolution._isSimulationInvalid; diff --git a/src/hooks/useTutorialSteps.js b/src/hooks/useTutorialSteps.js index c3419e533..960bae199 100644 --- a/src/hooks/useTutorialSteps.js +++ b/src/hooks/useTutorialSteps.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo } from 'react'; +import { useCallback, useEffect, useMemo } from '~/lib/react-debug'; import { FaYoutube as YoutubeIcon } from 'react-icons/fa'; import { Building, Permission, Inventory, Product } from '@influenceth/sdk'; @@ -44,7 +44,7 @@ const VideoLink = styled.div` `; const TutorialVideoLink = ({ link }) => { - const onClick = useCallback(() => { + const onClick = useCallback(import.meta.url, () => { window.open(link, '_blank'); }, [link]); return ( @@ -68,14 +68,14 @@ const useTutorialSteps = () => { const dispatchDismissCrewTutorial = useStore(s => s.dispatchDismissCrewTutorial); const dispatchDismissCrewTutorialStep = useStore(s => s.dispatchDismissCrewTutorialStep); - const dismissedTutorialSteps = useMemo(() => { + const dismissedTutorialSteps = useMemo(import.meta.url, () => { const dismissed = new Set(); (crewTutorial?.dismissedSteps || []).forEach((s) => dismissed.add(s)); (uncrewTutorial?.dismissedSteps || []).forEach((s) => dismissed.add(s)); return Array.from(dismissed); }, [crewTutorial?.dismissedSteps, uncrewTutorial?.dismissedSteps]); - const tutorialSteps = useMemo(() => { + const tutorialSteps = useMemo(import.meta.url, () => { if (loading) return []; const lotLease = crewAgreements?.find((a) => a.permission === Permission.IDS.USE_LOT); @@ -318,7 +318,7 @@ const useTutorialSteps = () => { ]; }, [crew, crewDeposits, loading, crewAgreements, crewBuildings]); - useEffect(() => { + useEffect(import.meta.url, () => { tutorialSteps.forEach((s) => { if (s.postcondition && !dismissedTutorialSteps.includes(s.key)) { // if postcondition is true (and not dismissed), then dismiss @@ -328,7 +328,7 @@ const useTutorialSteps = () => { }); }, [crew?.id, dismissedTutorialSteps, tutorialSteps]); - useEffect(() => { + useEffect(import.meta.url, () => { if (!loading) { if (Object.keys(tutorialSteps).length === dismissedTutorialSteps?.length) { dispatchDismissCrewTutorial(crew?.id, true); @@ -336,7 +336,7 @@ const useTutorialSteps = () => { } }, [crew?.id, dispatchDismissCrewTutorial, dismissedTutorialSteps, loading]) - return useMemo(() => { + return useMemo(import.meta.url, () => { return tutorialSteps.filter((s) => { return s.precondition && !dismissedTutorialSteps.includes((s.key)) }) diff --git a/src/hooks/useWalletAgreements.js b/src/hooks/useWalletAgreements.js index 4a6c0598b..baf7ade3d 100644 --- a/src/hooks/useWalletAgreements.js +++ b/src/hooks/useWalletAgreements.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { useQuery } from 'react-query'; import useSession from '~/hooks/useSession'; @@ -9,7 +9,7 @@ const useWalletAgreements = () => { const { accountAddress } = useSession(); const { crews, loading: crewsLoading } = useCrewContext(); - const crewIds = useMemo(() => { + const crewIds = useMemo(import.meta.url, () => { if (crewsLoading) return null; return (crews || []).map((c) => c.id); }, [crews, crewsLoading]); diff --git a/src/hooks/useWalletAsteroids.js b/src/hooks/useWalletAsteroids.js index c756d6ea9..4d9dcf17d 100644 --- a/src/hooks/useWalletAsteroids.js +++ b/src/hooks/useWalletAsteroids.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { useQuery } from 'react-query'; import esb from 'elastic-builder'; import { Entity } from '@influenceth/sdk'; @@ -12,9 +12,9 @@ const useWalletAsteroids = () => { const { accountAddress } = useSession(); const { crews, loading: crewsLoading } = useCrewContext(); - const controllerIds = useMemo(() => (crews || []).map((c) => c.id), [crews]); + const controllerIds = useMemo(import.meta.url, () => (crews || []).map((c) => c.id), [crews]); - const query = useMemo(() => { + const query = useMemo(import.meta.url, () => { if (!accountAddress || crewsLoading) return null; try { diff --git a/src/hooks/useWalletBuildings.js b/src/hooks/useWalletBuildings.js index 8ea0cf400..7764dfec8 100644 --- a/src/hooks/useWalletBuildings.js +++ b/src/hooks/useWalletBuildings.js @@ -5,7 +5,7 @@ import useSession from '~/hooks/useSession'; import useCrewContext from '~/hooks/useCrewContext'; import api from '~/lib/api'; import { useQuery } from 'react-query'; -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { entitiesCacheKey } from '~/lib/cacheKey'; export const statuses = [ @@ -18,9 +18,9 @@ const useWalletBuildings = () => { const { accountAddress } = useSession(); const { crews, loading: crewsLoading } = useCrewContext(); - const controllerIds = useMemo(() => (crews || []).map((c) => c.id), [crews]); + const controllerIds = useMemo(import.meta.url, () => (crews || []).map((c) => c.id), [crews]); - const query = useMemo(() => { + const query = useMemo(import.meta.url, () => { if (!accountAddress || crewsLoading) return null; try { diff --git a/src/hooks/useWalletLeasedLots.js b/src/hooks/useWalletLeasedLots.js index 4b366de32..e52b2fc2f 100644 --- a/src/hooks/useWalletLeasedLots.js +++ b/src/hooks/useWalletLeasedLots.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { Permission } from '@influenceth/sdk'; import useCrewContext from '~/hooks/useCrewContext'; @@ -10,12 +10,12 @@ const useWalletLeasedLots = (asteroidId, enabled = true) => { const { crews, loading: crewsLoading } = useCrewContext(); const { data, isLoading: dataLoading } = useWalletAgreements(); - const crewIds = useMemo(() => { + const crewIds = useMemo(import.meta.url, () => { if (crewsLoading) return []; return (crews || []).map((c) => c.id); }, [crews, crewsLoading]); - return useMemo(() => { + return useMemo(import.meta.url, () => { return { data: enabled && data ? data?.filter((a) => ( diff --git a/src/hooks/useWalletPurchasableBalances.js b/src/hooks/useWalletPurchasableBalances.js index d84d63186..de0dd0cd7 100644 --- a/src/hooks/useWalletPurchasableBalances.js +++ b/src/hooks/useWalletPurchasableBalances.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import usePriceConstants from '~/hooks/usePriceConstants'; import usePriceHelper from '~/hooks/usePriceHelper'; @@ -27,13 +27,13 @@ const useWalletPurchasableBalances = (overrideAccount) => { // reserve eth for gas if not planning to use sway // or have <10% of target reserve amount available in sway - const maintainEthGasReserve = useMemo(() => { + const maintainEthGasReserve = useMemo(import.meta.url, () => { const targetSwayReserve = priceHelper.from(GAS_BUFFER_VALUE_USDC * 0.1, TOKEN.USDC).to(TOKEN.SWAY); // reserve needed if setting is to pay w/ sway AND have sway return !(payGasWithSwayIfPossible && swayBalance > targetSwayReserve) }, [payGasWithSwayIfPossible, priceHelper, swayBalance]); - const ethGasReserveBalance = useMemo(() => { + const ethGasReserveBalance = useMemo(import.meta.url, () => { if (maintainEthGasReserve && ethBalance) { const ethValueInUSDC = Math.floor(priceHelper.from(ethBalance, TOKEN.ETH)?.usdcValue); return priceHelper.from(Math.min(ethValueInUSDC, GAS_BUFFER_VALUE_USDC), TOKEN.USDC); @@ -43,7 +43,7 @@ const useWalletPurchasableBalances = (overrideAccount) => { // NOTE: do not add SWAY here unless want SWAY to be auto-swappable for // purchases (i.e. crewmates, starter packs, etc) - const swappableTokenBalances = useMemo(() => { + const swappableTokenBalances = useMemo(import.meta.url, () => { const allTokens = { [TOKEN.ETH]: ethBalance ? (ethBalance - safeBigInt(Math.floor(ethGasReserveBalance.to(TOKEN.ETH)))) : 0n, [TOKEN.USDC]: usdcBalance || 0n @@ -54,7 +54,7 @@ const useWalletPurchasableBalances = (overrideAccount) => { }, [autoswap, baseToken, ethBalance, ethGasReserveBalance, usdcBalance]); const isLoading = isLoading1 || isLoading2 || isLoading3; - return useMemo(() => { + return useMemo(import.meta.url, () => { if (isLoading) return { data: null, refetch: () => {}, isLoading: true }; const combinedBalance = priceHelper.from(0n); diff --git a/src/hooks/useWalletShips.js b/src/hooks/useWalletShips.js index b3ce26a48..465cb120b 100644 --- a/src/hooks/useWalletShips.js +++ b/src/hooks/useWalletShips.js @@ -5,7 +5,7 @@ import useSession from '~/hooks/useSession'; import useCrewContext from '~/hooks/useCrewContext'; import api from '~/lib/api'; import { useQuery } from 'react-query'; -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { entitiesCacheKey } from '~/lib/cacheKey'; // TODO: should we filter out disabled ships? not a thing yet @@ -15,9 +15,9 @@ const useWalletShips = () => { const { accountAddress } = useSession(); const { crews, loading: crewsLoading } = useCrewContext(); - const controllerIds = useMemo(() => (crews || []).map((c) => c.id), [crews]); + const controllerIds = useMemo(import.meta.url, () => (crews || []).map((c) => c.id), [crews]); - const query = useMemo(() => { + const query = useMemo(import.meta.url, () => { if (!accountAddress || crewsLoading) return null; try { diff --git a/src/hooks/useWatchlist.js b/src/hooks/useWatchlist.js index 374cdfb12..3bcedc285 100644 --- a/src/hooks/useWatchlist.js +++ b/src/hooks/useWatchlist.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import { useQuery } from 'react-query'; import { Entity } from '@influenceth/sdk'; @@ -17,7 +17,7 @@ const useWatchlist = () => { { enabled: !!token } ); - const ids = useMemo(() => { + const ids = useMemo(import.meta.url, () => { if (watchlist.data) return watchlist.data.map(w => w.id); return []; }, [watchlist.data, watchlist.dataUpdatedAt]); diff --git a/src/hooks/useWebWorker.js b/src/hooks/useWebWorker.js index dace210e6..978c49df8 100644 --- a/src/hooks/useWebWorker.js +++ b/src/hooks/useWebWorker.js @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from '~/lib/react-debug'; import Worker from 'worker-loader!../worker'; // eslint-disable-line @@ -110,7 +110,7 @@ const totalWorkers = (navigator?.hardwareConcurrency || 4) - 1; // CPUs minus 1 const workerThreadPool = new WorkerThreadPool(totalWorkers); const useWebWorker = () => { - return useMemo(() => ({ + return useMemo(import.meta.url, () => ({ broadcast: (message) => workerThreadPool.broadcast(message), processInBackground: (message, callback, transfer) => workerThreadPool.addToQueue(message, callback, transfer), cancelBackgroundProcesses: (filterFunc) => workerThreadPool.removeFromQueue(filterFunc) diff --git a/src/hooks/useWebsocket.js b/src/hooks/useWebsocket.js index dfa1d249d..2fcf68b46 100644 --- a/src/hooks/useWebsocket.js +++ b/src/hooks/useWebsocket.js @@ -1,4 +1,4 @@ -import { useContext } from 'react'; +import { useContext } from '~/lib/react-debug'; import WebsocketContext from '~/contexts/WebsocketContext'; diff --git a/src/index.js b/src/index.js index 485f89084..99b17e089 100644 --- a/src/index.js +++ b/src/index.js @@ -1,4 +1,4 @@ -import { Suspense } from 'react'; +import { Suspense } from '~/lib/react-debug'; import { createRoot } from 'react-dom/client'; import { QueryClient, QueryClientProvider } from 'react-query'; import LoadingAnimation from 'react-spinners/PropagateLoader'; diff --git a/src/lib/react-debug.js b/src/lib/react-debug.js new file mode 100644 index 000000000..9cf68c7bd --- /dev/null +++ b/src/lib/react-debug.js @@ -0,0 +1,64 @@ +import * as React from 'react'; + +// TO USE THIS: +// - search and replace all `useCallback (` with `useCallback (import.meta.url, ` [*** remove spaces ***] +// - search and replace all `useEffect (` with `useEffect (import.meta.url, ` [*** remove spaces ***] +// - search and replace all `useLayoutEffect (` with `useLayoutEffect (import.meta.url, ` [*** remove spaces ***] +// - search and replace all `useMemo (` with `useMemo (import.meta.url, ` [*** remove spaces ***] +// - search and replace all `from ' react'` with `from ' ~/lib/react-debug'` [*** remove spaces ***] +// - (fix this file if the React.use* were overwritten below or import above) + +// TO UN-USE THIS: +// - search and replace all `( import.meta.url, ` with `(` [*** remove space ***] +// - search and replace all `from ' ~/lib/react-debug'` with `from ' react'` [*** remove spaces ***] + + +const enableLogs = false; + +const cleanse = (filename) => { + return filename.split('/src')[1]; +} + +const useCallbackDebug = (fileName, callback, dependencies) => { + return React.useMemo (() => { + if (enableLogs) console.log('useCallback', cleanse(fileName), dependencies.length); + return callback; + }, [...dependencies]); +}; + +const useEffectDebug = (fileName, callback, dependencies) => { + return React.useEffect (() => { + if (enableLogs) console.log('useEffect', cleanse(fileName), dependencies.length); + return callback(); + }, [...dependencies]); +}; + +const useMemoDebug = (fileName, callback, dependencies) => { + return React.useMemo (() => { + if (enableLogs) console.log('useMemo', cleanse(fileName), dependencies.length); + return callback(); + }, [...dependencies]); +}; + +const reactWithMods = { + ...React, + useCallback: useCallbackDebug, + useEffect: useEffectDebug, + useMemo: useMemoDebug, +}; + +export const useCallback = useCallbackDebug; +export const useEffect = useEffectDebug; +export const useMemo = useMemoDebug; + +export const createContext = React.createContext; +export const forwardRef = React.forwardRef; +export const useContext = React.useContext; +export const useLayoutEffect = React.useLayoutEffect; +export const useRef = React.useRef; +export const useState = React.useState; +export const Component = React.Component; +export const Fragment = React.Fragment; +export const Suspense = React.Suspense; + +export default reactWithMods; \ No newline at end of file diff --git a/src/simulation/MockDataManager.js b/src/simulation/MockDataManager.js index 2e58061cc..7cf5cc888 100644 --- a/src/simulation/MockDataManager.js +++ b/src/simulation/MockDataManager.js @@ -3,7 +3,7 @@ import { Building, Deposit, DryDock, Entity, Extractor, Inventory, Lot, Order, P import useSimulationState from '~/hooks/useSimulationState'; import SIMULATION_CONFIG from './simulationConfig'; -import { useEffect, useMemo, useState } from 'react'; +import { useEffect, useMemo, useState } from '~/lib/react-debug'; import { entitiesCacheKey } from '~/lib/cacheKey'; import { entityToAgreements } from '~/lib/utils'; import { statuses as walletBuildingStatuses } from '~/hooks/useWalletBuildings'; @@ -100,19 +100,19 @@ const MockDataItem = ({ overwrite }) => { const { dataUpdatedAt } = useQuery(overwrite.queryKey, () => {}, { enabled: false, staleTime: Infinity }); // if new overwrite, always overwrite - useEffect(() => { + useEffect(import.meta.url, () => { setOverwriteAt((dataUpdatedAt || 0) + 0.5); }, [overwrite]); // if new dataUpdatedAt, always overwrite UNLESS caused by the most recent overwrite - useEffect(() => { + useEffect(import.meta.url, () => { if (dataUpdatedAt !== overwrittenAt) { setOverwriteAt((dataUpdatedAt || 0) + 0.5); } }, [dataUpdatedAt]); // transform and overwrite data - useEffect(() => { + useEffect(import.meta.url, () => { const { queryKey, transformer } = overwrite; const transformedData = transformer(queryClient.getQueryData(queryKey)); if (transformedData !== undefined) { @@ -132,7 +132,7 @@ const MockDataManager = () => { const queryClient = useQueryClient(); const simulation = useSimulationState(); - const overwrites = useMemo(() => { + const overwrites = useMemo(import.meta.url, () => { const myCrewEntity = Entity.formatEntity({ id: SIMULATION_CONFIG.crewId, label: Entity.IDS.CREW }); const configs = []; @@ -484,7 +484,7 @@ const MockDataManager = () => { }, [simulation]); // on unmount, refetch all overwrites - useEffect(() => { + useEffect(import.meta.url, () => { return () => { overwrites.forEach(({ queryKey }) => { queryClient.invalidateQueries({ queryKey, refetchType: 'active' }); @@ -511,7 +511,7 @@ const MockDataManager = () => { // entitiesCacheKey(Entity.IDS.DEPOSIT, { controllerId, isDepleted: false }), // deliveries - // const cacheKey = useMemo(() => { + // const cacheKey = useMemo(import.meta.url, () => { // const k = {}; // if (destination) k.destination = safeEntityId(destination); // if (origin) k.origin = safeEntityId(origin); diff --git a/src/simulation/MockTransactionManager.js b/src/simulation/MockTransactionManager.js index 443030ce7..8c1d1f8f4 100644 --- a/src/simulation/MockTransactionManager.js +++ b/src/simulation/MockTransactionManager.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef } from 'react'; +import { useCallback, useEffect, useRef } from '~/lib/react-debug'; import { Asteroid, Building, Entity, Lot, Process, Product, Ship, Time } from '@influenceth/sdk'; import { camelCase, cloneDeep } from 'lodash'; @@ -29,7 +29,7 @@ const MockTransactionManager = () => { const createAlert = useStore(s => s.dispatchAlertLogged); - const simulateResultingEvent = useCallback((tx) => { + const simulateResultingEvent = useCallback(import.meta.url, (tx) => { // let activities = []; let activityResolutions = []; let events = []; @@ -534,7 +534,7 @@ const MockTransactionManager = () => { }, [simulation, crew]); const processed = useRef([]); - useEffect(() => { + useEffect(import.meta.url, () => { pendingTransactions.forEach((tx) => { if (!processed.current.includes(tx.txHash)) { processed.current.push(tx.txHash); diff --git a/src/simulation/useSimulationSteps.js b/src/simulation/useSimulationSteps.js index da4d37dfb..00fef941d 100644 --- a/src/simulation/useSimulationSteps.js +++ b/src/simulation/useSimulationSteps.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from '~/lib/react-debug'; import { Building, Crewmate, Entity, Inventory, Permission, Process, Processor, Product, Ship } from '@influenceth/sdk'; import { useHistory } from 'react-router-dom'; import { BiTransfer as TransferIcon } from 'react-icons/bi'; @@ -80,14 +80,14 @@ const useSimulationSteps = () => { const [transitioning, setTransitioning] = useState(); const isTransitioning = !!transitioning; - useEffect(() => { + useEffect(import.meta.url, () => { // (returns unlisten, so can just return directly to useEffect) return history.listen((location) => setLocationPath(location.pathname)); }, [history]); const resetAsteroidFilters = () => dispatchFiltersReset('asteroids'); - const advance = useCallback(() => { + const advance = useCallback(import.meta.url, () => { // track that step was completed fireTrackingEvent('simulation', { step: simulation.step }); @@ -103,7 +103,7 @@ const useSimulationSteps = () => { }, 0); }, [dispatchSimulationStep, simulation?.step]); - const simulationSteps = useMemo(() => { + const simulationSteps = useMemo(import.meta.url, () => { // selectLot let selectedLotIsLeasable = false; @@ -1086,7 +1086,7 @@ const useSimulationSteps = () => { ]); // cleanse selected step index - useEffect(() => { + useEffect(import.meta.url, () => { if (!isLoading) { if (simulation.step === undefined || simulation.step < 0) {// || simulation.step > simulationSteps.length - 1) { dispatchSimulationStep(0); @@ -1096,19 +1096,19 @@ const useSimulationSteps = () => { // load step object from step index const previousStep = useRef({}); - const currentStep = useMemo(() => { + const currentStep = useMemo(import.meta.url, () => { // TODO: use named index instead of numbers return isLoading ? previousStep.current : simulationSteps[simulation.step]; }, [simulationSteps, simulation.step]); previousStep.current = currentStep; - const isFastForwarding = useMemo( + const isFastForwarding = useMemo(import.meta.url, () => simulation?.canFastForward && (simulation?.crewReadyAt || simulation?.taskReadyAt) > 0, [simulation?.canFastForward, simulation?.crewReadyAt, simulation?.taskReadyAt] ); // autoadvance if ready to autoadvance (wait for fastforwarding as necessary) - useEffect(() => { + useEffect(import.meta.url, () => { if (currentStep?.shouldAdvance && currentStep.shouldAdvance()) { if (!isFastForwarding || !simulation?.canFastForward) { advance(); @@ -1117,14 +1117,14 @@ const useSimulationSteps = () => { }, [advance, currentStep, simulation?.canFastForward, isFastForwarding]); // if new step, run initialize() - useEffect(() => { + useEffect(import.meta.url, () => { if (currentStep?.initialize) { currentStep.initialize(); } }, [simulation.step]); // dispatch coachmark config - useEffect(() => { + useEffect(import.meta.url, () => { let currentCoachmarks = {}; if (!isFastForwarding) { if (currentStep && pendingTransactions.length === 0) { @@ -1142,21 +1142,21 @@ const useSimulationSteps = () => { }, [currentStep?.coachmarks, isFastForwarding, pendingTransactions]); // derive and dispatch enabled-action config - const enabledActions = useMemo(() => { + const enabledActions = useMemo(import.meta.url, () => { if (isFastForwarding) return []; return Object.keys(currentStep?.enabledActions || {}).filter((id) => { return !!currentStep?.enabledActions[id] }); }, [currentStep?.enabledActions, isFastForwarding]); - useEffect(() => { + useEffect(import.meta.url, () => { dispatchSimulationActions(enabledActions); return () => { dispatchSimulationActions([]); } }, [enabledActions]); - return useMemo(() => ({ + return useMemo(import.meta.url, () => ({ currentStepIndex: simulation?.step, currentStep, isLastStep: simulation?.step === simulationSteps?.length - 1,