Skip to content

Commit

Permalink
fix(robot): correct handle of /robot urls (#1244)
Browse files Browse the repository at this point in the history
  • Loading branch information
happylolonly authored Sep 5, 2024
1 parent 91c7712 commit baa5f4f
Show file tree
Hide file tree
Showing 11 changed files with 108 additions and 87 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ const findSelectAppByUrl = (
address: Option<string>
) => {
let pathname = url;
const isRobot = url.includes('@') || url.includes('neuron/');
const isRobot =
url.includes('@') || url.includes('neuron/') || url.includes('robot');
const isOracle = url.includes('oracle');
const isCyberver = url.includes('cyberver');

Expand Down
3 changes: 3 additions & 0 deletions src/features/particle/useParticleDetails.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { useQuery } from '@tanstack/react-query';
import useQueueIpfsContent from 'src/hooks/useQueueIpfsContent';

/**
@deprecated TODO: refactor to useParticle hook
*/
function useParticleDetails(
cid: string,
{ skip = false } = {},
Expand Down
1 change: 1 addition & 0 deletions src/features/passport/usePassportContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ type Props = {
skip?: boolean;
};

// TODO: use useQuery lib
function usePassportContract<DataType>({ query, skip }: Props) {
const [data, setData] = useState<DataType>();
const [loading, setLoading] = useState(false);
Expand Down
13 changes: 7 additions & 6 deletions src/layouts/Main.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from 'react';
import Header from 'src/containers/application/Header/Header';
import { useAppDispatch, useAppSelector } from 'src/redux/hooks';
import { useAppDispatch } from 'src/redux/hooks';
import { routes } from 'src/routes';
import { useDevice } from 'src/contexts/device';
import { setFocus } from 'src/containers/application/Header/Commander/commander.redux';
Expand All @@ -21,9 +21,6 @@ import styles from './Main.module.scss';
import SideHydrogenBtn from './ui/SideHydrogenBtn/SideHydrogenBtn';

function MainLayout({ children }: { children: JSX.Element }) {
const { defaultAccount } = useAppSelector(({ pocket }) => pocket);
const addressBech32 = defaultAccount.account?.cyber.bech32;

const currentAddress = useCurrentAddress();
const { viewportWidth } = useDevice();
const ref = useRef<HTMLDivElement>(null);
Expand Down Expand Up @@ -62,8 +59,12 @@ function MainLayout({ children }: { children: JSX.Element }) {
<div className={styles.wrapper} ref={ref}>
<Header />

{CHAIN_ID === Networks.BOSTROM && !isMobile && <SenseButton />}
{!isMobile && <SideHydrogenBtn address={addressBech32} />}
{currentAddress && !isMobile && (
<>
{CHAIN_ID === Networks.BOSTROM && !isMobile && <SenseButton />}
<SideHydrogenBtn />
</>
)}

{children}
<footer>
Expand Down
11 changes: 5 additions & 6 deletions src/layouts/ui/SideHydrogenBtn/SideHydrogenBtn.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import HydrogenBalance from 'src/components/HydrogenBalance/HydrogenBalance';
import SideButtonLink from 'src/components/sideButtonLink/SideButtonLink';
import useCurrentAddress from 'src/hooks/useCurrentAddress';
import { routes } from 'src/routes';

function SideHydrogenBtn({ address }: { address?: string }) {
function SideHydrogenBtn() {
const currentAddress = useCurrentAddress();
return (
<SideButtonLink
to={`${routes.neuron.getLink(address || '')}/sigma`}
buttonType="hydrogen"
>
<HydrogenBalance address={address} />
<SideButtonLink to={routes.robot.routes.sigma.path} buttonType="hydrogen">
<HydrogenBalance address={currentAddress} />
</SideButtonLink>
);
}
Expand Down
56 changes: 37 additions & 19 deletions src/pages/robot/Robot.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Route, Routes } from 'react-router-dom';
import { Navigate, Route, Routes } from 'react-router-dom';
import TxsTable from 'src/pages/robot/_refactor/account/component/txsTable';
import Sigma from 'src/containers/sigma';
import RoutedEnergy from 'src/containers/energy';
import TableDiscipline from 'src/containers/gol/table';
import useAdviserTexts from 'src/features/adviser/useAdviserTexts';
import { routes } from 'src/routes';
import Loader2 from 'src/components/ui/Loader2';
import Layout from './Layout/Layout';
import RobotContextProvider, { useRobotContext } from './robot.context';
import Brain from './Brain/Brain';
Expand All @@ -18,33 +20,51 @@ import Follows from './_refactor/account/tabs/Follows/Follows';
import Soul from './Soul/Soul';

function RobotRoutes() {
const { isLoading, address } = useRobotContext();
const { address, isFetched } = useRobotContext();

const newUser = !isLoading && !address;
const newUser = isFetched && !address;

useAdviserTexts({
defaultText: 'my robot',
defaultText: `${!newUser ? 'my' : 'welcome to'} robot`,
});

if (!isFetched) {
return <Loader2 />;
}

return (
<Routes>
<Route path="/" element={<Layout />}>
{newUser ? (
<Route index element={<ZeroUser />} />
<>
<Route index element={<ZeroUser />} />
<Route path="*" element={<Navigate to="/robot" />} />
</>
) : (
<Route element={<LayoutRoot />}>
<Route index element={newUser ? <ZeroUser /> : <FeedsTab />} />
<Route path="soul" element={<Soul />} />
{['energy', 'energy/:pageId'].map((path) => (
<Route key={path} path={path} element={<RoutedEnergy />} />
))}
<>
<Route element={<LayoutRoot />}>
<Route index element={<FeedsTab />} />
<Route path="soul" element={<Soul />} />

{/* energy */}
<Route
path="/grid"
element={<Navigate to={routes.robot.routes.energy.path} />}
/>
{['energy', 'energy/:pageId'].map((path) => (
<Route key={path} path={path} element={<RoutedEnergy />} />
))}

<Route path="swarm" element={<Follows />} />
<Route path="security" element={<Heroes />} />
<Route path="rights" element={<UnderConstruction />} />
<Route path="karma" element={<Karma />} />
<Route path="badges" element={<TableDiscipline />} />
</Route>
<Route path="swarm" element={<Follows />} />
<Route path="security" element={<Heroes />} />
<Route path="rights" element={<UnderConstruction />} />
<Route path="karma" element={<Karma />} />
<Route path="badges" element={<TableDiscipline />} />
</Route>

{/* should be for logined user, but without layout */}
<Route path="brain/*" element={<Brain />} />
</>
)}

<Route path="sigma" element={<Sigma />} />
Expand All @@ -54,8 +74,6 @@ function RobotRoutes() {
<Route key={path} path={path} element={<SensePage />} />
))}

<Route path="brain/*" element={<Brain />} />

<Route path="*" element={<p>Page should not exist</p>} />
</Route>
</Routes>
Expand Down
6 changes: 3 additions & 3 deletions src/pages/robot/ZeroUser/ZeroUser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ function ZeroUser() {

useEffect(() => {
setAdviser(
<>
<div>
Connect your wallet by adding a <Link to={routes.keys.path}>key</Link>{' '}
to start using robot. <br /> Get your first{' '}
to start using robot <br /> Get your first{' '}
<Link to={routes.citizenship.path}>citizenship</Link> to unlock all
features of cyb
</>
</div>
);

return () => {
Expand Down
87 changes: 36 additions & 51 deletions src/pages/robot/robot.context.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import React, { useCallback, useMemo, useState } from 'react';
import { useParams, useLocation, useNavigate } from 'react-router-dom';
import { CHAIN_ID } from 'src/constants/config';
import usePassportByAddress from 'src/features/passport/hooks/usePassportByAddress';
Expand All @@ -18,6 +18,7 @@ const RobotContext = React.createContext<{
isLoading: boolean;
addRefetch: (func: () => void) => void;
refetchData: () => void;
isFetched: boolean;
}>({
address: null,
passport: undefined,
Expand All @@ -26,10 +27,14 @@ const RobotContext = React.createContext<{
nickname: undefined,
addRefetch: () => {},
refetchData: () => {},
isFetched: false,
});

export const useRobotContext = () => React.useContext(RobotContext);

/**
* Complex logic change carefully
*/
function RobotContextProvider({ children }: { children: React.ReactNode }) {
const params = useParams();
const location = useLocation();
Expand All @@ -40,7 +45,9 @@ function RobotContextProvider({ children }: { children: React.ReactNode }) {
const currentAddress = useAppSelector(selectCurrentAddress);
const currentUserPassport = usePassportByAddress(currentAddress);

const { accounts } = useAppSelector(({ pocket }) => pocket);
const { accounts, isInitialized: isPocketInitialized } = useAppSelector(
({ pocket }) => pocket
);

const { username } = params;
const nickname =
Expand Down Expand Up @@ -136,59 +143,28 @@ function RobotContextProvider({ children }: { children: React.ReactNode }) {
const currentPassport = isOwner ? currentUserPassport : passportContract;
let currentRobotAddress = address || currentPassport.data?.owner || null;

if (
robotUrl &&
currentUserPassport.data &&
currentAddress === currentUserPassport.data.owner
) {
navigate(
location.pathname.replace(
routes.robot.path,
routes.robotPassport.getLink(
currentUserPassport.data.extension.nickname
)
),
{
replace: true,
}
);
}

if (CHAIN_ID === Networks.SPACE_PUSSY && currentRobotAddress) {
currentRobotAddress = fromBech32(currentRobotAddress, 'pussy');
}

const isLoading = currentPassport.loading;

// redirect from /robot to /@nickname
const newUser =
!passportContract.loading &&
!currentUserPassport.loading &&
!currentRobotAddress;

// redirects
useEffect(() => {
if (
newUser &&
location.pathname.includes(routes.robot.path) &&
// allowed routes
![
routes.robot.path,
routes.robot.routes.drive.path,
routes.robot.routes.sense.path,
].includes(location.pathname)
) {
navigate(routes.robot.path);
}

if (
robotUrl &&
currentUserPassport.data &&
currentAddress === currentUserPassport.data.owner
) {
navigate(
location.pathname.replace(
routes.robot.path,
routes.robotPassport.getLink(
currentUserPassport.data.extension.nickname
)
),
{
replace: true,
}
);
}
}, [
location.pathname,
robotUrl,
currentUserPassport.data,
newUser,
currentAddress,
navigate,
]);

const addRefetch = useCallback(
(func: () => void) => {
setRefetch((items) => [...items, func]);
Expand All @@ -200,6 +176,13 @@ function RobotContextProvider({ children }: { children: React.ReactNode }) {
refetchFuncs.forEach((func) => func());
}, [refetchFuncs]);

const isLoading = currentPassport.loading || false;

const isFetched =
currentPassport.data !== undefined ||
// zero user
(robotUrl && isPocketInitialized && !currentAddress);

const contextValue = useMemo(
() => ({
address: currentRobotAddress,
Expand All @@ -209,13 +192,15 @@ function RobotContextProvider({ children }: { children: React.ReactNode }) {
nickname: nickname || currentPassport.data?.extension.nickname,
refetchData,
isLoading,
isFetched,
}),
[
currentPassport.data,
nickname,
addRefetch,
refetchData,
isOwner,
isFetched,
isLoading,
currentRobotAddress,
]
Expand Down
7 changes: 7 additions & 0 deletions src/redux/features/pocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@ type SliceState = {
};
defaultAccount: DefaultAccount;
accounts: null | Accounts;
isInitialized: boolean;
};

const initialState: SliceState = {
actionBar: {
tweet: POCKET.STAGE_TWEET_ACTION_BAR.TWEET, // stage for tweet ActionBar: 'addAvatar' 'follow' 'tweet'
},
isInitialized: false,
defaultAccount: {
name: null,
account: null,
Expand Down Expand Up @@ -76,6 +78,9 @@ const slice = createSlice({

saveToLocalStorage(state);
},
setInitialized: (state) => {
state.isInitialized = true;
},
setStageTweetActionBar: (state, { payload }: PayloadAction<string>) => {
state.actionBar.tweet = payload;
},
Expand Down Expand Up @@ -191,6 +196,8 @@ export const initPocket = () => (dispatch: Dispatch) => {
});

accountsTemp && dispatch(setAccounts(accountsTemp));

dispatch(slice.actions.setInitialized());
};

const defaultNameAccount = () => {
Expand Down
5 changes: 4 additions & 1 deletion src/router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,10 @@ function AppRouter() {
<Route path="/ide" element={<FreestyleIde />} />

<Route path="/robot/*" element={<Robot />} />
<Route path="/ipfs" element={<Navigate to="/robot/drive" />} />
<Route
path="/ipfs"
element={<Navigate to={routes.settings.path} />}
/>

<Route path={routes.temple.path} element={<Temple />} />
<Route path={routes.neuron.path} element={<Robot />} />
Expand Down
3 changes: 3 additions & 0 deletions src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ export const routes = {
soul: {
path: '/robot/soul',
},
sigma: {
path: '/robot/sigma',
},
},
},
robotPassport: {
Expand Down

0 comments on commit baa5f4f

Please sign in to comment.