react#useState JavaScript Examples

The following examples show how to use react#useState. 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: counter-simplified.jsx    From MDXP with MIT License 6 votes vote down vote up
Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count - 1)}>-</button>
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
}
Example #2
Source File: footer.js    From about-1hive with GNU General Public License v3.0 6 votes vote down vote up
EmailSection = () => {
  const [email, setEmail] = useState('')

  return (
    <StyledGoal style={{ width: '100%', maxWidth: '450px' }}>
      <p>Subscribe to our newsletter for updates</p>

      <EmailRow
        action="https://uniswap.us19.list-manage.com/subscribe/post?u=c93471c1443f1e6365b5ca093&amp;id=7d591bff13"
        method="post"
        id="mc-embedded-subscribe-form"
        name="mc-embedded-subscribe-form"
        target="_blank"
        novalidate
      >
        <StyledInput
          type="email"
          value={email}
          name="EMAIL"
          id="mce-EMAIL"
          placeholder="[email protected]"
          required
          onChange={val => setEmail(val.target.value)}
        />
        <div>
          <InputButton type="submit" value="->" name="subscribe" id="mc-embedded-subscribe" />
        </div>
      </EmailRow>
    </StyledGoal>
  )
}
Example #3
Source File: app-logic.js    From payroll-app with GNU Affero General Public License v3.0 6 votes vote down vote up
export function useRequestMode(requestPanelOpen) {
  const [requestMode, setRequestMode] = useState({
    mode: MODE.ADD_EMPLOYEE,
    data: null,
  })

  const updateMode = useCallback(
    newMode => {
      setRequestMode(newMode)
      requestPanelOpen()
    },
    [requestPanelOpen]
  )

  return [requestMode, updateMode]
}
Example #4
Source File: index.js    From tulip-frontend with GNU Affero General Public License v3.0 6 votes vote down vote up
DropdownComponent = props => {
  const [selected, setSelected] = useState(0)
  return (
    <DropDown
      items={props.items}
      selected={selected}
      onChange={setSelected}
      css={props.css}
    />
  )
}
Example #5
Source File: index.js    From uniswap-v1-frontend with GNU General Public License v3.0 6 votes vote down vote up
export default function TokenLogo({ address, size = '1rem', ...rest }) {
  const [error, setError] = useState(false)

  let path = ''
  if (address === 'ETH') {
    return <StyledDaiLogo size={size} />
  } else if (address === '0x71850b7E9Ee3f13Ab46d67167341E4bDc905Eef9') {
    return <StyledHoneyLogo size={size} />
  } else if (!error && !BAD_IMAGES[address]) {
    path = TOKEN_ICON_API(address.toLowerCase())
  } else {
    return (
      <Emoji {...rest} size={size}>
        <span role="img" aria-label="Thinking">
          ?
        </span>
      </Emoji>
    )
  }

  return (
    <Image
      {...rest}
      alt={address}
      src={path}
      size={size}
      onError={() => {
        BAD_IMAGES[address] = true
        setError(true)
      }}
    />
  )
}
Example #6
Source File: Brightness.jsx    From razer-macos with GNU General Public License v2.0 6 votes vote down vote up
export default function Brightness({ title, currentBrightness, handleBrightnessChange }) {

  const [brightness, setBrightness] = useState(currentBrightness);

  const onChange = (value) => {
    setBrightness(value);
    handleBrightnessChange(value);
  };
  return (
    <Slider
      title={title}
      step={1}
      className='horizontal-slider'
      thumbClassName='slider-thumb'
      trackClassName='slider-track'
      min={0}
      max={100}
      value={brightness}
      onChange={onChange}
      renderThumb={(props, state) => (
        <div {...props}>{state.valueNow + '%'}</div>
      )}
    />
  );
}
Example #7
Source File: session.js    From rsc-www with GNU Affero General Public License v3.0 6 votes vote down vote up
SessionContextProvider = (props) => {
    const [user, setUser] = useState(props.session.user || {});
    const [token, setToken] = useState(props.session.token || '');

    const storeUser = (user) => {
        setUser({ id: user.id, username: user.username, rank: user.rank });
    };

    return (
        <SessionContext.Provider value={{ user, storeUser, token, setToken }}>
            {props.children}
        </SessionContext.Provider>
    );
}
Example #8
Source File: index.js    From react-json-view-compare with MIT License 6 votes vote down vote up
JsonCompare = props => {
  let { oldData, newData } = props;
  let [data, setMergeData] = useState([]);

  useEffect(() => {
    setMergeData(mergeData(oldData, newData));
  }, [oldData, newData]);

  return (
    <pre className="c-json-view">
      <p className="c-json-outter">{isArray(newData) ? '[' : '{'}</p>
      {data.map((item, index) => (
        <Tree key={index} {...item} />
      ))}
      <p className="c-json-outter">{isArray(newData) ? ']' : '}'}</p>
    </pre>
  );
}
Example #9
Source File: leagues.js    From poe-what-to-flip with MIT License 6 votes vote down vote up
useSelectedLeague = () => {
  const [leagues, setLeagues] = useState({});
  useEffect(() => {
    fetchLeagues().then(fetchedLeagues => {
      console.log(`Leagues: ${JSON.stringify(fetchedLeagues)}`);
      setLeagues(fetchedLeagues);
    });
  }, []);

  const [selectedMetaLeague, setSelectedMetaLeague] = useState("Temp SC");

  const [selectedLeague, setSelectedLeague] = useState();
  useEffect(() => {
    setSelectedLeague(leagues[selectedMetaLeague]);
  }, [leagues, selectedMetaLeague]);

  const metaLeagues = ["Temp SC", "Temp HC", "Standard", "Hardcore"];

  return {
    metaLeagues,
    selectedMetaLeague,
    selectedLeague,
    setSelectedMetaLeague,
  };
}
Example #10
Source File: index.js    From acy-dex-interface with MIT License 6 votes vote down vote up
export function useAllOrdersStats(chainId) {
  const query = gql(`{
    orderStat(id: "total") {
      openSwap
      openIncrease
      openDecrease
      executedSwap
      executedIncrease
      executedDecrease
      cancelledSwap
      cancelledIncrease
      cancelledDecrease
    }
  }`)

  const [res, setRes] = useState()

  useEffect(() => {
    getGmxGraphClient(chainId).query({ query }).then(setRes).catch(console.warn)
  }, [setRes, query, chainId])

  return res ? res.data.orderStat : null
}
Example #11
Source File: popup.jsx    From MDXP with MIT License 5 votes vote down vote up
Popup = ({children, time = 5000, step = 0}) => {
  const {stepIndex, mode} = useDeck();
  const [showPopup, setPopup] = useState(false);
  const style = (showPopup && (step === stepIndex) && (mode === deckModes.NORMAL)) ? {
    opacity: 1,
    transition: 'all 0.3s ease-out',
    width: '75%'
  } : {
    opacity: 0,
    transform: 'translate(-50%, 25%)',
    width: '75%'
  };

  useEffect(() => {
    if (step === stepIndex) {
      const timer = setTimeout(() => setPopup(true), time);
      return () => clearTimeout(timer);
    }

    setPopup(false);
  });

  return (
    <Place
      bottom="15px"
      sx={{
        ...style,
        bg: t => t.colors.MDXPYellow.slice(0, -1) + '22)',
        padding: 2,
        paddingLeft: t => t.space[3] - t.space[1],
        borderLeftWidth: t => t.space[1],
        borderLeftStyle: 'solid',
        borderLeftColor: 'MDXPYellow',
        borderRadius: '10px',
        '& p': {my: 0},
        fontSize: 'xsmall',
        lineHeight: '140%'
      }}
    >
      {children}
    </Place>
  );
}
Example #12
Source File: menu.js    From about-1hive with GNU General Public License v3.0 5 votes vote down vote up
export function useToggle(initialState = false) {
  const [state, setState] = useState(initialState)
  const toggle = useCallback(() => setState(state => !state), [])

  return [state, toggle]
}
Example #13
Source File: App.js    From payroll-app with GNU Affero General Public License v3.0 5 votes vote down vote up
function App() {
  const [screen, setScreen] = useState(MY_PAYROLL.id)
  const {
    actions,
    isSyncing,
    requestMode,
    panelState,
    requests,
  } = useAppLogic()
  const { appearance } = useGuiStyle()
  const { layoutName } = useLayout()
  const compactMode = layoutName === 'small'

  const handleScreenChange = useCallback(screenId => {
    setScreen(SCREENS[screenId].id)
  }, [])

  return (
    <Main theme={appearance} assetsUrl="./aragon-ui">
      <SyncIndicator visible={isSyncing} />
      <Header
        primary="Payroll"
        secondary={
          !isSyncing && (
            <>
              {screen === MY_PAYROLL.id && (
                <Button
                  mode="strong"
                  onClick={requests.payday}
                  label="Request salary"
                  icon={<IconPlus />}
                  display={compactMode ? 'icon' : 'label'}
                />
              )}
              {screen === TEAM_PAYROLL.id && (
                <Button
                  mode="strong"
                  onClick={requests.addEmployee}
                  label="New employee"
                  icon={<IconPlus />}
                  display={compactMode ? 'icon' : 'label'}
                />
              )}
            </>
          )
        }
      />
      {
        <Tabs
          items={SCREENS.map(screen => screen.label)}
          selected={SCREENS.findIndex(s => s.id === screen)}
          onChange={handleScreenChange}
        />
      }
      {screen === MY_PAYROLL.id && <MyPayroll isSyncing={isSyncing} />}
      {screen === TEAM_PAYROLL.id && (
        <TeamPayroll
          isSyncing={isSyncing}
          onRequestEditEquityOption={requests.editEquityOption}
          onRequestTerminateEmployee={requests.terminateEmployee}
        />
      )}
      <Panel
        requestMode={requestMode}
        panelState={panelState}
        actions={actions}
      />
    </Main>
  )
}
Example #14
Source File: index.js    From tulip-frontend with GNU Affero General Public License v3.0 5 votes vote down vote up
Approve = props => {
  const {
    _web3ReactContext: { chainId },
  } = useWallet()
  const [visible, setVisible] = useState(false)
  const [txHash, setTxHash] = useState('')
  const opener = useRef()
  const balanceToEth = props.amount.balance
  const approve = useApprove(props.token, balanceToEth, chainId)
  const network = getNetworkConfig(chainId)

  const transactionTime = new Date()
  transactionTime.setSeconds(transactionTime.getSeconds() + 8)

  const handleApprove = () => {
    approve()
      .then(x => {
        if (x) {
          setVisible(true)
          setTxHash(x.hash)
          x.wait()
            .then(() => {
              setVisible(false)
            })
            .catch(err => {
              props.onError(err)
            })
        }
      })
      .catch(err => {
        props.onError(err)
      })
  }

  return (
    <>
      <Button
        css={`
          background: linear-gradient(90deg, #aaf5d4, #7ce0d6);
        `}
        label="Approve"
        wide
        onClick={handleApprove}
        ref={opener}
      />
      <TransactionProgress
        transactionHashUrl={network.txUrl + txHash}
        progress={1}
        visible={visible}
        endTime={transactionTime}
        onClose={() => setVisible(false)}
        opener={opener}
        slow={false}
      />
    </>
  )
}
Example #15
Source File: index.js    From uniswap-v1-frontend with GNU General Public License v3.0 5 votes vote down vote up
export default function ContextualInfo({
  openDetailsText = 'Advanced Details',
  closeDetailsText = 'Hide Advanced',
  contextualInfo = '',
  allowExpand = false,
  isError = false,
  slippageWarning,
  highSlippageWarning,
  brokenTokenWarning,
  dropDownContent
}) {
  const [showDetails, setShowDetails] = useState(false)
  return !allowExpand ? (
    <SummaryWrapper brokenTokenWarning={brokenTokenWarning}>{contextualInfo}</SummaryWrapper>
  ) : (
    <>
      <SummaryWrapperContainer
        onClick={() => {
          !showDetails &&
            ReactGA.event({
              category: 'Advanced Interaction',
              action: 'Open Advanced Details',
              label: 'Swap/Send Page Details'
            })
          setShowDetails(s => !s)
        }}
      >
        <>
          <ErrorSpan isError={isError} slippageWarning={slippageWarning} highSlippageWarning={highSlippageWarning}>
            {(slippageWarning || highSlippageWarning) && (
              <span role="img" aria-label="warning">
                ⚠️
              </span>
            )}
            {contextualInfo ? contextualInfo : showDetails ? closeDetailsText : openDetailsText}
          </ErrorSpan>
          {showDetails ? (
            <ColoredDropup isError={isError} highSlippageWarning={highSlippageWarning} />
          ) : (
            <ColoredDropdown isError={isError} highSlippageWarning={highSlippageWarning} />
          )}
        </>
      </SummaryWrapperContainer>
      {showDetails && <Details>{dropDownContent()}</Details>}
    </>
  )
}
Example #16
Source File: CustomColor2.jsx    From razer-macos with GNU General Public License v2.0 5 votes vote down vote up
export default function CustomColor2({ deviceSelected }) {

  const componentToHex = (c) => {
    if (typeof c === 'undefined') {
      return '00';
    }
    var hex = c.toString(16);
    return hex.length == 1 ? '0' + hex : hex;
  };

  const rgbToHex = ({ r, g, b }) => {
    return '#' + componentToHex(r) + componentToHex(g) + componentToHex(b);
  };

  const [currentColor, setCurrentColor] = useState({
    hex: rgbToHex(deviceSelected.settings.customColor2.rgb),
    rgb: deviceSelected.settings.customColor2.rgb,
  });
  const handleChange = (newColor) => {
    setCurrentColor(newColor);
  };

  const handleClick = () => {
    deviceSelected.settings.customColor2 = currentColor;
    let payload = {
      device: deviceSelected,
    };
    ipcRenderer.send('request-set-custom-color', payload);
  };
  const styles = { 'default': { picker: { background: '#202124', boxShadow: 'none'}, body: {
        padding: '12px 0 0'
      } }};
  return (
    <div>
      <p>Secondary custom color selection (Starlight Dual Mode only)</p>
      <div className='control'>
        <ChromePicker color={currentColor} onChange={handleChange} width='100%' disableAlpha={true} styles={styles} defaultView={'rgb'}/>
      </div>
      <div className='control'>
        <button onClick={handleClick}>Save custom color</button>
      </div>
    </div>
  );
}
Example #17
Source File: drop-down.js    From rsc-www with GNU Affero General Public License v3.0 5 votes vote down vote up
export default function DropDown(props) {
    const [isVisible, setVisible] = useState(false);

    const [oldButton] = props.children;

    const button = React.cloneElement(oldButton, {
        onClick: () => setVisible(!isVisible)
    });

    useEffect(() => {
        window.addEventListener('mouseup', () => {
            setVisible(false);
        });
    }, []);

    return (
        <div className="rsc-drop-down">
            {button}
            <ul
                className="rsc-drop-down-links"
                style={{
                    display: isVisible ? 'block' : 'none'
                }}
            >
                {props.children.slice(1).map((a, i) => {
                    a = React.cloneElement(
                        a,
                        {
                            ...a.props,
                            className: (a.props.className || '') + ' rsc-link'
                        },
                        a.props.children
                    );

                    return (
                        <li key={i}>
                            <Link href={a.props.href}>{a}</Link>
                        </li>
                    );
                })}
            </ul>
        </div>
    );
}
Example #18
Source File: complexTree.js    From react-json-view-compare with MIT License 5 votes vote down vote up
export default function ComplexTree(props) {
  let {
    name,
    value,
    type,
    line,
    showIndex,
    needComma,
    level = 1,
    lineType,
    lastLineType,
    lastLine = null
  } = props;

  let [visiable, setVisiable] = useState(true);

  return (
    <div className="c-json-line">
      <p
        className={`c-json-p c-line-${lineType}`}
        onClick={() => setVisiable(!visiable)}
        style={getIndent(level)}
      >
        <span className="c-json-mark">{line}</span>
        <span className={`c-of-${lineType}`}></span>
        <span className="c-json-content">
          {showIndex && <span className="c-json-key">{name}: </span>}
          <span className="c-json-pt">{isArray(type) ? '[' : '{'}</span>
        </span>
        {!visiable && (
          <span className="c-json-pt">
            {isArray(type) ? '...]' : '...}'}
            {needComma ? ',' : ''}
          </span>
        )}
      </p>
      <div style={{ display: visiable ? 'block' : 'none' }}>
        {value.map((item, index) => (
          <Tree key={index} level={level + 1} {...item} />
        ))}
        <p
          className="c-json-feet"
          className={`c-json-p c-line-${lineType}`}
          style={getIndent(level)}
        >
          {lastLine && <span className="c-json-mark">{lastLine}</span>}
          {lastLineType && <span className={`c-of-${lastLineType}`}></span>}
          <span className="c-json-pt">
            {isArray(type) ? ']' : '}'}
            {needComma ? ',' : ''}
          </span>
        </p>
      </div>
    </div>
  );
}
Example #19
Source File: index.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export function useAllPositions(chainId, library) {
  const count = 1000
  const query = gql(`{
    aggregatedTradeOpens(
      first: ${count}
    ) {
      account
      initialPosition{
        indexToken
        collateralToken
        isLong
        sizeDelta
      }
      increaseList {
        sizeDelta
      }
      decreaseList {
        sizeDelta
      }
    }
  }`)

  const [res, setRes] = useState()

  useEffect(() => {
    nissohGraphClient.query({ query }).then(setRes).catch(console.warn)
  }, [setRes, query])

  const key = res ? `allPositions${count}__` : false
  const { data: positions = [] } = useSWR(key, async () => {
    const provider = getProvider(library, chainId)
    const vaultAddress = getContract(chainId, "Vault")
    const contract = new ethers.Contract(vaultAddress, Vault.abi, provider)
    const ret = await Promise.all(res.data.aggregatedTradeOpens.map(async dataItem => {
      try {
        const { indexToken, collateralToken, isLong } = dataItem.initialPosition
        const positionData = await contract.getPosition(dataItem.account, collateralToken, indexToken, isLong)
        const position = {
          size: bigNumberify(positionData[0]),
          collateral: bigNumberify(positionData[1]),
          entryFundingRate: bigNumberify(positionData[3]),
          account: dataItem.account
        }
        position.fundingFee = await contract.getFundingFee(collateralToken, position.size, position.entryFundingRate)
        position.marginFee = position.size.div(1000)
        position.fee = position.fundingFee.add(position.marginFee)

        const THRESHOLD = 5000
        const collateralDiffPercent = position.fee.mul(10000).div(position.collateral)
        position.danger = collateralDiffPercent.gt(THRESHOLD)

        return position
      } catch (ex) {
        console.error(ex)
      }
    }))

    return ret.filter(Boolean)
  })

  return positions
}
Example #20
Source File: navigation.jsx    From MDXP with MIT License 4 votes vote down vote up
Navigation = ({
  keyboardReference,
  touchReference,
  slideNavigation = true,
  modeNavigation = true,
  storageNavigation = true
}) => {
  const filteredKeyBindings = filterKeyBindings(slideNavigation, modeNavigation);
  const [help, setHelp] = useState(false);
  useKeyboard(keyboardReference, slideNavigation, modeNavigation, setHelp);
  useTouch(touchReference, 15, slideNavigation, modeNavigation);
  useStorageNavigation(storageNavigation);

  if (help) {
    return (
      <div
        sx={{
          bg: 'rgba(0,0,0,.8)',
          color: 'white',
          position: 'absolute',
          maxHeight: '100%',
          overflowY: 'auto',
          overflowX: 'hidden',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          zIndex: '10',
          p: '30px 50px',
          borderRadius: '20px',
          fontSize: '1.25rem',
          maxWidth: '1200px',
          width: '95%',
          '@media screen and (min-width: 64em)': {
            width: '85%'
          },
          '& h1': {
            fontSize: '1.2em',
            lineHeight: '120%',
            textTransform: 'uppercase',
            fontWeight: 'bold',
            width: '100%',
            textAlign: 'center'
          },
          '& h2': {
            fontSize: '1.1em',
            lineHeight: '120%',
            textTransform: 'uppercase',
            fontWeight: 'normal',
            mt: '0px'
          },
          '& hr': {
            borderTop: '2px solid white',
            height: '0px',
            width: '100%',
            my: '30px'
          }
        }}
      >
        <h1>MDXP Help</h1>
        <div
          sx={{
            display: 'flex',
            flexDirection: 'column',
            p: '0px'
          }}
        >
          {
            Object.entries(filteredKeyBindings).map(([mode, keys], i) => (
              <React.Fragment key={`mode_${i}`}>
                <div>
                  <h2>{mode}</h2>
                  <div
                    sx={{
                      display: 'grid',
                      gridTemplateColumns: 'repeat(auto-fit, minmax(325px, 1fr))',
                      gridGap: '30px 100px'
                    }}
                  >
                    {
                      Object.entries(keys).map(([action, data], ii) => (
                        <div sx={{display: 'flex'}} key={`binding_${i}_${ii}`}>
                          <div sx={{width: '55%'}}>{action}</div>
                          <div sx={{width: '45%', fontWeight: '300', textAlign: 'right'}}>
                            {
                              data.keys.map((k, iii) => (
                                <React.Fragment key={`key_${i}_${ii}_${iii}`}>
                                  <span>{k}</span>
                                  {(iii !== (data.keys.length - 1)) && <br />}
                                </React.Fragment>
                              ))
                            }
                          </div>
                        </div>
                      ))
                    }
                  </div>
                </div>
                {(i !== (Object.keys(filteredKeyBindings).length - 1)) && <hr />}
              </React.Fragment>
            ))
          }
        </div>
      </div>
    );
  }

  return null;
}
Example #21
Source File: header.js    From about-1hive with GNU General Public License v3.0 4 votes vote down vote up
Header = props => {
  const matches = useMediaQuery('only screen and (max-width: 1024px)')
  const node = useRef()
  const button = useRef()
  const [isMenuOpen, updateIsMenuOpen] = useState(false)
  const [darkMode, toggleDarkMode] = useDarkMode()

  const data = useStaticQuery(graphql`
    {
      site {
        siteMetadata {
          menulinks {
            name
            sublinks {
              description
              name
              link
            }
          }
          title
        }
      }
    }
  `)

  useLayoutEffect(() => {
    // Get original body overflow
    const originalStyle = window.getComputedStyle(document.body).overflow
    // Prevent scrolling on mount
    if (isMenuOpen) {
      document.body.style.overflow = 'hidden'
      document.body.style.maxHeight = '-webkit-fill-available'
    }
    // Re-enable scrolling when component unmounts
    return () => (document.body.style.overflow = originalStyle)
  }, [isMenuOpen]) // Empty array ensures effect is only run on mount and unmount

  useEffect(() => {
    const handleClickOutside = e => {
      if (node.current.contains(e.target) || button.current.contains(e.target)) {
        return
      }
      updateIsMenuOpen(false)
    }

    document.addEventListener('mousedown', handleClickOutside)

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [isMenuOpen, updateIsMenuOpen, matches])

  return (
    <StyledHeader open={isMenuOpen}>
      <StyledNavTitleWrapper>
        <StyledHomeLink
          to="/"
          style={{
            textDecoration: `none`
          }}
        >
          <StyledUni />

          <StyledWordmark />
        </StyledHomeLink>
        {props.path && props.path !== '/' && props.path !== '' && (
          <>
            <StyledNavTitle to={'/' + props.path.split('/')[1]}>/ {props.path.split('/')[1]}</StyledNavTitle>
          </>
        )}
      </StyledNavTitleWrapper>
      <MenuToggle ref={button} open={isMenuOpen} onClick={() => updateIsMenuOpen(!isMenuOpen)}>
        {isMenuOpen ? <StyledCloseIcon /> : <StyledMenuIcon />}
      </MenuToggle>
      <StyledNav ref={node} open={isMenuOpen}>
        {data.site.siteMetadata.menulinks
          .filter(item => {
            return item.name !== 'Community'
          })
          .map(item => {
            return <Menu key={item.name} data={item} />
          })}
        <StyledButton type="button" onClick={toggleDarkMode}>
          {darkMode ? <Sun size={20} /> : <Moon size={20} />}
        </StyledButton>
        {props.path !== undefined && <StyledTradeLink href="https://gardens.1hive.org/#/xdai/garden/0x8ccbeab14b5ac4a431fffc39f4bec4089020a155">Open Garden</StyledTradeLink>}
      </StyledNav>
    </StyledHeader>
  )
}
Example #22
Source File: DatePicker.js    From payroll-app with GNU Affero General Public License v3.0 4 votes vote down vote up
function DatePicker({
  initialDate,
  onSelect,
  hideYearSelector,
  yearFormat,
  hideMonthSelector,
  monthFormat,
  monthYearFormat,
  hideWeekDays,
  weekDayFormat,
  validFromToday,
  ...props
}) {
  const [selectedDate, setSelectedDate] = useState(initialDate)

  const setDate = ({ year, add }) => event => {
    setSelectedDate(
      dayjs(selectedDate)
        .startOf('month')
        [add ? 'add' : 'subtract'](1, year ? 'year' : 'month')
        .toDate()
    )
  }

  const today = dayjs()
    .startOf('day')
    .toDate()

  const selectedDayjs = dayjs(selectedDate || today)

  const isSelected = day => {
    if (initialDate) {
      return day.isSame(initialDate, 'day')
    }
    return false
  }

  return (
    <div
      css={`
        display: grid;
      `}
      {...props}
    >
      {!hideYearSelector && (
        <Selector
          prev={setDate({ year: true, add: false })}
          next={setDate({ year: true, add: true })}
          small
        >
          {selectedDayjs.format(yearFormat)}
        </Selector>
      )}

      {!hideMonthSelector && (
        <Selector
          prev={setDate({ year: false, add: false })}
          next={setDate({ year: false, add: true })}
        >
          {selectedDayjs.format(
            !hideYearSelector ? monthFormat : monthYearFormat
          )}
        </Selector>
      )}

      <div
        css={`
          display: grid;
          grid-template: auto / repeat(7, 1fr);
          width: ${31.5 * GU}px;
        `}
      >
        {!hideWeekDays &&
          eachDayOfInterval({
            start: selectedDayjs.startOf('week'),
            end: selectedDayjs.endOf('week'),
          }).map(day => {
            const dayJs = dayjs(day)
            return (
              <MonthDay key={dayJs.format('dd')} weekDay>
                {dayJs.format(weekDayFormat)}
              </MonthDay>
            )
          })}

        {eachDayOfInterval({
          start: selectedDayjs.startOf('month').startOf('week'),
          end: selectedDayjs.endOf('month').endOf('week'),
        }).map(day => {
          const dayJs = dayjs(day)
          return (
            <MonthDay
              key={dayJs.valueOf()}
              disabled={
                !selectedDayjs.isSame(dayJs, 'month') ||
                (validFromToday && dayJs.isBefore(today))
              }
              selected={isSelected(dayJs)}
              today={dayJs.isSame(today, 'day')}
              onClick={() => onSelect(dayJs.toDate())}
            >
              {dayJs.format(props.dayFormat)}
            </MonthDay>
          )
        })}
      </div>
    </div>
  )
}
Example #23
Source File: AccountModule.js    From tulip-frontend with GNU Affero General Public License v3.0 4 votes vote down vote up
function AccountModule() {
  const [activatingDelayed, setActivatingDelayed] = useState(null)
  const buttonRef = useRef()
  const { below } = useViewport()
  const { connectionBoxOpened, setConnectionBoxOpened } = useAppState()
  const compactMode = below('medium')
  const wallet = useWallet()
  const { account, connector, error, status } = wallet

  const open = useCallback(() => setConnectionBoxOpened(true), [])
  const toggle = useCallback(
    () => setConnectionBoxOpened(opened => !opened),
    []
  )

  useEffect(() => {
    let timer

    if (status === 'error') {
      setActivatingDelayed(null)
    }

    if (status === 'connecting') {
      setActivatingDelayed(connector)
      timer = setTimeout(() => {
        setActivatingDelayed(null)
      }, 400)
    }

    return () => clearTimeout(timer)
  }, [connector, status])

  const handleResetConnection = useCallback(() => {
    wallet.reset()
  }, [wallet])

  const handleActivate = useCallback(providerId => wallet.connect(providerId), [
    wallet,
  ])

  const previousScreenIndex = useRef(-1)

  const { screenIndex, direction } = useMemo(() => {
    const screenId = status === 'disconnected' ? 'providers' : status

    const screenIndex = SCREENS.findIndex(screen => screen.id === screenId)
    const direction = previousScreenIndex.current > screenIndex ? -1 : 1

    previousScreenIndex.current = screenIndex

    return { direction, screenIndex }
  }, [status])

  const screen = SCREENS[screenIndex]
  const screenId = screen.id

  const handlePopoverClose = useCallback(() => {
    if (screenId === 'connecting' || screenId === 'error') {
      // reject closing the popover
      return false
    }
    setConnectionBoxOpened(false)
  }, [screenId])

  return (
    <div
      ref={buttonRef}
      tabIndex="0"
      css={`
        display: flex;
        align-items: center;
        justify-content: space-around;
        width: ${compactMode ? 'auto' : `${24.5 * GU}px`};
        outline: 0;
      `}
    >
      {screen.id === 'connected' ? (
        <AccountButton onClick={toggle} />
      ) : (
        <Button
          icon={<IconConnect />}
          label="Connect account"
          onClick={toggle}
          display={compactMode ? 'icon' : 'all'}
        />
      )}
      <AccountPopover
        direction={direction}
        heading={screen.title}
        keys={({ screenId }) => screenId + status + error.name}
        onClose={handlePopoverClose}
        onOpen={open}
        opener={buttonRef.current}
        screenId={screenId}
        screenData={{
          account,
          activating: activatingDelayed,
          activationError: error,
          status,
          screenId,
        }}
        screenKey={({ account, activating, activationError, screenId }) =>
          (activationError ? activationError.name : '') +
          account +
          activating +
          screenId
        }
        visible={connectionBoxOpened}
      >
        {({ activating, activationError, screenId }) => {
          if (screenId === 'connecting') {
            return (
              <ScreenConnecting
                providerId={activating}
                onCancel={handleResetConnection}
              />
            )
          }
          if (screenId === 'connected') {
            return <ScreenConnected wallet={wallet} />
          }
          if (screenId === 'error') {
            return (
              <ScreenError
                error={activationError}
                onBack={handleResetConnection}
              />
            )
          }
          return <ScreenProviders onActivate={handleActivate} />
        }}
      </AccountPopover>
    </div>
  )
}