react-spring#useSpring JavaScript Examples

The following examples show how to use react-spring#useSpring. 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: MetricCard.js    From umami with MIT License 6 votes vote down vote up
MetricCard = ({
  value = 0,
  change = 0,
  label,
  reverseColors = false,
  format = formatNumber,
  hideComparison = false,
}) => {
  const props = useSpring({ x: Number(value) || 0, from: { x: 0 } });
  const changeProps = useSpring({ x: Number(change) || 0, from: { x: 0 } });

  return (
    <div className={styles.card}>
      <animated.div className={styles.value}>{props.x.interpolate(x => format(x))}</animated.div>
      <div className={styles.label}>
        {label}
        {~~change !== 0 && !hideComparison && (
          <animated.span
            className={`${styles.change} ${
              change >= 0
                ? !reverseColors
                  ? styles.positive
                  : styles.negative
                : !reverseColors
                ? styles.negative
                : styles.positive
            }`}
          >
            {changeProps.x.interpolate(x => `${change >= 0 ? '+' : ''}${format(x)}`)}
          </animated.span>
        )}
      </div>
    </div>
  );
}
Example #2
Source File: AnimatedPath.js    From likelihood with MIT License 6 votes vote down vote up
AnimatedPath = ({ data, x, sigma2, xScale, yScale, linex, mu, sample, animating }) => {
  const [val, set] = useSpring(() =>  ({value: mu, immediate: false, config: {duration: 500}} ));

  set({value: mu, immediate: !animating})

  const interp = (mu) => {
    const interpLine = data.map(d => ([d[0], logLikSum(sample, mu, d[0])]));
    return linex(interpLine);
  }

  return (
    <animated.path d={val.value.interpolate(mu => interp(mu))} className="LogLikSigma" />
  );
}
Example #3
Source File: AnimatedRightIcon.jsx    From Personal-Website with MIT License 6 votes vote down vote up
function AnimatedRightIcon({onClick, disabled}) {

  const props = useSpring({
    to: handleAnim,
    from: {opacity: 1, color: '#8892b0', height: '100px', width: '100px'},
    config: {duration: 1000},
    reset: true,
  });

  const [props2, set] = useSpring(() => ({ xys: [0, 0, 1], config: { mass: 5, tension: 350, friction: 40 } }))
// ...

  const Icon = animated(ChevronRightIcon);
  return (
    disabled ? <ChevronRightIcon style={{height: '100px', width: '100px', display: "none"}}/> :
    <Icon style={{...props,...props2, transform: props2.xys.interpolate(trans), cursor: "pointer"}} onMouseMove={({ clientX: x, clientY: y }) => set({ xys: calc(x, y) })}
          onMouseLeave={() => set({ xys: [0, 0, 1] })} onClick={onClick}
    />
  )
}
Example #4
Source File: VaccinationHeader.js    From covid19india-react with MIT License 6 votes vote down vote up
function Level({data}) {
  const {t} = useTranslation();

  const spring = useSpring({
    total: getStatistic(data, 'total', 'vaccinated'),
    // delta: getStatistic(data, 'delta', 'vaccinated'),
    config: SPRING_CONFIG_NUMBERS,
  });

  const statisticConfig = STATISTIC_CONFIGS.vaccinated;

  return (
    <div
      className="level-vaccinated fadeInUp"
      style={{animationDelay: `${750 + 4 * 250}ms`}}
    >
      <ShieldCheckIcon />
      <animated.div>
        {spring.total.to((total) => formatNumber(total, 'long'))}
      </animated.div>
      {/* <animated.div>
        {spring.delta.to(
          (delta) =>
            `(+ ${formatNumber(delta, 'long')})`
        )}
      </animated.div> */}
      <div>{t(statisticConfig.displayName)}</div>
    </div>
  );
}
Example #5
Source File: ValuePill.js    From dashboard with MIT License 6 votes vote down vote up
export function ValuePill({ title, value = 0 }) {
  const { v } = useSpring({
    from: {
      v: 0,
    },
    to: {
      v: value,
    },
    delay: 0,
    config: config.slow,
  });

  return (
    <div className="flex items-center justify-between h-6 dark:text-gray-200 dark:bg-gray-800 rounded-lg shadow-xs">
      <span className="mx-2 text-xxs font-medium leading-none xl:text-sm">
        {title}
      </span>
      <div className="flex items-center h-full text-xs font-medium bg-primary-500 rounded-lg xl:text-base">
        <animated.span className="inline-flex items-center justify-center align-bottom px-3 py-1 text-white leading-5 rounded-md shadow-xs">
          {v.interpolate((x) => Math.round(x))}
        </animated.span>
      </div>
    </div>
  );
}
Example #6
Source File: tabs.js    From proof-of-humanity-web with MIT License 6 votes vote down vote up
export function TabList({ sx, ...rest }) {
  const [tabIndex, setTabIndex] = useState(0);
  useEffect(() => {
    const _tabIndex = rest.children.findIndex((tab) => tab.props.selected);
    if (tabIndex !== _tabIndex) setTabIndex(_tabIndex);
  }, [rest.children, tabIndex]);

  const [measureRef, { width: _width, left }] = useMeasure();
  const width = _width / rest.children.length;
  const animatedStyle = useSpring({
    left: tabIndex * width,
  });
  return (
    <Box key={left} ref={measureRef} sx={{ position: "relative" }}>
      <Box
        as={_TabList}
        sx={{
          cursor: "pointer",
          display: "flex",
          listStyle: "none",
          variant: "tabs.tabList",
          ...sx,
        }}
        {...rest}
      />
      <AnimatedBox
        style={animatedStyle}
        sx={{
          backgroundColor: "primary",
          bottom: 0,
          height: 2,
          position: "absolute",
          width,
        }}
      />
    </Box>
  );
}
Example #7
Source File: Card.js    From codeprojects with BSD Zero Clause License 6 votes vote down vote up
function Card({ front, back }) {
  const [flipped, setFlipped] = useState(false)
  const { transform, opacity } = useSpring({
    opacity: flipped ? 1 : 0,
    transform: `perspective(600px), rotateX(${flipped ? 180 : 0})deg`,
    config: { mass: 5, tension: 500, friction: 80 },
  })
  return (
    <Container onClick={() => setFlipped(!flipped)}>
      <Front style={{ opacity: opacity.interpolate(o => 1 - o), transform }}>
        <div dangerouslySetInnerHTML={front}></div>
      </Front>
      <Back
        style={{
          opacity,
          transform: transform.interpolate(t => `${t} rotateX(180deg)`),
        }}
      >
        <div dangerouslySetInnerHTML={back}></div>
      </Back>
    </Container>
  )
}
Example #8
Source File: Modal.js    From umami with MIT License 6 votes vote down vote up
function Modal({ title, children }) {
  const props = useSpring({ opacity: 1, from: { opacity: 0 } });

  return ReactDOM.createPortal(
    <animated.div className={styles.modal} style={props}>
      <div className={styles.content}>
        {title && <div className={styles.header}>{title}</div>}
        <div className={styles.body}>{children}</div>
      </div>
    </animated.div>,
    document.getElementById('__modals'),
  );
}
Example #9
Source File: accordion.js    From proof-of-humanity-web with MIT License 6 votes vote down vote up
function AnimatedAccordionItemPanel({ expanded, ...rest }) {
  const [measureRef, { height }] = useMeasure();
  const animatedStyle = useSpring({
    height: expanded ? height : 0,
    overflow: "hidden",
  });
  return (
    <animated.div style={animatedStyle}>
      <Box ref={measureRef}>
        <Box as={_AccordionItemPanel} variant="accordion.panel" {...rest} />
      </Box>
    </animated.div>
  );
}
Example #10
Source File: FormLayout.js    From umami with MIT License 6 votes vote down vote up
ErrorTag = ({ msg }) => {
  const props = useSpring({ opacity: 1, from: { opacity: 0 } });

  return (
    <animated.div className={styles.error} style={props}>
      <div className={styles.msg}>{msg}</div>
    </animated.div>
  );
}
Example #11
Source File: ScrollGallery.js    From halo-lab with MIT License 6 votes vote down vote up
Gallery = ({ children, step }) => {
  const [scrollY, setScrollY] = useState(0);
  useEffect(() => {
    const handleScroll = () => setScrollY(window.scrollY);
    window.addEventListener('scroll', springDebounce(handleScroll));
    return () =>
      window.removeEventListener('scroll', springDebounce(handleScroll));
  }, [springDebounce]);

  const [{ springscrollY }, springsetScrollY] = useSpring(() => ({
    springscrollY: 0,
  }));
  const STEP = step;
  springsetScrollY({ springscrollY: scrollY });
  const interpHeader = springscrollY.interpolate(
    o => `translateX(-${o / STEP}px)`
  );

  return (
    <animated.div className={styles.items} style={{ transform: interpHeader }}>
      {children}
    </animated.div>
  );
}
Example #12
Source File: DataTable.js    From umami with MIT License 6 votes vote down vote up
AnimatedRow = ({ label, value = 0, percent, animate, format, onClick }) => {
  const props = useSpring({
    width: percent,
    y: value,
    from: { width: 0, y: 0 },
    config: animate ? config.default : { duration: 0 },
  });

  return (
    <div className={styles.row}>
      <div className={styles.label}>{label}</div>
      <div className={styles.value} onClick={onClick}>
        <animated.div className={styles.value}>{props.y?.interpolate(format)}</animated.div>
      </div>
      <div className={styles.percent}>
        <animated.div
          className={styles.bar}
          style={{ width: props.width.interpolate(n => `${n}%`) }}
        />
        <animated.span className={styles.percentValue}>
          {props.width.interpolate(n => `${n.toFixed(0)}%`)}
        </animated.span>
      </div>
    </div>
  );
}
Example #13
Source File: ProgressBar.js    From dshop with MIT License 5 votes vote down vote up
ProgressBar = ({
  onDone,
  duration = 2000,
  className = '',
  barClassName = '',
  delay = 0,
  done
}) => {
  const [config, setConfig] = useState({ duration })
  const props = useSpring({
    config,
    delay,
    from: { width: '0%' },
    to: { width: '100%' }
  })

  useEffect(() => {
    const d = setTimeout(() => {
      if (onDone) onDone()
    }, duration + delay)

    return () => {
      clearTimeout(d)
    }
  }, [])

  useEffect(() => {
    if (done) {
      setConfig({})
    }
  }, [done])

  return (
    <div className={`progress ${className}`}>
      <animated.div
        className={`progress-bar ${barClassName}`}
        style={{ ...props, transition: 'unset' }}
      />
    </div>
  )
}
Example #14
Source File: index.js    From halo-lab with MIT License 5 votes vote down vote up
Home = () => {
  const [props, set] = useSpring(() => ({
    xy: [0, 0],
    config: { mass: 10, tension: 550, friction: 140 },
  }));

  const title = 'Web Design and Development Services | Halo Lab';
  const description = `Halo Lab Team brings the design-driven development of your digital product to reality. We are working with a variety of projects, from the strict insurance website to a dynamic music application.`;
  return (
    <Providers>
      <div
        onMouseMove={({ clientX: x, clientY: y }) => set({ xy: calc(x, y) })}
      >
        <BackgroundStars animation={props} />
        <Layout>
          <Head title={title} description={description}>
            <script type="application/ld+json">
              {`{
              "@context": "schema.org",
              "@type":"Organization",
              "name":"site",
              "url":"https://halo-lab.com/",
              "logo":"https://halo-lab.com/logo.svg",
              "contactPoint":
              [
                {
                  "@type": "ContactPoint",
                  "telephone": "+380632362920",
                  "contactType": "",
                  "areaServed": ""
                }
              ],
              "sameAs":
              ["https://www.facebook.com/halolabteam/", "https://www.instagram.com/halolabteam/", "https://twitter.com/halolabteam"]
            }`}
            </script>
          </Head>
          <HomePage animation={props} />
        </Layout>
      </div>
    </Providers>
  );
}
Example #15
Source File: InfiniteLoader.js    From gitconvex with Apache License 2.0 5 votes vote down vote up
export default function InfiniteLoader({ loadAnimation }) {
  let infiniteLoader = useSpring({
    from: { marginLeft: "0px", opacity: 0 },
    to: async (next) => {
      let i = 100;
      while (--i) {
        await next({
          marginLeft: "10px",
          opacity: 0.5,
        });

        await next({
          marginLeft: "20px",
          opacity: 0.8,
        });

        await next({
          marginLeft: "30px",
          opacity: 1,
        });

        await next({
          marginLeft: "0px",
          opacity: 1,
        });
      }
    },
    config: {
      tension: "500",
    },
  });
  return (
    <div className="flex gap-4 mx-auto text-center">
      {loadAnimation ? (
        <>
          <animated.div
            className="bg-pink-200 w-8 h-8 rounded-full p-2"
            style={infiniteLoader}
          ></animated.div>
          <animated.div
            className="bg-green-200 w-8 h-8 rounded-full p-2"
            style={infiniteLoader}
          ></animated.div>
          <animated.div
            className="bg-blue-200 w-8 h-8 rounded-full p-2"
            style={infiniteLoader}
          ></animated.div>
        </>
      ) : null}
    </div>
  );
}
Example #16
Source File: Checkbox.js    From use-sound with MIT License 5 votes vote down vote up
Checkbox = ({
  size = 18,
  name,
  checked,
  label,
  onChange,
  onMouseDown,
  onMouseUp,
}) => {
  const [active, setActive] = React.useState(false);

  const springConfig = {
    tension: 400,
    friction: 22,
    clamp: !checked,
  };

  const filledScale = checked ? (active ? 1.4 : 1) : 0;
  const filledSpring = useSpring({
    transform: `scale(${filledScale})`,
    config: springConfig,
  });

  const outlineScale = active ? 0.8 : 1;
  const outlineSpring = useSpring({
    transform: `scale(${outlineScale})`,
    config: springConfig,
  });

  return (
    <Wrapper>
      <RealCheckbox
        onMouseDown={() => {
          setActive(true);
          onMouseDown();
        }}
        onMouseUp={() => {
          setActive(false);
          onMouseUp();
        }}
        onChange={onChange}
        onClick={onChange}
      />
      <VisibleContents>
        <VisibleBox style={{ width: size, height: size, ...outlineSpring }}>
          <Filled style={filledSpring} />
        </VisibleBox>

        <Text>{label}</Text>
      </VisibleContents>
    </Wrapper>
  );
}
Example #17
Source File: Modal.js    From dshop with MIT License 5 votes vote down vote up
Modal = ({ children, onClose, className, shouldClose }) => {
  const [show, setShow] = useState(false)
  const [shouldCloseInt, setShouldCloseInt] = useState(false)

  const bgProps = useSpring({
    config: { duration: 150 },
    opacity: show ? 0.7 : 0
  })

  const modalProps = useSpring({
    config: { mass: 0.75, tension: 300, friction: 20 },
    opacity: show ? 1 : 0,
    transform: show ? 'translate3d(0px,0,0)' : 'translate3d(0,-100px,0)'
  })

  const el = useRef(document.createElement('div'))

  function doClose() {
    setShow(false)
    return setTimeout(onClose, 150)
  }

  useEffect(() => {
    document.body.appendChild(el.current)
    document.getElementById('app').style.filter = 'blur(2px)'
    function onKeyDown(e) {
      // Esc
      if (e.keyCode === 27) {
        doClose()
      }
    }
    document.addEventListener('keydown', onKeyDown)
    setShow(true)
    return () => {
      document.getElementById('app').style.filter = ''
      document.removeEventListener('keydown', onKeyDown)
      el.current.parentElement.removeChild(el.current)
    }
  }, [el])

  useEffect(() => {
    let timeout
    if (shouldClose || shouldCloseInt) {
      timeout = doClose()
    }
    return () => clearTimeout(timeout)
  }, [el, shouldClose, shouldCloseInt])

  const cmp = (
    <>
      <animated.div className="modal-backdrop" style={bgProps} />
      <animated.div
        className="modal d-block"
        tabIndex="-1"
        style={modalProps}
        onMouseDown={() => setShouldCloseInt(true)}
      >
        <div
          onMouseDown={(e) => e.stopPropagation()}
          className={`modal-dialog modal-dialog-centered ${className || ''}`}
          role="document"
        >
          <div className="modal-content">{children}</div>
        </div>
      </animated.div>
    </>
  )

  return createPortal(cmp, el.current)
}
Example #18
Source File: StateHeader.js    From covid19india-react with MIT License 5 votes vote down vote up
function StateHeader({data, stateCode}) {
  const {t} = useTranslation();

  const trail = useMemo(() => {
    const styles = [];

    [0, 0, 0].map((element, index) => {
      styles.push({
        animationDelay: `${index * 250}ms`,
      });
      return null;
    });

    return styles;
  }, []);

  const spring = useSpring({
    total: getStatistic(data, 'total', 'tested'),
    config: SPRING_CONFIG_NUMBERS,
  });

  return (
    <div className="StateHeader">
      <div className="header-left">
        <StateDropdown {...{stateCode}} hyperlink={false} trail={trail[0]} />
        {data?.meta?.['last_updated'] && (
          <h5 className="fadeInUp" style={trail[1]}>
            {`${t('Last Updated on')} ${formatDate(
              data.meta.last_updated,
              'dd MMM, p'
            )} ${t('IST')}`}
          </h5>
        )}
      </div>

      <div className="header-right fadeInUp" style={trail[2]}>
        <h5>{t('Tested')}</h5>
        <animated.h2>
          {spring.total.to((total) => formatNumber(total, 'long'))}
        </animated.h2>
        {data?.meta?.tested?.date && (
          <h5 className="timestamp">
            {`${t('As of')} ${formatDate(data.meta.tested.date, 'dd MMMM')}`}
          </h5>
        )}
        {data?.meta?.tested?.source && (
          <h5>
            {`${t('per')} `}
            <a href={data.meta.tested.source} target="_noblank">
              {t('source')}
            </a>
          </h5>
        )}
      </div>
    </div>
  );
}
Example #19
Source File: WeeklyTracker.jsx    From Corona-tracker with MIT License 5 votes vote down vote up
WeeklyTracker = props => {
  const { children, setToggleValue, setDetailData } = props;
  const classes = useStyles();
  let swiped = false;

  const [{ x }, set] = useSpring(() => ({
    x: 0,
    onRest: () => {
      if (swiped) {
        // After swipe animation finishes, show survey details
        setDetailData([children.props.dayData]);
        setToggleValue('showMeMore');
      }
    },
  }));

  const bind = useDrag(
    ({ down, movement: [mx], swipe: [swipeX] }) => {
      if (swipeX === 1) {
        // User swiped
        set({ x: window.innerWidth });
        swiped = true;
        return;
      }

      // Don't allow user to drag off the left side of the screen
      if (mx < 0) {
        return;
      }

      set({ x: down ? mx : 0, immediate: down });
    },
    { axis: 'x' }
  );

  return (
    <div className={classes.noSelect}>
      <animated.div className={classes.item}>
        <animated.div {...bind()} className={classes.fg} style={{ x }}>
          {children}
        </animated.div>
      </animated.div>
    </div>
  );
}
Example #20
Source File: Level.js    From covid19india-react with MIT License 5 votes vote down vote up
function PureLevelItem({statistic, total, delta}) {
  const {t} = useTranslation();
  const spring = useSpring({
    total: total,
    delta: delta,
    config: SPRING_CONFIG_NUMBERS,
  });

  const statisticConfig = STATISTIC_CONFIGS[statistic];

  return (
    <>
      <h5>{t(capitalize(statisticConfig.displayName))}</h5>
      <animated.h4>
        {statistic !== 'active' ? (
          delta > 0 ? (
            /* Add space after + because react-spring regex bug */
            spring.delta.to(
              (delta) =>
                `+ ${formatNumber(
                  delta,
                  statisticConfig.format !== 'short'
                    ? statisticConfig.format
                    : 'long',
                  statistic
                )}`
            )
          ) : (
            <HeartFillIcon size={9} verticalAlign={2} />
          )
        ) : (
          '\u00A0'
        )}
      </animated.h4>
      <animated.h1>
        {spring.total.to((total) =>
          formatNumber(
            total,
            statisticConfig.format !== 'short'
              ? statisticConfig.format
              : 'long',
            statistic
          )
        )}
      </animated.h1>
    </>
  );
}
Example #21
Source File: boardBox.js    From personal-site with MIT License 5 votes vote down vote up
BoardBox = props => {
  const [flipped, set] = useState(false)
  const { transform, opacity } = useSpring({
    opacity: flipped ? 1 : 0,
    transform: `perspective(600px) rotateX(${flipped ? 180 : 0}deg)`,
    config: { mass: 5, tension: 500, friction: 80 },
  })
  return (
    <div className="board__wrapper">
      <div
        className="board__box"
        onMouseEnter={() => set(state => !state)}
        onMouseLeave={() => set(state => !state)}
        role="button"
        tabIndex="0"
      >
        <a.video
          className="back"
          loop={true}
          autoPlay={true}
          muted={true}
          playsInline={true}
          style={{
            opacity: opacity.interpolate(o => 1 - o),
            transform,
          }}
        >
          <source src={props.bgwebm} type="video/webm" />
          <source src={props.bgmp4} type="video/mp4" />
        </a.video>
        <a.div
          className="front"
          style={{
            opacity,
            transform: transform.interpolate(t => `${t} rotateX(180deg)`),
          }}
        >
          <p>{props.title}</p>
          <a
            className="btn btn--secondary"
            href={props.url}
            target="_blank"
            rel="noopener noreferrer"
          >
            View
          </a>
        </a.div>
      </div>
    </div>
  )
}
Example #22
Source File: useSlider.js    From react-instagram-zoom-slider with MIT License 5 votes vote down vote up
export default function useSlider({ initialSlide, slides }) {
  const [{ x, scale }, set] = useSpring(() => ({
    x: typeof window !== 'undefined' ? -window.innerWidth * initialSlide : 0,
    scale: 1,
    config: { tension: 270, clamp: true },
  }))

  const index = useRef(initialSlide)

  // Slide numbers (for display purposes only)
  const [currentSlide, updateSlide] = useState(initialSlide)
  const [zooming, setZooming] = useState(false)

  const onScale = useCallback(
    slideProps => {
      set({ scale: slideProps.scale })
      if (slideProps.scale === 1) {
        setZooming(false)
      } else {
        setZooming(true)
      }
    },
    [set]
  )

  const bind = useDrag(
    ({
      down,
      movement: [xMovement],
      direction: [xDir],
      distance,
      swipe: [swipeX],
      cancel,
      touches,
    }) => {
      // We don't want to interrupt the pinch-to-zoom gesture
      if (touches > 1) {
        cancel()
      }

      // We have swiped past halfway
      if (!down && distance > window.innerWidth / 2) {
        // Move to the next slide
        const slideDir = xDir > 0 ? -1 : 1
        index.current = clamp(index.current + slideDir, 0, slides.length - 1)

        set({
          x: -index.current * window.innerWidth + (down ? xMovement : 0),
          immediate: false,
        })
      } else if (swipeX !== 0) {
        // We have detected a swipe - update the new index
        index.current = clamp(index.current - swipeX, 0, slides.length - 1)
      }

      // Animate the transition
      set({
        x: -index.current * window.innerWidth + (down ? xMovement : 0),
        immediate: down,
      })

      // Update the slide number for display purposes
      updateSlide(index.current)
    },
    {
      axis: 'x',
      bounds: {
        left: currentSlide === slides.length - 1 ? 0 : -Infinity,
        right: index.current === 0 ? 0 : Infinity,
        top: 0,
        bottom: 0,
      },
      rubberband: true,
      enabled: slides.length > 1,
    }
  )

  return [zooming, scale, currentSlide, bind, x, onScale]
}
Example #23
Source File: InfoCard.js    From dashboard with MIT License 5 votes vote down vote up
export function InfoCard({ title, value, delta = null, small = false }) {
  const { _value, _delta } = useSpring({
    from: { _value: 0, _delta: 0 },
    to: {
      _value: value,
      _delta: delta || 0,
    },
    delay: 0,
    config: config.slow,
  });
  return (
    <Card>
      <CardBody className="flex flex-col">
        <div>
          <p
            className={clsx(
              small ? "mb-1 text-xs" : "mb-2 text-sm",
              "dark:text-gray-400 text-gray-600 font-medium"
            )}
          >
            {title}
          </p>
          <div className="flex">
            <animated.p
              className={clsx(
                small ? "text-base" : "text-lg",
                "dark:text-gray-200 text-gray-700 font-semibold"
              )}
            >
              {_value.interpolate((x) => Math.round(x))}
            </animated.p>
            {delta !== null && (
              <animated.span
                className={clsx(
                  small ? "text-xs" : "text-sm",
                  "ml-2 dark:text-gray-400 text-gray-600"
                )}
              >
                {_delta.interpolate((y) => {
                  const x = Math.round(y);
                  return x === 0 ? "-" : x > 0 ? `+${x}` : x;
                })}
              </animated.span>
            )}
          </div>
        </div>
      </CardBody>
    </Card>
  );
}
Example #24
Source File: accordion.js    From proof-of-humanity-web with MIT License 5 votes vote down vote up
function AnimatedAccordionItemHeading({ expanded, children, ...rest }) {
  const animatedRectangleAStyle = useSpring({
    opacity: expanded ? 0 : 1,
    scaleX: expanded ? 0 : 1,
    transformOrigin: "center",
  });
  const animatedRectangleBStyle = useSpring({
    rotate: expanded ? 0 : -90,
    transformOrigin: "center",
  });
  return (
    <Box as={_AccordionItemHeading} {...rest}>
      <Box
        as={_AccordionItemButton}
        variant="accordion.heading"
        sx={{
          backgroundImage({ colors: { accent, accentComplement } }) {
            return `linear-gradient(90deg, ${accent} 0%, ${accentComplement} 100%, ${accentComplement} 100%)`;
          },
          position: "relative",
        }}
      >
        {children}
        <SVG
          sx={{
            position: "absolute",
            right: 2,
            top: "50%",
            transform: "translateY(-50%)",
          }}
          height={24}
          viewBox="0 0 24 24"
          width={24}
        >
          <Rectangle
            style={{
              ...animatedRectangleAStyle,
              transform: animatedRectangleAStyle.scaleX.interpolate(
                (scaleX) => `scaleX(${scaleX})`
              ),
            }}
          />
          <Rectangle
            style={{
              ...animatedRectangleBStyle,
              transform: animatedRectangleBStyle.rotate.interpolate(
                (rotate) => `rotate(${rotate}deg)`
              ),
            }}
          />
        </SVG>
      </Box>
    </Box>
  );
}
Example #25
Source File: boardBox.js    From bartzalewski.com-v2 with MIT License 5 votes vote down vote up
BoardBox = ({ bgwebm, title, url }) => {
  const [flipped, set] = useState(false)
  const { transform, opacity } = useSpring({
    opacity: flipped ? 1 : 0,
    transform: `perspective(600px) rotateX(${flipped ? 180 : 0}deg)`,
    config: { mass: 5, tension: 500, friction: 80 },
  })
  return (
    <Container className="board__wrapper">
      <Wrapper
        className="board__box"
        onMouseEnter={() => set((state) => !state)}
        onMouseLeave={() => set((state) => !state)}
        role="button"
        tabIndex="0"
      >
        <a.video
          className="back"
          loop={true}
          autoPlay={true}
          muted={true}
          playsInline={true}
          style={{
            opacity: opacity.interpolate((o) => 1 - o),
            transform,
          }}
        >
          <Source src={bgwebm} type="video/webm" />
        </a.video>
        <a.div
          className="front"
          style={{
            opacity,
            transform: transform.interpolate((t) => `${t} rotateX(180deg)`),
          }}
        >
          <Title>{title}</Title>
          <Button
            className="btn btn--secondary"
            href={url}
            target="_blank"
            rel="noopener noreferrer"
          >
            View
          </Button>
        </a.div>
      </Wrapper>
    </Container>
  )
}
Example #26
Source File: MenuExpanded.jsx    From hiring-channel-frontend with MIT License 5 votes vote down vote up
MenuExpanded = (props) => {
  const { firstName, lastName, corporateName, image, id } = useSelector(
    (state) => state.authState
  );
  const history = useHistory();
  const dispatch = useDispatch();
  /** start of animation section */
  const [springProps, set] = useSpring(() => ({
    transform: "translate(100%)",
  }));
  useEffect(() => {
    set({
      transform: props.displayed ? "translate(0%)" : "translate(100%)",
    });
  }, [props.displayed, set]);
  /** end of animation section */
  return (
    <>
      <animated.div className="menu-container-show" style={springProps}>
        <div className="user-group-menu">
          <div className="user-icon-menu">
            {/* <p>T</p> */}
            <img src={image ? image : user_icon} alt="" />
          </div>
          <h5
            onClick={() => {
              history.push(`/user/${id}`);
            }}
          >
            {firstName ? `${firstName} ${lastName}` : corporateName}
          </h5>
        </div>
        <div className="message-menu">
          <div className="message-icon">
            <img src={chat_icon} alt="" />
          </div>
          <h5>Message</h5>
        </div>
        <div className="notification-menu">
          <div className="notification-icon">
            <img src={bell_icon} alt="" />
          </div>
          <h5>Notification</h5>
        </div>
        <Button
          className="logout-btn"
          variant="danger"
          onClick={() => {
            dispatch(logout());
          }}
        >
          Log Out
        </Button>
      </animated.div>
    </>
  );
}
Example #27
Source File: Toaster.js    From dshop with MIT License 5 votes vote down vote up
Toast = ({ id, num, message, onHide, type = 'success' }) => {
  const [show, setShow] = useState(false)

  const modalProps = useSpring({
    config: { mass: 0.75, tension: 300, friction: 20 },
    opacity: show ? 1 : 0,
    top: show ? num * 50 + 20 : -50,
    zIndex: num + 1100
  })

  useEffect(() => {
    setShow(true)
    const showTimeout = setTimeout(() => setShow(false), 3000)
    const hideTimeout = setTimeout(() => onHide(id), 3200)
    return () => {
      clearTimeout(showTimeout)
      clearTimeout(hideTimeout)
      onHide(id)
    }
  }, [])

  const el = useRef(document.createElement('div'))

  useEffect(() => {
    document.body.appendChild(el.current)
    el.current.classList.add('d-toaster')

    return () => {
      if (el.current.parentElement) {
        el.current.parentElement.removeChild(el.current)
      }
    }
  }, [el])

  const cmp = (
    <animated.div className={`d-toast ${type}`} style={modalProps}>
      {type === 'error' ? (
        <svg width="14" height="14" viewBox="0 0 14 14">
          <path
            fill="#D50000"
            fillRule="evenodd"
            d="M9.123 4l.858.858-2.121 2.14L10 9.113l-.859.858L7.01 7.857 4.899 10l-.852-.851 2.105-2.14L4 4.925l.85-.85L7 6.15 9.122 4zM7 0C3.134 0 0 3.134 0 7s3.134 7 7 7 7-3.134 7-7-3.134-7-7-7z"
          />
        </svg>
      ) : (
        <svg width="14" height="14" viewBox="0 0 14 14">
          <path
            fill="#0077F5"
            fillRule="evenodd"
            d="M6.27 10.087L3.647 7.541l1.083-1.084L6.271 7.92l3.292-3.374 1.083 1.084-4.375 4.458zM7 0C3.134 0 0 3.134 0 7s3.134 7 7 7 7-3.134 7-7-3.134-7-7-7z"
          />
        </svg>
      )}
      {message}
    </animated.div>
  )

  return createPortal(cmp, el.current)
}
Example #28
Source File: popup.js    From proof-of-humanity-web with MIT License 5 votes vote down vote up
export default function Popup({
  contentStyle,
  overlayStyle,
  onOpen,
  onClose,
  sx,
  children,
  ...rest
}) {
  const [animatedStyle, setAnimatedStyle] = useSpring(() => ({
    opacity: 0,
    scale: 0,
    config: { tension: 300 },
  }));
  return (
    <ReactJSPopup
      contentStyle={{
        background: "none",
        border: "none",
        boxShadow: "none",
        ...contentStyle,
      }}
      overlayStyle={{ overflow: "scroll", ...overlayStyle }}
      onOpen={() => {
        setAnimatedStyle({ opacity: 1, scale: 1 });
        if (onOpen) onOpen();
      }}
      onClose={() => {
        setAnimatedStyle({ opacity: 0, scale: 0 });
        if (onClose) onClose();
      }}
      {...rest}
      arrow={false}
    >
      {(props) => (
        <AnimatedBox
          style={{
            opacity: animatedStyle.opacity,
            transform: animatedStyle.scale.interpolate(
              (scale) => `scale(${scale})`
            ),
          }}
          sx={{
            backgroundColor: "background",
            borderRadius: 3,
            boxShadow: "rgba(0, 0, 0, 0.2) 0 1px 3px",
            padding: 1,
            ...sx,
          }}
        >
          {typeof children === "function" ? children(props) : children}
        </AnimatedBox>
      )}
    </ReactJSPopup>
  );
}
Example #29
Source File: Landing.jsx    From SWEethearts-2.0 with MIT License 5 votes vote down vote up
Landing = ({ history }) => {
  //react spring stuff
  const calc = (x, y) => [
    -(y - window.innerHeight / 2) / 20,
    (x - window.innerWidth / 2) / 20,
    1.1,
  ];
  const trans = (x, y, s) =>
    `perspective(600px) rotateX(${x}deg) rotateY(${y}deg) scale(${s})`;
  const [props, set] = useSpring(() => ({
    xys: [0, 0, 1],
    config: { mass: 5, tension: 350, friction: 40 },
  }));
  //

  return (
    //react spring stuff
    <animated.div
      onMouseMove={({ clientX: x, clientY: y }) => set({ xys: calc(x, y) })}
      onMouseLeave={() => set({ xys: [0, 0, 1] })}
      style={{ transform: props.xys.interpolate(trans) }}
    >
      <Container fluid className="container" style={{ marginTop: '20vh' }}>
        <div className="mt-5">
          <h1 className="d-flex justify-content-center">
            {' '}
            Welcome to SWEetHearts!{' '}
          </h1>
          <br />
          <h2 className="mb-5 d-flex justify-content-center">
            {' '}
            A place where developers make their dreams come true{' '}
          </h2>
          <br />
        </div>
        <div className="mt-5 d-flex justify-content-center">
          <Button
            className="w-25"
            onClick={() => redirectToPath(history, '/explore')}
            size="lg"
            variant="outline-primary"
            block
          >
            Start Exploring
          </Button>
        </div>
      </Container>
    </animated.div>
  );
}