@material-ui/core#MuiThemeProvider TypeScript Examples

The following examples show how to use @material-ui/core#MuiThemeProvider. 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: ThemeProvider.tsx    From cards-against-formality-pwa with BSD 2-Clause "Simplified" License 6 votes vote down vote up
export default function ThemeProvider({ children }: any) {

  const [name, setName] = useState<'dark' | 'light'>(defaultTheme?.length ? defaultTheme : 'dark');
  const theme = useMemo(() => createMuiTheme({
    palette: {
      type: name
    }
  }), [name]);

  const onChange = useCallback(() => {
    setName(prevName => prevName === 'dark' ? 'light' : 'dark')
  }, []);

  useEffect(() => {
    if (name?.length) {
      // Use indexed-db in the future for async storage.
      localStorage.setItem(storageName, name)
    }
  }, [name]);

  return <ThemeContext.Provider value={{ name, onChange }}>
    <MuiThemeProvider theme={theme}>
      {children}
    </MuiThemeProvider>
  </ThemeContext.Provider>
}
Example #2
Source File: ApiBar.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
ApiBar = () => {
  const classes = useStyles();

  return (
    <Context.Consumer>
      {value => (
        <div className={classes.root}>
          <MuiThemeProvider theme={textFieldTheme}>
            <TextField
              label="Project ID"
              variant="outlined"
              defaultValue={value.projectId}
              onChange={e =>
                value.setProjectId?.(parseInt(e.target.value, 10) || undefined)
              }
            />
          </MuiThemeProvider>
        </div>
      )}
    </Context.Consumer>
  );
}
Example #3
Source File: index.tsx    From github-deploy-center with MIT License 6 votes vote down vote up
ReactDOM.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <MuiThemeProvider theme={theme}>
        <CssBaseline />
        <Provider value={overmind}>
          <App />
        </Provider>
      </MuiThemeProvider>
      <ReactQueryDevtools />
    </QueryClientProvider>
  </React.StrictMode>,
  document.getElementById('root')
)
Example #4
Source File: App.tsx    From mo360-ftk with MIT License 6 votes vote down vote up
swidget: ISwidget = (): JSX.Element => {
  return (
    <App name="My-App" init={init} config={config}>
      <MuiThemeProvider theme={theme}>
        <CssBaseline>
          <TranslationProvider translations={TranslationsI18n}>
            <Route />
          </TranslationProvider>
        </CssBaseline>
      </MuiThemeProvider>
    </App>
  );
}
Example #5
Source File: layout.tsx    From mtcute with GNU Lesser General Public License v3.0 5 votes vote down vote up
export default function ({
    children,
    location,
}: {
    children: NonNullable<React.ReactNode>
    location: any
}): React.ReactElement {
    const [theme, setTheme] = useState<'light' | 'dark'>('light')
    const path: string = location.pathname

    useEffect(() => {
        if (isTouchDevice()) document.documentElement.classList.add('touch')
    }, [])

    const muiTheme = createMuiTheme({
        palette: {
            type: theme,
            primary:
                theme === 'dark'
                    ? {
                          main: blue[300],
                      }
                    : undefined,
            secondary: {
                main: blue[800],
            },
        },
    })

    const isDesktop = useMediaQuery(muiTheme.breakpoints.up('sm'))

    return (
        <>
            <Helmet
                titleTemplate="%s | TL Reference"
                defaultTitle="TL Reference"
            />
            <MuiThemeProvider theme={muiTheme}>
                <>
                    <AppBar position="static" color="secondary">
                        <Toolbar>
                            {isDesktop ? (
                                <DesktopNavigation path={path} />
                            ) : (
                                <MobileNavigation path={path} />
                            )}
                            <GlobalSearchField isMobile={!isDesktop} />
                            <Tooltip title="Toggle dark theme">
                                <IconButton
                                    color="inherit"
                                    onClick={() =>
                                        setTheme(
                                            theme === 'dark' ? 'light' : 'dark'
                                        )
                                    }
                                >
                                    {theme === 'light' ? (
                                        <NightsStayIcon />
                                    ) : (
                                        <Brightness7Icon />
                                    )}
                                </IconButton>
                            </Tooltip>
                        </Toolbar>
                    </AppBar>
                    {children}
                </>
            </MuiThemeProvider>
        </>
    )
}
Example #6
Source File: AppContext.tsx    From firetable with Apache License 2.0 4 votes vote down vote up
AppProvider: React.FC = ({ children }) => {
  // Store currentUser from Firebase Auth
  const [currentUser, setCurrentUser] = useState<
    firebase.User | null | undefined
  >();
  useEffect(() => {
    auth.onAuthStateChanged((auth) => {
      setCurrentUser(auth);
    });
  }, []);

  // Store matching userDoc
  const [userDoc, dispatchUserDoc] = useDoc({});
  // Get userDoc
  useEffect(() => {
    if (currentUser) {
      analytics.setUserId(currentUser.uid);
      analytics.setUserProperties({
        ft_instance: window.location.hostname,
      });
      dispatchUserDoc({ path: `_FT_USERS/${currentUser.uid}` });
    }
  }, [currentUser]);

  // Infer theme based on system settings
  const prefersDarkTheme = useMediaQuery("(prefers-color-scheme: dark)", {
    noSsr: true,
  });
  // Store theme
  const [theme, setTheme] = useThemeState<keyof typeof Themes>(
    prefersDarkTheme ? "dark" : "light"
  );
  // Store if theme was overridden
  const [themeOverridden, setThemeOverridden] = useThemeOverriddenState(false);
  // Update theme when system settings change
  useEffect(() => {
    if (themeOverridden) return;
    if (prefersDarkTheme && theme !== "dark") setTheme("dark");
    if (!prefersDarkTheme && theme !== "light") setTheme("light");
  }, [prefersDarkTheme, themeOverridden]);

  // Store themeCustomization from userDoc
  const [themeCustomization, setThemeCustomization] = useState<ThemeOptions>(
    {}
  );
  const generatedTheme = Themes[theme](themeCustomization);

  useEffect(() => {
    if (userDoc.doc) {
      // Set theme customizations from user doc
      setThemeCustomization(userDoc.doc.theme);
    } else if (
      !userDoc.doc &&
      !userDoc.loading &&
      userDoc.path &&
      currentUser
    ) {
      // Set userDoc if it doesn’t exist
      const userFields = ["email", "displayName", "photoURL", "phoneNumber"];
      const userData = userFields.reduce((acc, curr) => {
        if (currentUser[curr]) {
          return { ...acc, [curr]: currentUser[curr] };
        }
        return acc;
      }, {});
      db.doc(userDoc.path).set(
        {
          tables: {},
          user: userData,
          theme: {
            palette: {
              primary: { main: "#ef4747" },
            },
          },
        },
        { merge: true }
      );
    }
  }, [userDoc]);

  return (
    <AppContext.Provider
      value={{
        userDoc: { state: userDoc, dispatch: dispatchUserDoc },
        currentUser,
        theme,
        themeOverridden,
        setTheme,
        setThemeOverridden,
      }}
    >
      <MuiThemeProvider theme={generatedTheme}>
        <CssBaseline />
        <ErrorBoundary>{children}</ErrorBoundary>
      </MuiThemeProvider>
    </AppContext.Provider>
  );
}
Example #7
Source File: DateInput.tsx    From halstack-react with Apache License 2.0 4 votes vote down vote up
DxcDateInput = React.forwardRef<RefType, DateInputPropsType>(
  (
    {
      label,
      name,
      defaultValue = "",
      value,
      format = "dd-MM-yyyy",
      helperText,
      placeholder = false,
      clearable,
      disabled,
      optional,
      onChange,
      onBlur,
      error,
      autocomplete,
      margin,
      size,
      tabIndex,
    },
    ref
  ) => {
    const [innerValue, setInnerValue] = useState(defaultValue);
    const [isOpen, setIsOpen] = useState(false);
    const [anchorEl, setAnchorEl] = useState(null);

    const colorsTheme = useTheme();
    const translatedLabels = useTranslatedLabels();
    const refDate = ref || useRef(null);

    const handleCalendarOnKeyDown = (event) => {
      switch (event.keyCode) {
        case 27: // Esc
          event.preventDefault();
          setIsOpen(false);
          break;
      }
    };
    const handleCalendarOnClick = (newDate) => {
      const newValue = dayjs(newDate).format(format.toUpperCase());
      value ?? setInnerValue(newValue);
      newDate?.toJSON()
        ? onChange?.({
            value: newValue,
            date: newDate,
          })
        : onChange?.({
            value: newValue,
          });
    };
    const handleIOnChange = ({ value: newValue, error: inputError }) => {
      value ?? setInnerValue(newValue);
      const dayjsDate = dayjs(newValue, format.toUpperCase(), true);
      const invalidDateMessage =
        newValue !== "" && !dayjsDate.isValid() && translatedLabels.dateInput.invalidDateErrorMessage;
      const callbackParams =
        inputError || invalidDateMessage
          ? { value: newValue, error: inputError || invalidDateMessage }
          : { value: newValue };
      dayjsDate.isValid()
        ? onChange?.({
            ...callbackParams,
            date: dayjsDate.toDate(),
          })
        : onChange?.(callbackParams);
    };
    const handleIOnBlur = ({ value, error: inputError }) => {
      const dayjsDate = dayjs(value, format.toUpperCase(), true);
      const invalidDateMessage =
        value !== "" && !dayjsDate.isValid() && translatedLabels.dateInput.invalidDateErrorMessage;
      const callbackParams =
        inputError || invalidDateMessage ? { value, error: inputError || invalidDateMessage } : { value };
      dayjsDate.isValid()
        ? onBlur?.({
            ...callbackParams,
            date: dayjsDate.toDate(),
          })
        : onBlur?.(callbackParams);
    };

    const openCalendar = () => {
      const dateBtn = refDate.current.getElementsByTagName("button")[0];
      setIsOpen(!isOpen);
      setAnchorEl(dateBtn);
    };
    const closeCalendar = () => {
      setIsOpen(false);
    };

    const calendarAction = {
      onClick: openCalendar,
      icon: (
        <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24" fill="currentColor">
          <path d="M0 0h24v24H0z" fill="none" />
          <path d="M20 3h-1V1h-2v2H7V1H5v2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 18H4V8h16v13z" />
        </svg>
      ),
    };

    const dateTheme = createMuiTheme({
      overrides: {
        MuiTypography: {
          root: {
            fontFamily: `${colorsTheme.dateInput.pickerFontFamily} !important`,
          },
        },
        MuiPickersYearSelection: {
          container: {
            color: colorsTheme.dateInput.pickerYearFontColor,
            "&::-webkit-scrollbar": {
              width: "3px",
            },

            "&::-webkit-scrollbar-track": {
              backgroundColor: "#D9D9D9",
              borderRadius: "3px",
            },

            "&::-webkit-scrollbar-thumb": {
              backgroundColor: "#666666",
              borderRadius: "3px",
            },
          },
        },
        MuiPickersToolbar: {
          toolbar: {
            backgroundColor: colorsTheme.dateInput.pickerBackgroundColor,
            color: colorsTheme.dateInput.pickerDayFontColor,
          },
        },
        MuiIconButton: {
          root: {
            height: "36px",
            width: "36px",
            padding: "0px",
          },
        },
        MuiTouchRipple: {
          child: {
            opacity: "0",
          },
        },
        MuiButtonBase: {
          root: {
            "&:focus": {
              outline: colorsTheme.dateInput.pickerFocusColor + " solid 2px",
            },
          },
        },
        MuiPickersBasePicker: {
          pickerView: {
            minWidth: "unset",
            maxWidth: "unset",
            minHeight: "unset",
            padding: "0px 10px",
            height: colorsTheme.dateInput.pickerHeight,
            width: colorsTheme.dateInput.pickerWidth,
            backgroundColor: colorsTheme.dateInput.pickerBackgroundColor,
            fontFamily: colorsTheme.dateInput.pickerFontFamily,
          },
        },
        MuiPickersToolbarText: {
          toolbarTxt: {
            color: colorsTheme.dateInput.pickerActualDateFontColor,
            fontFamily: colorsTheme.dateInput.pickerFontFamily,
            fontSize: "2rem",
          },
          toolbarBtnSelected: {
            color: colorsTheme.dateInput.pickerActualDateFontColor,
          },
        },
        MuiPickersCalendarHeader: {
          transitionContainer: {
            color: colorsTheme.dateInput.pickerMonthFontColor,
          },
          dayLabel: {
            color: colorsTheme.dateInput.pickerWeekFontColor,
            fontFamily: colorsTheme.dateInput.pickerFontFamily,
          },
          switchHeader: {
            backgroundColor: "#ffffff",
            color: colorsTheme.dateInput.pickerDayFontColor,
          },
          iconButton: {
            backgroundColor: colorsTheme.dateInput.pickerMonthArrowsBackgroundColor,
            "&:hover": {
              backgroundColor: colorsTheme.dateInput.pickerMonthArrowsBackgroundColor,
            },
          },
        },
        MuiPickersCalendar: {
          week: {
            marginBottom: "2px",
          },
        },
        MuiPickersDay: {
          current: {
            color: colorsTheme.dateInput.pickerDayFontColor,
          },
          day: {
            fontFamily: colorsTheme.dateInput.pickerFontFamily,
            color: colorsTheme.dateInput.pickerDayFontColor,
            "&:hover": {
              backgroundColor: colorsTheme.dateInput.pickerHoverDateBackgroundColor,
              color: colorsTheme.dateInput.pickerHoverDateFontColor,
            },
          },
          daySelected: {
            backgroundColor: colorsTheme.dateInput.pickerSelectedDateBackgroundColor,
            color: colorsTheme.dateInput.pickerSelectedDateColor,
            "&:hover": {
              backgroundColor: colorsTheme.dateInput.pickerSelectedDateBackgroundColor,
              color: colorsTheme.dateInput.pickerSelectedDateColor,
              opacity: "1",
            },
          },
        },
        MuiPickersYear: {
          yearSelected: {
            color: colorsTheme.dateInput.pickerSelectedDateColor,
            backgroundColor: colorsTheme.dateInput.pickerSelectedDateBackgroundColor,
            margin: "0px 100px",
            borderRadius: "20px",
          },
          root: {
            "&:focus": {
              color: colorsTheme.dateInput.pickerHoverDateFontColor,
              backgroundColor: colorsTheme.dateInput.pickerHoverDateBackgroundColor,
            },
          },
        },
        MuiPickersModal: {
          dialogAction: {
            color: "pink",
          },
        },
      },
    });

    return (
      <ThemeProvider theme={colorsTheme}>
        <MuiThemeProvider theme={dateTheme}>
          <MuiPickersUtilsProvider utils={DayjsUtils}>
            <StyledDPicker>
              <DxcTextInput
                label={label}
                name={name}
                defaultValue={defaultValue}
                value={value ?? innerValue}
                helperText={helperText}
                placeholder={placeholder ? format.toUpperCase() : null}
                action={calendarAction}
                clearable={clearable}
                disabled={disabled}
                optional={optional}
                onChange={handleIOnChange}
                onBlur={handleIOnBlur}
                error={error}
                autocomplete={autocomplete}
                margin={margin}
                size={size}
                tabIndex={tabIndex}
                ref={refDate}
              />
              <Popover
                onKeyDown={handleCalendarOnKeyDown}
                open={isOpen}
                anchorEl={anchorEl}
                anchorOrigin={{
                  vertical: "bottom",
                  horizontal: "left",
                }}
                transformOrigin={{
                  vertical: "top",
                  horizontal: "center",
                }}
                PaperProps={{
                  style: {
                    marginTop: "10px",
                  },
                }}
              >
                <ClickAwayListener onClickAway={closeCalendar}>
                  <Paper role="dialog" aria-modal="true">
                    <DatePicker
                      variant="static"
                      value={getValueForPicker(value ?? innerValue, format)}
                      onChange={(date) => handleCalendarOnClick(date)}
                      format={format}
                      disabled={disabled}
                    />
                  </Paper>
                </ClickAwayListener>
              </Popover>
            </StyledDPicker>
          </MuiPickersUtilsProvider>
        </MuiThemeProvider>
      </ThemeProvider>
    );
  }
)
Example #8
Source File: index.tsx    From gatsby-theme-pristine with Apache License 2.0 4 votes vote down vote up
Layout: React.FC = ({ children }) => {
  const darkMode = useDarkMode();
  const theme = darkMode.value ? darkTheme : lightTheme;
  const components = {
    h1: (props: any) => <Typography variant={"h1"} {...props} gutterBottom={true} />,
    h2: (props: any) => <Typography variant={"h2"} {...props} gutterBottom={true} />,
    h3: (props: any) => <Typography variant={"h3"} {...props} gutterBottom={true} />,
    h4: (props: any) => <Typography variant={"h4"} {...props} gutterBottom={true} />,
    h5: (props: any) => <Typography variant={"h5"} {...props} gutterBottom={true} />,
    h6: (props: any) => <Typography variant={"h6"} {...props} gutterBottom={true} />,
    Demo: (props: any) => <h1>This is a demo component</h1>,
    code: (props: any) => <CodeBlock darkMode={darkMode.value} {...props} />,
    thematicBreak: (props: any) => <Divider  {...props} />,
    a: (props: any) => <Link {...props} />,
    table: (props: any) => <Table {...props} style={{ marginBottom: "15px", ...props.style }} />,
    thead: (props: any) => <TableHead {...props} />,
    tr: (props: any) => <TableRow {...props} />,
    tableBody: (props: any) => <TableBody {...props} />,
    td: (props: any) => {
      return (
        <TableCell>
          {props.children || ""}
        </TableCell>
      );
    },
  };
  const [open, setOpen] = useState();

  const data = useStaticQuery(graphql`
    query LayoutQuery {
      site {
        siteMetadata {
          title
          description
          logoUrl
          primaryColor
          secondaryColor
          footerLinks {
            name
            link
          }
        }
      }
    }
  `);

  return (
    <MDXProvider components={components}>
      <MuiThemeProvider theme={{
        ...theme,
        palette: {
          ...theme.palette,
          primary: {
            ...theme.palette.primary,
            main: data.site.siteMetadata.primaryColor,
          },
          secondary: {
            ...theme.palette.secondary,
            main: data.site.siteMetadata.secondaryColor,
          }
        }
      }}>
        <Sidebar open={open} onClose={() => setOpen(false)} />
        <AppBar position="fixed" color="default" elevation={0}>
          <Toolbar>
            <IconButton onClick={() => setOpen(true)}>
              <MenuIcon fontSize="small" />
            </IconButton>
            <Grid container alignContent="center" alignItems="center" justify="space-between">
              <Grid item container direction="row" xs={5}>
                <Grid style={{ paddingRight: "5px" }}>
                  <img
                    alt="logo"
                    height="30"
                    style={{
                      marginTop: "6px",
                    }}
                    src={data.site.siteMetadata.logoUrl} />
                </Grid>
                <Grid style={{ marginTop: "7px" }}>
                  <GatsbyLink to="/" style={{ textDecoration: "none" }}>
                    <Typography color="textSecondary" variant="h6">
                      {data.site.siteMetadata.title}
                    </Typography>
                  </GatsbyLink>
                </Grid>
              </Grid>
              <Grid item container direction="row" xs={7} justify="flex-end" alignItems="center">
                <Hidden only="xs">
                  <Search />
                </Hidden>
                <Tooltip title={"Toggle Dark Mode"}>
                  <IconButton onClick={darkMode.toggle}>
                    {darkMode.value ? <Brightness3Icon fontSize="small" /> : <WbSunnyIcon fontSize="small" />}
                  </IconButton>
                </Tooltip>
              </Grid>
            </Grid>
          </Toolbar>
        </AppBar>
        <Container>
          <CssBaseline />
          <div style={{ padding: "30px", paddingTop: "64px" }}>
            {children}
            <Footer footerLinks={data.site.siteMetadata.footerLinks} />
          </div>
        </Container>
      </MuiThemeProvider >
    </MDXProvider >
  );
}