Files
xrpl-dev-portal/content/static/js/xrpl-guard.tsx
Jackson Mills 64a91fc0a8 Migrate the faucet page to Redocly (#2243)
* Get basic HTML loading for faucet page

* Add xrpl.js implementation

* Add sidebar and fix throbber

* Add translates

* Try to format sidebar

* Fix formatting

* Support xrpl.js

* Fix links

* Comment out XRPLGuard for now

* Make AMM Devnet faucet work

* Improve readability

* Update all instances of link + fix topnav

* Remove unnecessary file

* Use a more current version of xrpl

* Add missing loader while keys are generating

* Type with xrpl and remove unnecessary script

* Use string interpolation instead of multiple trans

* Move faucets into a json file

* Remove the old faucet code

* Use xrpl-beta directly

* Use dropsToXRP

* Support hooks natively

* Remove AMM-Devnet

* Revert changes to link path

* Revert link changes pt 2

* Revert pt 3

* Use XRPLoader for loading icon

* Fix small mistakes

* Remove unnecessary changes
2024-01-31 16:07:14 -08:00

86 lines
2.1 KiB
TypeScript

import { useTranslate } from '@portal/hooks';
import { isFunction } from './type-helpers'
import { FC } from 'react'
import { useEffect, useState } from 'react'
import React = require('react');
import XRPLoader from '../components/XRPLoader';
export const MIN_LOADER_MS = 1250
export const DEFAULT_TIMEOUT = 1000
const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay))
/**
* Evaluate a check function will eventually resolve to `true`
*
* If check is initially true, immediatly return `isTrue`
* If check is initially false and becomes true, return true after `timeoutMs`
*/
export const useThrottledCheck = (
check: () => boolean,
timeoutMs = DEFAULT_TIMEOUT,
) => {
const [isTrue, setIsTrue] = useState(() => check())
useEffect(() => {
const doCheck = async (tries = 0) => {
const waitMs = 250,
waitedMs = tries * waitMs
if (check()) {
const debouncedDelay =
waitedMs < timeoutMs ? timeoutMs - (waitedMs % timeoutMs) : 0
setTimeout(() => setIsTrue(true), debouncedDelay)
return
}
await sleep(waitMs)
doCheck(tries + 1)
}
if (!isTrue) {
doCheck()
}
}, [check, isTrue])
return isTrue
}
/**
* Show a loading spinner if XRPL isn't loaded yet by
* waiting at least MIN_LOADER_MS before rendering children
* in order to make the visual loading transition smooth
*
* e.g. if xrpl loads after 500ms, wait
* another MIN_LOADER_MS - 500ms before rendering children
*
* @param {function} testCheck for testing only, a check function to use
*/
export const XRPLGuard: FC<{ testCheck?: () => boolean, children }> = ({
testCheck,
children,
}) => {
const { translate } = useTranslate();
const isXRPLLoaded = useThrottledCheck(
// @ts-expect-error - xrpl is added via a script tag (TODO: Directly import when xrpl.js 3.0 is released)
testCheck ?? (() => typeof xrpl === 'object'),
MIN_LOADER_MS,
)
return (
<>
{isXRPLLoaded ? (
isFunction(children) ? (
children()
) : (
children
)
) : <XRPLoader message={translate("Loading...")}/>
}
</>
)
}