Skip to content

Commit

Permalink
optimize for crust wallet
Browse files Browse the repository at this point in the history
	1. GetNickname only befor priminum
	2. redirect add loading
	3. remove google anylitic
  • Loading branch information
XueMoMo committed Jul 16, 2024
1 parent 96f35ac commit 8b8672c
Show file tree
Hide file tree
Showing 9 changed files with 349 additions and 285 deletions.
439 changes: 217 additions & 222 deletions components/GetNickname.tsx

Large diffs are not rendered by default.

66 changes: 46 additions & 20 deletions components/Redirect.tsx
Original file line number Diff line number Diff line change
@@ -1,39 +1,65 @@
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import Device from 'device.js';
import Device from "device.js";
import { useRouter } from "next/router";
import { useEffect } from "react";
import { useEffect, useState } from "react";
import { Dimmer, Loader, Progress } from "semantic-ui-react";
import { useContextWrapLoginUser } from "../lib/wallet/hooks";

const NO_CHECK_USER = [
'/files/share',
'/files/receive'
]
function RedirectLoading(p: { children?: React.ReactNode }) {
// const [percent, setPercent] = useState(0);
// useEffect(() => {
// const timer = setInterval(() => {
// setPercent((p) => {
// p >= 80 && clearInterval(timer);
// return p + 1;
// });
// }, 200);
// return () => clearInterval(timer);
// }, []);
return (
<>
{p.children}
<Dimmer active inverted style={{ position: "fixed", left: 0, top: 0, width: "100vw", height: "100vh" }}>
<Loader active inverted size="large" />
</Dimmer>
{/* <Progress
success
percent={percent}
indicating
size="tiny"
style={{ position: "fixed", zIndex: 1000, top: 0, left: 0, width: "100%" }}
/> */}
</>
);
}

const NO_CHECK_USER = ["/files/share", "/files/receive"];
export default function Redirect(props: { children: any }) {
const wUser = useContextWrapLoginUser();
const router = useRouter();
useEffect(() => {
const isMobile = new Device().mobile
if (router.pathname !== '/mobile' && isMobile) {
router.replace('/mobile')
} else if (router.pathname === '/mobile' && !isMobile) {
router.replace('/')
const isMobile = new Device().mobile;
if (router.pathname !== "/mobile" && isMobile) {
router.replace("/mobile");
} else if (router.pathname === "/mobile" && !isMobile) {
router.replace("/");
}
}, [router])
}, [router]);

// no support mobile
if (router.pathname === '/mobile') return props.children;
if (router.pathname === "/mobile") return props.children;
// no check user
if (NO_CHECK_USER.includes(router.pathname)) return props.children;

// check user
if ((!wUser.account || !wUser.authBasic) && (router.pathname !== '' && router.pathname !== '/')) {
router.replace('/')
return null
if ((!wUser.account || !wUser.authBasic) && router.pathname !== "" && router.pathname !== "/") {
router.replace("/");
return <RedirectLoading>{props.children}</RedirectLoading>;
}
if (wUser.account && wUser.authBasic && (router.pathname === '' || router.pathname === '/')) {
router.replace(`/home/${window.location.search}`)
return null

if (wUser.account && wUser.authBasic && (router.pathname === "" || router.pathname === "/")) {
router.replace(`/home/${window.location.search}`);
return <RedirectLoading>{props.children}</RedirectLoading>;
}
return props.children;
}
8 changes: 6 additions & 2 deletions components/User.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import _ from "lodash";
import { useRouter } from "next/router";
import React, { useCallback, useMemo, useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { FiCheck, FiChevronDown, FiChevronUp } from "react-icons/fi";
import { Dropdown, Item, Segment } from "semantic-ui-react";
import styled from "styled-components";
Expand Down Expand Up @@ -157,7 +157,11 @@ function User(props: Props) {
const [ftmAccount, ftmAccont2] = useMemo(() => [shortStr(user.account), shortStr(user.account, 14)], [user]);
const _onClickLogout = useCallback(user.logout, [user]);
const showSwitchAccount = user.wallet === "crust" || user.wallet === "polkadot-js";
const [mRewards] = useGet(() => getEarnRewards(user.account), [user.account, isCrust], "getEarnRewards");
const [firstExpandUser, toggleFirstExpandUser] = useToggle();
useEffect(() => {
open && toggleFirstExpandUser(true);
},[open])
const [mRewards] = useGet(() => getEarnRewards(user.account), [user.account, isCrust, firstExpandUser], "getEarnRewards");
const { rewards } = useAutoUpdateToStore({ key: "rewards", value: mRewards });
const totalRewards = getFormatValue(rewards, "total.total");
const r = useRouter();
Expand Down
11 changes: 6 additions & 5 deletions components/root/MApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,22 @@ import I18NextHttpBackend from "i18next-http-backend";
import { AppProps } from 'next/app';
import Head from "next/head";
import { useRouter } from "next/router";
import React, { useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { initReactI18next } from "react-i18next";
import { Dimmer, Loader } from "semantic-ui-react";
import { AppProvider, AppType, useApp } from '../../lib/AppContext';
import { initAlert } from "../../lib/initAlert";
import { initApi } from "../../lib/initApi";
import { initAppStore } from "../../lib/initAppStore";
import { initReCaptcha } from "../../lib/initGoogleReCaptcha";
import { initLoading } from "../../lib/initLoading";
import { ContextWrapLoginUser, useLoginUser } from "../../lib/wallet/hooks";
import AlertMessage from "../AlertMessage";
import { GetNickname } from '../GetNickname';
import { ReCaptcha } from "../comom/ReCaptcha";
import Layout, { siteTitle } from "../layout";
import Redirect from "../Redirect";
import { BasePropsWithChildren } from "../types";
import { ReCaptcha } from "../comom/ReCaptcha";
import { initReCaptcha } from "../../lib/initGoogleReCaptcha";
import { useLoadNickname } from "../../lib/useNickname";

function initI18n() {
const [init, setInit] = useState(false)
Expand Down Expand Up @@ -49,6 +49,7 @@ function MAppProvider(props: BasePropsWithChildren) {
const loading = initLoading()
const store = initAppStore()
const recaptcha = initReCaptcha()
useLoadNickname()
const appType = useMemo<AppType>(() => ({ alert, api, loading, store, recaptcha }), [alert, api, loading, store, recaptcha])
return <AppProvider value={appType}>
{props.children}
Expand Down Expand Up @@ -91,7 +92,7 @@ function DefAppPage({ Component, pageProps }: AppProps) {
{
showPage && <Redirect>
<Component {...pageProps} />
<GetNickname />
{/* <GetNickname /> */}
</Redirect>
}
<MAppLoading show={wUser.isLoad} />
Expand Down
23 changes: 23 additions & 0 deletions lib/useNickname.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import _ from "lodash";
import { useEffect } from "react";
import { getMemberByAccount, getNickNameByAccount } from "./http/share_earn";
import { useContextWrapLoginUser } from "./wallet/hooks";

export function useLoadNickname() {
const wUser = useContextWrapLoginUser();
const { account, wallet } = wUser;
useEffect(() => {
if (account && wallet === "crust") {
wUser.setIsLoadingNickname(true);
getMemberByAccount(account)
.then(wUser.setMember)
.catch(console.error)
.then(() => getNickNameByAccount(account))
.then((name) => wUser.setNickName(name))
.catch(console.error)
.then(() => wUser.setIsLoadingNickname(false));
}
wUser.setMember(undefined);
wUser.setNickName("");
}, [account, wallet]);
}
8 changes: 6 additions & 2 deletions lib/wallet/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ export function saveLastUser(wallet: WalletType, data: LoginUser, key: KEY_TYPE
export interface WrapLoginUser extends LoginUser {
nickName?: string;
setNickName: Dispatch<SetStateAction<string>>;
isLoadingNickname?: boolean;
setIsLoadingNickname: Dispatch<SetStateAction<boolean>>;
member?: Member;
setMember: Dispatch<SetStateAction<Member>>;
isLoad: boolean;
Expand Down Expand Up @@ -454,7 +456,7 @@ export function useLoginUser(key: KEY_TYPE = "files:login"): WrapLoginUser {

setLoginUser({ ...defLoginUser });
}, [setLoginUser, account]);

const [isLoadingNickname,setIsLoadingNickname] = useState();
const wUser: WrapLoginUser = useMemo(() => {
const wrapLoginUser: WrapLoginUser = {
...account,
Expand Down Expand Up @@ -484,9 +486,11 @@ export function useLoginUser(key: KEY_TYPE = "files:login"): WrapLoginUser {
setNickName,
setMember,
member,
setIsLoadingNickname,
isLoadingNickname
};
return wrapLoginUser;
}, [account, accounts, isLoad, setLoginUser, logout, nickName, member, key]);
}, [account, accounts, isLoad, setLoginUser, logout, nickName, member, key, isLoadingNickname]);
const uSign = useSign(wUser);
wUser.sign = uSign.sign;
return wUser;
Expand Down
2 changes: 1 addition & 1 deletion pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default function App({ Component, ...props }: AppProps) {
},[])
useConfigDomain()
const r = useRouter()
useGaPageView()
// useGaPageView()
if (!isClient) {
return null
}
Expand Down
12 changes: 6 additions & 6 deletions pages/_document.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,26 @@ class MyDocument extends Document {
return (
<Html>
<Head>
<script dangerouslySetInnerHTML={{
{/* <script dangerouslySetInnerHTML={{
__html: `
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer',${GTM_ID});
` }} />
<script async src={`https://www.googletagmanager.com/gtag/js?id=${GA_ID}`} />
<script dangerouslySetInnerHTML={{
` }} /> */}
{/* <script async src={`https://www.googletagmanager.com/gtag/js?id=${GA_ID}`} /> */}
{/* <script dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', ${GA_ID}, { page_path: window.location.pathname });
` }}
/>
/> */}
</Head>
<body>
<noscript><iframe src={`https://www.googletagmanager.com/ns.html?id=${GTM_ID}`} height="0" width="0" style={{ display: 'none', visibility: 'hidden' }}></iframe></noscript>
{/* <noscript><iframe src={`https://www.googletagmanager.com/ns.html?id=${GTM_ID}`} height="0" width="0" style={{ display: 'none', visibility: 'hidden' }}></iframe></noscript> */}
<Main />
<NextScript />
</body>
Expand Down
65 changes: 38 additions & 27 deletions pages/user.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { format } from 'date-fns';
import { toBlob } from 'html-to-image';
import _ from 'lodash';
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Loader } from 'semantic-ui-react';
import styled from "styled-components";
import { BindAirdrop } from '../components/BindAirdrop';
import Btn from "../components/Btn";
Expand All @@ -22,6 +23,8 @@ import { BlobFile } from '../lib/types';
import { useAuthGateway, useAuthPinner } from '../lib/useAuth';
import { useUpload } from '../lib/useUpload';
import { formatCRU, trimZero } from '../lib/utils';
import { useContextWrapLoginUser } from '../lib/wallet/hooks';
import { GetNickname } from '../components/GetNickname';

export interface Props {
className?: string
Expand All @@ -30,6 +33,7 @@ export interface Props {
function Index(props: Props) {
const { className } = props
const { alert, loading } = useApp()
const wUser = useContextWrapLoginUser()
const { isCrust, isPremiumUser, deposit, doGetDeposit, hasDeposit, user, loading: isLoadingDeposit } = useGetDepost()
const [nickStat, setNickStat] = useSafeState<{ error?: string, shareFrom?: string, checking: boolean }>({ checking: false })
const [inputNickname, setInputNickname] = useState<string>()
Expand Down Expand Up @@ -60,11 +64,12 @@ function Index(props: Props) {

//
const [value, setValue] = useState<string>()
const [config] = useGet(() => getShareEarnConfig())
const [config, _doRegetConfig, isLoadingConfig] = useGet(() => getShareEarnConfig())
const showBasePrice = config && config.showBase
const showDeposit = isCrust && !hasDeposit && !isLoadingDeposit
const showDeposit = isCrust && !hasDeposit
const showClaim = isCrust && hasDeposit
const [dest] = useGet(() => getDepositAddress())
const [dest, _doRegetDepositAddress, isLoadingDepositAddress] = useGet(() => getDepositAddress())
const showPremiumLoading = isLoadingDeposit || wUser.isLoadingNickname || isLoadingConfig || isLoadingDepositAddress
const fValue = useMemo(() => formatCRU(value), [value])
const cTime = useMemo(() => new Date().getTime() / 1000, [])
const fCalimValue = useMemo(() => {
Expand Down Expand Up @@ -158,7 +163,7 @@ function Index(props: Props) {
.catch(console.error)
.then(loading.hide)
}


return <PageUserSideLayout path={'/user'} className={className}>
<div className="user-Info">
Expand Down Expand Up @@ -207,29 +212,35 @@ function Index(props: Props) {
{
showDeposit && <MCard>
<div className="title font-sans-semibold">Get Premium</div>
<div className="text font-sans-regular">
{
showBasePrice ? <>
Deposit <span className={classNames('origin', 'isBase')}>{baseGuaranteeAmount} CRU</span><span className='reffer'>(now {guaranteeAmount} CRU for Discount!)</span> to become a Premium User. <br />
Deposit <span className={classNames('origin', 'isBase')}>{baseGuaranteeDiscountWithReferer} CRU</span><span className='reffer'>(now {guaranteeDiscountWithReferer} CRU for Discount!)</span> if you have an invitation code (the Nickname of your inviter).<br />
</> : <>
Deposit <span className={classNames('origin')}>{guaranteeAmount} CRU</span> to become a Premium User. <br />
Deposit <span className={classNames('origin')}>{guaranteeDiscountWithReferer} CRU</span> if you have an invitation code (the Nickname of your inviter).<br />
</>
}
The deposit can be redeemed {days} days after your deposit date.
</div>
<div className={'btns mbtns'}>
<input
className="input-Nickname"
spellCheck="false"
placeholder="Enter inviter’s Nickname(Leave blank if you have no inviter.)"
onChange={_onChangeNickname} />
{nickStat.error && <span className="input-NickError">{nickStat.error}</span>}
<br />
<Btn content={onGoingDeposit ? 'Please wait for transaction finalization…' : `Deposit ${fValue} CRU`} disabled={disabledDeposit} onClick={_onClickDeposit} />
<a href="/docs/CrustFiles_Users" target="_blank">How to deposit?</a>
</div>
{
showPremiumLoading ? <div style={{ paddingBottom: '1.2rem'}}><Loader active size='medium'/></div> :
true ? <GetNickname/> :
<>
<div className="text font-sans-regular">
{
showBasePrice ? <>
Deposit <span className={classNames('origin', 'isBase')}>{baseGuaranteeAmount} CRU</span><span className='reffer'>(now {guaranteeAmount} CRU for Discount!)</span> to become a Premium User. <br />
Deposit <span className={classNames('origin', 'isBase')}>{baseGuaranteeDiscountWithReferer} CRU</span><span className='reffer'>(now {guaranteeDiscountWithReferer} CRU for Discount!)</span> if you have an invitation code (the Nickname of your inviter).<br />
</> : <>
Deposit <span className={classNames('origin')}>{guaranteeAmount} CRU</span> to become a Premium User. <br />
Deposit <span className={classNames('origin')}>{guaranteeDiscountWithReferer} CRU</span> if you have an invitation code (the Nickname of your inviter).<br />
</>
}
The deposit can be redeemed {days} days after your deposit date.
</div>
<div className={'btns mbtns'}>
<input
className="input-Nickname"
spellCheck="false"
placeholder="Enter inviter’s Nickname(Leave blank if you have no inviter.)"
onChange={_onChangeNickname} />
{nickStat.error && <span className="input-NickError">{nickStat.error}</span>}
<br />
<Btn content={onGoingDeposit ? 'Please wait for transaction finalization…' : `Deposit ${fValue} CRU`} disabled={disabledDeposit} onClick={_onClickDeposit} />
<a href="/docs/CrustFiles_Users" target="_blank">How to deposit?</a>
</div>
</>
}
</MCard>}
{
showClaim && <MCard>
Expand Down

0 comments on commit 8b8672c

Please sign in to comment.