@/utils#isSSR JavaScript Examples

The following examples show how to use @/utils#isSSR. 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: ShareButton.js    From warsinhk with MIT License 4 votes vote down vote up
function ShareButton(props) {
  const [anchorEl, setAnchorEl] = React.useState(null)
  const { site } = useStaticQuery(
    graphql`
      query {
        site {
          siteMetadata {
            siteUrl
          }
        }
      }
    `
  )

  function getPageUrl() {
    let url = `${site.siteMetadata.siteUrl}${fullPath}`

    if (props.caseId) {
      url = `${site.siteMetadata.siteUrl}${fullPath}/${props.caseId}`
    }

    if (!isSSR()) {
      url = url + decodeURIComponent(window.location.hash)
    }

    return url
  }

  function handleShareButtonClick(event) {
    if (!isSSR() && isWebShareAPISupported()) {
      const data = getWebShareData(getPageUrl())
      if (navigator.canShare(data)) {
        navigator.share(data).then(() => {
          trackCustomEvent({
            category: "general",
            action: "click",
            label: "share",
          })
        })

        return
      }
    }

    setAnchorEl(event.currentTarget)
  }

  function handleShareButtonClose(media) {
    setAnchorEl(null)
    if (typeof media === "string") {
      trackCustomEvent({
        category: "general",
        action: "click",
        label: `share_${media}`,
      })
    }
  }
  const { pathname: fullPath } = useLocation()

  const url = getPageUrl()

  return (
    <>
      <StyledIconButton
        color="inherit"
        aria-label="Share"
        aria-controls="share-menu"
        aria-haspopup="true"
        onClick={handleShareButtonClick}
      >
        <ShareIcon />
      </StyledIconButton>
      <Menu
        id="share-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleShareButtonClose}
      >
        <MenuItem onClick={() => handleShareButtonClose("facebook")}>
          <FacebookShareButton
            url={getShareUrl(url, "facebook")}
            children={<FacebookIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("telegram")}>
          <TelegramShareButton
            url={getShareUrl(url, "telegram")}
            children={<TelegramIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("whatsapp")}>
          <WhatsappShareButton
            url={getShareUrl(url, "whatsapp")}
            children={<WhatsappIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("twitter")}>
          <TwitterShareButton
            url={getShareUrl(url, "twitter")}
            children={<TwitterIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("link")}>
          <StyledCopyIcon
            onClick={() => {
              navigator.clipboard.writeText(url)
            }}
          />
        </MenuItem>
      </Menu>
    </>
  )
}
Example #2
Source File: high-risk.js    From warsinhk with MIT License 4 votes vote down vote up
HighRiskPage = () => {
  const allCasesPageData = useAllCasesData()
  const data = useMemo(() => {
    const edges = _orderBy(
      _flatMap(allCasesPageData.patient_track.group, "edges"),
      "node.end_date"
    ).filter(i => i.node.action_zh !== "求醫")
    return { allWarsCaseLocation: { edges } }
  }, [allCasesPageData])
  const [searchStartDate, setSearchStartDate] = useState(null)
  const [searchEndDate, setSearchEndDate] = useState(null)
  const { i18n, t } = useTranslation()

  const withinBoderFilter = ({ node }) => node.sub_district_zh !== "境外"

  const mapPinType = item => {
    switch (item.type) {
      case "self":
      case "relatives":
        return "confirmed_case"
      default:
        return item.type
    }
  }

  const groupedLocations = Object.values(
    _groupBy(
      data.allWarsCaseLocation.edges.filter(withinBoderFilter).map(e => {
        const item = e.node
        const end_date = item.end_date === "Invalid date" ? "" : item.end_date
        return {
          ...item,
          end_date,
          pass14days: calculatePastNdays(
            {
              case_no: item.case_no,
              date: item.end_date,
            },
            14
          ),
          pinType: mapPinType(item),
        }
      }),
      node => `${node.sub_district_zh}${node.location_zh}`
    )
  ).map(cases => {
    const casesPass14daysArray = [...new Set(cases.map(c => c.pass14days))]
    return {
      node: {
        ...cases[0],
        cases: cases.filter(
          c =>
            withLanguage(i18n, c, "location") ===
            withLanguage(i18n, cases[0], "location")
        ), // Quick fix for filtering locations
        allPass14days:
          casesPass14daysArray.length === 1 &&
          casesPass14daysArray.pop() === true,
      },
    }
  })

  const [filteredLocations, setFilteredLocations] = useState(groupedLocations)
  const container = useRef(null)
  const [fullscreenEnabled, setFullPageState] = useState(false)
  const toggleFullScreen = async () => {
    if (!container.current || !document.fullscreenEnabled) return
    if (!document.fullscreenElement) {
      await container.current.requestFullscreen().catch()
    } else {
      await document.exitFullscreen().catch()
    }
    setFullPageState(Boolean(document.fullscreenElement))
  }

  useEffect(() => {
    const onfullscreenchange = () => {
      setFullPageState(Boolean(document.fullscreenElement))
    }
    document.addEventListener("fullscreenchange", onfullscreenchange)
    return () =>
      document.removeEventListener("fullscreenchange", onfullscreenchange)
  })
  const filteredOptionsWithDate = filteredLocations
    .filter(loc => filterByDate(loc.node, searchStartDate, searchEndDate))
    .sort((a, b) => {
      // Active cards on top
      if (a.node.allPass14days > b.node.allPass14days) return 1
      if (a.node.allPass14days < b.node.allPass14days) return -1

      if (a.node.end_date > b.node.end_date) return -1
      if (a.node.end_date < b.node.end_date) return 1

      return 0
    })
  const options = [
    {
      label: t("search.sub_district"),
      options: createDedupOptions(
        i18n,
        data.allWarsCaseLocation.edges.filter(withinBoderFilter),
        "sub_district"
      ),
      defaultSize: 100,
    },
    {
      // For 班次 / 航班: Only ferry no, flight no, and train no are searchable, ignore building
      label: t("search.location"),
      options: createDedupOptions(
        i18n,
        data.allWarsCaseLocation.edges.filter(withinBoderFilter),
        "location"
      ),
    },
  ]
  const { fullPageContent } = useStyle()
  return (
    <Layout>
      <SEO title="HighRiskPage" />
      <div ref={container} className={fullPageContent}>
        {/* SSR do not show the map */}
        {!isSSR() && (
          <AutoSizer defaultWidth={800} defaultHeight={600}>
            {({ width, height }) => (
              <React.Suspense fallback={<div />}>
                <HighRiskMap
                  t={t}
                  language={i18n.language}
                  getTranslated={(node, key) => withLanguage(i18n, node, key)}
                  filteredLocations={filteredOptionsWithDate.map(i => i.node)}
                  height={height}
                  width={width}
                  dateFilterEnabled={searchStartDate && searchEndDate}
                  fullscreenEnabled={fullscreenEnabled}
                  datePicker={
                    <DatePicker
                      startDate={searchStartDate}
                      endDate={searchEndDate}
                      setSearchStartDate={setSearchStartDate}
                      setSearchEndDate={setSearchEndDate}
                    />
                  }
                  selectBar={
                    <MultiPurposeSearch
                      list={groupedLocations}
                      placeholder={t("search.placeholder")}
                      options={options}
                      searchKey="high_risk"
                      onListFiltered={list => {
                        setFilteredLocations(list)
                      }}
                    />
                  }
                  toggleFullScreen={toggleFullScreen}
                  renderCard={({ node, isActive }) => {
                    return (
                      <HighRiskCardItem
                        key={node.id}
                        node={{ node }}
                        i18n={i18n}
                        t={t}
                        isActive={isActive}
                      />
                    )
                  }}
                ></HighRiskMap>
              </React.Suspense>
            )}
          </AutoSizer>
        )}
      </div>
    </Layout>
  )
}