@mui/material#ThemeProvider TypeScript Examples

The following examples show how to use @mui/material#ThemeProvider. 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: Theme.tsx    From wallet-adapter with Apache License 2.0 6 votes vote down vote up
Theme: FC<{ children: ReactNode }> = ({ children }) => {
    return (
        <StyledEngineProvider injectFirst>
            <ThemeProvider theme={theme}>
                <SnackbarProvider>{children}</SnackbarProvider>
            </ThemeProvider>
        </StyledEngineProvider>
    );
}
Example #2
Source File: _app.tsx    From Cromwell with MIT License 6 votes vote down vote up
function App(props: AppPropsWithLayout) {
    const { Component, emotionCache = clientSideEmotionCache } = props;
    const getLayout = Component.getLayout ?? ((page) => page);
    const cmsProps: TPageCmsProps | undefined = props.pageProps?.cmsProps;
    const theme = getTheme(cmsProps?.palette);

    return (
        <CacheProvider value={emotionCache}>
            <ThemeProvider theme={theme}>
                {getLayout(<>
                    {Component && <Component {...(props.pageProps ?? {})} />}
                    {!isServer() && document?.body && ReactDOM.createPortal(
                        <div className={"global-toast"} ><ToastContainer /></div>, document.body)}
                </>)}
            </ThemeProvider>
        </CacheProvider>
    );
}
Example #3
Source File: Theme.tsx    From GTAV-NativeDB with MIT License 6 votes vote down vote up
function Theme({ children }: { children: ReactNode }) {
  const settings = useSettings()
  const systemIsDark = useMediaQuery('(prefers-color-scheme: dark)')
  const dark = settings.theme === 'dark' || (settings.theme === 'system' && systemIsDark)
  const theme = useMemo(
    () => createTheme(dark ? darkTheme : lightTheme),
    [dark]
  )

  useEffect(() => {
    document.querySelector('meta[name="theme-color"]')
      ?.setAttribute('content', dark ? '#272727' :'#0e752e')
  }, [dark])

  return (
    <ThemeProvider theme={theme}>
      {children}
    </ThemeProvider>
  )
}
Example #4
Source File: ContextProvider.tsx    From wallet-adapter with Apache License 2.0 6 votes vote down vote up
ContextProvider: FC<{ children: ReactNode }> = ({ children }) => {
    return (
        <StyledEngineProvider injectFirst>
            <ThemeProvider theme={theme}>
                <SnackbarProvider>
                    <AutoConnectProvider>
                        <WalletContextProvider>{children}</WalletContextProvider>
                    </AutoConnectProvider>
                </SnackbarProvider>
            </ThemeProvider>
        </StyledEngineProvider>
    );
}
Example #5
Source File: theme-provider.component.tsx    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
ThemeProviderComponent = (props) => {
  const { children } = props;

  return (
    <CacheProvider value={cache}>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        {children}
      </ThemeProvider>
    </CacheProvider>
  );
}
Example #6
Source File: index.tsx    From example with MIT License 6 votes vote down vote up
ReactDOM.render(
  <React.StrictMode>
      <CssBaseline />
      <ThemeProvider theme={appTheme}>
          <BrowserRouter>
              <App />
          </BrowserRouter>
      </ThemeProvider>
  </React.StrictMode>,
  document.getElementById('root')
);
Example #7
Source File: main.tsx    From rewind with MIT License 6 votes vote down vote up
ReactDOM.render(
  <StrictMode>
    <AppInfoProvider appInfo={appInfo}>
      <TheaterProvider theater={theater}>
        <ThemeProvider theme={RewindTheme}>
          <CssBaseline />
          <WebTestApp />
        </ThemeProvider>
      </TheaterProvider>
    </AppInfoProvider>
  </StrictMode>,

  document.getElementById("root"),
);
Example #8
Source File: LegendStyleProvider.tsx    From legend-studio with Apache License 2.0 6 votes vote down vote up
LegendStyleProvider: React.FC<{
  children: React.ReactNode;
}> = (props) => {
  const { children } = props;

  return (
    // Make sure CSS for MUI generated by `emotion` are injected before our styling code
    // this ensures our styling code can override MUI styles
    // See https://mui.com/guides/interoperability/#css-injection-order-3
    <StyledEngineProvider injectFirst={true}>
      <ThemeProvider theme={LegendCustomMUITheme}>{children}</ThemeProvider>
    </StyledEngineProvider>
  );
}
Example #9
Source File: Style.tsx    From multi-downloader-nx with MIT License 5 votes vote down vote up
Style: React.FC = ({children}) => {
  return <ThemeProvider theme={makeTheme('dark')}>
    <Container sx={{ mt: 3 }} maxWidth='xl'>
      <Box sx={{ position: 'fixed', height: '100%', width: '100%', zIndex: -500, backgroundColor: 'rgb(0, 30, 60)', top: 0, left: 0 }}/>
      {children}
    </Container>
  </ThemeProvider>;
}
Example #10
Source File: index.tsx    From Search-Next with GNU General Public License v3.0 5 votes vote down vote up
Table: React.FC<TableProps> = (props) => {
  const {
    dataSource,
    columns,
    height = 300,
    disableSelectionOnClick = true,
    exportBtn = false,
    pagination,
    pageinationConfig,
  } = props;
  const [pageConfig, setPageConfig] = useState({
    current: 1,
    pageSize: 10,
    pageSizeOptions: [10, 20, 40],
  } as PageinationConfig);

  const theme = createTheme(
    {
      palette: {
        primary: { main: '#1976d2' },
      },
    },
    zhCN,
  );

  const CustomToolbar = () => {
    return (
      <GridToolbarContainer className={gridClasses.toolbarContainer}>
        {exportBtn && <GridToolbarExport />}
      </GridToolbarContainer>
    );
  };

  useEffect(() => {
    if (pageinationConfig) setPageConfig(pageinationConfig);
  }, [pageinationConfig]);

  return (
    <div style={{ height }}>
      <div style={{ display: 'flex', height: '100%' }}>
        <div style={{ flexGrow: 1 }}>
          <ThemeProvider theme={theme}>
            <DataGrid
              disableSelectionOnClick={disableSelectionOnClick}
              rows={dataSource}
              columns={columns}
              components={{
                Toolbar: CustomToolbar,
              }}
            />
          </ThemeProvider>
        </div>
      </div>
    </div>
  );
}
Example #11
Source File: AppThemeProvider.tsx    From mui-toolpad with MIT License 5 votes vote down vote up
export default function AppThemeProvider({ node, children }: ThemeProviderProps) {
  const theme = React.useMemo(() => createToolpadTheme(node), [node]);
  return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
}
Example #12
Source File: App.tsx    From genshin-optimizer with MIT License 5 votes vote down vote up
function App() {
  const [database, setDatabase] = useState(() => new ArtCharDatabase(new DBLocalStorage(localStorage)))
  const dbContextObj = useMemo(() => ({ database, setDatabase }), [database, setDatabase])
  return <React.StrictMode>
    {/* https://mui.com/guides/interoperability/#css-injection-order-2 */}
    <StyledEngineProvider injectFirst>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <DatabaseContext.Provider value={dbContextObj}>
          <HashRouter basename="/">
            <MatchTitle />
            <Grid container direction="column" minHeight="100vh">
              <Grid item >
                <Header anchor="back-to-top-anchor" />
              </Grid>
              <Container maxWidth="xl" sx={{ px: { xs: 0.5, sm: 1, md: 2 } }}>
                <Suspense fallback={<Skeleton variant="rectangular" sx={{ width: "100%", height: "100%" }} />}>
                  <Routes>
                    <Route index element={<PageHome />} />
                    <Route path="/artifacts" element={<PageArtifact />} />
                    <Route path="/weapons" element={<PageWeapon />} />
                    <Route path="/characters/*"  >
                      <Route index element={<PageCharacter />} />
                      <Route path=":characterKey/*" element={<CharacterDisplay />} />
                    </Route>
                    <Route path="/tools" element={<PageTools />} />
                    <Route path="/setting" element={<PageSettings />} />
                    <Route path="/doc/*" element={<PageDocumentation />} />
                    <Route path="/scanner" element={<PageScanner />} />
                  </Routes>
                </Suspense>
              </Container>
              {/* make sure footer is always at bottom */}
              <Grid item flexGrow={1} />
              <Grid item >
                <Footer />
              </Grid>
            </Grid>
            <ScrollTop >
              <Fab color="secondary" size="small" aria-label="scroll back to top">
                <KeyboardArrowUp />
              </Fab>
            </ScrollTop>
          </HashRouter>
        </DatabaseContext.Provider>
      </ThemeProvider>
    </StyledEngineProvider>
  </React.StrictMode>
}
Example #13
Source File: preview.tsx    From react-hook-form-mui with MIT License 5 votes vote down vote up
decorators = [(Story: Story) => (
  <CacheProvider value={clientSideEmotionCache}>
    <ThemeProvider theme={theme}>
      <Suspense fallback={<div>loading</div>}><Story /></Suspense>
    </ThemeProvider>
  </CacheProvider>
)]
Example #14
Source File: _app.tsx    From fluttertemplates.dev with MIT License 5 votes vote down vote up
function MyApp({ Component, pageProps }: AppProps) {
  const [darkMode, setDarkMode] = useState<boolean>(false);

  useEffect(() => {
    const _item = localStorage.getItem("darkMode") ?? "false";
    setDarkMode(JSON.parse(_item));

    // Remove the server-side injected CSS.
    const jssStyles = document.querySelector("#jss-server-side");
    if (jssStyles) {
      jssStyles.parentElement?.removeChild(jssStyles);
    }
  }, []);

  const theme: Theme = useMemo(
    () =>
      createTheme({
        palette: {
          mode: darkMode ? "dark" : "light",
          primary: {
            main: darkMode ? "#222432" : "#ffffff",
          },
          secondary: {
            main: darkMode ? "#0468d7" : "#0468d7",
          },
          background: {
            default: darkMode ? "#222432" : "#ffffff",
            paper: darkMode ? "#22293d" : "#f1f3f4",
          },
        },
      }),
    [darkMode]
  );

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline enableColorScheme />

      <Header
        isDarkMode={darkMode}
        onThemeChange={() => {
          localStorage.setItem("darkMode", (!darkMode).toString());
          setDarkMode(!darkMode);
        }}
      />
      <div
        style={{
          minHeight: "80vh",
        }}
      >
        <Component {...pageProps} />
      </div>

      <SubmitProposalSection />

      <Footer />
    </ThemeProvider>
  );
}
Example #15
Source File: main.tsx    From rewind with MIT License 5 votes vote down vote up
async function initialize() {
  let api: FrontendPreloadAPI;
  if (window.api) {
    api = window.api;
  } else {
    api = {
      getAppVersion: () => Promise.resolve(environment.appVersion),
      getPlatform: () => Promise.resolve(environment.platform),
      reboot: () => console.log("Rebooting ..."),
      selectDirectory: () => Promise.resolve("C:\\Mocked\\Path"),
      selectFile: () => Promise.resolve("C:\\Mocked\\File.osr"),
      onManualReplayOpen: (listener) => console.log(`Registered a listener for opening replay files manually`),
    };
  }
  const [appVersion, platform] = await Promise.all([api.getAppVersion(), api.getPlatform()]);
  const appInfo = { appVersion, platform };

  console.log(`Initializing with version=${appVersion} on platform=${platform}`);

  api.onManualReplayOpen((file) => {
    // todo: refactor
    // Changes to the analyzer page
    store.dispatch(push("/analyzer"));
    theater.analyzer.loadReplay(`local:${file}`);
  });

  ReactDOM.render(
    <StrictMode>
      <AppInfoProvider appInfo={appInfo}>
        <Provider store={store}>
          <ConnectedRouter history={history}>
            <ThemeProvider theme={RewindTheme}>
              <CssBaseline />
              <TheaterProvider theater={theater}>
                <RewindApp />
              </TheaterProvider>
            </ThemeProvider>
          </ConnectedRouter>
        </Provider>
      </AppInfoProvider>
    </StrictMode>,
    document.getElementById("root"),
  );

  // This starts off with /splash -> Maybe do it somewhere else?
  store.dispatch(push("/splash"));
}
Example #16
Source File: App.tsx    From abrechnung with GNU Affero General Public License v3.0 5 votes vote down vote up
export default function App() {
    const darkModeSystem = useMediaQuery("(prefers-color-scheme: dark)");
    const userThemeSettings = useRecoilValue(themeSettings);

    const useDarkMode: PaletteMode =
        userThemeSettings.darkMode === "browser" ? (darkModeSystem ? "dark" : "light") : userThemeSettings.darkMode;

    const theme = useMemo(
        () =>
            createTheme({
                palette: {
                    mode: useDarkMode,
                },
            }),
        [useDarkMode]
    );

    return (
        <StyledEngineProvider injectFirst>
            <ThemeProvider theme={theme}>
                <CssBaseline />
                <LocalizationProvider dateAdapter={DateAdapter}>
                    <ToastContainer
                        position="top-right"
                        autoClose={5000}
                        hideProgressBar={false}
                        newestOnTop={false}
                        closeOnClick
                        rtl={false}
                        pauseOnFocusLoss
                        draggable
                        pauseOnHover
                    />
                    <Router>
                        <Switch>
                            {routes.map((route) => {
                                const authRoute = route.auth ? (
                                    <AuthenticatedRoute>{route.component}</AuthenticatedRoute>
                                ) : (
                                    route.component
                                );

                                const layoutRoute =
                                    route.layout === undefined || route.layout ? (
                                        <Layout>
                                            <Suspense fallback={<Loading />}>{authRoute}</Suspense>
                                        </Layout>
                                    ) : (
                                        <Suspense fallback={<Loading />}>{authRoute}</Suspense>
                                    );

                                return (
                                    <Route
                                        key={route.path}
                                        exact={route.exact !== undefined && route.exact}
                                        path={route.path}
                                    >
                                        {layoutRoute}
                                    </Route>
                                );
                            })}
                        </Switch>
                    </Router>
                </LocalizationProvider>
            </ThemeProvider>
        </StyledEngineProvider>
    );
}
Example #17
Source File: App.tsx    From ExpressLRS-Configurator with GNU General Public License v3.0 5 votes vote down vote up
export default function App() {
  const {
    networkDevices,
    newNetworkDevices,
    removeDeviceFromNewList,
  } = useNetworkDevices();

  const [device, setDevice] = useState<string | null>('');

  const onDeviceChange = useCallback(
    (dnsDevice: MulticastDnsInformation | null) => {
      const dnsDeviceName = dnsDevice?.name ?? null;
      setDevice(dnsDeviceName);
      if (dnsDevice) {
        const dnsDeviceType = dnsDevice.type.toUpperCase();
        if (dnsDeviceType === 'TX' || dnsDeviceType === 'RX') {
          window.location.href = '#/configurator';
        } else if (dnsDeviceType === 'TXBP' || dnsDeviceType === 'VRX') {
          window.location.href = '#/backpack';
        }
      }
    },
    []
  );

  return (
    <StyledEngineProvider injectFirst>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <ApolloProvider client={client}>
          <AppStateProvider>
            <HashRouter>
              <Routes>
                <Route
                  path="/"
                  element={<Navigate replace to="/configurator" />}
                />
                <Route
                  path="/configurator"
                  element={
                    <ConfiguratorView
                      key="configurator"
                      gitRepository={Config.expressLRSGit}
                      selectedDevice={device}
                      networkDevices={networkDevices}
                      onDeviceChange={onDeviceChange}
                      deviceType={DeviceType.ExpressLRS}
                    />
                  }
                />
                <Route
                  path="/backpack"
                  element={
                    <ConfiguratorView
                      key="backpack"
                      gitRepository={Config.backpackGit}
                      selectedDevice={device}
                      networkDevices={networkDevices}
                      onDeviceChange={onDeviceChange}
                      deviceType={DeviceType.Backpack}
                    />
                  }
                />
                <Route path="/settings" element={<SettingsView />} />
                <Route path="/logs" element={<LogsView />} />
                <Route path="/serial-monitor" element={<SerialMonitorView />} />
                <Route path="/support" element={<SupportView />} />
              </Routes>
            </HashRouter>
            <WifiDeviceNotification
              newNetworkDevices={newNetworkDevices}
              removeDeviceFromNewList={removeDeviceFromNewList}
              onDeviceChange={onDeviceChange}
            />
          </AppStateProvider>
        </ApolloProvider>
      </ThemeProvider>
    </StyledEngineProvider>
  );
}
Example #18
Source File: CustomCMSApp.tsx    From firecms with MIT License 4 votes vote down vote up
/**
 * This is an example of how to use the components provided by FireCMS for
 * a better customisation.
 * @constructor
 */
export function CustomCMSApp() {

    const signInOptions = DEFAULT_SIGN_IN_OPTIONS;

    const navigation: NavigationBuilder = ({ user }: NavigationBuilderProps) => ({
        collections: [
            buildCollection({
                path: "products",
                schema: productSchema,
                name: "Products",
                permissions: ({ user }) => ({
                    edit: true,
                    create: true,
                    delete: true
                })
            })
        ]
    });

    const myAuthenticator: Authenticator = ({ user }) => {
        console.log("Allowing access to", user?.email);
        return true;
    };

    const {
        firebaseApp,
        firebaseConfigLoading,
        configError,
        firebaseConfigError
    } = useInitialiseFirebase({ firebaseConfig });

    const authDelegate: FirebaseAuthDelegate = useFirebaseAuthDelegate({
        firebaseApp,
        signInOptions
    });

    const dataSource = useFirestoreDataSource({
        firebaseApp: firebaseApp
        // You can add your `FirestoreTextSearchController` here
    });
    const storageSource = useFirebaseStorageSource({ firebaseApp: firebaseApp });

    if (configError) {
        return <div> {configError} </div>;
    }

    if (firebaseConfigError) {
        return <div>
            It seems like the provided Firebase config is not correct. If you
            are using the credentials provided automatically by Firebase
            Hosting, make sure you link your Firebase app to Firebase
            Hosting.
        </div>;
    }

    if (firebaseConfigLoading || !firebaseApp) {
        return <CircularProgressCenter/>;
    }

    return (
        <Router>
            <FireCMS navigation={navigation}
                     authDelegate={authDelegate}
                     authentication={myAuthenticator}
                     dataSource={dataSource}
                     storageSource={storageSource}
                     entityLinkBuilder={({ entity }) => `https://console.firebase.google.com/project/${firebaseApp.options.projectId}/firestore/data/${entity.path}/${entity.id}`}
            >
                {({ context, mode, loading }) => {

                    const theme = createCMSDefaultTheme({ mode });

                    let component;
                    if (loading) {
                        component = <CircularProgressCenter/>;
                    } else if (!context.authController.canAccessMainView) {
                        component = (
                            <FirebaseLoginView
                                allowSkipLogin={false}
                                signInOptions={signInOptions}
                                firebaseApp={firebaseApp}
                                authDelegate={authDelegate}/>
                        );
                    } else {
                        component = (
                            <Scaffold name={"My Online Shop"}>
                                <NavigationRoutes/>
                                <SideEntityDialogs/>
                            </Scaffold>
                        );
                    }

                    return (
                        <ThemeProvider theme={theme}>
                            <CssBaseline/>
                            {component}
                        </ThemeProvider>
                    );
                }}
            </FireCMS>
        </Router>
    );

}
Example #19
Source File: CallOverlay.tsx    From airmessage-web with Apache License 2.0 4 votes vote down vote up
export default function CallOverlay() {
	const displaySnackbar = useContext(SnackbarContext);
	const existingTheme = useTheme();
	const existingThemeMode = existingTheme.palette.mode;
	
	//Invert theme
	const theme = useMemo(() => {
		return createTheme({
			palette: {
				mode: existingThemeMode === "light" ? "dark" : "light",
				messageIncoming: undefined,
				messageOutgoing: undefined,
				messageOutgoingTextMessage: undefined
			}
		});
	}, [existingThemeMode]);
	
	//Subscribe to incoming caller updates
	const [incomingCaller, setIncomingCaller] = useState<string | undefined>(undefined);
	useEffect(() => {
		ConnectionManager.incomingCallerEmitter.registerListener((caller) => {
			//Update the caller state
			setIncomingCaller(caller);
			
			//Display a notification
			getNotificationUtils().updateCallerNotification(caller);
		});
		return () => ConnectionManager.incomingCallerEmitter.unregisterListener(setIncomingCaller);
	}, [setIncomingCaller]);
	
	//Subscribe to outgoing callee updates
	const [outgoingCallee, setOutgoingCallee] = useState<string[] | undefined>(undefined);
	useEffect(() => {
		ConnectionManager.outgoingCalleeEmitter.registerListener(setOutgoingCallee);
		return () => ConnectionManager.outgoingCalleeEmitter.unregisterListener(setOutgoingCallee);
	}, [setOutgoingCallee]);
	
	const [outgoingCalleeReadable, setOutgoingCalleeReadable] = useState<string>("");
	useEffect(() => {
		//Ignore if there is no outgoing callee
		if(outgoingCallee === undefined) {
			setOutgoingCalleeReadable("");
			return;
		}
		
		//Set a quick title by joining the member's addresses
		setOutgoingCalleeReadable(buildListString(outgoingCallee));
		
		//Look up the member's names to build the title
		let invalidated = false;
		getMemberTitle(outgoingCallee).then((title) => {
			if(invalidated) return;
			setOutgoingCalleeReadable(title);
		});
		
		return () => {
			invalidated = true;
		};
	}, [outgoingCallee, setOutgoingCalleeReadable]);
	
	//Set to true between the time that we have responded to an incoming call, and the server has yet to answer our message
	const [incomingCallLoading, setIncomingCallLoading] = useState(false);
	useEffect(() => {
		//When the incoming caller changes, reset the loading state
		setIncomingCallLoading(false);
	}, [incomingCaller, setIncomingCallLoading]);
	
	const declineIncomingCall = useCallback(() => {
		setIncomingCallLoading(true);
		ConnectionManager.handleIncomingFaceTimeCall(incomingCaller!, false);
	}, [setIncomingCallLoading, incomingCaller]);
	
	const acceptIncomingCall = useCallback(() => {
		setIncomingCallLoading(true);
		ConnectionManager.handleIncomingFaceTimeCall(incomingCaller!, true);
	}, [setIncomingCallLoading, incomingCaller]);
	
	const [outgoingCallLoading, setOutgoingCallLoading] = useState(false);
	useEffect(() => {
		//When the outgoing callee changes, reset the loading state
		setOutgoingCallLoading(false);
	}, [outgoingCallee, setOutgoingCallLoading]);
	
	const cancelOutgoingCall = useCallback(() => {
		setOutgoingCallLoading(true);
		ConnectionManager.dropFaceTimeCallServer();
	}, [setOutgoingCallLoading]);
	
	const [errorDetailsDisplay, setErrorDetailsDisplay] = useState<string | undefined>(undefined);
	
	//Subscribe to event updates
	useEffect(() => {
		const listener = (event: CallEvent) => {
			switch(event.type) {
				case "outgoingAccepted":
				case "incomingHandled":
					//Open the FaceTime link in a new tab
					window.open(event.faceTimeLink, "_blank");
					break;
				case "outgoingError":
				case "incomingHandleError":
					//Let the user know that something went wrong
					displaySnackbar({
						message: "Your call couldn't be completed",
						action: (
							<Button onClick={() => setErrorDetailsDisplay(event.errorDetails)}>
								Details
							</Button>
						),
					});
					break;
			}
		};
		
		ConnectionManager.callEventEmitter.registerListener(listener);
		return () => ConnectionManager.callEventEmitter.unregisterListener(listener);
	}, [displaySnackbar, setErrorDetailsDisplay]);
	
	return (<>
		<ThemeProvider theme={theme}>
			<Stack sx={{
				position: "absolute",
				top: 0,
				right: 0,
				padding: 1
			}} spacing={1}>
				{incomingCaller !== undefined && (
					<CallNotificationIncoming
						caller={incomingCaller}
						onDecline={declineIncomingCall}
						onAccept={acceptIncomingCall}
						loading={incomingCallLoading} />
				)}
				
				{outgoingCallee !== undefined && (
					<CallNotificationOutgoing
						callee={outgoingCalleeReadable}
						onCancel={cancelOutgoingCall}
						loading={outgoingCallLoading} />
				)}
			</Stack>
		</ThemeProvider>
		
		<Dialog
			open={errorDetailsDisplay !== undefined}
			onClose={() => setErrorDetailsDisplay(undefined)}>
			<DialogTitle>Call error details</DialogTitle>
			<DialogContent>
				<DialogContentText>
					{errorDetailsDisplay}
				</DialogContentText>
			</DialogContent>
			<DialogActions>
				<Button onClick={() => setErrorDetailsDisplay(undefined)} color="primary">
					OK
				</Button>
			</DialogActions>
		</Dialog>
	</>);
}
Example #20
Source File: _app.tsx    From frontend with MIT License 4 votes vote down vote up
function CustomApp({
  Component,
  emotionCache = clientSideEmotionCache,
  pageProps: { session, dehydratedState, ...pageProps },
}: CustomAppProps) {
  const router = useRouter()
  const { i18n } = useTranslation()
  const { initialize, trackEvent } = useGTM()
  const onError = useCallback((error: unknown) => {
    if (error && isAxiosError(error)) {
      // Redirect to login
      if (error.response?.status === 401) {
        router.push({
          pathname: routes.login,
          query: { callbackUrl: router.asPath },
        })
      }
    }
  }, [])

  const [queryClient] = React.useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            queryFn,
            onError,
            staleTime: 25000,
          },
          mutations: { onError },
        },
      }),
  )

  useEffect(() => {
    // Init GTM
    initialize({
      events: { user_lang: i18n.language },
    })
  }, [])

  // Register route change complete event handlers
  useEffect(() => {
    const onRouteChange = (url: string) => {
      trackEvent({
        event: 'page_view',
        user_lang: i18n.language,
        page_title: document.title,
        page_pathname: url,
        page_location:
          document.location.protocol +
          '//' +
          document.location.hostname +
          document.location.pathname +
          document.location.search,
      })
    }

    router.events.on('routeChangeComplete', onRouteChange)
    return () => router.events.off('routeChangeComplete', onRouteChange)
  }, [i18n.language])

  return (
    <CacheProvider value={emotionCache}>
      <Head>
        <title>Podkrepi.bg</title>
        <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
      </Head>
      <ThemeProvider theme={theme}>
        {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
        <CssBaseline />
        <SessionProvider session={session} refetchInterval={60}>
          <QueryClientProvider client={queryClient}>
            <Hydrate state={dehydratedState}>
              <Component {...pageProps} />
            </Hydrate>
          </QueryClientProvider>
        </SessionProvider>
      </ThemeProvider>
    </CacheProvider>
  )
}
Example #21
Source File: Layout.tsx    From Cromwell with MIT License 4 votes vote down vote up
function Layout() {
  const forceUpdate = useForceUpdate();
  setStoreItem('forceUpdatePage', forceUpdate);

  onStoreChange('userInfo', (user) => {
    if (user && user.role !== userRole) {
      userRole = user.role;
      forceUpdate();
    }
  });

  useEffect(() => {
    store.setStateProp({
      prop: 'forceUpdateApp',
      payload: forceUpdate,
    });
  }, []);

  const darkMode = getStoreItem('theme')?.mode === 'dark';

  document.body.classList.remove('modeDark', 'modeLight');
  document.body.classList.add(darkMode ? 'modeDark' : 'modeLight');

  const theme = createTheme(darkMode ? {
    palette: {
      primary: {
        main: '#9747d3',
        light: '#9747d3',
        dark: '#8228c5',
      },
      secondary: {
        main: '#910081',
        light: '#910081',
        dark: '#910081',
      }
    },
  } : {
    palette: {
      primary: {
        main: '#8228c5',
        light: '#8561c5',
        dark: '#482880',
      },
      secondary: {
        main: '#910081',
        light: '#910081',
        dark: '#910081',
      }
    },
  });

  return (
    <ThemeProvider theme={theme}>
      <div className={clsx(styles.Layout)}>
        <BrowserRouter basename={'admin'}>
          <div className={styles.sidebar}>
            <Sidebar />
          </div>
          <div className={styles.main}>
            <Toolbar className={styles.dummyToolbar} />
            <Switch>
              {getPageInfos().map(page => {
                if (page.roles && !page.roles.includes(getStoreItem('userInfo')?.role))
                  return null;
                return (
                  <Route exact={!page.baseRoute}
                    path={page.route}
                    key={page.name}
                    component={(props: RouteComponentProps) => {
                      return (
                        <PageErrorBoundary>
                          <Suspense fallback={/*<LoadBox />*/<></>}>
                            <page.component {...props} />
                          </Suspense>
                        </PageErrorBoundary>
                      )
                    }}
                  />
                )
              })}
              <Route key={'404'} >
                <Page404 />
              </Route>
            </Switch>
          </div>
        </BrowserRouter>
        {document?.body && ReactDOM.createPortal(
          <div className={styles.toastContainer} ><ToastContainer /></div>, document.body)}
        <FileManager />
        <ConfirmPrompt />
        <LayoutPortal />
      </div>
    </ThemeProvider>
  );
}
Example #22
Source File: FirebaseCMSApp.tsx    From firecms with MIT License 4 votes vote down vote up
/**
 * This is the default implementation of a FireCMS app using the Firebase services
 * as a backend.
 * You can use this component as a full app, by specifying collections and
 * entity schemas.
 *
 * This component is in charge of initialising Firebase, with the given
 * configuration object.
 *
 * If you are building a larger app and need finer control, you can use
 * {@link FireCMS}, {@link Scaffold}, {@link SideEntityDialogs}
 * and {@link NavigationRoutes} instead.
 *
 * @param props
 * @constructor
 * @category Firebase
 */
export function FirebaseCMSApp({
                                   name,
                                   logo,
                                   toolbarExtraWidget,
                                   authentication,
                                   schemaOverrideHandler,
                                   navigation,
                                   textSearchController,
                                   allowSkipLogin,
                                   signInOptions = DEFAULT_SIGN_IN_OPTIONS,
                                   firebaseConfig,
                                   onFirebaseInit,
                                   primaryColor,
                                   secondaryColor,
                                   fontFamily,
                                   dateTimeFormat,
                                   locale,
                                   HomePage,
                                   basePath,
                                   baseCollectionPath,
                                   LoginViewProps
                               }: FirebaseCMSAppProps) {

    const {
        firebaseApp,
        firebaseConfigLoading,
        configError,
        firebaseConfigError
    } = useInitialiseFirebase({ onFirebaseInit, firebaseConfig });

    const authDelegate: FirebaseAuthDelegate = useFirebaseAuthDelegate({
        firebaseApp,
        signInOptions
    });

    const dataSource = useFirestoreDataSource({
        firebaseApp: firebaseApp,
        textSearchController
    });
    const storageSource = useFirebaseStorageSource({ firebaseApp: firebaseApp });

    if (configError) {
        return <div> {configError} </div>;
    }

    if (firebaseConfigError) {
        return <div>
            It seems like the provided Firebase config is not correct. If you
            are using the credentials provided automatically by Firebase
            Hosting, make sure you link your Firebase app to Firebase
            Hosting.
        </div>;
    }

    if (firebaseConfigLoading || !firebaseApp) {
    return <>
        <CssBaseline/>
        <CircularProgressCenter/>
    </>;
    }

    return (
        <BrowserRouter basename={basePath}>
            <FireCMS navigation={navigation}
                     authDelegate={authDelegate}
                     authentication={authentication}
                     schemaOverrideHandler={schemaOverrideHandler}
                     dateTimeFormat={dateTimeFormat}
                     dataSource={dataSource}
                     storageSource={storageSource}
                     entityLinkBuilder={({ entity }) => `https://console.firebase.google.com/project/${firebaseApp.options.projectId}/firestore/data/${entity.path}/${entity.id}`}
                     locale={locale}
                     basePath={basePath}
                     baseCollectionPath={baseCollectionPath}>
                {({ context, mode, loading }) => {

                    const theme = createCMSDefaultTheme({
                        mode,
                        primaryColor,
                        secondaryColor,
                        fontFamily
                    });

                    let component;
                    if (loading) {
                        component = <CircularProgressCenter/>;
                    } else if (!context.authController.canAccessMainView) {
                        component = (
                            <FirebaseLoginView
                                logo={logo}
                                allowSkipLogin={allowSkipLogin}
                                signInOptions={signInOptions ?? DEFAULT_SIGN_IN_OPTIONS}
                                firebaseApp={firebaseApp}
                                authDelegate={authDelegate}
                                {...LoginViewProps}
                                />
                        );
                    } else {
                        component = (
                            <Scaffold name={name}
                                      logo={logo}
                                      toolbarExtraWidget={toolbarExtraWidget}>
                                <NavigationRoutes HomePage={HomePage}/>
                                <SideEntityDialogs/>
                            </Scaffold>
                        );
                    }

                    return (
                        <ThemeProvider theme={theme}>
                            <CssBaseline/>
                            {component}
                        </ThemeProvider>
                    );
                }}
            </FireCMS>
        </BrowserRouter>
    );
}