react-device-detect#isMobile TypeScript Examples

The following examples show how to use react-device-detect#isMobile. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From cuiswap with GNU General Public License v3.0 6 votes vote down vote up
export function useEagerConnect() {
  const { activate, active } = useWeb3ReactCore() // specifically using useWeb3ReactCore because of what this hook does
  const [tried, setTried] = useState(false)

  useEffect(() => {
    injected.isAuthorized().then(isAuthorized => {
      if (isAuthorized) {
        activate(injected, undefined, true).catch(() => {
          setTried(true)
        })
      } else {
        if (isMobile && window.ethereum) {
          activate(injected, undefined, true).catch(() => {
            setTried(true)
          })
        } else {
          setTried(true)
        }
      }
    })
  }, [activate]) // intentionally only running on mount (make sure it's only mounted once :))

  // if the connection worked, wait until we get confirmation of that to flip the flag
  useEffect(() => {
    if (active) {
      setTried(true)
    }
  }, [active])

  return tried
}
Example #2
Source File: URLWarning.tsx    From sybil-interface with GNU General Public License v3.0 6 votes vote down vote up
export default function URLWarning() {
  const toggleURLWarning = useURLWarningToggle()
  const showURLWarning = useURLWarningVisible()

  return isMobile ? (
    <PhishAlert isActive={showURLWarning}>
      <div style={{ display: 'flex' }}>
        <AlertTriangle style={{ marginRight: 6 }} size={12} /> Make sure the URL is
        <code style={{ padding: '0 4px', display: 'inline', fontWeight: 'bold' }}>app.uniswap.org</code>
      </div>
      <StyledClose size={12} onClick={toggleURLWarning} />
    </PhishAlert>
  ) : window.location.hostname === 'app.uniswap.org' ? (
    <PhishAlert isActive={showURLWarning}>
      <div style={{ display: 'flex' }}>
        <AlertTriangle style={{ marginRight: 6 }} size={12} /> Always make sure the URL is
        <code style={{ padding: '0 4px', display: 'inline', fontWeight: 'bold' }}>app.uniswap.org</code> - bookmark it
        to be safe.
      </div>
      <StyledClose size={12} onClick={toggleURLWarning} />
    </PhishAlert>
  ) : null
}
Example #3
Source File: ScreenResolutionMessage.tsx    From amplication with Apache License 2.0 6 votes vote down vote up
function ScreenResolutionMessage() {
  const { innerWidth } = useWindowSize();

  if (!innerWidth || innerWidth > MIN_WIDTH) return null;

  return (
    <div
      className={classNames(CLASS_NAME, {
        "screen-resolution-message--mobile": isMobile,
      })}
    >
      <MobileImage />
      <div className={`${CLASS_NAME}__title`}>
        Your resolution is too small{" "}
      </div>
      <div className={`${CLASS_NAME}__message`}>
        {isMobile ? (
          <>To enjoy Amplication please open it from a computer.</>
        ) : (
          <>
            To enjoy Amplication resize your browser to be at least {MIN_WIDTH}
            px&nbsp;wide.
          </>
        )}
      </div>
    </div>
  );
}
Example #4
Source File: ios-viewport-fix.tsx    From react-celo with MIT License 6 votes vote down vote up
export default function IOSViewportFix() {
  const { pendingActionCount, connectionCallback } = useCeloInternal();
  const isOpen = pendingActionCount > 0 || Boolean(connectionCallback);

  const tags = useMemo(
    () =>
      isMobile &&
      isOpen && (
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1"
        />
      ),
    [isOpen]
  );
  return <Helmet>{tags}</Helmet>;
}
Example #5
Source File: index.tsx    From cheeseswap-interface with GNU General Public License v3.0 6 votes vote down vote up
export default function Modal({
  isOpen,
  onDismiss,
  minHeight = false,
  maxHeight = 50,
  initialFocusRef,
  children
}: ModalProps) {
  const fadeTransition = useTransition(isOpen, null, {
    config: { duration: 200 },
    from: { opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 }
  })

  return (
    <>
      {fadeTransition.map(
        ({ item, key, props }) =>
          item && (
            <StyledDialogOverlay key={key} style={props} onDismiss={onDismiss} initialFocusRef={initialFocusRef}>
              <StyledDialogContent
                aria-label="dialog content"
                minHeight={minHeight}
                maxHeight={maxHeight}
                mobile={isMobile}
              >
                {/* prevents the automatic focusing of inputs on mobile by the reach dialog */}
                {!initialFocusRef && isMobile ? <div tabIndex={1} /> : null}
                {children}
              </StyledDialogContent>
            </StyledDialogOverlay>
          )
      )}
    </>
  )
}
Example #6
Source File: hooks.ts    From roamjs-com with MIT License 6 votes vote down vote up
useIsMobile = (): boolean => {
  const [mobile, setMobile] = useState(false);

  useEffect(() => {
    setMobile(isMobile);
  }, [setMobile]);

  return mobile;
}
Example #7
Source File: ExchangeList.tsx    From dyp with Do What The F*ck You Want To Public License 6 votes vote down vote up
export default function ExchangeList() {
  // const toggleURLWarning = useURLWarningToggle()
  // const showURLWarning = useURLWarningVisible()

  return isMobile ? (
    <PhishAlert isActive={true}>
      <div style={{ display: 'flex' }}>
        <img src={Kucoin} width={30} height={30} style={{ margin: '10px', marginLeft: '0px' }} alt={'logo'} />
        <code style={{ marginTop: '19px', display: 'inline', fontWeight: 'bold' }}>
          <PointerLink>
            <ExternalLink target="_blank" style={{ color: 'white' }} href="https://trade.kucoin.com/DYP-USDT">
              DYP trading is now live on #KuCoin!
            </ExternalLink>
          </PointerLink>
        </code>
      </div>
    </PhishAlert>
  ) : window.location.hostname === 'dyp.finance' ? (
    <PhishAlert isActive={true}>
      <div style={{ display: 'flex' }}>
        <img src={Kucoin} width={30} height={30} style={{ margin: '10px', marginLeft: '25px' }} alt={'logo'} />
        <code style={{ marginTop: '18px', display: 'inline', fontWeight: 'bold', fontSize: '13px' }}>
          <PointerLink>
            <ExternalLink target="_blank" style={{ color: 'white' }} href="https://trade.kucoin.com/DYP-USDT">
              DYP trading is now live on #KuCoin!
            </ExternalLink>
          </PointerLink>
        </code>
      </div>
    </PhishAlert>
  ) : null
}
Example #8
Source File: index.tsx    From goose-frontend-amm with GNU General Public License v3.0 6 votes vote down vote up
export default function Modal({
  isOpen,
  onDismiss,
  minHeight = false,
  maxHeight = 50,
  initialFocusRef,
  children,
}: ModalProps) {
  const fadeTransition = useTransition(isOpen, null, {
    config: { duration: 200 },
    from: { opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 },
  })

  return (
    <>
      {fadeTransition.map(
        ({ item, key, props }) =>
          item && (
            <StyledDialogOverlay key={key} style={props} onDismiss={onDismiss} initialFocusRef={initialFocusRef}>
              <StyledDialogContent
                aria-label="dialog content"
                minHeight={minHeight}
                maxHeight={maxHeight}
                mobile={isMobile}
              >
                {/* prevents the automatic focusing of inputs on mobile by the reach dialog */}
                {/* eslint-disable */}
                {!initialFocusRef && isMobile ? <div tabIndex={1} /> : null}
                {/* eslint-enable */}
                {children}
              </StyledDialogContent>
            </StyledDialogOverlay>
          )
      )}
    </>
  )
}
Example #9
Source File: SearchSidebar.tsx    From peterportal-client with MIT License 6 votes vote down vote up
SearchSidebar = () => {
  const dispatch = useAppDispatch();
  return (
    <div className="search-sidebar" >
      {isMobile && <div><CloseButton className='close-icon' onClick={() => { dispatch(setShowSearch(false)) }} /></div>}
      <div className='search-body'>
        <Droppable droppableId="search" type="COURSE">
          {(provided) => {
            return (
              <div
                ref={provided.innerRef}
                style={{ height: "100%" }}
                {...provided.droppableProps}
              >
                <div className='search-sidebar-content'>
                  <div className='search-sidebar-search-module'>
                    <SearchModule index='courses' />
                  </div>
                  <SearchHitContainer index='courses' CourseHitItem={CourseHitItem} />
                </div>
                {provided.placeholder}
              </div>
            );
          }}
        </Droppable>
      </div>
    </div>
  );
}
Example #10
Source File: index.ts    From mozartfinance-swap-interface with GNU General Public License v3.0 6 votes vote down vote up
export function useEagerConnect() {
  const { activate, active } = useWeb3ReactCore() // specifically using useWeb3ReactCore because of what this hook does
  const [tried, setTried] = useState(false)

  useEffect(() => {
    injected.isAuthorized().then((isAuthorized) => {
      const hasSignedIn = window.localStorage.getItem(connectorLocalStorageKey)
      if (isAuthorized && hasSignedIn) {
        activate(injected, undefined, true).catch(() => {
          setTried(true)
        })
      } else if (isMobile && window.ethereum && hasSignedIn) {
        activate(injected, undefined, true).catch(() => {
          setTried(true)
        })
      } else {
        setTried(true)
      }
    })
  }, [activate]) // intentionally only running on mount (make sure it's only mounted once :))

  // if the connection worked, wait until we get confirmation of that to flip the flag
  useEffect(() => {
    if (active) {
      setTried(true)
    }
  }, [active])

  return tried
}
Example #11
Source File: index.ts    From pancake-swap-exchange-testnet with GNU General Public License v3.0 6 votes vote down vote up
export function useEagerConnect() {
  const { activate, active } = useWeb3ReactCore() // specifically using useWeb3ReactCore because of what this hook does
  const [tried, setTried] = useState(false)

  useEffect(() => {
    injected.isAuthorized().then((isAuthorized) => {
      const hasSignedIn = window.localStorage.getItem(connectorLocalStorageKey)
      if (isAuthorized && hasSignedIn) {
        activate(injected, undefined, true).catch(() => {
          setTried(true)
        })
      } else if (isMobile && window.ethereum && hasSignedIn) {
        activate(injected, undefined, true).catch(() => {
          setTried(true)
        })
      } else {
        setTried(true)
      }
    })
  }, [activate]) // intentionally only running on mount (make sure it's only mounted once :))

  // if the connection worked, wait until we get confirmation of that to flip the flag
  useEffect(() => {
    if (active) {
      setTried(true)
    }
  }, [active])

  return tried
}
Example #12
Source File: index.ts    From pancake-swap-testnet with MIT License 6 votes vote down vote up
export function useEagerConnect() {
  const { activate, active } = useWeb3ReactCore() // specifically using useWeb3ReactCore because of what this hook does
  const [tried, setTried] = useState(false)

  useEffect(() => {
    injected.isAuthorized().then((isAuthorized) => {
      const hasSignedIn = window.localStorage.getItem(connectorLocalStorageKey)
      if (isAuthorized && hasSignedIn) {
        activate(injected, undefined, true).catch(() => {
          setTried(true)
        })
      } else if (isMobile && window.ethereum && hasSignedIn) {
        activate(injected, undefined, true).catch(() => {
          setTried(true)
        })
      } else {
        setTried(true)
      }
    })
  }, [activate]) // intentionally only running on mount (make sure it's only mounted once :))

  // if the connection worked, wait until we get confirmation of that to flip the flag
  useEffect(() => {
    if (active) {
      setTried(true)
    }
  }, [active])

  return tried
}
Example #13
Source File: index.tsx    From panther-frontend-dex with GNU General Public License v3.0 6 votes vote down vote up
export default function Modal({
  isOpen,
  onDismiss,
  minHeight = false,
  maxHeight = 50,
  initialFocusRef,
  children,
}: ModalProps) {
  const fadeTransition = useTransition(isOpen, null, {
    config: { duration: 200 },
    from: { opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 },
  })

  return (
    <>
      {fadeTransition.map(
        ({ item, key, props }) =>
          item && (
            <StyledDialogOverlay key={key} style={props} onDismiss={onDismiss} initialFocusRef={initialFocusRef}>
              <StyledDialogContent
                aria-label="dialog content"
                minHeight={minHeight}
                maxHeight={maxHeight}
                mobile={isMobile}
              >
                {/* prevents the automatic focusing of inputs on mobile by the reach dialog */}
                {/* eslint-disable */}
                {!initialFocusRef && isMobile ? <div tabIndex={1} /> : null}
                {/* eslint-enable */}
                {children}
              </StyledDialogContent>
            </StyledDialogOverlay>
          )
      )}
    </>
  )
}
Example #14
Source File: index.tsx    From spacesvr with MIT License 6 votes vote down vote up
defaultCanvasProps: Partial<ContainerProps> = {
  gl: {
    powerPreference: "high-performance",
    antialias: true,
    depth: true,
    alpha: false,
    stencil: false,
  },
  shadows: false,
  camera: { position: [0, 2, 0], near: 0.01, far: 150 },
  resize: { polyfill: ResizeObserver },
  dpr: 1,
  raycaster: {
    enabled: isMobile,
  },
  // disable default enter vr button
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  onCreated: () => {},
}
Example #15
Source File: bigbook2.tsx    From website with MIT License 6 votes vote down vote up
render() {
		const { groupedByTier } = this.state;
		const header = this.props.data.sections.edges[0];

		return (
			<Layout title='The Big Book of Behold Advice'>
				<div>
						<Header as='h2' style={{ paddingTop: '1em' }}>
							{header.node.frontmatter.title}
						</Header>
						<div dangerouslySetInnerHTML={{ __html: header.node.html }} />
				</div>
				{[...groupedByTier.keys()].map((tier, idx) => (
					<React.Fragment key={idx}>
						<Header as='h3'>Tier {formatTierLabel(tier, true)}</Header>
						<Grid columns={isMobile ? 4 : 6}>{groupedByTier.get(tier).map(entry => this.renderCrew(entry))}</Grid>
					</React.Fragment>
				))}
			</Layout>
		);
	}
Example #16
Source File: index.ts    From forward.swaps with GNU General Public License v3.0 6 votes vote down vote up
export function useEagerConnect() {
  const { activate, active } = useWeb3ReactCore() // specifically using useWeb3ReactCore because of what this hook does
  const [tried, setTried] = useState(false)

  useEffect(() => {
    injected.isAuthorized().then(isAuthorized => {
      if (isAuthorized) {
        activate(injected, undefined, true).catch(() => {
          setTried(true)
        })
      } else {
        if (isMobile && window.ethereum) {
          activate(injected, undefined, true).catch(() => {
            setTried(true)
          })
        } else {
          setTried(true)
        }
      }
    })
  }, [activate]) // intentionally only running on mount (make sure it's only mounted once :))

  // if the connection worked, wait until we get confirmation of that to flip the flag
  useEffect(() => {
    if (active) {
      setTried(true)
    }
  }, [active])

  return tried
}
Example #17
Source File: URLWarning.tsx    From luaswap-interface with GNU General Public License v3.0 6 votes vote down vote up
export default function URLWarning() {
  const toggleURLWarning = useURLWarningToggle()
  const showURLWarning = useURLWarningVisible()

  return isMobile ? (
    <PhishAlert isActive={showURLWarning}>
      <div style={{ display: 'flex' }}>
        <AlertTriangle style={{ marginRight: 6 }} size={12} /> Make sure the URL is
        <code style={{ padding: '0 4px', display: 'inline', fontWeight: 'bold' }}>app.luaswap.org</code>
      </div>
      <StyledClose size={12} onClick={toggleURLWarning} />
    </PhishAlert>
  ) : window.location.hostname === 'app.luaswap.org' ? (
    <PhishAlert isActive={showURLWarning}>
      <div style={{ display: 'flex' }}>
        <AlertTriangle style={{ marginRight: 6 }} size={12} /> Always make sure the URL is
        <code style={{ padding: '0 4px', display: 'inline', fontWeight: 'bold' }}>app.luaswap.org</code> - bookmark it
        to be safe.
      </div>
      <StyledClose size={12} onClick={toggleURLWarning} />
    </PhishAlert>
  ) : null
}
Example #18
Source File: index.tsx    From calories-in with MIT License 6 votes vote down vote up
function FoodsDrawer({
  onClose,
  isOpen,
  mealName,
  mealForm,
  canSelect = true,
  onSelectedFoods,
}: Props) {
  const searchInputRef = useRef<HTMLInputElement>(null)

  return (
    <Drawer
      initialFocusRef={isMobile ? undefined : searchInputRef}
      isOpen={isOpen}
      size="md"
      placement="right"
      onClose={onClose}
    >
      <DrawerOverlay />
      <Content
        onClose={onClose}
        mealName={mealName}
        mealForm={mealForm}
        onSelectedFoods={onSelectedFoods}
        searchInputRef={searchInputRef}
        canSelect={canSelect}
      />
    </Drawer>
  )
}
Example #19
Source File: index.ts    From pancakeswap-testnet with GNU General Public License v3.0 6 votes vote down vote up
export function useEagerConnect() {
  const { activate, active } = useWeb3ReactCore() // specifically using useWeb3ReactCore because of what this hook does
  const [tried, setTried] = useState(false)

  useEffect(() => {
    injected.isAuthorized().then((isAuthorized) => {
      const hasSignedIn = window.localStorage.getItem(connectorLocalStorageKey)
      if (isAuthorized && hasSignedIn) {
        activate(injected, undefined, true).catch(() => {
          setTried(true)
        })
      } else if (isMobile && window.ethereum && hasSignedIn) {
        activate(injected, undefined, true).catch(() => {
          setTried(true)
        })
      } else {
        setTried(true)
      }
    })
  }, [activate]) // intentionally only running on mount (make sure it's only mounted once :))

  // if the connection worked, wait until we get confirmation of that to flip the flag
  useEffect(() => {
    if (active) {
      setTried(true)
    }
  }, [active])

  return tried
}
Example #20
Source File: AgencyInfo.tsx    From caritas-onlineBeratung-frontend with GNU Affero General Public License v3.0 5 votes vote down vote up
AgencyInfo = (props: DisplayAgencyInfoProps) => {
	const agencyInfoRef = React.useRef<HTMLDivElement>(null);
	const [displayAgencyInfo, setDisplayAgencyInfo] =
		useState<AgencyDataInterface>(null);

	useEffect(() => {
		const handleClickOutside = (event) => {
			if (
				!agencyInfoRef.current?.contains(event.target) &&
				!event.target.getAttribute('data-agency-info-id') &&
				!event.target.closest('[data-agency-info-id]')
			) {
				setDisplayAgencyInfo(null);
			}
		};
		document.addEventListener('click', handleClickOutside);
		return () => {
			document.removeEventListener('click', handleClickOutside);
		};
	}, [displayAgencyInfo]);

	return (
		<div className="agencyInfo__wrapper">
			<InfoIcon
				data-agency-info-id={props.agency.id}
				onClick={() =>
					displayAgencyInfo?.id === props.agency.id
						? setDisplayAgencyInfo(null)
						: setDisplayAgencyInfo(props.agency)
				}
				onMouseEnter={() => {
					if (!isMobile) {
						setDisplayAgencyInfo(props.agency);
					}
				}}
				onMouseLeave={() => {
					if (!isMobile) {
						setDisplayAgencyInfo(null);
					}
				}}
			/>
			{displayAgencyInfo && displayAgencyInfo?.id === props.agency.id && (
				<div
					className={`agencyInfo ${
						props.isProfileView ? 'agencyInfo--above' : ''
					}`}
					ref={agencyInfoRef}
				>
					{displayAgencyInfo.teamAgency && (
						<div className="agencyInfo__teamAgency">
							<InfoIcon />
							<Text
								text={translate(
									'registration.agency.preselected.isTeam'
								)}
								type="infoSmall"
							/>
						</div>
					)}
					{displayAgencyInfo.name && (
						<Text
							className="agencyInfo__name"
							text={displayAgencyInfo.name}
							type="standard"
						/>
					)}
					{displayAgencyInfo.description && (
						<Text
							className="agencyInfo__description"
							text={displayAgencyInfo.description}
							type="infoSmall"
						/>
					)}
				</div>
			)}
		</div>
	);
}
Example #21
Source File: index.tsx    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
Filter = () => {
  const { guild_id: guildId } =
    useParams<{ chain_name?: string; guild_id?: string }>();
  const [viewFilter, setViewFilter] = useState(false);
  const { totalFilters } = useFilter();

  const history = useHistory();
  const location = useLocation();

  const { account } = useWeb3React();
  const { data: votingPower } = useVotingPowerOf({
    contractAddress: guildId,
    userAddress: account,
  });
  const { data: guildConfig } = useGuildConfig(guildId);
  const isProposalCreationAllowed = useMemo(() => {
    if (!guildConfig || !votingPower) {
      return false;
    }
    if (votingPower.gte(guildConfig.votingPowerForProposalCreation)) {
      return true;
    }
    return false;
  }, [votingPower, guildConfig]);
  const [openSearchBar, setOpenSearchBar] = useState(false);
  return (
    <FilterContainer>
      <FilterRow>
        {isMobile && !isProposalCreationAllowed && (
          <FilterButton
            onClick={() => setViewFilter(!viewFilter)}
            active={viewFilter || totalFilters > 0}
          >
            Filter
            {totalFilters > 0 && <FilterBadge>{totalFilters}</FilterBadge>}
          </FilterButton>
        )}
        {isDesktop && <FilterMenu />}

        <ButtonContainer>
          <StyledIconButton
            variant="secondary"
            padding="0.4rem"
            onClick={() => setOpenSearchBar(!openSearchBar)}
          >
            <AiOutlineSearch size={20} />
          </StyledIconButton>
          {isProposalCreationAllowed && (
            <Button
              variant="secondary"
              onClick={() => history.push(location.pathname + '/proposalType')}
              data-testid="create-proposal-button"
            >
              Create Proposal
            </Button>
          )}
        </ButtonContainer>
      </FilterRow>
      {isMobile && viewFilter && <FilterMenu />}
      {openSearchBar ? (
        <StyledInputWrapper>
          <Input
            icon={<AiOutlineSearch size={24} />}
            placeholder="Search title, ENS, address"
          />
        </StyledInputWrapper>
      ) : null}
    </FilterContainer>
  );
}
Example #22
Source File: index.tsx    From cuiswap with GNU General Public License v3.0 5 votes vote down vote up
export default function Header() {
  const { account, chainId } = useActiveWeb3React()

  const userEthBalance = useETHBalances([account])[account]
  const [isDark] = useDarkModeManager()

  return (
    <HeaderFrame>
      <RowBetween style={{ alignItems: 'flex-start' }} padding="1rem 1rem 0 1rem">
        <HeaderElement>
          <Title href=".">
            <UniIcon>
              <img src={isDark ? LogoDark : Logo} alt="logo" />
            </UniIcon>
            <TitleText>
              <img style={{ marginLeft: '4px', marginTop: '4px' }} src={isDark ? WordmarkDark : Wordmark} alt="logo" />
            </TitleText>
          </Title>
        </HeaderElement>
        <HeaderControls>
          <HeaderElement>
            <TestnetWrapper>
              {!isMobile && NETWORK_LABELS[chainId] && <NetworkCard>{NETWORK_LABELS[chainId]}</NetworkCard>}
            </TestnetWrapper>
            <AccountElement active={!!account} style={{ pointerEvents: 'auto' }}>
              {account && userEthBalance ? (
                <BalanceText style={{ flexShrink: 0 }} pl="0.75rem" pr="0.5rem" fontWeight={500}>
                  {userEthBalance?.toSignificant(4)} ETH
                </BalanceText>
              ) : null}
              <Web3Status />
            </AccountElement>
          </HeaderElement>
          <HeaderElementWrap>
            <VersionSwitch />
            <Settings />
            <Menu />
          </HeaderElementWrap>
        </HeaderControls>
      </RowBetween>
    </HeaderFrame>
  )
}
Example #23
Source File: index.ts    From interface-v2 with GNU General Public License v3.0 5 votes vote down vote up
export function useEagerConnect() {
  const { activate, active } = useWeb3ReactCore(); // specifically using useWeb3ReactCore because of what this hook does
  const [tried, setTried] = useState(false);

  const checkInjected = useCallback(() => {
    return injected.isAuthorized().then((isAuthorized) => {
      if (isAuthorized) {
        activate(injected, undefined, true).catch(() => {
          setTried(true);
        });
      } else {
        if (isMobile && window.ethereum) {
          activate(injected, undefined, true).catch(() => {
            setTried(true);
          });
        } else {
          setTried(true);
        }
      }
    });
  }, [activate]);

  useEffect(() => {
    Promise.race([
      safeApp.getSafeInfo(),
      new Promise((resolve) => setTimeout(resolve, 100)),
    ]).then(
      (safe) => {
        if (safe) activate(safeApp, undefined, true);
        else checkInjected();
      },
      () => {
        checkInjected();
      },
    );
  }, [activate, checkInjected]); // intentionally only running on mount (make sure it's only mounted once :))

  // if the connection worked, wait until we get confirmation of that to flip the flag
  useEffect(() => {
    if (active) {
      setTried(true);
    }
  }, [active]);

  return tried;
}
Example #24
Source File: index.tsx    From sybil-interface with GNU General Public License v3.0 5 votes vote down vote up
export default function Modal({
  isOpen,
  onDismiss,
  minHeight = false,
  maxHeight = 90,
  initialFocusRef,
  children,
}: ModalProps): JSX.Element {
  const fadeTransition = useTransition(isOpen, null, {
    config: { duration: 200 },
    from: { opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 },
  })

  const [{ y }, set] = useSpring(() => ({ y: 0, config: { mass: 1, tension: 210, friction: 20 } }))
  const bind = useGesture({
    onDrag: (state) => {
      set({
        y: state.down ? state.movement[1] : 0,
      })
      if (state.movement[1] > 300 || (state.velocity > 3 && state.direction[1] > 0)) {
        onDismiss()
      }
    },
  })

  return (
    <>
      {fadeTransition.map(
        ({ item, key, props }) =>
          item && (
            <StyledDialogOverlay key={key} style={props} onDismiss={onDismiss} initialFocusRef={initialFocusRef}>
              <StyledDialogContent
                {...(isMobile
                  ? {
                      ...bind(),
                      style: { transform: y.interpolate((y: any) => `translateY(${y > 0 ? y : 0}px)`) },
                    }
                  : {})}
                aria-label="dialog content"
                minHeight={minHeight}
                maxHeight={maxHeight}
                mobile={isMobile}
              >
                {/* prevents the automatic focusing of inputs on mobile by the reach dialog */}
                {!initialFocusRef && isMobile ? <div tabIndex={1} /> : null}
                {children}
              </StyledDialogContent>
            </StyledDialogOverlay>
          )
      )}
    </>
  )
}
Example #25
Source File: index.tsx    From basement-grotesque with SIL Open Font License 1.1 5 votes vote down vote up
Range = ({
  label,
  name,
  onChange,
  min,
  max,
  step,
  value,
  renderValue
}: RangeProps) => {
  const [isMobileSSRSafe, setIsMobileSSRSafe] = useState(false)
  const [isGrabbing, setIsGrabbing] = useState(false)
  const { setType } = useCursor()

  useEffect(() => {
    setIsMobileSSRSafe(isMobile)
  }, [])

  const handlePointerDown = useCallback(() => {
    setType('grabbing')
    setIsGrabbing(true)
  }, [setType])

  const handlePointerUp = useCallback(() => {
    setType('grab')
    setIsGrabbing(false)
  }, [setType])

  return (
    <div
      style={{
        ['--thumb-width' as string]: isMobileSSRSafe ? '24px' : '18px'
      }}
    >
      <Flex>
        <Label htmlFor={`range-${name}`}>{label}</Label>
        <Value>{renderValue(value)}</Value>
      </Flex>
      <input
        type="range"
        className={s.range}
        min={min}
        max={max}
        step={step}
        value={value}
        name={name}
        id={`range-${name}`}
        onChange={onChange}
        onPointerDown={handlePointerDown}
        onPointerUp={handlePointerUp}
        data-cursor={isGrabbing ? 'grabbing' : 'grab'}
      />
    </div>
  )
}
Example #26
Source File: modal-container.tsx    From react-celo with MIT License 5 votes vote down vote up
export default function ModalContainer({
  onBack,
  onClose,
  selectedProvider,
  tray,
  content,
}: Props) {
  const theme = useTheme();
  let contentToRender = null;

  if (isMobile) {
    if (selectedProvider) {
      contentToRender = <div className={styles.trayContainer}>{content}</div>;
    } else {
      contentToRender = <div className={styles.contentContainer}>{tray}</div>;
    }
  } else {
    contentToRender = (
      <div className={styles.layout}>
        <div className={styles.trayContainer}>{tray}</div>
        <div
          className={styles.contentContainer}
          style={{ borderColor: theme.muted }}
        >
          {content}
        </div>
      </div>
    );
  }

  return (
    <div
      className={`react-celo ${styles.container}`}
      style={{ background: theme.background }}
    >
      <div
        className={`react-celo-connect-container ${styles.innerContainer}`}
        style={{ color: theme.textSecondary }}
      >
        <button onClick={onClose} className={styles.closeButton}>
          {/* https://fontawesome.com/icons/xmark?s=solid */}
          <svg
            className={styles.svg}
            xmlns="http://www.w3.org/2000/svg"
            viewBox="0 0 320 512"
          >
            <path d="M310.6 361.4c12.5 12.5 12.5 32.75 0 45.25C304.4 412.9 296.2 416 288 416s-16.38-3.125-22.62-9.375L160 301.3L54.63 406.6C48.38 412.9 40.19 416 32 416S15.63 412.9 9.375 406.6c-12.5-12.5-12.5-32.75 0-45.25l105.4-105.4L9.375 150.6c-12.5-12.5-12.5-32.75 0-45.25s32.75-12.5 45.25 0L160 210.8l105.4-105.4c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25l-105.4 105.4L310.6 361.4z" />
          </svg>{' '}
        </button>
        {isMobile && selectedProvider && (
          <button onClick={onBack} className={styles.backButton}>
            {/* https://fontawesome.com/icons/arrow-left-long?s=solid */}
            <svg
              className={styles.svg}
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 512 512"
            >
              <path d="M9.375 233.4l128-128c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25L109.3 224H480c17.69 0 32 14.31 32 32s-14.31 32-32 32H109.3l73.38 73.38c12.5 12.5 12.5 32.75 0 45.25c-12.49 12.49-32.74 12.51-45.25 0l-128-128C-3.125 266.1-3.125 245.9 9.375 233.4z" />
            </svg>{' '}
          </button>
        )}
        {contentToRender}
      </div>
    </div>
  );
}
Example #27
Source File: index.tsx    From cheeseswap-interface with GNU General Public License v3.0 5 votes vote down vote up
export default function Header() {
  const isDark = useIsDarkMode()
  const { account, chainId } = useActiveWeb3React()
  const userEthBalance = useETHBalances(account ? [account] : [])?.[account ?? '']
  return (
    <HeaderFrame>
      <RowBetween style={{ alignItems: 'flex-start' }}>
        <HeaderElement>
          <Title href="/">
            <CheeseIcon>
              { !isDark?
                <img src={Logob} alt="logo" />
                :
                <img src={Logow} alt="logo" />
              }
            </CheeseIcon>
          </Title>
        </HeaderElement>

        <Nav />
        <HeaderControls>
          {!isMobile && <ThemeSwitch />}
          <HeaderElement>
            <TestnetWrapper>
              {!isMobile && chainId && NETWORK_LABELS[chainId] && <NetworkCard>{NETWORK_LABELS[chainId]}</NetworkCard>}
            </TestnetWrapper>
            <AccountElement active={!!account} style={{ pointerEvents: 'auto' }}>
              {account && userEthBalance ? (
                <BalanceText style={{ flexShrink: 0 }} pl="0.75rem" pr="0.5rem" fontWeight={700}>
                  {userEthBalance?.toSignificant(4)} BNB
                </BalanceText>
              ) : null}
              <Web3Status />
            </AccountElement>
          </HeaderElement>
          <HeaderElementWrap>
            {isMobile && <ThemeSwitch />}
            <Settings />
            <Menu />
          </HeaderElementWrap>
        </HeaderControls>
      </RowBetween>
    </HeaderFrame>
  )
}
Example #28
Source File: App.tsx    From polkabridge-launchpad with MIT License 5 votes vote down vote up
Providers: React.FC = ({ children }) => {
  const { chainId, changeNetwork, setConnected, status } = useNetwork()

  useEffect(() => {
    ;(async () => {
      if (isMobile) {
        //enable window.ethereum for mobile device
        const account = await getCurrentAccount()
      }
      // console.log('prev  id', chainId)
      const _id = await getCurrentNetworkId()
      // console.log('testConnect:  init with network id ', _id)
      changeNetwork(_id)
      if (Number(_id) !== Number(chainId)) {
        if (isMobile) {
          window.location.reload()
        }
      }
      localStorage.chainId = _id
    })()
  }, [chainId, changeNetwork])
  return (
    <ThemeProvider theme={theme}>
      <UseWalletProvider
        chainId={chainId}
        connectors={{
          walletconnect: { rpcUrl: config.ankrEthereumRpc },
        }}
      >
        <PolkaBridgeProvider>
          <TransactionProvider>
            <LaunchpadsProvider>
              <Router>
                <ModalsProvider>{children}</ModalsProvider>
              </Router>
            </LaunchpadsProvider>
          </TransactionProvider>
        </PolkaBridgeProvider>
      </UseWalletProvider>
    </ThemeProvider>
  )
}
Example #29
Source File: BscStake.tsx    From dyp with Do What The F*ck You Want To Public License 5 votes vote down vote up
export default function BscStake() {
  // const toggleURLWarning = useURLWarningToggle()
  // const showURLWarning = useURLWarningVisible()

  return isMobile ? (
    <PhishAlert isActive={true}>
      <div style={{ display: 'flex' }}>
        <img
          src={BscChain}
          width={30}
          height={30}
          style={{ margin: '10px', marginLeft: '0px', borderRadius: '25px' }}
          alt={'logo'}
        />
        <code style={{ marginTop: '19px', display: 'inline', fontWeight: 'bold' }}>
          <PointerLink>
            <ExternalLink target="_blank" style={{ color: 'white' }} href="https://app-bsc.dyp.finance">
              DYP staking dApp is live on Binance Smart Chain
            </ExternalLink>
          </PointerLink>
        </code>
      </div>
    </PhishAlert>
  ) : window.location.hostname === 'dyp.finance' ? (
    <PhishAlert isActive={true}>
      <div style={{ display: 'flex' }}>
        <img
          src={BscChain}
          width={30}
          height={30}
          style={{ margin: '10px', marginLeft: '25px', borderRadius: '25px' }}
          alt={'logo'}
        />
        <code style={{ marginTop: '18px', display: 'inline', fontWeight: 'bold', fontSize: '13px' }}>
          <PointerLink>
            <ExternalLink target="_blank" style={{ color: 'white' }} href="https://app-bsc.dyp.finance">
              DeFi Yield Protocol staking dApp is live on Binance Smart Chain
            </ExternalLink>
          </PointerLink>
        </code>
      </div>
    </PhishAlert>
  ) : null
}