react-scroll#scroller JavaScript Examples

The following examples show how to use react-scroll#scroller. 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: SnapshotListView.jsx    From amazon-connect-snippets with MIT No Attribution 6 votes vote down vote up
handleClickSnapshot(e, snapshot) {
        e.preventDefault();

        const { selectLog, selectSnapshots } = this.props;
        selectLog(snapshot._targetEventKeys);
        selectSnapshots([snapshot._key]);

        const anchor = `L${snapshot._targetEventKeys[0]}`;
        scroller.scrollTo(anchor, {
            duration: 800,
            delay: 0,
            smooth: 'easeInOutQuart',
        });
    }
Example #2
Source File: index.jsx    From dubbogo.github.io with Apache License 2.0 6 votes vote down vote up
componentDidMount() {
    // 通过请求获取生成好的json数据,静态页和json文件在同一个目录下
    fetch(window.location.pathname.replace(/\.html$/i, '.json'))
    .then(res => res.json())
    .then((md) => {
      this.setState({
        __html: md && md.__html ? md.__html : '',
      });
    });
    this.markdownContainer.addEventListener('click', (e) => {
      const isAnchor = e.target.nodeName.toLowerCase() === 'a' && e.target.getAttribute('href') && anchorReg.test(e.target.getAttribute('href'));
      if (isAnchor) {
        e.preventDefault();
        const id = e.target.getAttribute('href').slice(1);
        scroller.scrollTo(id, {
          duration: 1000,
          smooth: 'easeInOutQuint',
        });
      }
    });
  }
Example #3
Source File: index.jsx    From dubbogo.github.io with Apache License 2.0 6 votes vote down vote up
componentDidMount() {
    // 通过请求获取生成好的json数据,静态页和json文件在同一个目录下
    fetch(window.location.pathname.replace(/\.html$/i, '.json'))
    .then(res => res.json())
    .then((md) => {
      this.setState({
        __html: md && md.__html ? md.__html : '',
      });
    });
    this.markdownContainer.addEventListener('click', (e) => {
      const isAnchor = e.target.nodeName.toLowerCase() === 'a' && e.target.getAttribute('href') && anchorReg.test(e.target.getAttribute('href'));
      if (isAnchor) {
        e.preventDefault();
        const id = e.target.getAttribute('href').slice(1);
        scroller.scrollTo(id, {
          duration: 1000,
          smooth: 'easeInOutQuint',
        });
      }
    });
  }
Example #4
Source File: useSmoothScrollTo.jsx    From gatsby-startbootstrap-agency with MIT License 6 votes vote down vote up
useSmoothScrollTo = (anchorOrPosition, options = {}) => {
  const opts = React.useMemo(
    () => ({
      ...DefOptions,
      ...options,
    }),
    [options],
  );

  const handleScrollTo = React.useCallback(() => {
    switch (typeof anchorOrPosition) {
      case "number":
      case "bigint":
        animateScroll.scrollTo(anchorOrPosition, opts);
        break;
      case "string":
        scroller.scrollTo(anchorOrPosition, opts);
        break;
      default:
        break;
    }
  }, [anchorOrPosition, opts]);

  return handleScrollTo;
}
Example #5
Source File: about.js    From plataforma-sabia with MIT License 5 votes vote down vote up
Welcome = () => {
	const router = useRouter();
	const { t } = useTranslation(['common', 'pages']);
	const { user } = useAuth();

	const handleIntroButtonClick = (e) => {
		e.preventDefault();
		if (!user?.email) {
			router.push(internalPages.signIn);
		} else {
			toast.info('Iremos te redirecionar para a página principal da plataforma');
			router.push('/');
		}
	};

	useEffect(() => {
		if (isRunningOnBrowser()) {
			const routerHref = router.asPath.split('#')[1];

			if (routerHref) {
				scroller.scrollTo(routerHref, {
					duration: 1,
					offset: -headerHeightInPx,
					smooth: true,
				});
			}
		}
	}, [router.asPath]);

	return (
		<>
			<Head
				title={t('pages:about.title')}
				description={t('pages:about.description')}
				keywords={t('pages:about.keywords')}
			/>
			<Element id="intro" name="intro" className="element">
				<Intro
					title="A vitrine tecnológica mais completa do semiárido"
					subtitle="Um ambiente digital interativo voltado a difundir as tecnologias demandadas e
					ofertadas na resolução de problemas do semiárido brasileiro."
					image={{
						src: '/search-engines-rafiki.svg',
						alt:
							'Mulher de costas segurando uma lupa gigante e olhando para uma barra de busca gigante',
					}}
					button={{
						label: 'Acesse agora',
						handleButtonClick: handleIntroButtonClick,
					}}
				/>
				<About />
			</Element>
			<Element id="features" name="features" className="element">
				<Features />
			</Element>
			{false && (
				<Element id="resources" name="resources" className="element">
					<Resources />
				</Element>
			)}
			<Element id="contact" name="contact" className="element">
				<Contact />
			</Element>
		</>
	);
}
Example #6
Source File: Navigation.js    From ResumeOnTheWeb-Gatsby with MIT License 4 votes vote down vote up
Navigation = () => {
  const [isMobile, setIsMobile] = useState(false);
  const { dark, toggleDark } = useContext(ThemeContext);
  const data = useStaticQuery(graphql`
    {
      icon: file(relativePath: { eq: "icon.png" }) {
        childImageSharp {
          gatsbyImageData(width: 32, height: 32, layout: FIXED)
        }
      }
    }
  `);

  useEffect(() => {
    if (typeof window !== `undefined`) {
      const { isMobile } = require("../utils");
      setIsMobile(isMobile);
    }
  }, []);

  const scrollToTop = () =>
    scroll.scrollToTop({
      delay: 50,
      duration: 600,
      smooth: "easeInOutCubic",
    });

  const scrollTo = id =>
    scroller.scrollTo(id, {
      delay: 50,
      offset: -50,
      duration: 600,
      smooth: "easeInOutCubic",
    });

  const SectionLink = x => {
    const Icon = x.icon;

    return (
      <Tooltip key={x.id} title={x.title} placement="right" arrow>
        <div onClick={() => scrollTo(x.id)}>
          <Icon />
        </div>
      </Tooltip>
    );
  };

  return (
    <div
      className={`${styles.container} animated ${
        isMobile ? "fadeInDown" : "fadeInLeft"
      }`}
    >
      <Tooltip title="Go to Top" placement="right" arrow>
        <div className="flex-center cursor-pointer" onClick={scrollToTop}>
          <GatsbyImage
            className="grayscale"
            alt="Amruth Pillai - Iconmark"
            image={data.icon.childImageSharp.gatsbyImageData}
          />
        </div>
      </Tooltip>

      <div className="hidden md:flex flex-col justify-center items-center">
        <div className={styles.menu}>
          <MdMenu />
        </div>
        <div className={styles.sectionLinks}>{sections.map(SectionLink)}</div>
      </div>

      <Tooltip title="Toggle Dark Mode" placement="right" arrow>
        <div
          className="flex-center cursor-pointer hover:text-primary-500"
          onClick={toggleDark}
        >
          {dark ? <IoIosMoon /> : <IoIosSunny />}
        </div>
      </Tooltip>
    </div>
  );
}
Example #7
Source File: index.js    From circles-website with GNU Affero General Public License v3.0 4 votes vote down vote up
function FAQ({ t }) {
  const [inputValue, setInputValue] = useState('');
  const { pathname, query, push } = useRouter();
  const inputRef = useRef();

  const selectedIndex = query.open && Number(query.open);
  const items = t('items', { returnObjects: true });

  useEffect(() => {
    if (selectedIndex) {
      const openItem = items && items[selectedIndex];
      scroller.scrollTo(openItem.question, {
        duration: 300,
        smooth: true,
        offset: -90,
      });
    }
  }, [selectedIndex]);

  useEffect(() => {
    if (!selectedIndex) {
      scroller.scrollTo('page-wrapper', {
        duration: 200,
        smooth: true,
      });
      inputRef.current.focus();
    }
  }, []);

  const getPathnameWithLang = () => {
    let pathnameWithLang = pathname;
    if (i18n.language !== 'en') {
      pathnameWithLang = '/' + i18n.language + pathname;
    }
    return pathnameWithLang;
  };

  const setSelectedIndex = (itemIndex) => {
    const pathnameWithLang = getPathnameWithLang();
    push(
      { pathname: pathnameWithLang, query: { open: itemIndex } },
      undefined,
      {
        shallow: true,
        scroll: false,
      }
    );
    setInputValue('');
  };

  let suggestions = [];
  if (inputValue.length > 3) {
    items.forEach((item, index) => {
      if (item.question.toLowerCase().includes(inputValue.toLowerCase())) {
        suggestions.push({
          label: (
            <ScrollLink
              onClick={() => setSelectedIndex(index)}
              to={item.question}
              smooth
              duration={300}
              offset={-80}
            >
              <Box pad="small">{item.question}</Box>
            </ScrollLink>
          ),
          value: item.question,
          topic: item.topic,
          index,
        });
      }
    });
  }

  const onSelect = (event) => {
    const suggestion = event.suggestion;
    setSelectedIndex(suggestion.index);
    setInputValue('');
    scroller.scrollTo(suggestion.question, {
      duration: 300,
      offset: -80,
      smooth: true,
    });
  };

  const handlePanelSelect = (index) => {
    if (index === selectedIndex) {
      setSelectedIndex(null);
      return;
    }
    setSelectedIndex(index);
  };

  const onFilterFocus = () => {
    const pathnameWithLang = getPathnameWithLang();
    push({ pathname: pathnameWithLang, query: {} }, undefined, {
      shallow: true,
      scroll: false,
    });
  };

  const isClient = typeof window !== 'undefined';

  return (
    <div className="page">
      <Head>
        <title>Circles UBI | Frequently Asked Questions</title>
        <link
          rel="stylesheet"
          type="text/css"
          charSet="UTF-8"
          href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.css"
        />
        <link
          rel="stylesheet"
          type="text/css"
          href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick-theme.min.css"
        />
        <meta
          name="description"
          content="Circles | A Basic Income in the Blockchain"
        />
        <meta
          name="keywords"
          content="circles, circle, gift economy, cryptocurrency, universal basic income, blockchain,
          ubi, money, berlin, andrew yang, bernie sanders, doughnut economics, degrowth, local community currency, p2p, commons, democratic money,
          faircoin, trustlines, gnosis"
        />
      </Head>

      <Layout>
        {(large) => (
          <Box
            width="large"
            alignSelf="center"
            className="page-wrapper"
            elevation="medium"
          >
            <Element name="page-wrapper">
              <Box width="100%" pad={{ top: 'large' }}>
                <Box alignSelf="center">
                  <Image
                    src="/images/logo.svg"
                    margin={{ bottom: 'large' }}
                    style={{ width: 90, height: 90 }}
                  />
                </Box>
                <Box
                  margin={{ left: 'medium', right: 'medium' }}
                  width="medium"
                  alignSelf="center"
                >
                  <Text
                    weight="bold"
                    size="large"
                    textAlign="center"
                    margin={{ bottom: 'medium' }}
                  >
                    {t('title')}
                  </Text>
                  <Box pad={{ horizontal: 'medium' }}>
                    <Grommet theme={textFieldTheme}>
                      <FormField>
                        <TextInput
                          ref={inputRef}
                          value={inputValue}
                          suggestions={suggestions}
                          placeholder={t('placeholder')}
                          type="search"
                          dropProps={{ pad: { horizontal: 'medium' } }}
                          onChange={(event) => {
                            setInputValue(event.target.value);
                          }}
                          onFocus={onFilterFocus}
                          onSelect={onSelect}
                        />
                      </FormField>
                    </Grommet>
                  </Box>
                </Box>
              </Box>
            </Element>
            <Row>
              <Box width="100%">
                <Box pad={{ top: 'large', horizontal: 'large' }}>
                  <Text
                    margin={{ top: 'medium', bottom: 'medium' }}
                    size="large"
                  >
                    Video Library
                  </Text>
                  <VideoSlider large={large} />
                </Box>

                <Box
                  margin={{ left: 'medium', right: 'medium' }}
                  width="large"
                  pad={{ horizontal: 'large', bottom: 'large' }}
                  alignSelf="center"
                >
                  {isClient && (
                    <Accordion activeIndex={selectedIndex} animate={false}>
                      {items.map((item, index) => (
                        <Box key={item.question}>
                          {(index === 0 ||
                            item.topic !== items[index - 1].topic) && (
                            <Text
                              margin={{ top: 'xlarge', bottom: 'medium' }}
                              size="large"
                            >
                              {item.topic}
                            </Text>
                          )}
                          <AccordionPanel
                            id={item.question}
                            header={
                              <Box
                                direction="row"
                                pad="medium"
                                onClick={() => handlePanelSelect(index)}
                              >
                                <Element
                                  name={item.question}
                                  style={{ flexBasis: '100%', flexGrow: 3 }}
                                >
                                  <Text weight="bold">{item.question}</Text>
                                </Element>
                                {index === selectedIndex ? <Up /> : <Down />}
                              </Box>
                            }
                          >
                            <Box
                              pad={{
                                horizontal: 'medium',
                                bottom: 'medium',
                              }}
                              animation="fadeIn"
                            >
                              {item.answer.map((paragraph) => (
                                <Paragraph
                                  key={paragraph && paragraph.substring(0, 20)}
                                  className="faq-answer-anchor"
                                  size="small"
                                >
                                  {renderHTML(paragraph)}
                                </Paragraph>
                              ))}
                            </Box>
                          </AccordionPanel>
                        </Box>
                      ))}
                    </Accordion>
                  )}
                </Box>
              </Box>
            </Row>
          </Box>
        )}
      </Layout>
    </div>
  );
}
Example #8
Source File: index.js    From circles-website with GNU Affero General Public License v3.0 4 votes vote down vote up
// import { withTranslation } from '../../i18n';

function Hubs({ t }) {
  const [inputValue, setInputValue] = useState('');
  const [selectedIndex, setSelectedIndex] = useState(null);

  useEffect(() => {
    scroller.scrollTo('page-wrapper', {
      duration: 200,
      smooth: true,
    });
    inputRef.current.focus();
  }, []);

  const inputRef = useRef();

  // let suggestions = [];
  // if (inputValue.length > 3) {
  //   hubs.forEach((item, index) => {
  //     if (item.question.toLowerCase().includes(inputValue.toLowerCase())) {
  //       suggestions.push({
  //         label: (
  //           <ScrollLink
  //             onClick={() => handleSelect(index)}
  //             to={item.question}
  //             smooth
  //             duration={300}
  //             offset={-50}
  //           >
  //             <Box pad="small">{item.question}</Box>
  //           </ScrollLink>
  //         ),
  //         value: item.question,
  //         topic: item.topic,
  //         index,
  //       });
  //     }
  //   });
  // }

  const handleSelect = (index) => {
    setSelectedIndex(index);
    setInputValue('');
  };

  const onSelect = (event) => {
    const suggestion = event.suggestion;
    handleSelect(suggestion.index);
    scroller.scrollTo(suggestion.value, {
      duration: 300,
      offset: -50,
      smooth: true,
    });
  };

  const isClient = typeof window !== 'undefined';

  return (
    <div className="page">
      <Head>
        <title>Circles UBI | Community Hubs</title>
        <link
          rel="stylesheet"
          type="text/css"
          charSet="UTF-8"
          href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.css"
        />
        <link
          rel="stylesheet"
          type="text/css"
          href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick-theme.min.css"
        />
        <meta
          name="description"
          content="Circles | A Basic Income in the Blockchain"
        />
        <meta
          name="keywords"
          content="circles, circle, gift economy, cryptocurrency, universal basic income, blockchain,
          ubi, money, berlin, andrew yang, bernie sanders, doughnut economics, degrowth, local community currency, p2p, commons, democratic money,
          faircoin, trustlines, gnosis"
        />
      </Head>

      <Layout>
        {(large) => (
          <Box width="xlarge" style={{ margin: '0 auto' }}>
            <Box width="100%" pad={{ top: 'large' }}>
              <Box alignSelf="center">
                <Image
                  src="/images/logo.svg"
                  margin={{ bottom: 'large' }}
                  style={{ width: 90, height: 90 }}
                />
              </Box>
              <Box
                margin={{ left: 'medium', right: 'medium' }}
                width="medium"
                alignSelf="center"
              >
                <Text
                  weight="bold"
                  size="large"
                  textAlign="center"
                  margin={{ bottom: 'medium' }}
                >
                  Search for Hubs
                </Text>
                <Box
                  pad={{ horizontal: 'medium', top: 'small' }}
                  background="light-1"
                  margin={{ bottom: 'small' }}
                >
                  <FormField>
                    <TextInput
                      ref={inputRef}
                      value={inputValue}
                      onChange={(event) => {
                        setSelectedIndex(null);
                        setInputValue(event.target.value);
                      }}
                      // onSelect={onSelect}
                      // suggestions={suggestions}
                      placeholder="Berlin"
                      // type="search"
                      dropProps={{ pad: { horizontal: 'medium' } }}
                    />
                  </FormField>
                </Box>
              </Box>
            </Box>
            <Row>
              <Box width="100%">
                <Box
                  margin={{ left: 'medium', right: 'medium' }}
                  width="xlarge"
                  pad={{ horizontal: 'large', bottom: 'large' }}
                  alignSelf="center"
                >
                  <Map />
                </Box>
              </Box>
            </Row>
          </Box>
        )}
      </Layout>
    </div>
  );
}
Example #9
Source File: Page.jsx    From intergalactic with MIT License 4 votes vote down vote up
PageView = ({ route, page }) => {
  const tabs = [];

  const routeDepth = route.split('/').length;
  if (routeDepth === 2 && routes[route].children?.length > 0) {
    tabs.push(routes[route], ...routes[route].children);
  } else if (routeDepth === 3 && routeParents[route]?.children.length > 0) {
    tabs.push(routeParents[route], ...routeParents[route].children);
  }

  const currentHeading = typeof window !== 'undefined' ? window.location.hash.substring(1) : '';
  const headingOptions = getHeadingOptions(page.headings);

  const rootRoute = routeDepth === 3 ? routeParents[route] : routes[route];
  const category = routeDepth === 3 ? routeParents[rootRoute.route] : routeParents[route];

  const htmlTitle = routeParents[route].title
    ? `${page.title} | ${routeParents[route].title}`
    : `${page.title}`;

  useLegacyPageHashes(page.legacyHeaderHashes);

  return (
    <>
      <Helmet>
        <title>{htmlTitle}</title>
      </Helmet>
      {!!headingOptions.length && (
        <Select
          className={styles.mobileSelect}
          options={headingOptions}
          {...(currentHeading ? { defaultValue: currentHeading } : {})}
          onChange={(value) => {
            scroller.scrollTo(value, {
              smooth: true,
              offset: -150,
              duration: 200,
            });
          }}
          placeholder="Select section"
          size="l"
          id="select"
        />
      )}
      <Row className={styles.homePage}>
        <Col sm={12} md={4} span={3}>
          <div className={styles.sideBar}>
            <SideBarNavigation navigation={navigationTree.filter((nav) => !nav.metadata.hide)} />
          </div>
        </Col>
        <Col sm={12} md={8} span={7} id="main-content">
          <div className={styles.documentationWrapper}>
            <DocsHeader
              title={rootRoute.title}
              category={category.title}
              fileSource={rootRoute.metadata?.fileSource}
              beta={rootRoute.metadata?.beta}
              sourcePath={page.sourcePath}
            />
            <Docs tokens={page.tokens} tabs={tabs} />
          </div>
          <div className={styles.nextGuide}>
            {routePrevSiblings[route] && (
              <div className={styles.navigationButton}>
                <ArrowLeftXS mr={2} />
                <Link to={'/' + routePrevSiblings[route].route} rel="noopener noreferrer">
                  {routePrevSiblings[route].title}
                </Link>
              </div>
            )}
            {routeNextSiblings[route] && (
              <div className={styles.navigationButton}>
                <Link to={'/' + routeNextSiblings[route].route} rel="noopener noreferrer">
                  {routeNextSiblings[route].title}
                </Link>
                <ArrowRightXS ml={2} />
              </div>
            )}
          </div>
        </Col>
        <Col md={0} span={2}>
          <SideBarHeading headings={page.headings} />
        </Col>
      </Row>
    </>
  );
}