@/utils#saveToLocalStorage JavaScript Examples

The following examples show how to use @/utils#saveToLocalStorage. 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: MultiPurposeSearch.js    From warsinhk with MIT License 4 votes vote down vote up
MultiPurposeSearch = props => {
  const {
    options,
    list,
    placeholder,
    onListFiltered,
    searchKey,
    filterWithOr = true,
  } = props

  const [filters, setFilters] = useState([])
  const [histories, setHistories] = useState([])
  const sortedOptions = options.map(opt => ({
    ...opt,
    options: sortOptionsWithHistories(opt.options, histories),
  }))
  const { t, i18n } = useTranslation()
  useEffect(() => {
    const v = loadFromLocalStorage(searchKey)
    if (v) {
      setHistories(JSON.parse(v))
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const customStyles = {
    control: () => ({
      display: "flex",
      backgroundColor: "#FFF",
      border: "1px solid hsl(0, 0%, 80%)",
      borderRadius: "6px",
      padding: "2px",
    }),
    placeholder: () => ({
      fontSize: "14px",
    }),
    menu: () => ({
      backgroundColor: "#FFF",
      zIndex: 999,
    }),
    multiValue: styles => ({
      ...styles,
      background: "#505096",
      color: "#ffffff",
      padding: "3px 3px 3px 10px",
      borderRadius: "16px",
    }),
    multiValueLabel: () => ({
      fontSize: "14px",
      fontWeight: 700,
    }),
    groupHeading: styles => ({
      ...styles,
      fontVariant: "normal",
      fontSize: "14px",
    }),
  }

  return (
    <AsyncSelect
      styles={customStyles}
      closeMenuOnSelect={false}
      loadOptions={(input, callback) =>
        callback(filterSearchOptions(sortedOptions, input, 5))
      }
      isMulti
      placeholder={placeholder}
      noOptionsMessage={() => t("text.not_found")}
      defaultOptions={filterSearchOptions(sortedOptions, null, 10)}
      onChange={selectedArray => {
        trackCustomEvent({
          category: searchKey,
          action: "search_input",
          label: selectedArray ? selectedArray.join(",") : "",
        })
        if (selectedArray && selectedArray.length > (filters || []).length) {
          let historiesToSave = [
            ...histories,
            selectedArray[selectedArray.length - 1],
          ]
          if (historiesToSave.length >= 10) {
            historiesToSave.shift()
          }
          setHistories(historiesToSave)
          saveToLocalStorage(searchKey, JSON.stringify(historiesToSave))
          onListFiltered(filterValues(i18n, list, selectedArray, filterWithOr))
        } else if (selectedArray && selectedArray.length > 0) {
          onListFiltered(filterValues(i18n, list, selectedArray, filterWithOr))
        } else {
          // return whole list if input is empty
          onListFiltered(list)
        }
        setFilters(selectedArray)
      }}
    />
  )
}
Example #2
Source File: index.js    From warsinhk with MIT License 4 votes vote down vote up
export default function IndexPage({ data }) {
  const { t } = useTranslation()

  const [modules, setModules] = React.useState([])
  const [showSettings, setShowSettings] = React.useState(false)

  // TODO: useMemo to cache the components
  const components = {}
  const registerComponent = (
    key,
    titleKey,
    component,
    { rowSpan = 1, showTitle = true } = {}
  ) => {
    components[key] = {
      id: key,
      title: t(titleKey),
      component,
      rowSpan,
      showTitle,
    }
  }

  const renderComponent = (key, data) => {
    if (components[key]) {
      const Component = components[key].component
      return (
        <ModuleContainer>
          {components[key].showTitle && (
            <Typography variant="h2">{components[key].title}</Typography>
          )}
          <Suspense fallback={<ComponentLoading />}>
            <Component data={data} />
          </Suspense>
        </ModuleContainer>
      )
    }
    return <></>
  }

  const registerComponents = () => {
    registerComponent(
      "daily_stat",
      "dashboard.latest_figures",
      React.lazy(() =>
        import(
          /* webpackPrefetch: true */ "@/components/molecules/dashboard/DailyStats.js"
        )
      )
    )

    registerComponent(
      "important_information",
      "dashboard.important_information",
      React.lazy(() =>
        import(
          /* webpackPrefetch: true */ "@/components/molecules/dashboard/ImportantInformation.js"
        )
      ),
      {
        showTitle: false,
      }
    )

    registerComponent(
      "confirmed_chart",
      "dashboard.case_highlights_area",
      React.lazy(() =>
        import(
          /* webpackPrefetch: true */ "@/components/molecules/dashboard/ConfirmedCaseVisual"
        )
      ),
      {
        rowSpan: 4,
      }
    )

    registerComponent(
      "confirmed_digest_gender",
      "dashboard.case_highlights_gender",
      React.lazy(() =>
        import(
          /* webpackPrefetch: true */ "@/components/molecules/dashboard/ConfirmedCaseDigestGender"
        )
      ),
      {
        rowSpan: 2,
      }
    )

    registerComponent(
      "passenger_daily",
      "dashboard.daily_passengers",
      React.lazy(() =>
        import(
          /* webpackPrefetch: true */ "@/components/molecules/dashboard/PassengerDailyFigure"
        )
      )
    )

    registerComponent(
      "confirmed_digest_age",
      "dashboard.case_highlights_age",
      React.lazy(() =>
        import(
          /* webpackPrefetch: true */ "@/components/molecules/dashboard/ConfirmedCaseDigestAge"
        )
      )
    )

    registerComponent(
      "outbound_alert",
      "dashboard.outbound_alert",
      React.lazy(() =>
        import(
          /* webpackPrefetch: true */ "@/components/molecules/dashboard/OutboundAlert.js"
        )
      ),
      {
        rowSpan: 3,
        showTitle: false,
      }
    )

    registerComponent(
      "carousel",
      "dashboard.carousel",
      React.lazy(() =>
        import(
          /* webpackPrefetch: true */ "@/components/molecules/dashboard/Carousel.js"
        )
      ),
      {
        showTitle: false,
      }
    )

    registerComponent(
      "friendly_links",
      "dashboard.friendly_links",
      React.lazy(() =>
        import(
          /* webpackPrefetch: true */ "@/components/molecules/dashboard/FriendlyLinks.js"
        )
      ),
      {
        showTitle: false,
      }
    )

    registerComponent(
      "latest_cases",
      "dashboard.latest_cases",
      React.lazy(() =>
        import(
          /* webpackPrefetch: true */ "@/components/molecules/dashboard/LatestCases.js"
        )
      ),
      {
        rowSpan: 6,
      }
    )

    registerComponent(
      "epidemic_chart",
      "dashboard.epidemic_chart",
      React.lazy(() =>
        import(
          /* webpackPrefetch: true */ "@/components/molecules/dashboard/EpidemicChart.js"
        )
      ),
      {
        rowSpan: 4,
      }
    )

    registerComponent(
      "isolation_beds",
      "dashboard.isolation_beds",
      React.lazy(() =>
        import(
          /* webpackPrefetch: true */ "@/components/molecules/dashboard/ConfirmedLineChart.js"
        )
      ),
      {
        rowSpan: 2,
      }
    )
  }

  const handleModuleChange = id => {
    const index = modules.indexOf(id)
    if (index >= 0) {
      modules.splice(index, 1)
    } else {
      modules.push(id)
    }
    setModules([...modules])
    saveToLocalStorage(LOCAL_STORAGE_KEY_DASHBOARD, [...modules])
    trackCustomEvent({
      category: "dashboard",
      action: "module_change",
      label: modules.join(","),
    })
  }

  // load the settings from localStorage
  const LOCAL_STORAGE_KEY_DASHBOARD = "index-dashboard-module"
  const LOCAL_STORAGE_KEY_DASHBOARD_NEW_MODULES = "index-dashboard-module-new"
  registerComponents()

  React.useEffect(() => {
    const moduleString = loadFromLocalStorage(LOCAL_STORAGE_KEY_DASHBOARD)
    const loadedNewModules = loadFromLocalStorage(
      LOCAL_STORAGE_KEY_DASHBOARD_NEW_MODULES
    )
    let newModules = []
    if (loadedNewModules) {
      const alreadyLoadedNewModules = loadedNewModules.split(",")
      NEW_FEATURES.forEach(f => {
        if (alreadyLoadedNewModules.indexOf(f) < 0) {
          newModules.push(f)
        }
      })
    } else {
      newModules = NEW_FEATURES
    }

    saveToLocalStorage(LOCAL_STORAGE_KEY_DASHBOARD_NEW_MODULES, NEW_FEATURES)
    if (moduleString) {
      setModules(moduleString.split(",").concat(newModules))
    } else {
      // default modules
      setModules(DEFAULT_MODULES.concat(newModules))
    }
    // eslint-disable-line
  }, [])

  // store the information of which module on left/right (only for desktop)
  const columnMap = []
  let left = 0
  let right = 0
  for (let i = 0; i < modules.length; i++) {
    const m = components[modules[i]]
    if (right >= left) {
      left += _get(m, "rowSpan", 1)
      columnMap.push("left")
    } else {
      right += _get(m, "rowSpan", 1)
      columnMap.push("right")
    }
  }

  return (
    <>
      <SEO title="Home" />
      <Layout>
        <IndexContainer>
          {showSettings && (
            <ModuleContainer className="settingContainer">
              <FormControl component="fieldset">
                <FormLabel component="legend">
                  {t("dashboard.settings")}
                </FormLabel>
                {Object.values(components).map(component => (
                  <FormGroup>
                    <FormControlLabel
                      control={
                        <Checkbox
                          color="primary"
                          checked={modules.indexOf(component.id) >= 0}
                          onChange={() => handleModuleChange(component.id)}
                        />
                      }
                      label={component.title}
                    />
                  </FormGroup>
                ))}
              </FormControl>
            </ModuleContainer>
          )}
          <SplitWrapper>
            <SessionWrapper>
              <IndexAlertMessage />
              {modules
                .filter((_, i) => columnMap[i] === "left")
                .map((m, i) => (
                  <React.Fragment key={i}>
                    {renderComponent(m, data)}
                  </React.Fragment>
                ))}
            </SessionWrapper>
            <SessionWrapper>
              {modules
                .filter((_, i) => columnMap[i] === "right")
                .map((m, i) => (
                  <React.Fragment key={i}>
                    {renderComponent(m, data)}
                  </React.Fragment>
                ))}
            </SessionWrapper>
          </SplitWrapper>
          <Fab
            color="primary"
            className="fab"
            onClick={() => {
              if (!showSettings) {
                window.scrollTo(0, 0)
              }
              setShowSettings(!showSettings)
            }}
          >
            <SettingIcon />
          </Fab>
        </IndexContainer>
      </Layout>
    </>
  )
}