react-icons/md#MdClose JavaScript Examples
The following examples show how to use
react-icons/md#MdClose.
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: Sidebar.js From gatsby-airtable-design-project with BSD Zero Clause License | 6 votes |
Sidebar = () => {
const { links, hideSidebar } = useContext(GatsbyContext)
return (
<Wrapper>
<div className="container">
<button onClick={hideSidebar}>
<MdClose className="icon" />
</button>
<div className="links">
{links.map((link, index) => {
const { url, label, icon } = link
return (
<Link to={url} key={index} onClick={hideSidebar}>
{icon}
{label}
</Link>
)
})}
</div>
</div>
</Wrapper>
)
}
Example #2
Source File: mobile-nav-menu.js From strapi-starter-next-corporate with MIT License | 6 votes |
MobileNavMenu = ({ navbar, closeSelf }) => {
// Prevent window scroll while mobile nav menu is open
useLockBodyScroll()
return (
<div className="w-screen h-screen fixed top-0 left-0 overflow-y-scroll bg-white z-10 pb-6">
<div className="container h-full flex flex-col justify-between">
{/* Top section */}
<div className="flex flex-row justify-between py-2 items-center">
{/* Company logo */}
<NextImage width="120" height="33" media={navbar.logo} />
{/* Close button */}
<button onClick={closeSelf} className="py-1 px-1">
<MdClose className="h-8 w-auto" />
</button>
</div>
{/* Bottom section */}
<div className="flex flex-col justify-end w-9/12 mx-auto">
<ul className="flex flex-col list-none gap-6 items-baseline text-xl mb-10">
{navbar.links.map((navLink) => (
<li key={navLink.id} className="block w-full">
<CustomLink link={navLink}>
<div className="hover:text-gray-900 py-6 flex flex-row justify-between items-center">
<span>{navLink.text}</span>
<MdChevronRight className="h-8 w-auto" />
</div>
</CustomLink>
</li>
))}
</ul>
<ButtonLink
button={navbar.button}
appearance={getButtonAppearance(navbar.button.type, "light")}
/>
</div>
</div>
</div>
)
}
Example #3
Source File: notification-banner.js From strapi-starter-next-corporate with MIT License | 6 votes |
NotificationBanner = ({ data: { text, type }, closeSelf }) => {
return (
<div
className={classNames(
// Common classes
"text-white px-2 py-2",
{
// Apply theme based on notification type
"bg-blue-600": type === "info",
"bg-orange-600": type === "warning",
"bg-red-600": type === "alert",
}
)}
>
<div className="container flex flex-row justify-between items-center ">
<div className="rich-text-banner flex-1">
<Markdown>{text}</Markdown>
</div>
<button onClick={closeSelf} className="px-1 py-1 flex-shrink-0">
<MdClose className="h-6 w-auto" color="#fff" />
</button>
</div>
</div>
)
}
Example #4
Source File: styles.js From plataforma-sabia with MIT License | 6 votes |
CloseIcon = styled(MdClose)`
${({ theme: { colors } }) => css`
cursor: pointer;
position: absolute;
top: -2.4rem;
right: 0;
width: 2.4rem;
height: 2.4rem;
color: ${colors.white};
`}
`
Example #5
Source File: styles.js From plataforma-sabia with MIT License | 6 votes |
Close = styled(MdClose)`
${({ theme }) => css`
color: ${theme.colors.white};
cursor: pointer;
margin-left: auto;
width: 2.4rem;
height: 2.4rem;
`}
`
Example #6
Source File: Modal.js From acy-dex-interface with MIT License | 5 votes |
export default function Modal(props) {
const { isVisible, setIsVisible, className, zIndex } = props;
const modalRef = useRef(null);
useLockBodyScroll(modalRef, isVisible);
useEffect(
() => {
function close(e) {
if (e.keyCode === 27) {
setIsVisible(false);
}
}
window.addEventListener('keydown', close);
return () => window.removeEventListener('keydown', close);
},
[setIsVisible]
);
const fadeVariants = {
hidden: { opacity: 0 },
visible: { opacity: 1 },
};
return (
<AnimatePresence>
{isVisible && (
<motion.div
className={cx('Modal', className)}
style={{ zIndex }}
initial="hidden"
animate="visible"
exit="hidden"
variants={fadeVariants}
transition={{ duration: 0.2 }}
>
<div
className="Modal-backdrop"
style={{
overflow: isVisible ? 'hidden' : 'visible',
position: 'fixed',
}}
onClick={() => setIsVisible(false)}
/>
<div className="Modal-content">
<div className="Modal-title-bar">
<div className="Modal-title">{props.label}</div>
<div className="Modal-close-button" onClick={() => setIsVisible(false)}>
<MdClose fontSize={20} className="Modal-close-icon" />
</div>
</div>
<div className="divider" />
<div className="Modal-body" ref={modalRef}>
{props.children}
</div>
</div>
</motion.div>
)}
</AnimatePresence>
);
}
Example #7
Source File: SearchForm.js From airdnd-frontend with MIT License | 4 votes |
SearchForm = ({
isSearchBtnClicked,
type,
changeType,
searchData,
changeSearchData,
changeAutoComplete,
locationResult,
handleSubmit,
setCheckIn,
setCheckOut,
increaseGuestCount,
decreaseGuestCount,
refObj,
}) => {
const { location, checkIn, checkOut, guests } = searchData;
const { adult, child, infant } = guests;
const guestCount = adult + child + infant;
const {
searchFormRef,
locationWrapperRef,
checkInWrapperRef,
checkOutWrapperRef,
guestsWrapperRef,
locationListRef,
calendarPopupRef,
guestsPopupRef,
locationResetBtnRef,
checkInResetBtnRef,
checkOutResetBtnRef,
guestsResetBtnRef,
} = refObj;
return (
<StSearchForm
onSubmit={handleSubmit}
isSearchBtnClicked={isSearchBtnClicked}
ref={searchFormRef}
>
<StFormItemWrapper
type={type}
name="location"
width="30%"
tabIndex="1"
ref={locationWrapperRef}
onClick={() => changeType('location')}
>
<StPlaceLabel>
<StTextWrapper>
<StTypeText>위치</StTypeText>
<StPlaceInput
value={location}
name="location"
placeholder="어디로 여행가세요?"
onFocus={e => {
changeAutoComplete(e.target.value);
}}
onChange={e => {
changeAutoComplete(e.target.value);
}}
autoComplete="off"
required
></StPlaceInput>
</StTextWrapper>
</StPlaceLabel>
<SearchLocationPopup
type={type}
changeType={changeType}
searchData={searchData}
ref={locationListRef}
locationResult={locationResult}
changeSearchData={changeSearchData}
></SearchLocationPopup>
<StResetBtn
btnType="circle"
name="location"
ref={locationResetBtnRef}
pointer={type === 'location' && location}
onClick={() => {
changeSearchData('location', '');
}}
>
<MdClose />
</StResetBtn>
</StFormItemWrapper>
<StFormItemWrapper
type={type}
name="checkIn"
width="20%"
tabIndex="2"
ref={checkInWrapperRef}
>
<StTextWrapper>
<StTypeText>체크인</StTypeText>
<StContentText value={checkIn}>
{checkIn || '날짜 추가'}
</StContentText>
</StTextWrapper>
<StResetBtn
btnType="circle"
name="checkIn"
pointer={type === 'checkIn' && checkIn}
ref={checkInResetBtnRef}
onClick={() => {
changeSearchData('checkIn', '');
checkOut && changeSearchData('checkOut', '');
}}
>
<MdClose />
</StResetBtn>
</StFormItemWrapper>
<StFormItemWrapper
type={type}
name="checkOut"
width="20%"
tabIndex="3"
ref={checkOutWrapperRef}
>
<SearchCalendarPopup
type={type}
changeType={changeType}
searchData={searchData}
ref={calendarPopupRef}
setCheckIn={setCheckIn}
setCheckOut={setCheckOut}
></SearchCalendarPopup>
<StTextWrapper>
<StTypeText>체크아웃</StTypeText>
<StContentText value={checkOut}>
{checkOut || '날짜 추가'}
</StContentText>
</StTextWrapper>
<StResetBtn
btnType="circle"
name="checkOut"
pointer={type === 'checkOut' && checkOut}
ref={checkOutResetBtnRef}
onClick={() => {
changeSearchData('checkOut', '');
}}
>
<MdClose />
</StResetBtn>
</StFormItemWrapper>
<StFormItemWrapper
type={type}
name="guests"
width="30%"
tabIndex="4"
ref={guestsWrapperRef}
>
<StTextWrapper>
<StTypeText>인원</StTypeText>
<StContentText value={guestCount} name="guests">
{guestCount
? !infant
? `게스트 ${+adult + +child}명`
: `게스트 ${+adult + +child}명, 유아 ${infant}명`
: '게스트 추가'}
</StContentText>
</StTextWrapper>
<StResetBtn
btnType="circle"
name="guests"
pointer={type === 'guests' && guestCount > 0}
ref={guestsResetBtnRef}
onClick={() => {
changeSearchData('guests', { adult: 0, child: 0, infant: 0 });
}}
>
<MdClose />
</StResetBtn>
<SearchGuestsPopup
type={type}
searchData={searchData}
increaseGuestCount={increaseGuestCount}
decreaseGuestCount={decreaseGuestCount}
ref={guestsPopupRef}
></SearchGuestsPopup>
</StFormItemWrapper>
<SearchButton></SearchButton>
</StSearchForm>
);
}
Example #8
Source File: SignupEmailModal.js From airdnd-frontend with MIT License | 4 votes |
SignupEmailModal = ({
modalVisible,
form,
invalid,
refObj,
range,
loading,
result,
isPwdFocused,
openLoginModal,
closeModal,
cleanupModal,
onFormChange,
handleSubmit,
onPwdFocused,
onGoogleLoginSuccess,
onGoogleLoginFailure,
}) => {
const {
email,
firstName,
lastName,
pwd,
birthMonth,
birthDay,
birthYear,
} = form;
const {
pwdValidation: { pwdLevel, pwdLength, pwdContain, pwdCase },
} = invalid;
const {
emailRef,
firstNameRef,
lastNameRef,
pwdRef,
birthMonthRef,
birthDayRef,
birthYearRef,
} = refObj;
return (
<StSignupEmailModal
modalState={modalVisible}
header
title="회원가입"
width="570px"
height="670px"
setModalState={closeModal}
cleanup={cleanupModal}
>
<StSignupFormWrapper>
<StSignupForm onSubmit={handleSubmit}>
{result && result !== 'Success' && (
<StResultWrapper result={result}>
<StErrorWrapper>
<AiOutlineWarning></AiOutlineWarning>
</StErrorWrapper>
<StResultTextWrapper>
{result === 'AlreadyEmail' && (
<StResultText>이메일이 이미 존재합니다.</StResultText>
)}
{result === 'Error' && (
<StResultText>회원가입에 실패하였습니다.</StResultText>
)}
</StResultTextWrapper>
</StResultWrapper>
)}
<StInputWrapper>
<StInput
value={email}
onChange={({ target: { value } }) => onFormChange('email', value)}
focusBorderColor
placeholder="이메일 주소"
ref={emailRef}
isInvalid={invalid.email}
></StInput>
<RiMailLine />
{email.length === 0 && invalid.email && (
<StValidationText isInvalid={invalid.email}>
이메일을 입력하세요.
</StValidationText>
)}
{email.length > 0 && invalid.email && result !== 'AlreadyEmail' && (
<StValidationText isInvalid={invalid.email}>
이메일 형식이 맞지 않습니다.
</StValidationText>
)}
</StInputWrapper>
<StInputWrapper>
<StInput
value={firstName}
onChange={({ target: { value } }) =>
onFormChange('firstName', value)
}
focusBorderColor
placeholder="이름 (예: 길동)"
ref={firstNameRef}
isInvalid={invalid.firstName}
></StInput>
<RiUserLine />
{firstName.length === 0 && invalid.firstName && (
<StValidationText isInvalid={invalid.firstName}>
이름을 입력하세요.
</StValidationText>
)}
{firstName.length > 35 && invalid.firstName && (
<StValidationText isInvalid={invalid.firstName}>
이름을 입력할 수 있는 최대 글자 수는 35자입니다. 다시
시도하세요.
</StValidationText>
)}
{firstName.length !== 0 &&
firstName.length < 35 &&
invalid.firstName && (
<StValidationText isInvalid={invalid.firstName}>
이름에 유효한 글자를 입력하세요.
</StValidationText>
)}
</StInputWrapper>
<StInputWrapper>
<StInput
value={lastName}
onChange={({ target: { value } }) =>
onFormChange('lastName', value)
}
focusBorderColor
placeholder="성 (예: 홍)"
ref={lastNameRef}
isInvalid={invalid.lastName}
></StInput>
<RiUserLine />
{lastName.length === 0 && invalid.lastName && (
<StValidationText isInvalid={invalid.lastName}>
성을 입력하세요.
</StValidationText>
)}
{lastName.length > 35 && invalid.lastName && (
<StValidationText isInvalid={invalid.lastName}>
성을 입력할 수 있는 최대 글자 수는 35자입니다. 다시 시도하세요.
</StValidationText>
)}
{lastName.length !== 0 &&
lastName.length < 35 &&
invalid.lastName && (
<StValidationText isInvalid={invalid.lastName}>
성에 유효한 글자를 입력하세요.
</StValidationText>
)}
</StInputWrapper>
<StInputWrapper name="password">
<StInput
type="password"
value={pwd}
onChange={({ target: { value } }) => onFormChange('pwd', value)}
onFocus={() => onPwdFocused(true)}
focusBorderColor
placeholder="비밀번호 설정하기"
ref={pwdRef}
isInvalid={invalid.pwd}
></StInput>
<RiEyeCloseLine />
{pwd.length === 0 && invalid.pwd && (
<StValidationText isInvalid={invalid.pwd}>
비밀번호를 입력하세요.
</StValidationText>
)}
{pwd.length > 0 && invalid.pwd && (
<StValidationText isInvalid={invalid.pwd}>
비밀번호 형식이 맞지 않습니다.
</StValidationText>
)}
{isPwdFocused && (
<StPwdValidationList>
<StPwdValidationItem isPwdValid={pwdLevel}>
{pwdLevel >= 1 ? <MdCheck /> : <MdClose />}
<StPwdValidationText>
비밀번호 보안 수준:
<StPwdValidationLevelText pwdLevel={pwdLevel}>
{pwdLevel
? pwdLevel === 2
? ' 강함'
: ' 보통'
: ' 약함'}
</StPwdValidationLevelText>
</StPwdValidationText>
</StPwdValidationItem>
{pwdLevel === 0 && (
<>
<StPwdValidationItem isPwdValid={pwdContain}>
{pwdContain ? <MdCheck /> : <MdClose />}
<StPwdValidationText>
비밀번호에 본인 이름이나 이메일 주소를 포함할 수
없습니다.
</StPwdValidationText>
</StPwdValidationItem>
<StPwdValidationItem isPwdValid={pwdLength}>
{pwdLength ? <MdCheck /> : <MdClose />}
<StPwdValidationText>최소 8자</StPwdValidationText>
</StPwdValidationItem>
<StPwdValidationItem isPwdValid={pwdCase}>
{pwdCase ? <MdCheck /> : <MdClose />}
<StPwdValidationText>
숫자나 기호를 포함하세요
</StPwdValidationText>
</StPwdValidationItem>
</>
)}
</StPwdValidationList>
)}
</StInputWrapper>
<StBirthDayTitle>생일</StBirthDayTitle>
<StBirthDayText>
만 18세 이상의 성인만 회원으로 가입할 수 있습니다. 생일은 다른
에어비앤비 이용자에게 공개되지 않습니다.
</StBirthDayText>
<StBirthDayWrapper>
<StBirthDayDropDown
name="birthMonth"
width="40%"
title="월"
options={range(1, 12, 1)}
outline
value={birthMonth}
isInvalid={invalid.birthMonth}
onChange={({ target: { value } }) =>
onFormChange('birthMonth', value)
}
ref={birthMonthRef}
></StBirthDayDropDown>
<StBirthDayDropDown
name="birthDay"
width="22%"
title="일"
options={range(1, 31, 1)}
outline
value={birthDay}
isInvalid={invalid.birthDay}
onChange={({ target: { value } }) =>
onFormChange('birthDay', value)
}
ref={birthDayRef}
></StBirthDayDropDown>
<StBirthDayDropDown
name="birthYear"
width="33%"
title="년"
options={range(1900, new Date().getFullYear(), 1).reverse()}
outline
value={birthYear}
isInvalid={invalid.birthYear}
onChange={({ target: { value } }) =>
onFormChange('birthYear', value)
}
ref={birthYearRef}
></StBirthDayDropDown>
</StBirthDayWrapper>
{(isNaN(birthMonth) || isNaN(birthDay) || isNaN(birthYear)) &&
(invalid.birthMonth || invalid.birthDay || invalid.birthYear) && (
<StValidationText>
계속하시려면 생일을 선택하세요.
</StValidationText>
)}
{!isNaN(birthMonth) &&
!isNaN(birthDay) &&
!isNaN(birthYear) &&
(invalid.birthMonth || invalid.birthDay || invalid.birthYear) && (
<StValidationText>
입력하신 생일을 다시 한번 확인하세요. 올바른 날짜 형식이
아닙니다.
</StValidationText>
)}
<StSubmitButton isLoading={loading} border="none" type="submit">
{loading ? <StSubmitLoader /> : '가입하기'}
</StSubmitButton>
</StSignupForm>
<StDividerLine />
<StLoginButtonWrapper>
<StLoginText>이미 에어비앤비 계정이 있나요?</StLoginText>
<StLoginButton
isLoading={loading}
btnType="color"
onClick={openLoginModal}
>
로그인
</StLoginButton>
</StLoginButtonWrapper>
</StSignupFormWrapper>
</StSignupEmailModal>
);
}
Example #9
Source File: ShelleyHaskellStakingCalculator.js From testnets-cardano-org with MIT License | 4 votes |
Calculator = ({
currencies,
content,
initialValues,
initialCalculator,
origin,
pathname,
}) => {
const [allCurrencies, setAllCurrencies] = useState(
JSON.parse(JSON.stringify(currencies))
)
const [values, setValues] = useState(
getDefaultValues(allCurrencies[0], initialValues)
)
const [type, setType] = useState(initialCalculator)
const [showAdvancedOptions, setShowAdvancedOptions] = useState(false)
const [shareModalVisible, setShareModalVisible] = useState(false)
const [copied, setCopied] = useState(false)
const containerRef = useRef(null)
const copiedTimeout = useRef(null)
const modalContent = useRef(null)
function getInitialCurrency(key) {
return currencies.filter((currency) => currency.key === key).shift() || {}
}
function getTotalADAInCirculation(epoch, startingTotalADAInCirculation) {
let i = 1
let totalADAInCirculation =
startingTotalADAInCirculation || values.totalADAInCirculation
while (i < epoch) {
const reserve = values.totalADA - totalADAInCirculation
totalADAInCirculation += reserve * values.expansionRate
i++
}
return totalADAInCirculation
}
function getEpochDistributableRewards(
totalADAInCirculation,
transactionFeesPerEpoch
) {
const reserve = values.totalADA - totalADAInCirculation
return (
(reserve * values.expansionRate + transactionFeesPerEpoch) *
(1 - values.treasuryRate)
)
}
function getDistributableRewards(epoch) {
let transactionFeesPerEpoch = parseFloat(values.transactionFeesPerEpoch)
if (
!transactionFeesPerEpoch ||
isNaN(transactionFeesPerEpoch) ||
transactionFeesPerEpoch < 0
)
transactionFeesPerEpoch = 0
const totalADAInCirculation = getTotalADAInCirculation(epoch)
const epochDistribution = getEpochDistributableRewards(
totalADAInCirculation,
transactionFeesPerEpoch
)
return epochDistribution
}
const setValue = (key, value) => {
const newValues = { ...values, [key]: value }
if (
key === 'currency' &&
value.exchangeRate !== values.currency.exchangeRate
) {
const stakePoolFixedFeeInADA = toADA(parseFloat(values.stakePoolFixedFee))
newValues.stakePoolFixedFee = `${fromADA(
stakePoolFixedFeeInADA,
value.exchangeRate
)}`
}
setValues(newValues)
}
const updateType = (type) => (e) => {
e.preventDefault()
setType(type)
}
const fromADA = (amount, exchangeRate = null) => {
let exchangeRateUsed = parseFloat(
exchangeRate === null ? values.currency.exchangeRate : exchangeRate
)
if (isNaN(exchangeRateUsed) || exchangeRateUsed <= 0)
exchangeRateUsed =
getInitialCurrency(values.currency.key).exchangeRate || 1
return amount * exchangeRateUsed
}
const toADA = (amount, exchangeRate = null) => {
let exchangeRateUsed = parseFloat(
exchangeRate === null ? values.currency.exchangeRate : exchangeRate
)
if (isNaN(exchangeRateUsed) || exchangeRateUsed <= 0)
exchangeRateUsed =
getInitialCurrency(values.currency.key).exchangeRate || 1
return amount / exchangeRateUsed
}
const toggleShowAdvancedOptions = (e) => {
e.preventDefault()
setShowAdvancedOptions(!showAdvancedOptions)
}
const reset = () => {
const currency = currencies
.filter((currency) => currency.key === values.currency.key)
.shift()
setAllCurrencies(JSON.parse(JSON.stringify(currencies)))
setValues(getDefaultValues(currency, initialValues))
}
const onReset = (e) => {
e.preventDefault()
reset()
}
const getCurrencySymbol = (key) =>
(currencies.filter((currency) => currency.key === key).shift() || {})
.symbol || null
const normalizeLargeNumber = (number, dp = 0, preserveDP = false) => {
let negative = number < 0
const normalizedNumber = Math.abs((number || 0).toFixed(dp))
if (normalizedNumber === 0) negative = false
const asStringArray = `${normalizedNumber}`.split('.')
const n = asStringArray[0].split('').reverse()
let i = 3
while (i < n.length) {
n.splice(i, 0, ',')
i += 4
}
let finalNumber = n
.reverse()
.join('')
.concat(asStringArray[1] ? `.${asStringArray[1]}` : '')
if (!preserveDP && finalNumber.indexOf('.') > -1) {
while (finalNumber[finalNumber.length - 1] === '0') {
finalNumber = finalNumber.substring(0, finalNumber.length - 1)
}
}
return `${negative ? '-' : ''}${finalNumber.replace(/\.$/, '')}`
}
const getShareableLink = () => {
const params = new URLSearchParams()
const keys = [
'ada',
'stakePoolControl',
'operatorsStake',
'stakePoolMargin',
'stakePoolPerformance',
'totalStakePools',
'influenceFactor',
'transactionFeesPerEpoch',
'stakePoolFixedFee',
'treasuryRate',
'expansionRate',
'epochDurationInDays',
'currentEpoch',
]
keys.forEach((key) => params.set(key, values[key]))
params.set('calculator', type)
return `${origin}${pathname}?${params.toString()}`
}
const copyShareableLink = (e) => {
e.preventDefault()
const el = document.createElement('textarea')
const link = getShareableLink()
el.value = link
el.setAttribute('readonly', 'true')
el.setAttribute('aria-hidden', 'true')
el.setAttribute('tab-index', '-1')
el.style.position = 'absolute'
el.style.left = '-999999px'
modalContent.current.appendChild(el)
el.select()
document.execCommand('copy')
modalContent.current.removeChild(el)
clearTimeout(copiedTimeout.current)
setCopied(true)
copiedTimeout.current = setTimeout(() => setCopied(false), 500)
}
const CalculatorComponent = type === 'delegator' ? Delegator : Operator
return (
<Container ref={containerRef}>
<Introduction paddingBottom={1} textAlign="center">
<p>{content.staking_calculator.select_a_calculator}</p>
<p>{content.staking_calculator.i_want_to}</p>
</Introduction>
<CalculatorPicker>
<div>
<Button
variant={type === 'delegator' ? 'contained' : 'outlined'}
onClick={updateType('delegator')}
color="primary"
fullWidth
>
<DelegatorIcon active={type === 'delegator'} />
<span>{content.staking_calculator.delegate_my_stake}</span>
</Button>
<CardanoLogo active={type === 'delegator'} />
</div>
<div>
<Button
variant={type === 'operator' ? 'contained' : 'outlined'}
onClick={updateType('operator')}
color="primary"
fullWidth
>
<OperatorIcon active={type === 'operator'} />
<span>{content.staking_calculator.run_a_stake_pool}</span>
</Button>
<CardanoLogo active={type === 'operator'} />
</div>
</CalculatorPicker>
<Actions>
<div>
<div>
<Button
color="primary"
variant={showAdvancedOptions ? 'contained' : 'outlined'}
onClick={toggleShowAdvancedOptions}
fullWidth
>
{content.staking_calculator.show_advanced_options}
<Box component="span" marginLeft={0.8}>
{showAdvancedOptions ? <MdVisibilityOff /> : <MdVisibility />}
</Box>
</Button>
</div>
<div>
<Button
color="primary"
variant="outlined"
onClick={onReset}
fullWidth
>
{content.staking_calculator.reset}
<Box component="span" marginLeft={0.8}>
<MdRotateLeft />
</Box>
</Button>
</div>
</div>
<div>
<div>
<Button
color="primary"
variant="outlined"
onClick={(e) => {
e.preventDefault()
setShareModalVisible(true)
}}
fullWidth
>
{content.staking_calculator.share}
<Box component="span" marginLeft={0.8}>
<MdFileUpload />
</Box>
</Button>
{shareModalVisible && (
<Modal
open={shareModalVisible}
onClose={(e) => {
e.preventDefault()
setShareModalVisible(false)
}}
disableScrollLock
>
<ModalContent ref={modalContent}>
<CloseModal
href="#"
onClick={(e) => {
e.preventDefault()
setShareModalVisible(false)
}}
>
<MdClose />
</CloseModal>
<ModalContentInner>
<Box textAlign="center">
<ShareLinks>
<div>
<TwitterLink
href={`https://twitter.com/intent/tweet?text=${getShareableLink()}`}
>
<FaTwitter />{' '}
<span>{content.staking_calculator.tweet}</span>
</TwitterLink>
</div>
<div>
<FacebookLink
href={`https://www.facebook.com/dialog/share?href=${getShareableLink()}&display=popup&app_id=282617186477949&redirect_uri=https://facebook.com/`}
>
<FaFacebookF />{' '}
<span>{content.staking_calculator.share}</span>
</FacebookLink>
</div>
</ShareLinks>
<p>
<CopyToClipboardLink
href="#copy-to-clipboard"
onClick={copyShareableLink}
>
<FaClipboard />{' '}
<span className="text">
{content.staking_calculator.copy_to_clipboard}
</span>
{copied && (
<AnimatedClipboard>
<FaClipboard />
</AnimatedClipboard>
)}
</CopyToClipboardLink>
</p>
</Box>
</ModalContentInner>
</ModalContent>
</Modal>
)}
</div>
<div />
</div>
</Actions>
<Inputs>
<CalculatorComponent
values={values}
setValue={setValue}
content={content}
toADA={toADA}
fromADA={fromADA}
showAdvancedOptions={showAdvancedOptions}
HalfWidthGroup={HalfWidthGroup}
FullWidthGroup={FullWidthGroup}
getCurrencySymbol={getCurrencySymbol}
currencies={currencies}
normalizeLargeNumber={normalizeLargeNumber}
getDistributableRewards={getDistributableRewards}
getTotalADAInCirculation={getTotalADAInCirculation}
containerRef={containerRef}
/>
</Inputs>
</Container>
)
}
Example #10
Source File: WalletDownloaders.js From testnets-cardano-org with MIT License | 4 votes |
WalletDownloaders = ({ gaCategory, settingsEndpoint }) => {
const [ platformsData, setPlatformsData ] = useState(null)
const [ loading, setLoading ] = useState(true)
const [ hasError, setHasError ] = useState(false)
const [ activeModal, setActiveModal ] = useState('')
const checksumRefs = {
windows: useRef(null),
darwin: useRef(null),
linux: useRef(null)
}
const validateData = (data) => {
if (!data.platforms) return false
const validPlatforms = [ 'windows', 'darwin', 'linux' ]
if (Object.keys(data.platforms).length !== validPlatforms.length) return false
let valid = true
validPlatforms.forEach(platform => {
if (!data.platforms[platform]) {
valid = false
} else {
const validKeys = [ 'signature', 'hash', 'URL', 'version', 'SHA256' ]
if (Object.keys(data.platforms[platform]).length !== validKeys.length) {
valid = false
} else {
validKeys.forEach(key => {
if (typeof data.platforms[platform][key] !== 'string' || !data.platforms[platform][key]) valid = false
})
}
}
})
return valid
}
const loadDaedalusData = async () => {
try {
setLoading(true)
const result = await fetch(settingsEndpoint)
const jsonResult = await result.json()
if (!validateData(jsonResult)) throw new Error('Invalid data')
setPlatformsData(Object.keys(jsonResult.platforms).map(platform => ({ ...jsonResult.platforms[platform], key: platform })))
setLoading(false)
} catch (error) {
console.error(error.message, error)
analytics.exception({ description: error.message, fatal: false, args: [ settingsEndpoint ], error })
setHasError(true)
setLoading(false)
}
}
useEffect(() => {
loadDaedalusData()
}, [])
const getOrderedPlatforms = (order) => {
const platforms = []
order.forEach(platform => {
platforms.push(platformsData.filter(({ key }) => platform === key).shift())
})
return platforms.filter(platform => Boolean(platform))
}
const checksumOnClick = (SHA256, platform, version) => (e) => {
e.preventDefault()
analytics.click({ category: gaCategory, label: `checksum_copy_${platform}_${version}`, event: e })
const el = checksumRefs[platform].current
if (!el) return
el.select()
el.setSelectionRange(0, SHA256.length)
document.execCommand('copy')
}
const openModal = (name) => (e) => {
e.preventDefault()
setActiveModal(name)
}
const getFilename = (URL) => URL.replace(/^.*\/(.*?)$/, '$1')
const renderTemplateString = (content, { SHA256, URL, version, hash, signature }) => {
const params = {
sha256: SHA256,
version,
hash,
signature,
filename: getFilename(URL)
}
return content.replace(/{{\s?([^}\s]+)\s?}}/g, (original, key) => {
return params[key] || original
})
}
const getPGPFilename = (URL) => `${getFilename(URL)}.asc`
const getPGPBlob = (signature) => window.Blob && new window.Blob([ signature ], { type: 'text/txt' })
const getPGPSignatureHref = (signature) => {
const blob = getPGPBlob(signature)
return blob ? URL.createObjectURL(blob) : '#'
}
const onDownloadPGPSignature = (signature, URL) => (e) => {
if (window.navigator.msSaveBlob || e.target.href === '#') e.preventDefault()
if (window.navigator.msSaveBlob) window.navigator.msSaveBlob(getPGPBlob(signature), getPGPFilename(URL))
}
const unCacheURL = (url) => {
return url + '?t=' + (new Date().getTime())
}
return (
<GlobalContentQuery
render={content => (
<Box marginTop={4} marginBottom={4}>
{platformsData && !hasError && !loading &&
<Container>
{getOrderedPlatforms(content.downloaders_content.platforms_order.map(platform => platform.platform_name)).map(({ key, signature, hash, URL, version, SHA256 }) => (
<Box flex={1} key={key} display='flex' flexDirection='column' justifyContent='flex-end' textAlign='center'>
<span><strong>{content.downloaders_content[key].full_label}</strong></span>
<span>{content.downloaders_content.version}: {version}</span>
<Box marginTop={1} marginBottom={1}>
<Button
component={Link}
href={unCacheURL(URL)}
variant='contained'
color='primary'
tracking={{ category: gaCategory, label: `download_${key}_${version}` }}
>
{content.downloaders_content[key].short_label}<Box component='span' marginLeft={1}><FaDownload /></Box>
</Button>
</Box>
<Box>
<span>{content.downloaders_content.sha_checksum}</span>
<ChecksumArea
ref={checksumRefs[key]}
title={content.downloaders_content.copy_to_clipboard}
onClick={checksumOnClick(SHA256, key, version)}
aria-label={content.downloaders_content.copy_to_clipboard}
value={SHA256}
readOnly
rows={3}
/>
<Link
href='#'
onClick={openModal(`${key}_checksum`)}
tracking={{ category: gaCategory, label: `view_checksum_instructions_${key}_${version}` }}
>
{content.downloaders_content.verify_checksum}
</Link>
<Modal
open={activeModal === `${key}_checksum`}
onClose={openModal('')}
disableScrollLock
>
<ModalContent>
<CloseModal
href='#'
onClick={openModal('')}
>
<MdClose />
</CloseModal>
<ModalContentInner>
<Markdown
source={renderTemplateString(content.downloaders_content[key].checksum_instructions, { SHA256, signature, hash, URL, version })}
/>
</ModalContentInner>
</ModalContent>
</Modal>
</Box>
<Box marginTop={1}>
<Link
onClick={onDownloadPGPSignature(signature, URL)}
tracking={{ category: gaCategory, label: `download_pgp_signature_${key}_${version}` }}
href={getPGPSignatureHref(signature)}
download={getPGPFilename(URL)}
>
{content.downloaders_content.pgp_signature}<Box marginLeft={1} component='span'><FaDownload /></Box>
</Link>
<Box>
<Link
href='#'
onClick={openModal(`${key}_pgp`)}
tracking={{ category: gaCategory, label: `view_pgp_instructions_${key}_${version}` }}
>
{content.downloaders_content.verify_signature}
</Link>
<Modal
open={activeModal === `${key}_pgp`}
onClose={openModal('')}
disableScrollLock
>
<ModalContent>
<CloseModal
href='#'
onClick={openModal('')}
>
<MdClose />
</CloseModal>
<ModalContentInner>
<Markdown
source={renderTemplateString(content.downloaders_content[key].signature_instructions, { SHA256, signature, hash, URL, version })}
/>
</ModalContentInner>
</ModalContent>
</Modal>
</Box>
</Box>
</Box>
))}
</Container>
}
{loading &&
<LoadingContainer>
<div>
<CircularProgress />
</div>
</LoadingContainer>
}
{hasError &&
<ErrorContainer pl={12} pr={12}>
<Typography variant='h1' color='error'><FaCogs /></Typography>
<Typography variant='h3' color='error'>{content.downloaders_content.no_releases_available}</Typography>
</ErrorContainer>
}
</Box>
)}
/>
)
}
Example #11
Source File: index.js From hackchat-client with Do What The F*ck You Want To Public License | 4 votes |
export function MainMenu({
mainMenuIsOpen,
usersMenuIsOpen,
ChannelsModalIsOpen,
joinMenuIsOpen,
localeMenuIsOpen,
onOpenMainMenu,
onCloseMainMenu,
onOpenUsersModal,
onCloseUsersModal,
onOpenChannelsModal,
onCloseChannelsModal,
onOpenJoinMenu,
onCloseJoinMenu,
onOpenLocaleMenu,
onCloseLocaleMenu,
history,
intl,
}) {
useInjectReducer({ key: 'mainMenu', reducer });
const usersBtnToolTip = intl.formatMessage(messages.usersBtnToolTip);
const channelsBtnToolTip = intl.formatMessage(messages.channelsBtnToolTip);
const joinBtnToolTip = intl.formatMessage(messages.joinBtnToolTip);
const languageBtnToolTip = intl.formatMessage(messages.languageBtnToolTip);
const mainIcon = mainMenuIsOpen ? <MdClose /> : <MdMenu />;
const menuBtnText = intl.formatMessage(messages.menuBtnToolTip);
const settingsBtnText = intl.formatMessage(messages.settingsBtnToolTip);
return (
<div>
<Collapse className="fixed-bottom" isOpen={mainMenuIsOpen}>
<Container fluid>
<Row className="mx-auto">
<Col>
<MenuButton
onClick={() => {
if (ChannelsModalIsOpen) {
onCloseUsersModal();
} else {
onOpenUsersModal();
}
}}
toolTip={usersBtnToolTip}
>
<MdPeople />
</MenuButton>
<UsersModal open={usersMenuIsOpen} />
</Col>
</Row>
<Row className="mx-auto">
<Col>
<MenuButton
onClick={() => {
if (ChannelsModalIsOpen) {
onCloseChannelsModal();
} else {
onOpenChannelsModal();
}
}}
toolTip={channelsBtnToolTip}
>
<MdForum />
</MenuButton>
<ChannelsModal open={ChannelsModalIsOpen} />
</Col>
</Row>
<Row className="mx-auto">
<Col>
<MenuButton
onClick={() => {
if (joinMenuIsOpen) {
onCloseJoinMenu();
} else {
onOpenJoinMenu();
}
}}
toolTip={joinBtnToolTip}
>
<FaPlus />
</MenuButton>
<JoinModal open={joinMenuIsOpen} />
</Col>
</Row>
<Row className="mx-auto">
<Col>
<MenuButton
onClick={() => {
if (localeMenuIsOpen) {
onCloseLocaleMenu();
} else {
onOpenLocaleMenu();
}
}}
toolTip={languageBtnToolTip}
>
<MdLanguage />
</MenuButton>
<LocaleModal open={localeMenuIsOpen} />
</Col>
</Row>
<Row className="mx-auto">
<Col>
<MenuButton
onClick={() => {
history.push('/settings');
}}
toolTip={settingsBtnText}
>
<MdSettings />
</MenuButton>
</Col>
</Row>
<Row>
<Col>
<Spacer />
</Col>
</Row>
</Container>
</Collapse>
<MenuButton
isMain
className="fixed-bottom"
onClick={() => {
if (mainMenuIsOpen) {
onCloseMainMenu();
} else {
onOpenMainMenu();
}
}}
toolTip={menuBtnText}
>
{mainIcon}
</MenuButton>
</div>
);
}
Example #12
Source File: video.esm.js From reactjs-media with MIT License | 4 votes |
ReactVideo = function ReactVideo(props) {
var _useState = useState(false),
_useState2 = _slicedToArray(_useState, 2),
playing = _useState2[0],
setplaying = _useState2[1];
var video = useRef(null);
var div = useRef(null);
var sect = useRef(null);
var vdiv = useRef(null);
var _useState3 = useState(false),
_useState4 = _slicedToArray(_useState3, 2),
error = _useState4[0],
seterror = _useState4[1];
var _useState5 = useState(false),
_useState6 = _slicedToArray(_useState5, 2),
y = _useState6[0],
sety = _useState6[1];
var _useState7 = useState(false),
_useState8 = _slicedToArray(_useState7, 2),
x = _useState8[0],
setx = _useState8[1];
var _useState9 = useState(false),
_useState10 = _slicedToArray(_useState9, 2),
on = _useState10[0],
seton = _useState10[1];
var _useState11 = useState(true),
_useState12 = _slicedToArray(_useState11, 2),
loaded = _useState12[0],
setloaded = _useState12[1];
var _useState13 = useState(false),
_useState14 = _slicedToArray(_useState13, 2),
fulls = _useState14[0],
setfulls = _useState14[1];
var _useState15 = useState(false),
_useState16 = _slicedToArray(_useState15, 2),
mute = _useState16[0],
setmute = _useState16[1];
var _useState17 = useState(false),
_useState18 = _slicedToArray(_useState17, 2),
more = _useState18[0],
setmore = _useState18[1];
var _useState19 = useState('00:00'),
_useState20 = _slicedToArray(_useState19, 2),
ct = _useState20[0],
setcurrenttime = _useState20[1];
var _useState21 = useState('00:00'),
_useState22 = _slicedToArray(_useState21, 2),
ctt = _useState22[0],
setctt = _useState22[1];
var _useState23 = useState(0),
_useState24 = _slicedToArray(_useState23, 2),
ofwidth = _useState24[0],
setofwidth = _useState24[1];
var mm = function mm() {
setmore(!more);
};
function va(e) {
var x = e.nativeEvent.layerX;
var offsetWidth = vdiv.current.offsetWidth;
var time = x / offsetWidth * 1;
video.current.volume = time;
}
function foward(e) {
var x = 0.025 * video.current.duration;
video.current.currentTime += x;
if (props.onFoward) {
props.onFoward();
}
}
function rewind(e) {
var x = 0.05 * video.current.currentTime;
video.current.currentTime -= x;
if (props.onRewind) {
props.onRewind();
}
}
function onSeek(e) {
var x = e.nativeEvent.layerX;
var offsetWidth = div.current.offsetWidth;
var duration = video.current.duration;
var time = x / offsetWidth * duration;
video.current.currentTime = time;
var xx = x - 12;
var seekwidth = xx / offsetWidth * 100;
setofwidth(seekwidth);
if (props.onSeek) {
props.onSeek();
}
}
function onMove(e) {
var x = e.nativeEvent.layerX;
var offsetWidth = div.current.offsetWidth;
var duration = video.current.duration;
var time = x / offsetWidth * duration;
setctt(calcTime(time));
var xx = x - 12;
var seekwidth = xx / offsetWidth * 100;
setofwidth(seekwidth);
if (props.onSeek) {
props.onSeek();
}
}
function addp() {
if (video.current.playbackRate < 16) {
video.current.playbackRate += 1;
}
}
function minusp() {
if (video.current.playbackRate > 0) {
video.current.playbackRate -= 1;
}
}
function TimeUpdate(e) {
var _video$current = video.current,
currentTime = _video$current.currentTime,
duration = _video$current.duration;
setcurrenttime(calcTime(currentTime));
if (props.onTimeUpdate) {
props.onTimeUpdate(e, currentTime, duration);
}
}
function Mute(_x) {
return _Mute.apply(this, arguments);
}
function _Mute() {
_Mute = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(e) {
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return setmute(!mute);
case 2:
if (video.current.volume > 0) {
video.current.volume = 0;
} else {
video.current.volume = 1;
}
if (props.onMute) {
props.onMute(mute);
}
case 4:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _Mute.apply(this, arguments);
}
function calcTime(d) {
if (isNaN(d)) {
return '00:00';
}
var hours = d / 3600;
var hh = d % 3600;
var time = hh / 60;
var h = Math.floor(hours);
var f = Math.floor(time);
var seconds = d % 60;
seconds = Math.floor(seconds);
if (seconds < 10) {
seconds = "0".concat(seconds);
}
if (f < 10) {
f = "0".concat(f);
}
if (h <= 0) {
h = "";
} else if (h < 10 && h > 0) {
h = "0".concat(h, ":");
}
return "".concat(h).concat(f, ":").concat(seconds);
}
function pp() {
video.current.requestPictureInPicture();
if (props.onRequestPictureInPicture) {
props.onRequestPictureInPicture();
}
}
function setClipboard(text) {
navigator.clipboard.writeText(text).then(function () {}, function () {
// eslint-disable-next-line no-restricted-globals
alert('failed to copy url');
});
}
var play = function play(e) {
video.current.play();
setplaying(true);
if (props.onPlay) {
props.onPlay(e);
}
};
var pause = function pause(e) {
video.current.pause();
setplaying(false);
if (props.onPause) {
props.onPause(e);
}
};
function contextMenu(e) {
var _e$nativeEvent = e.nativeEvent,
clientY = _e$nativeEvent.clientY,
clientX = _e$nativeEvent.clientX;
setx(clientX);
sety(clientY);
seton(true);
}
var enterFullScreen = function enterFullScreen(e) {
sect.current.requestFullscreen();
if (props.onEnterFullScreen) {
props.onEnterFullScreen(e);
}
setfulls(true);
};
var exitFullScreen = function exitFullScreen() {
sect.current.ownerDocument.exitFullscreen();
setfulls(false);
};
function handleClose() {
seton(false);
}
return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("style", {
jsx: "true"
}, "\n .video-react-pause:hover,\n .video-react-play:hover,\n .video-react-volume:hover,\n .video-react-rewind:hover,\n .video-react-more:hover,\n .video-react-fullscreen:hover,\n .video-react-forward:hover {\n color: ".concat(props.primaryColor, ";\n }\n .finnished {\n background-color: ").concat(props.primaryColor, " !important;\n }\n .point {\n background-color: ").concat(props.primaryColor, " !important;\n }\n \n ")), /*#__PURE__*/React.createElement("section", {
onContextMenu: function onContextMenu(e) {
e.preventDefault();
contextMenu(e);
},
onBlur: function onBlur() {
handleClose();
},
className: "one___flkjsjJJNJnn_nANN8hG_YG7GY7g7BH9 ".concat(props.className),
ref: sect
}, /*#__PURE__*/React.createElement(Video, {
onError: function onError() {
seterror(true);
},
ref: {
video: video
},
autoPlay: props.autoPlay ? true : false,
onPause: function onPause() {
setplaying(false);
},
onPlay: function onPlay() {
setplaying(true);
},
className: "video-react",
onTimeUpdate: function onTimeUpdate(e) {
TimeUpdate(e);
},
src: props.src,
type: props.type ? props.type : "video/mp4"
}), video.current ? /*#__PURE__*/React.createElement(React.Fragment, null, video.current.seeking ? /*#__PURE__*/React.createElement("div", {
className: "video-react-loading"
}) : /*#__PURE__*/React.createElement(React.Fragment, null)) : /*#__PURE__*/React.createElement(React.Fragment, null), /*#__PURE__*/React.createElement(ControlsBar, {
ref: {
div: div,
vdiv: vdiv
},
video: video,
ctt: ctt,
onMouseMove: onMove,
ofwidth: ofwidth,
onSeek: onSeek,
ct: ct,
calcTime: calcTime,
pause: pause,
play: play,
rewind: rewind,
foward: foward,
va: va,
Mute: Mute,
playing: playing,
fulls: fulls,
exitFullScreen: exitFullScreen,
enterFullScreen: enterFullScreen,
more: more,
pp: pp,
minusp: minusp,
addp: addp,
mm: mm
}), /*#__PURE__*/React.createElement("div", {
className: "video-react-error_12ede3ws3",
style: error ? {
opacity: 1
} : {}
}, /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement(MdErrorOutline, null)), " ", /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement("b", null, "Error:"), " Failed to load Video"), /*#__PURE__*/React.createElement("span", {
className: "cancel",
onClick: function onClick() {
seterror(false);
}
}, /*#__PURE__*/React.createElement(MdClose, null))), on ? /*#__PURE__*/React.createElement("div", {
className: "menu-c",
onClick: function onClick() {
handleClose();
}
}, /*#__PURE__*/React.createElement("div", {
className: "menu-contxt",
onClick: function onClick() {
handleClose();
}
}, /*#__PURE__*/React.createElement("div", {
className: "video-rect-context",
style: {
top: y,
left: x
}
}, /*#__PURE__*/React.createElement("ul", {
className: "context-list"
}, playing ? /*#__PURE__*/React.createElement("li", {
className: "play",
onClick: pause
}, /*#__PURE__*/React.createElement("span", {
className: "i"
}, /*#__PURE__*/React.createElement(MdPause, null)), /*#__PURE__*/React.createElement("span", {
className: "t"
}, "Pause")) : /*#__PURE__*/React.createElement("li", {
className: "play",
onClick: play
}, /*#__PURE__*/React.createElement("span", {
className: "i"
}, /*#__PURE__*/React.createElement(MdPlayArrow, null)), /*#__PURE__*/React.createElement("span", {
className: "t"
}, "Play")), /*#__PURE__*/React.createElement("li", {
onClick: function onClick() {
setClipboard(video.current ? video.current.currentSrc : '');
}
}, /*#__PURE__*/React.createElement("span", {
className: "i"
}, /*#__PURE__*/React.createElement(MdFlipToBack, null)), /*#__PURE__*/React.createElement("span", {
className: "t"
}, "Copy Video Url")), video.current ? /*#__PURE__*/React.createElement(React.Fragment, null, video.current.loop ? /*#__PURE__*/React.createElement("li", {
onClick: function onClick() {
video.current.loop = false;
}
}, /*#__PURE__*/React.createElement("span", {
className: "i"
}, /*#__PURE__*/React.createElement(MdLoop, null)), /*#__PURE__*/React.createElement("span", {
className: "t"
}, "Stop Loop")) : /*#__PURE__*/React.createElement("li", {
onClick: function onClick() {
video.current.loop = true;
}
}, /*#__PURE__*/React.createElement("span", {
className: "i"
}, /*#__PURE__*/React.createElement(MdLoop, null)), /*#__PURE__*/React.createElement("span", {
className: "t"
}, "Loop"))) : /*#__PURE__*/React.createElement(React.Fragment, null))))) : /*#__PURE__*/React.createElement(React.Fragment, null), playing === false && loaded === true ? /*#__PURE__*/React.createElement("div", {
className: "poster"
}, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("img", {
src: props.poster,
alt: "video poster"
}), /*#__PURE__*/React.createElement("div", {
style: props.primaryColor ? {
background: props.primaryColor
} : {},
onClick: function onClick() {
play();
setloaded(false);
}
}, /*#__PURE__*/React.createElement(MdPlayArrow, null)))) : /*#__PURE__*/React.createElement(React.Fragment, null), props.childern));
}
Example #13
Source File: react-video.jsx From reactjs-media with MIT License | 4 votes |
ReactVideo = (props) => {
const [playing, setplaying] = useState(false)
const video = useRef(null)
const div = useRef(null)
const sect = useRef(null)
const vdiv = useRef(null)
const [error, seterror] = useState(false)
const [y, sety] = useState(false)
const [x, setx] = useState(false)
const [on, seton] = useState(false)
const [loaded, setloaded] = useState(true)
const [fulls, setfulls] = useState(false)
const [mute, setmute] = useState(false)
const [more, setmore] = useState(false)
const [ct, setcurrenttime] = useState('00:00')
const [ctt, setctt] = useState('00:00')
const [ofwidth, setofwidth] = useState(0)
const mm = () => {
setmore(!more)
}
function va(e) {
const x = e.nativeEvent.layerX
const { offsetWidth } = vdiv.current
let time = (x / offsetWidth) * 1
video.current.volume = time
}
function foward(e) {
let x = 0.025 * video.current.duration
video.current.currentTime += x
if (props.onFoward) {
props.onFoward()
}
}
function rewind(e) {
let x = 0.05 * video.current.currentTime
video.current.currentTime -= x
if (props.onRewind) {
props.onRewind()
}
}
function onSeek(e) {
const x = e.nativeEvent.layerX
const { offsetWidth } = div.current
const { duration } = video.current
let time = (x / offsetWidth) * duration
video.current.currentTime = time
let xx = x - 12
let seekwidth = (xx / offsetWidth) * 100
setofwidth(seekwidth)
if (props.onSeek) {
props.onSeek()
}
}
function onMove(e) {
const x = e.nativeEvent.layerX
const { offsetWidth } = div.current
const { duration } = video.current
let time = (x / offsetWidth) * duration
setctt(calcTime(time))
let xx = x - 12
let seekwidth = (xx / offsetWidth) * 100
setofwidth(seekwidth)
if (props.onSeek) {
props.onSeek()
}
}
function addp() {
if (video.current.playbackRate < 16) {
video.current.playbackRate += 1
}
}
function minusp() {
if (video.current.playbackRate > 0) {
video.current.playbackRate -= 1
}
}
function TimeUpdate(e) {
const { currentTime, duration } = video.current
setcurrenttime(calcTime(currentTime))
if (props.onTimeUpdate) {
props.onTimeUpdate(e, currentTime, duration)
}
}
async function Mute(e) {
await setmute(!mute)
if (video.current.volume > 0) {
video.current.volume = 0
} else {
video.current.volume = 1
}
if (props.onMute) {
props.onMute(mute)
}
}
function calcTime(d) {
if (isNaN(d)) {
return '00:00'
}
let hours = d / 3600;
let hh = d % 3600;
let time = hh / 60;
let h = Math.floor(hours)
let f = Math.floor(time)
let seconds = d % 60
seconds = Math.floor(seconds)
if (seconds < 10) {
seconds = `0${seconds}`
}
if (f < 10) {
f = `0${f}`
}
if (h <= 0) {
h = ``
} else if (h < 10 && h > 0) {
h = `0${h}:`
}
return `${h}${f}:${seconds}`
}
function pp() {
video.current.requestPictureInPicture()
if (props.onRequestPictureInPicture) {
props.onRequestPictureInPicture()
}
}
function setClipboard(text) {
navigator.clipboard.writeText(text).then(function () {
}, function () {
// eslint-disable-next-line no-restricted-globals
alert('failed to copy url')
});
}
const play = (e) => {
video.current.play()
setplaying(true)
if (props.onPlay) {
props.onPlay(e)
}
}
const pause = (e) => {
video.current.pause()
setplaying(false)
if (props.onPause) {
props.onPause(e)
}
}
function contextMenu(e) {
const { clientY, clientX } = e.nativeEvent
setx(clientX)
sety(clientY)
seton(true)
}
const enterFullScreen = (e) => {
sect.current.requestFullscreen()
if (props.onEnterFullScreen) {
props.onEnterFullScreen(e)
}
setfulls(true)
}
const exitFullScreen = () => {
sect.current.ownerDocument.exitFullscreen()
setfulls(false)
}
function handleClose() {
seton(false)
}
return (
<div>
<style jsx="true">{`
.video-react-pause:hover,
.video-react-play:hover,
.video-react-volume:hover,
.video-react-rewind:hover,
.video-react-more:hover,
.video-react-fullscreen:hover,
.video-react-forward:hover {
color: ${props.primaryColor};
}
.finnished {
background-color: ${props.primaryColor} !important;
}
.point {
background-color: ${props.primaryColor} !important;
}
`}</style>
<section onContextMenu={(e) => {
e.preventDefault()
contextMenu(e)
}} onBlur={() => {
handleClose()
}} className={`one___flkjsjJJNJnn_nANN8hG_YG7GY7g7BH9 ${props.className}`} ref={sect} >
<Video onError={() => {
seterror(true)
}} ref={{ video: video }} autoPlay={props.autoPlay ? true : false} onPause={() => {
setplaying(false)
}} onPlay={() => {
setplaying(true)
}} className='video-react' onTimeUpdate={(e) => {
TimeUpdate(e)
}} src={props.src} type={props.type ? props.type : "video/mp4"} />
{video.current ? <>
{video.current.seeking ?
<div className="video-react-loading"></div> : <></>}</> : <></>}
<ControlsBar ref={{ div, vdiv }} video={video} ctt={ctt} onMouseMove={onMove} ofwidth={ofwidth} onSeek={onSeek} ct={ct} calcTime={calcTime} pause={pause} play={play} rewind={rewind} foward={foward} va={va} Mute={Mute} playing={playing} fulls={fulls} exitFullScreen={exitFullScreen} enterFullScreen={enterFullScreen} more={more} pp={pp} minusp={minusp} addp={addp} mm={mm} />
<div className="video-react-error_12ede3ws3" style={error ? { opacity: 1 } : {}}>
<span><MdErrorOutline /></span> <span><b>Error:</b> Failed to load Video</span>
<span className="cancel" onClick={() => {
seterror(false)
}}>
<MdClose />
</span>
</div>
{on ?
<div className="menu-c" onClick={() => {
handleClose()
}}>
<div className="menu-contxt" onClick={() => {
handleClose()
}}>
<div className="video-rect-context" style={{ top: y, left: x }}>
<ul className="context-list">
{playing ?
<li className="play" onClick={pause} ><span className="i"><MdPause /></span><span className="t">Pause</span></li> : <li className="play" onClick={play} ><span className="i"><MdPlayArrow /></span><span className="t">Play</span></li>}
<li onClick={() => { setClipboard(video.current ? video.current.currentSrc : '') }}><span className="i"><MdFlipToBack /></span><span className="t" >Copy Video Url</span></li>
{video.current ? <>{video.current.loop ? <li onClick={() => {
video.current.loop = false
}} ><span className="i"><MdLoop /></span><span className="t">Stop Loop</span></li> : <li onClick={() => {
video.current.loop = true
}} ><span className="i"><MdLoop /></span><span className="t">Loop</span></li>
}</> : <></>}
</ul>
</div></div></div> : <></>}
{playing === false && loaded === true ? <div className="poster">
<div>
<img src={props.poster} alt="video poster" />
<div style={props.primaryColor ? { background: props.primaryColor } : {}} onClick={() => {
play()
setloaded(false)
}}><MdPlayArrow /></div>
</div>
</div> : <></>}
{props.childern}
</section>
</div>
)
}