@reach/router#Router JavaScript Examples

The following examples show how to use @reach/router#Router. 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: index.js    From cord-19 with Apache License 2.0 6 votes vote down vote up
function App() {
  return (
    <Flex flexDirection="column" minHeight="100vh">
      <Box width={1}>
        <NavMenu />
      </Box>
      <Router primary={false} component={React.Fragment}>
        <Main path="/" />
        <Search path="/search" />
        <Article path="/article/:id" />
        <Error default />
      </Router>
    </Flex>
  );
}
Example #2
Source File: index.js    From devrel-kpis with MIT License 6 votes vote down vote up
IndexPage = () => {
  // Use a shared key to that animation understands its the same component
  const sharedKey = "__index__";

  return (
    <Page title="">
      <AnimateSharedLayout type="crossfade" transition={{ type: "spring", damping: 9, mass: 0.3, velocity: 20 }}>
        <Router>
          <PageContent key={sharedKey} path="/" />
          <PageContent key={sharedKey} path="/t/:tipId" />
          <PageContent key={sharedKey} path="/:tagId" />
          <PageContent key={sharedKey} path="/:tagId/:tipId" />
        </Router>
      </AnimateSharedLayout>
    </Page>
  );
}
Example #3
Source File: index.js    From inboxzero-web with MIT License 6 votes vote down vote up
IndexPage = () => {
  // Use a shared key to that animation understands its the same component
  const sharedKey = "__index__";

  return (
    <Page title="">
      <AnimateSharedLayout type="crossfade" transition={{ type: "spring", damping: 9, mass: 0.3, velocity: 20 }}>
        <Router>
          <PageContent key={sharedKey} path="/" />
          <PageContent key={sharedKey} path="/t/:tipId" />
          <PageContent key={sharedKey} path="/:tagId" />
          <PageContent key={sharedKey} path="/:tagId/:tipId" />
        </Router>
      </AnimateSharedLayout>
    </Page>
  );
}
Example #4
Source File: MainContent.js    From hooks-workshop with MIT License 6 votes vote down vote up
MainContent = (props) => (
  <main>
    <Router>
      <Article path="/" />
      <Profile
        path="profile"
        name={props.name}
        setName={props.setName}
        birthMonth={props.birthMonth}
        setBirthMonth={props.setBirthMonth}
        birthDay={props.birthDay}
        setBirthDay={props.setBirthDay}
      />
    </Router>
  </main>
)
Example #5
Source File: App.js    From just-one with MIT License 6 votes vote down vote up
render() {
    return (
      <div className="App-Wrapper">
        <Router>
          <Splash path="/" default />
          <Room path="/room/:roomName" />
        </Router>
      </div>
    );
  }
Example #6
Source File: app.js    From aws-amplify-gatsby-auth with MIT License 6 votes vote down vote up
App = () => (
  <Layout>
    <Router>
      <PrivateRoute path="/app/home" component={Home} />
      <PrivateRoute path="/app/profile" component={Details} />
      <Login path="/app/login" />
      <SignUp path="/app/signup" />
    </Router>
  </Layout>
)
Example #7
Source File: resources.js    From new_sommelier_website with MIT License 6 votes vote down vote up
render() {
    console.log(this.state);
    return (
      <Layout location={this.props.location}>
        <SEO title="Resources" description="Sommelier upcoming events."/>
        <Router>
          {<ResourcesPage blok={this.state} path='/resources' />}
        </Router>
      </Layout>
    )
  }
Example #8
Source File: events.js    From new_sommelier_website with MIT License 6 votes vote down vote up
render() {
    console.log(this.state);
    return (
      <Layout location={this.props.location}>
        <SEO title="Events" description="Sommelier upcoming events."/>
        <Router>
          {<EventPage blok={this.state} title='Upcoming Events' history={false} path='/events' />}
        </Router>
      </Layout>
    )
  }
Example #9
Source File: history.js    From new_sommelier_website with MIT License 6 votes vote down vote up
render() {
    //console.log(this.state);
    return (
      <Layout location={this.props.location}>
        <SEO title="Events" description="Sommelier upcoming events."/>
        <Router>
          {<EventPage blok={this.state} title='Past Events' history={true} path='/events/history' />}
        </Router>
      </Layout>
    )
  }
Example #10
Source File: blog.js    From new_sommelier_website with MIT License 6 votes vote down vote up
render() {
    return (
      <Layout location={this.props.location}>
        <SEO title={this.state.story ? this.state.story.content.title : "Sommelier"} description="Sommelier is the new Coprocessor for the Ethereum VM" image={this.state.story ? this.state.story.content.image : null}/>
        <Router>
          {this.state.story && <Page blok={this.state.story.content} path='/blog' />}
        </Router>
      </Layout>
    )
  }
Example #11
Source File: MainContentInitial.js    From hooks-workshop with MIT License 6 votes vote down vote up
MainContent = (props) => (
  <main>
    <Router>
      <Article path="/" />
      <Profile
        path="profile"
        name={props.name}
        setName={props.setName}
        birthMonth={props.birthMonth}
        setBirthMonth={props.setBirthMonth}
        birthDay={props.birthDay}
        setBirthDay={props.setBirthDay}
      />
    </Router>
  </main>
)
Example #12
Source File: App.js    From eos-icons-landing with MIT License 6 votes vote down vote up
App = () => {
  const [state, dispatch] = useReducer(iconsReducer, eosIconsState)
  const container = React.useRef(null)
  return (
    <AppContext.Provider value={{ state, dispatch }}>
      <div className='App'>
        <Navigation resetIconSetState={container.current} />
        <div className='app-container'>
          <Router primary={false}>
            <Home path='/' container={container} />
            <Docs path='/docs' />
            <CookiesPage path='/cookies-policy' />
            <ThankYou path='/thankyou' />
            <PageNotFound path='*' />
            <AboutPage path='/about' />
            <TeamPage path='/team' />
            <Cheatsheet path='/cheatsheet' />
          </Router>
          <ScrollToTopBtn />
        </div>
        <CookiesBanner />
        <Footer />
      </div>
    </AppContext.Provider>
  )
}
Example #13
Source File: Application.js    From React-Messenger-App with MIT License 6 votes vote down vote up
function Application() {
  const user = null;
  return (
        user ?
        <ProfilePage />
      :
        <Router>
          <SignUp path="signUp" />
          <SignIn path="/" />
          <PasswordReset path = "passwordReset" />
        </Router>

  );
}
Example #14
Source File: index.js    From hooks-workshop with MIT License 6 votes vote down vote up
App = () => (
  <div>
    <nav className={styles.nav}>
      <Link to="meme-creator" getProps={isActive}>Meme Creator</Link>
      <Link to="star-wars-info" getProps={isActive}>Star Wars Info</Link>
      <Link to="personal-blog" getProps={isActive}>Personal Blog</Link>
    </nav>
    <Router>
      <MemeCreator path="meme-creator" />
      <StarWarsInfo path="star-wars-info" />
      <PersonalBlog path="personal-blog/*" />
      <Redirect from="/" to="meme-creator" noThrow />
    </Router>
  </div>
)
Example #15
Source File: MainContentContext.js    From hooks-workshop with MIT License 5 votes vote down vote up
MainContent = (props) => (
  <main>
    <Router>
      <Article path="/" />
      <Profile path="profile" />
    </Router>
  </main>
)
Example #16
Source File: App.js    From PyLot with MIT License 5 votes vote down vote up
App = () => {
  const signedStateHook = useState(["Signed Out", "None", "None"]); //maybe add a dictionary similar to the one in SignInContext.js
  const [signInState, setSignInState] = useContext(SignInContext);
  return (
    <React.StrictMode>
      <SignInContext.Provider value={signedStateHook}>
        <div className="main-container">
          <div className="side-container">
            <Router>
              <Sidebar
                options={["Home", "Sign In"]}
                links={["/", "/signupin"]}
                path="/signup"
              />
              <Sidebar options={["Home"]} links={["/"]} path="/signupin" />
              <Sidebar
                options={["Sign Up / Sign In"]}
                links={["/signupin"]}
                home={true}
                path="/"
              />
              <Sidebar
                options={["Home"]}
                links={["/"]}
                path="/serverDetails/*"
              />
              <Sidebar options={["Home"]} links={["/"]} path="/addServer" />
              <Sidebar options={["Home"]} links={["/"]} path="/notebook" />
              <Sidebar options={["Home"]} links={["/"]} path="/terminal/*" />
              <Sidebar options={["Home"]} links={["/"]} path="/notebooks/*" />
              <Sidebar options={["Home"]} links={["/"]} path="/addNotebook" />
              <Sidebar
                options={["Home"]}
                links={["/"]}
                path="/deleteNotebook"
              />
              <Sidebar options={["Home"]} links={["/"]} path="/editor/*" />
              {/* <Sidebar options={["Home"]} links={["/notebooks"]} path="/view/*" /> */}
            </Router>
          </div>
          <div className="nested-main-container">
            <Router>
              <Home path="/" />
              <About path="/about" />
              <Signupin path="/signupin" />
              <Signup path="/signup" />
              <ServerDetails path="/serverDetails/:username/:serverName/:ipAddr/:serverUser/:serverPassword" />
              <Logout path="/logout" />
              <AddServer path="/addServer" />
              <SocketApi path="/testSocket" />
              <Notebook path="/notebooks/:username/:notebookName" />
              <Terminal path="/terminal/:username/:serverName" />
              {/* <Editor path="/editor/"/> */}
              <Editor path="/editor/:username/:notebook/:tile" />
              <NotebooksDisplay path="/notebooks/:username" />
              <AddNotebook path="/addNotebook" />
              <DeleteNotebook path="/deleteNotebook" />
              <View path="/view/:username/:notebook/:tile"/>
            </Router>
          </div>
        </div>
      </SignInContext.Provider>
    </React.StrictMode>
  );
}
Example #17
Source File: App.js    From haskell.foundation with MIT License 5 votes vote down vote up
App = ({ element }) => {
  function languageOnUpdate ({ lang, prevLang, url, prevURL }) {
    if (prevURL && url !== prevURL) navigate(url)
    if (prevLang && lang !== prevLang) analytics.autoCapture({ category: analytics.constants.LANGUAGE, action: 'language_updated', label: lang })
  }

  function themeOnUpdate ({ theme, prevTheme }) {
    if (prevTheme && theme !== prevTheme) analytics.autoCapture({ category: analytics.constants.THEME, action: 'theme_updated', label: theme })
  }

  function getRoutes (lang) {
    const routes = config.routes.map(({ path, component, props }) => {
      const Component = require(`./routes/${component}.js`).default
      const routes = [ <Component {...props} path={path} key={path} /> ]
      if (config.localization.createLocalizedPages && config.localization.createDefaultPages) {
        routes.push(<Component {...props} key={`/${lang}${path}`} path={`/${lang}${path}`} />)
      }

      return routes
    })

    return routes.reduce((accumulator, currentValue) => [ ...accumulator, ...currentValue ], [])
  }

  return (
    <Location>
      {({ location: { pathname, search, hash } }) => (
        <Language.Provider
          location={{ pathname, search, hash }}
          availableLanguages={config.availableLanguages}
          alternativeLanguages={config.alternativeLanguages}
          onUpdate={languageOnUpdate}
          useURL={config.localization.useURL}
          useNavigator={config.localization.useNavigator}
          persistLang={config.localization.persistLang}
        >
          <Theme.Provider
            themes={getThemes()}
            onUpdate={themeOnUpdate}
            transformTheme={({ config }) => theme.convertThemeToMaterial(config)}
          >
            <Theme.Consumer>
              {({ theme, originalTheme }) => (
                <MaterialUIThemeProvider theme={theme}>
                  <StyledThemeProvider theme={theme}>
                    <Language.Consumer>
                      {({ key: lang }) => (
                        <LinkProvider lang={lang} component={Link}>
                          <Styles theme={originalTheme.config} />
                          <GlobalStyles />
                          <Router>
                            {getRoutes(lang)}
                            <DefaultRoute default element={element} />
                          </Router>
                        </LinkProvider>
                      )}
                    </Language.Consumer>
                  </StyledThemeProvider>
                </MaterialUIThemeProvider>
              )}
            </Theme.Consumer>
          </Theme.Provider>
        </Language.Provider>
      )}
    </Location>
  )
}
Example #18
Source File: [...].js    From create-magic-app with MIT License 5 votes vote down vote up
App = () => {
  return (
    <Router basepath="/app">
      <PrivateRoute path="/profile" component={Profile} />
      <Login path="/login" />
    </Router>
  )
}
Example #19
Source File: Ai.js    From network-rc with Apache License 2.0 5 votes vote down vote up
render() {
    const {
      state: { sampleList, ai, loading },
      props: { controller, cameraEnabled, canvasRef },
      menuItem,
    } = this;

    return (
      <Spin spinning={loading} tip={loading}>
        <Match path=":current">
          {(props) => (
            <Menu
              selectedKeys={[props.match && props.match.current]}
              mode="horizontal"
            >
              {menu.map((i) => menuItem(i))}
            </Menu>
          )}
        </Match>
        <Router>
          <AiSample
            path="sample"
            onFinish={(sampleList) => this.setState({ sampleList })}
            sampleList={sampleList}
            canvasRef={canvasRef}
            cameraEnabled={cameraEnabled}
            controller={controller}
          />
          <AiTrain
            path="train"
            sampleList={sampleList}
            controller={controller}
            ai={ai}
          />
          <AiDrive
            path="drive"
            controller={controller}
            canvasRef={canvasRef}
            cameraEnabled={cameraEnabled}
            ai={ai}
          />
        </Router>
      </Spin>
    );
  }
Example #20
Source File: index.js    From yasn with MIT License 5 votes vote down vote up
function App() {
  const userCookie = cookies.get('userCookie');
  const userEmail = userCookie.Email;
  const googleToken = userCookie.Token;

  const [profile, setProfile] = useContext(ProfileContext);

  useEffect(() => {
    axios
      .get(
        `${ConnectServerUrl}/checkprofile?` +
          queryString.stringify(
            { email: userEmail, googleToken },
            { withCredentials: true }
          )
      )
      .then((res) => {
        cookies.set('userDetails', res.data[0]);
        if (res.data === 'invalid token') {
          cookies.remove('userCookie');
          window.location.reload();
        }
        if (!res.data) setProfile(false);
      });
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        {profile ? (
          <>
            <NavAppBar>
              <StoreProvider store={store}>
                <Router>
                  <HomePage path="/" />
                  <HomePage path="/home/:tag" />
                  <ChatApp path="/chat" />
                  <ProfilePage path="/profile" />
                  <ProfilePage path="/user/:username" />
                  <AddPostPage path="/add" />
                  <SignIn path="/signin" />
                  <HomePage path="*" />
                </Router>
              </StoreProvider>
            </NavAppBar>
          </>
        ) : (
          <AddProfile />
        )}
      </header>
    </div>
  );
}
Example #21
Source File: dashboard.js    From gatsby-apollo-wpgraphql-jwt-starter with MIT License 5 votes vote down vote up
Dashboard = () => {
  const auth = useAuth()
  return (
    <Layout>

      <hr/>

      {
        auth.isLoggedIn() &&
        <>
          <h2>Dashboard</h2>
          <nav>
            <Link to={"/dashboard/"}>Dashboard</Link> {" | "}
            <Link to={"/dashboard/userarea/"}>User Area</Link> {" | "}
            <a
              href="/"
              onClick={event => {
                event.preventDefault()
                logout(() => navigate(`/dashboard/`))
              }}
            >
              log out
            </a>
          </nav>
        </>
      }

      {/* This also defines the space, where the routes get rendered */}
      <div className={"DashboardMain"} style={{ backgroundColor: "#f9f9f9", padding: 16 }}>
        <UserProvider>
          <Router id="router">
            <PageNotFound default/>
            <LoginForm path="/dashboard/login/"/>
            <SignUpForm path="/dashboard/signup/"/>
            <PrivateRoute path="/dashboard/" component={DashboardIndex}/>
            <PrivateRoute path="/dashboard/userarea/" component={UserArea}/>
          </Router>
        </UserProvider>
      </div>

    </Layout>
  )
}
Example #22
Source File: root.js    From cybsec with GNU Affero General Public License v3.0 5 votes vote down vote up
Root = () =>
  createElement(
    Router,
    {
      basepath: __PATH_PREFIX__,
    },
    createElement(RouteHandler, { path: `/*` })
  )
Example #23
Source File: Controller.js    From network-rc with Apache License 2.0 4 votes vote down vote up
render() {
    const {
      fixContent,
      ttsInput,
      props: {
        statusInfo,
        action,
        cameraEnabled,
        videoEl,
        onTTS,
        ttsPlaying,
        setting,
        playAudio,
        serverConfig,
        changeChannel,
        editabled,
        cameraList,
        channelStatus,
        saveServerConfig,
        isFullscreen,
        session,
        webrtcChannel,
      },
    } = this;
    const { isShowButton, ttsInputVisible, text } = this.state;
    const { channelList = [], specialChannel = {} } = serverConfig;
    const speedChannel = channelList.find(
      ({ id }) => id === specialChannel.speed
    );
    const { audioList = [] } = serverConfig;

    return (
      <div className="controller">
        <Router className="controller-router">
          <Ai
            path="ai/learn/*"
            canvasRef={videoEl}
            cameraEnabled={cameraEnabled}
            action={action}
            onAi={(isAiControlling) => this.setState({ isAiControlling })}
          />
          <ObjectDetection
            path="ai/coco-ssd/*"
            videoEl={videoEl}
            cameraEnabled={cameraEnabled}
            action={action}
            onAi={(isAiControlling) => this.setState({ isAiControlling })}
          />
        </Router>
        {!isFullscreen && (
          <Form className="controller-form" size="small" layout="inline">
            <Form.Item>
              <Popover
                content={fixContent}
                title="修正"
                trigger="click"
                placement="topLeft"
              >
                <Button icon={<SlidersOutlined />}>修正</Button>
              </Popover>
            </Form.Item>
            {speedChannel && (
              <>
                <Form.Item>
                  <Popover
                    placement="topLeft"
                    content={
                      <Slider
                        defaultValue={speedChannel.valuePostive * 100}
                        min={0}
                        max={100}
                        onChange={(v) => {
                          speedChannel.valuePostive = v / 100;
                          saveServerConfig({
                            channelList,
                          });
                        }}
                        arrowPointAtCenter
                        style={{ width: "30vw" }}
                      />
                    }
                  >
                    <Button shape="round">
                      前进:{Math.round(speedChannel.valuePostive * 100)}
                    </Button>
                  </Popover>
                </Form.Item>
                <Form.Item>
                  <Popover
                    placement="topLeft"
                    content={
                      <Slider
                        defaultValue={speedChannel.valueNegative * -100}
                        min={0}
                        max={100}
                        style={{ width: "30vw" }}
                        onChange={(v) => {
                          speedChannel.valueNegative = (v / 100) * -1;
                          saveServerConfig({
                            channelList,
                          });
                        }}
                      />
                    }
                  >
                    <Button shape="round">
                      倒退:{Math.round(speedChannel.valueNegative * -100)}
                    </Button>
                  </Popover>
                </Form.Item>
              </>
            )}

            <Form.Item>
              <Gamepad
                changeChannel={changeChannel}
                channelList={serverConfig.channelList}
                channelStatus={channelStatus}
                playAudio={playAudio}
                serverConfig={serverConfig}
              />
            </Form.Item>

            <Form.Item>
              <Orientation
                changeChannel={changeChannel}
                channelStatus={channelStatus}
                serverConfig={serverConfig}
              />
            </Form.Item>
            <Form.Item>
              <Keybord
                playAudio={playAudio}
                channelStatus={channelStatus}
                channelList={serverConfig.channelList}
                changeChannel={changeChannel}
                serverConfig={serverConfig}
                onEnter={() => {
                  this.setState({ ttsInputVisible: true });
                  setTimeout(() => {
                    ttsInput.current && ttsInput.current.focus();
                  }, 200);
                }}
              />
            </Form.Item>
            <Form.Item>
              <Popover
                arrowPointAtCenter
                trigger="click"
                placement="topRight"
                visible={ttsInputVisible}
                onVisibleChange={(ttsInputVisible) => {
                  this.setState({ ttsInputVisible });
                  setTimeout(() => {
                    ttsInput.current && ttsInput.current.focus();
                  }, 200);
                }}
                content={
                  <form>
                    <Input.Search
                      ref={ttsInput}
                      name="tts"
                      style={{ width: "60vw" }}
                      placeholder="发送语音"
                      enterButton="发送"
                      value={text}
                      onChange={(e) => this.setState({ text: e.target.value })}
                      onSearch={(text) => {
                        onTTS(text);
                        this.setState({ text: "" });
                      }}
                      loading={ttsPlaying}
                      onKeyDown={(e) => {
                        e.stopPropagation();
                        if (e.key === "Escape") {
                          this.setState({ ttsInputVisible: false });
                        }
                      }}
                    />
                  </form>
                }
              >
                <Button shape="round">
                  <SendOutlined />
                </Button>
              </Popover>
            </Form.Item>

            {audioList
              .filter((i) => i.showFooter)
              .map(({ path, text, name }) => (
                <Form.Item key={name}>
                  <Button
                    shape="round"
                    onClick={() => playAudio({ path, text })}
                    icon={<SoundOutlined />}
                  >
                    {name}
                  </Button>
                </Form.Item>
              ))}

            <Form.Item>
              <Popover
                placement="topRight"
                content={
                  <Space size={[16, 16]} wrap>
                    <Form.Item extra="显示触控 UI">
                      <Switch
                        checked={isShowButton}
                        onChange={(isShowButton) => {
                          store.set("is-show-button", isShowButton);
                          this.setState({ isShowButton });
                        }}
                        checkedChildren={<DragOutlined />}
                        unCheckedChildren={<DragOutlined />}
                      />
                    </Form.Item>
                    {audioList
                      .filter((i) => !i.showFooter)
                      .map(({ path, text, name, type }) => (
                        <Form.Item extra={`播放${name}`} key={name}>
                          {type === "audio" && (
                            <Button
                              shape="round"
                              onClick={() => playAudio({ path })}
                              icon={<SoundOutlined />}
                            >
                              {name}
                            </Button>
                          )}
                          {type === "text" && (
                            <Button
                              shape="round"
                              onClick={() => playAudio({ text })}
                              icon={<SoundOutlined />}
                            >
                              {name}
                            </Button>
                          )}
                          {type === "stop" && (
                            <Button
                              shape="round"
                              onClick={() => playAudio({ stop: true })}
                              icon={<StopOutlined />}
                            >
                              {name}
                            </Button>
                          )}
                        </Form.Item>
                      ))}
                  </Space>
                }
              >
                <Button shape="round">
                  <MoreOutlined />
                </Button>
              </Popover>
            </Form.Item>
            <Form.Item>
              <Microphone
                url={
                  setting.host &&
                  `${
                    window.location.protocol === "https:" ? "wss://" : "ws://"
                  }${setting.host}/audio`
                }
              />
            </Form.Item>
          </Form>
        )}
        <ControlUI
          webrtcChannel={webrtcChannel}
          session={session}
          channelStatus={channelStatus}
          isShowButton={isShowButton}
          uiComponentList={serverConfig.uiComponentList}
          channelList={serverConfig.channelList}
          changeChannel={changeChannel}
          editabled={editabled}
          cameraList={cameraList}
          setting={setting}
          isFullscreen={isFullscreen}
          statusInfo={statusInfo}
        />
      </div>
    );
  }
Example #24
Source File: App.js    From network-rc with Apache License 2.0 4 votes vote down vote up
render() {
    const {
      disconnect,
      controller,
      changeChannel,
      changeSetting,
      changeLight,
      changePower,
      piPowerOff,
      login,
      saveServerConfig,
      resetServerConfig,
      resetChannel,
      changeVolume,
      changeMicVolume,
      changeEditabled,
      updateVersion,
      state: {
        version,
        cameraList,
        setting,
        wsConnected,
        cameraEnabled,
        action,
        isFullscreen,
        serverConfig,
        lightEnabled,
        delay,
        powerEnabled,
        isLogin,
        ttsPlaying,
        volume,
        micVolume,
        session,
        editabled,
        gpioChannelStatus,
        updateStaus,
        connectType,
        webrtcChannel,
        locked,
        enabledControllerMicphone,
        statusInfo,
      },
      tts,
      playAudio,
      playCarMicphonne,
      changeControllerMicphone,
    } = this;

    return (
      <div className="App" ref={this.appRef}>
        {!isFullscreen && (
          <Status
            statusInfo={statusInfo}
            channelStatus={gpioChannelStatus}
            delay={delay}
            connectType={connectType}
            onCarMicphoneChange={playCarMicphonne}
            onControllerMicphoneChange={changeControllerMicphone}
            locked={locked}
            {...{
              version,
              wsConnected,
              isFullscreen,
              lightEnabled,
              powerEnabled,
              changePower,
              changeLight,
              piPowerOff,
              setting,
              isLogin,
              session,
              changeEditabled,
              editabled,
              changeChannel,
              serverConfig,
              updateStaus,
              enabledControllerMicphone,
            }}
            disabled={!isLogin}
          />
        )}

        <Router className="app-page">
          <Setting
            path={`${pubilcUrl}/setting`}
            {...setting}
            cameraList={cameraList}
            wsConnected={wsConnected}
            onDisconnect={disconnect}
            onSubmit={changeSetting}
            saveServerConfig={saveServerConfig}
            resetServerConfig={resetServerConfig}
            resetChannel={resetChannel}
            serverConfig={serverConfig}
            changeVolume={changeVolume}
            changeMicVolume={changeMicVolume}
            volume={volume}
            micVolume={micVolume}
            updateVersion={updateVersion}
            updateStaus={updateStaus}
          />
          {wsConnected && (
            <Login path={`${pubilcUrl}/login`} onSubmit={login} />
          )}
          {isLogin ? (
            <>
              <Controller
                statusInfo={statusInfo}
                connectType={connectType}
                session={session}
                path={`${pubilcUrl}/controller`}
                controller={controller}
                lightEnabled={lightEnabled}
                cameraEnabled={cameraEnabled}
                action={action}
                powerEnabled={powerEnabled}
                onTTS={tts}
                playAudio={playAudio}
                ttsPlaying={ttsPlaying}
                setting={setting}
                saveServerConfig={saveServerConfig}
                serverConfig={serverConfig}
                changeChannel={changeChannel}
                editabled={editabled}
                cameraList={cameraList}
                channelStatus={gpioChannelStatus}
                isFullscreen={isFullscreen}
                webrtcChannel={webrtcChannel}
              />
            </>
          ) : undefined}
        </Router>
      </div>
    );
  }
Example #25
Source File: App.js    From AdaptivApps-fe with MIT License 4 votes vote down vote up
function App() {
  const { getIdTokenClaims } = useAuth0();
  const [authToken, setAuthToken] = useState();

  const request = async operation => {
    const token = await getIdTokenClaims();
    setAuthToken(token.__raw);
    operation.setContext(context => ({
      headers: {
        ...context.headers,
        Authorization: token.__raw,
      },
    }));
  };

  const requestLink = new ApolloLink(
    (operation, forward) =>
      new Observable(observer => {
        let handle;
        Promise.resolve(operation)
          .then(oper => {
            request(oper)
          })
          .then(() => {
            handle = forward(operation).subscribe({
              next: observer.next.bind(observer),
              error: observer.error.bind(observer),
              complete: observer.complete.bind(observer),
            });
          })
          .catch(observer.error.bind(observer));
        return () => {
          if (handle) handle.unsubscribe();
        };
      })
  );

  const httpLink = new HttpLink({ 
    uri: process.env.REACT_APP_API_URL,
    credentials: "same-origin", 
  });

  var location = window.location, new_uri;

  location.protocol === "https:" ? new_uri = "wss://" : new_uri = "ws://";

  const wsLink = new WebSocketLink({
    uri: `${new_uri}${process.env.REACT_APP_WS_URL}`,
    options: {
      reconnect: true,
      connectionParams: {
        authToken: authToken,
      }
    }
  });

  const link = split(
    // split based on operation type
    ({ query }) => {
      const { kind, operation } = getMainDefinition(query);
      return (
        kind === 'OperationDefinition' &&
        operation === 'subscription'
      );
    },
    wsLink,
    httpLink,
  );

  const client = new ApolloClient({
    link: ApolloLink.from([
      onError(({ graphQLErrors, networkError }) => {
        if (graphQLErrors)
          graphQLErrors.forEach(({ message, locations, path }) =>
            console.log(
              `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
            )
          );
        if (networkError) console.log(`[Network error]: ${networkError}`);
      }),
      requestLink,
      link
    ]),
    cache: new InMemoryCache(),
  });

  return (
    <ApolloProvider client={client}>
      <div className="App">
        <Router>
          <Accessibility path="/accessibility" />
          <PrivacyPolicy path="/privacy-policy" />
          <PrivateRoute path="/" component={DashRouter}>
            <UserProfile path="/" />
            <EventsCalendar path="calendar" />
            <ActivityList path="calendar/:eventId" />
            <MyEvents path="myevents" />
            <MyEventDetails path="myevents/:eventId" />
            <ManageEvents path="manage" />
            <ManageUsers path="users" />
            <ChatFeature path="chats" />
          </PrivateRoute>
        </Router>
      </div>
    </ApolloProvider>
  );
}
Example #26
Source File: App.js    From speed-spend with MIT License 4 votes vote down vote up
function Content({ userSession }) {
  const authenticated = userSession && userSession.isUserSignedIn();
  const decentralizedID =
    userSession && userSession.isUserSignedIn() && userSession.loadUserData().decentralizedID;
  return (
    <>
      {!authenticated && <Landing />}
      {decentralizedID && (
        <>
          <Router>
            <AppBody path="/">
              <Overview path="/" decentralizedID={decentralizedID} />
              <OverviewTokens path="/tokens" />
              <OverviewContracts path="/contracts" />
              <OverviewNFTs path="/nfts" />
              <OverviewPox path="/pox" />
              <SpeedSpend
                path="/speed-spend"
                decentralizedID={decentralizedID}
                userSession={userSession}
              />
              <Hodl path="/hodl" decentralizedID={decentralizedID} userSession={userSession} />
              <HodlTokens
                path="/hodl-tokens"
                decentralizedID={decentralizedID}
                userSession={userSession}
              />
              <Jackpot
                path="/jackpot"
                decentralizedID={decentralizedID}
                userSession={userSession}
              />
              <AtTwo path="/at-two" decentralizedID={decentralizedID} userSession={userSession} />
              <SendMany
                path="/send-many"
                decentralizedID={decentralizedID}
                userSession={userSession}
              />
              <Monsters
                exact
                path="/monsters"
                decentralizedID={decentralizedID}
                userSession={userSession}
              />
              <StacksPops
                exact
                path="/stackspops"
                decentralizedID={decentralizedID}
                userSession={userSession}
              />
              <Marketplace
                exact
                path="/openriff"
                decentralizedID={decentralizedID}
                userSession={userSession}
              />
              <MonsterDetails
                path="/monsters/:monsterId"
                decentralizedID={decentralizedID}
                userSession={userSession}
              />
              <Rockets
                path="/rockets"
                decentralizedID={decentralizedID}
                userSession={userSession}
              />
              <RocketDetails
                path="/rockets/:rocketId"
                decentralizedID={decentralizedID}
                userSession={userSession}
              />
              <PoolRegistry
                path="/pools"
                decentralizedID={decentralizedID}
                userSession={userSession}
              />
              <PoolDetails
                path="/pools/join/:poolAddress"
                decentralizedID={decentralizedID}
                userSession={userSession}
              />
              <PoolDetails
                path="/pools/:poolId"
                decentralizedID={decentralizedID}
                userSession={userSession}
              />
              <PoolAudit
                path="/pool-audit"
                decentralizedID={decentralizedID}
                userSession={userSessionState}
              />
              <Swap path="/swap" decentralizedID={decentralizedID} userSession={userSessionState} />
              <PoxLite
                path="/poxlite"
                decentralizedID={decentralizedID}
                userSession={userSession}
              />
              <MyProfile path="/me" decentralizedID={decentralizedID} userSession={userSession} />
              <ClarityValues path="/cv" />
              <AddressConversion path="/addresses" />
              <Gaia path="/gaia" userSession={userSession} />
              <StackingActivies path="/stacking"></StackingActivies>
            </AppBody>
          </Router>
        </>
      )}
    </>
  );
}
Example #27
Source File: App.js    From testnets-cardano-org with MIT License 4 votes vote down vote up
App = ({ element }) => {
  function languageOnUpdate ({ lang, prevLang }) {
    if (prevLang && lang !== prevLang) {
      navigate(`/${lang}/`)
      analytics.autoCapture({ category: analytics.constants.LANGUAGE, action: 'language_updated', label: lang })
    }
  }

  function themeOnUpdate ({ theme, prevTheme }) {
    if (prevTheme && theme !== prevTheme) analytics.autoCapture({ category: analytics.constants.THEME, action: 'theme_updated', label: theme })
  }

  function getRoutes (lang) {
    const routes = config.routes.map(({ path, component, props }) => {
      const Component = require(`./routes/${component}.js`).default
      const routes = [ <Component {...props} path={path} key={path} /> ]
      if (config.localization.createLocalizedPages && config.localization.createDefaultPages) {
        routes.push(<Component {...props} key={`/${lang}${path}`} path={`/${lang}${path}`} />)
      }

      return routes
    })

    return routes.reduce((accumulator, currentValue) => [ ...accumulator, ...currentValue ], [])
  }

  return (
    <Location>
      {({ location: { pathname, search, hash } }) => (
        <Language.Provider
          location={{ pathname, search, hash }}
          availableLanguages={config.availableLanguages}
          alternativeLanguages={config.alternativeLanguages}
          onUpdate={languageOnUpdate}
          useURL={config.localization.useURL}
          useNavigator={config.localization.useNavigator}
          persistLang={config.localization.persistLang}
        >
          <Theme.Provider
            themes={getThemes()}
            onUpdate={themeOnUpdate}
            transformTheme={({ config }) => theme.convertThemeToMaterial(config)}
          >
            <Search.Provider>
              <Theme.Consumer>
                {({ theme, originalTheme }) => (
                  <MaterialUIThemeProvider theme={theme}>
                    <StyledThemeProvider theme={theme}>
                      <Language.Consumer>
                        {({ key: lang }) => (
                          <LinkProvider
                            lang={lang}
                            component={Link}
                            isStatic={href => {
                              if (href.match(/^blob:/)) return true
                              return false
                            }}
                          >
                            <MarkdownProvider
                              markdownProps={{
                                renderers: {
                                  code: theme.type === 'dark' ? DarkCodeRenderer : LightCodeRenderer,
                                  link: IOHKLink
                                }
                              }}
                            >
                              <Styles theme={originalTheme.config} />
                              <Style />
                              <Header />
                              <Router>
                                {getRoutes(lang)}
                                <DefaultRoute default element={element} />
                              </Router>
                              <Zendesk zendeskKey={config.zendeskKey} color={{ theme: theme.colors.primary.main }} />
                            </MarkdownProvider>
                          </LinkProvider>
                        )}
                      </Language.Consumer>
                    </StyledThemeProvider>
                  </MaterialUIThemeProvider>
                )}
              </Theme.Consumer>
            </Search.Provider>
          </Theme.Provider>
        </Language.Provider>
      )}
    </Location>
  )
}
Example #28
Source File: production-app.js    From cybsec with GNU Affero General Public License v3.0 4 votes vote down vote up
// Let the site/plugins run code very early.
apiRunnerAsync(`onClientEntry`).then(() => {
  // Let plugins register a service worker. The plugin just needs
  // to return true.
  if (apiRunner(`registerServiceWorker`).length > 0) {
    require(`./register-service-worker`)
  }

  class RouteHandler extends React.Component {
    render() {
      let { location } = this.props

      return (
        <EnsureResources location={location}>
          {({ pageResources, location }) => (
            <RouteUpdates location={location}>
              <ScrollContext
                location={location}
                shouldUpdateScroll={shouldUpdateScroll}
              >
                <PageRenderer
                  {...this.props}
                  location={location}
                  pageResources={pageResources}
                  {...pageResources.json}
                />
              </ScrollContext>
            </RouteUpdates>
          )}
        </EnsureResources>
      )
    }
  }

  const { page, location: browserLoc } = window
  if (
    // Make sure the window.page object is defined
    page &&
    // The canonical path doesn't match the actual path (i.e. the address bar)
    __PATH_PREFIX__ + page.path !== browserLoc.pathname &&
    // ...and if matchPage is specified, it also doesn't match the actual path
    (!page.matchPath ||
      !match(__PATH_PREFIX__ + page.matchPath, browserLoc.pathname)) &&
    // Ignore 404 pages, since we want to keep the same URL
    page.path !== `/404.html` &&
    !page.path.match(/^\/404\/?$/) &&
    // Also ignore the offline shell (since when using the offline plugin, all
    // pages have this canonical path)
    !page.path.match(/^\/offline-plugin-app-shell-fallback\/?$/)
  ) {
    navigate(
      __PATH_PREFIX__ + page.path + browserLoc.search + browserLoc.hash,
      { replace: true }
    )
  }

  loader.getResourcesForPathname(browserLoc.pathname).then(() => {
    const Root = () =>
      createElement(
        Router,
        {
          basepath: __PATH_PREFIX__,
        },
        createElement(RouteHandler, { path: `/*` })
      )

    const WrappedRoot = apiRunner(
      `wrapRootElement`,
      { element: <Root /> },
      <Root />,
      ({ result }) => {
        return { element: result }
      }
    ).pop()

    let NewRoot = () => WrappedRoot

    const renderer = apiRunner(
      `replaceHydrateFunction`,
      undefined,
      ReactDOM.hydrate
    )[0]

    domReady(() => {
      renderer(
        <NewRoot />,
        typeof window !== `undefined`
          ? document.getElementById(`___gatsby`)
          : void 0,
        () => {
          postInitialRenderWork()
          apiRunner(`onInitialClientRender`)
        }
      )
    })
  })
})