@mui/material/styles#ThemeProvider JavaScript Examples

The following examples show how to use @mui/material/styles#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: index.js    From react-material-workspace-layout with MIT License 6 votes vote down vote up
Header = ({
  leftSideContent = null,
  hideHeaderText = false,
  items,
  onClickItem,
}: Props) => {
  return (
    <ThemeProvider theme={theme}>
      <Container>
        <Box flexGrow={1}>{leftSideContent}</Box>
        {items.map((item) => (
          <HeaderButton
            key={item.name}
            hideText={hideHeaderText}
            onClick={() => onClickItem(item)}
            {...item}
          />
        ))}
      </Container>
    </ThemeProvider>
  )
}
Example #2
Source File: index.js    From FSE-Planner with MIT License 6 votes vote down vote up
root.render(
  <React.StrictMode>
    <StyledEngineProvider injectFirst>
      <ThemeProvider theme={Theme}>
        <ErrorBoundary>
          <App />
        </ErrorBoundary>
      </ThemeProvider>
    </StyledEngineProvider>
  </React.StrictMode>
);
Example #3
Source File: App.js    From material-ui-color with MIT License 6 votes vote down vote up
export default function App() {
  const [color, setColor] = useState(createColor("#000"));
  const handleChange = (value) => {
    console.log("onChange=", value);
    setColor(value);
  };

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Container maxWidth="sm">
        <Box my={4}>
          <Typography variant="h4" component="h1" gutterBottom>
            material-ui-color Picker
          </Typography>
          <div>
            <ColorPicker value={color} onChange={handleChange} />
          </div>
        </Box>
        <Box>
          <a href="https://github.com/mikbry/material-ui-color">
            made using material-ui-color
          </a>
          <div>Javascript, material-ui and React</div>
        </Box>
      </Container>
    </ThemeProvider>
  );
}
Example #4
Source File: client.js    From Edlib with GNU General Public License v3.0 6 votes vote down vote up
hydrate(
    <CacheProvider value={emotionCache}>
        <ThemeProvider theme={muiTheme}>
            <BrowserRouter>
                <FetchProvider initialState={window.__FETCH_STATE__ || {}}>
                    {/* eslint-disable-next-line no-restricted-globals*/}
                    <ConfigurationProvider
                        apiUrl={(
                            location.protocol +
                            '//' +
                            location.host
                        ).replace('www', 'api')}
                        wwwUrl={location.protocol + '//' + location.host}
                    >
                        <App />
                    </ConfigurationProvider>
                </FetchProvider>
            </BrowserRouter>
        </ThemeProvider>
    </CacheProvider>,
    document.getElementById('root')
);
Example #5
Source File: index.js    From karto with MIT License 6 votes vote down vote up
root.render(
    <StrictMode>
        <StyledEngineProvider injectFirst>
            <ThemeProvider theme={theme}>
                <CssBaseline/>
                <App/>
            </ThemeProvider>
        </StyledEngineProvider>
    </StrictMode>
);
Example #6
Source File: index.js    From react-material-workspace-layout with MIT License 6 votes vote down vote up
WorkContainer = React.forwardRef(({ children }, ref) => {
  return (
    <ThemeProvider theme={theme}>
      <Container ref={ref}>
        {children}
        <ShadowOverlay />
      </Container>
    </ThemeProvider>
  )
})
Example #7
Source File: index.js    From react-material-workspace-layout with MIT License 6 votes vote down vote up
RightSidebar = ({ children, initiallyExpanded, height }) => {
  const [expanded, toggleExpanded] = useReducer(
    (state) => !state,
    initiallyExpanded === undefined
      ? getInitialExpandedState()
      : initiallyExpanded
  )

  useEffect(() => {
    if (initiallyExpanded === undefined) {
      window.localStorage.__REACT_WORKSPACE_LAYOUT_EXPANDED =
        JSON.stringify(expanded)
    }
  }, [initiallyExpanded, expanded])

  const containerStyle = useMemo(() => ({ height: height || "100%" }), [height])

  return (
    <ThemeProvider theme={theme}>
      <Container className={expanded ? "expanded" : ""} style={containerStyle}>
        <Slider className={expanded ? "expanded" : ""}>
          <InnerSliderContent>{children}</InnerSliderContent>
        </Slider>
        <Expander
          onClick={toggleExpanded}
          className={expanded ? "expanded" : ""}
        >
          {expanded ? (
            <ContractIcon className="icon" />
          ) : (
            <ExpandIcon className="icon" />
          )}
        </Expander>
      </Container>
    </ThemeProvider>
  )
}
Example #8
Source File: index.js    From react-material-workspace-layout with MIT License 6 votes vote down vote up
HeaderButton = ({
  name,
  icon,
  disabled,
  onClick,
  hideText = false,
}) => {
  const customIconMapping = useIconDictionary()
  return (
    <ThemeProvider theme={theme}>
      <StyledButton onClick={onClick} disabled={disabled}>
        <ButtonInnerContent>
          <IconContainer textHidden={hideText}>
            {icon || getIcon(name, customIconMapping)}
          </IconContainer>
          {!hideText && (
            <Text>
              <div>{name}</div>
            </Text>
          )}
        </ButtonInnerContent>
      </StyledButton>
    </ThemeProvider>
  )
}
Example #9
Source File: index.js    From react-material-workspace-layout with MIT License 5 votes vote down vote up
SidebarBox = ({
  icon,
  title,
  subTitle,
  children,
  noScroll = false,
  expandedByDefault,
}) => {
  const classes = useStyles()
  const content = (
    <div
      className={classnames(classes.expandedContent, noScroll && "noScroll")}
    >
      {children}
    </div>
  )

  const [expanded, changeExpandedState] = useState(
    expandedByDefault === undefined
      ? getExpandedFromLocalStorage(title)
      : expandedByDefault
  )
  const changeExpanded = useCallback(
    (expanded) => {
      changeExpandedState(expanded)
      setExpandedInLocalStorage(title, expanded)
    },
    [changeExpandedState, title]
  )

  const toggleExpanded = useEventCallback(() => changeExpanded(!expanded))
  const customIconMapping = useIconDictionary()
  const TitleIcon = customIconMapping[title.toLowerCase()]
  return (
    <ThemeProvider theme={theme}>
      <div className={classes.container}>
        <div className={classes.header}>
          <div className="iconContainer">
            {icon || <TitleIcon className={classes.titleIcon} />}
          </div>
          <Typography className={classes.title}>
            {title} <span>{subTitle}</span>
          </Typography>
          <IconButton onClick={toggleExpanded} className={classes.expandButton}>
            <ExpandIcon
              className={classnames("icon", expanded && "expanded")}
            />
          </IconButton>
        </div>
        {noScroll ? (
          expanded ? (
            content
          ) : null
        ) : (
          <Collapse in={expanded}>
            <ResizePanel direction="s" style={{ height: 200 }}>
              <div
                className="panel"
                style={{ display: "block", overflow: "hidden", height: 500 }}
              >
                {content}
              </div>
            </ResizePanel>
          </Collapse>
        )}
      </div>
    </ThemeProvider>
  )
}
Example #10
Source File: index.js    From mui-image with ISC License 5 votes vote down vote up
render(
	<ThemeProvider theme={theme}>
		<CssBaseline />
		<Demo />
	</ThemeProvider>,
	document.querySelector('#demo')
);
Example #11
Source File: index.js    From react-material-workspace-layout with MIT License 5 votes vote down vote up
IconSidebar = ({
  items = emptyAr,
  onClickItem,
  selectedTools = emptyAr,
}: Props) => {
  const customIconMapping = useIconDictionary()
  return (
    <ThemeProvider theme={theme}>
      <Container>
        {items.map((item) => {
          let NameIcon =
            customIconMapping[item.name.toLowerCase()] ||
            iconMapping[item.name.toLowerCase()] ||
            iconMapping["help"]

          const buttonPart = (
            <IconButton
              key={item.name}
              color={
                item.selected || selectedTools.includes(item.name.toLowerCase())
                  ? "primary"
                  : "default"
              }
              disabled={Boolean(item.disabled)}
              onClick={item.onClick ? item.onClick : () => onClickItem(item)}
            >
              {item.icon || <NameIcon />}
            </IconButton>
          )

          if (!item.helperText) return buttonPart

          return (
            <Tooltip key={item.name} title={item.helperText} placement="right">
              {buttonPart}
            </Tooltip>
          )
        })}
      </Container>
    </ThemeProvider>
  )
}
Example #12
Source File: index.js    From admin-web with GNU Affero General Public License v3.0 5 votes vote down vote up
//import * as serviceWorker from './serviceWorker';
//import { serviceWorkerNewContent } from './actions/common';

// Root function
function main() {
  const loader = async () => {
    return import('./App');
  };

  // Async loading support.
  const LoadableApp = Loadable({
    loader,
    loading: Loading,
    timeout: 20000,
    delay: 300,
  });

  ReactDOM.render(
    <Provider store={store}>
      <StyledEngineProvider injectFirst>
        <ThemeProvider theme={theme}>
          <Router>
            <LoadableApp />
          </Router>
        </ThemeProvider>
      </StyledEngineProvider>
    </Provider>,
    document.getElementById('root')
  );

  /*serviceWorker.register({
    onUpdate: () => {
      // A new service worker has been installed. Show update notification.
      store.dispatch(serviceWorkerNewContent());
    },
    onOffline: () => {
      // Service worker reported offline.
      console.info('serviceWorker onOffline'); // eslint-disable-line no-console
    },
  });*/
}
Example #13
Source File: Job.js    From FSE-Planner with MIT License 5 votes vote down vote up
// Generate all components to render leg
function Job(props) {

  // Add line
  return new JobSegment(props.positions, {
    weight: props.weight,
    color: props.color,
    highlight: props.highlight,
    bothWays: props.rleg
  })
    .bindTooltip(() => {
      var div = document.createElement('div');
      const root = createRoot(div);
      flushSync(() => {
        root.render((
          <ThemeProvider theme={Theme}>
            <Tooltip {...props} />
          </ThemeProvider>
        ));
      });
      return div;
    }, {sticky: true})
    .on('contextmenu', (evt) => {
      L.DomEvent.stopPropagation(evt);
      const actions = [
        {
          name: <span>Open {props.fromIcao} in FSE</span>,
          onClick: () => {
            let w = window.open('https://server.fseconomy.net/airport.jsp?icao='+props.fromIcao, 'fse');
            w.focus();
          }
        },
        {
          name: <span>Open {props.toIcao} in FSE</span>,
          onClick: () => {
            let w = window.open('https://server.fseconomy.net/airport.jsp?icao='+props.toIcao, 'fse');
            w.focus();
          }
        },
        {
          name: <span>View jobs <NavigationIcon fontSize="inherit" sx={{transform: 'rotate('+props.leg.direction+'deg)', verticalAlign: 'text-top'}} /></span>,
          onClick: () => {
            props.actions.current.openTable();
            props.actions.current.goTo(props.toIcao, props.fromIcao);
          }
        }
      ];
      if (props.rleg) {
        actions.push({
          name: <span>View jobs <NavigationIcon fontSize="inherit" sx={{transform: 'rotate('+(props.leg.direction+180)+'deg)', verticalAlign: 'text-top'}} /></span>,
          onClick: () => {
            props.actions.current.openTable();
            props.actions.current.goTo(props.fromIcao, props.toIcao);
          }
        })
      }
      props.actions.current.contextMenu({
        mouseX: evt.originalEvent.clientX,
        mouseY: evt.originalEvent.clientY,
        title: <span>{props.fromIcao} - {props.toIcao} <NavigationIcon fontSize="inherit" sx={{transform: 'rotate('+props.leg.direction+'deg)', verticalAlign: 'text-top'}} /></span>,
        actions: actions
      });
    });

}
Example #14
Source File: GPS.js    From FSE-Planner with MIT License 5 votes vote down vote up
function GPSLayer(props) {

  const s = props.settings;
  const group = L.featureGroup();
  const wrap = num => num+iWrap(num, s.display.map.center);

  // Create lines if needed
  if (props.connections) {
    let legs = {};
    for (const c of props.connections) {
      const [frID, toID] = c;

      const fr = { latitude: props.points[frID][0], longitude: props.points[frID][1] };
      const to = { latitude: props.points[toID][0], longitude: props.points[toID][1] };

      let key = frID+"-"+toID;
      if (!legs.hasOwnProperty(key)) {
        legs[key] = {
          direction: Math.round(getRhumbLineBearing(fr, to)),
          distance: Math.round(convertDistance(getDistance(fr, to), 'sm')),
        }
      }
    }

    const legsKeys = Object.keys(legs);

    for (var i = 0; i < legsKeys.length; i++) {
      const [fr, to] = legsKeys[i].split('-');
      const leg = legs[legsKeys[i]];
      const rleg = legs[to+'-'+fr]

      // Ensure only one line for both way legs
      if (rleg && fr > to) { continue; }

      new JobSegment([[props.points[fr][0], wrap(props.points[fr][1])], [props.points[to][0], wrap(props.points[to][1])]], {
        weight: props.weight,
        color: props.color,
        highlight: props.highlight,
        bothWays: rleg
      })
        .bindTooltip(() => {
          var div = document.createElement('div');
          const root = createRoot(div);
          flushSync(() => {
            root.render((
              <ThemeProvider theme={Theme}>
                <Typography variant="body1"><b>{leg.distance} NM</b></Typography>
              </ThemeProvider>
            ));
          });
          return div;
        }, {sticky: true})
        .addTo(group);
    }
  }

  // Create markers
  for (const [latitude, longitude, label] of props.points) {
    Marker({
      position: [latitude, wrap(longitude)],
      size: props.size,
      color: props.color,
      icao: label,
      icaodata: props.fseicaodata,
      actions: props.actions,
      sim: 'gps'
    })
      .addTo(group);
  }

  return group;

}
Example #15
Source File: App.js    From sampo-ui with MIT License 5 votes vote down vote up
App = () => (
  <LocalizationProvider dateAdapter={AdapterMoment}>
    <ThemeProvider theme={theme}>
      <SemanticPortal />
    </ThemeProvider>
  </LocalizationProvider>
)
Example #16
Source File: sampleComponent.jsx    From redis-examples with MIT License 5 votes vote down vote up
export default function Showcase(parameters) {

  const userSettings = parameters.userSettings
  const [theme, setTheme] = useState("light")
  const [greetingMessage, setGreetingMessage] = useState("Anonymous Person")

  const items = []
  if (userSettings) {

    const obj = userSettings[0]

    for (const key in userSettings) {
      items.push(<li key={key}> {key}: {userSettings[key]} </li>)
    }

    if (userSettings["themePreference"] != theme) {
      setTheme(userSettings["themePreference"] == "light" ? "light" : "dark")
    }

    if (!greetingMessage || userSettings["greetingMessage"] != greetingMessage) {
      if (userSettings["greetingMessage"]) {
        setGreetingMessage(userSettings["greetingMessage"])
      }
      else {
        setGreetingMessage("patladi")
      }
    }
  }

  return (
    <div>
      <div style={{
        padding: 10,
        margin: 10,
        backgroundColor: theme == "light" ? "grey" : "orange",
        border: "solid",
        borderWidth: "30px",
        borderColor: theme == "light" ? "#B2B2B2" : "black"
      }}>
        <ThemeProvider
          theme={theme == "light" ? lightTheme : darkTheme}
        >

          <h2>Hi, {greetingMessage}!</h2>
          <p>User and their preferences:</p>
          {items}

        </ThemeProvider>

      </div>
    </div>
  );
}
Example #17
Source File: server.js    From Edlib with GNU General Public License v3.0 4 votes vote down vote up
renderApp = async (req, res) => {
    const context = {};
    const emotionCache = createEmotionCache();
    const sheet = new ServerStyleSheet();

    const emotionServers = [
        // Every emotion cache used in the app should be provided.
        // Caches for MUI should use "prepend": true.
        // MUI cache should come first.
        emotionCache,
        getTssDefaultEmotionCache({ doReset: true }),
    ].map(createEmotionServer);

    const wwwUrl = `${req.protocol}://${req.get('host')}`;

    const SetupApp = (initialState, promiseList = []) => (
        <CacheProvider value={emotionCache}>
            <ThemeProvider theme={muiTheme}>
                <StaticRouter context={context} location={req.url}>
                    <FetchProvider
                        promiseList={promiseList}
                        initialState={initialState}
                        ssrCookies={res.getCookies()}
                        ssrAddCookiesFromSetCookie={res.addCookiesFromSetCookie}
                    >
                        <ConfigurationProvider
                            apiUrl={wwwUrl.replace('www', 'api')}
                            wwwUrl={wwwUrl}
                            isSSR
                            cookies={req.cookies}
                        >
                            <App />
                        </ConfigurationProvider>
                    </FetchProvider>
                </StaticRouter>
            </ThemeProvider>
        </CacheProvider>
    );

    const maxDepth = 10;
    const getStateFromTree = async (state = {}, depth = 0) => {
        const promiseList = [];
        renderToString(SetupApp(state, promiseList));
        if (promiseList.length !== 0 && depth < maxDepth) {
            await addPromiseListToState(state, promiseList);

            return getStateFromTree(state, depth + 1);
        }

        return { state };
    };

    const { state } = await getStateFromTree();

    const markup = renderToString(sheet.collectStyles(SetupApp(state, [])));
    const helmet = Helmet.renderStatic();

    // Grab the CSS from emotion
    const styleTagsAsStr = emotionServers
        .map(({ extractCriticalToChunks, constructStyleTagsFromChunks }) =>
            constructStyleTagsFromChunks(extractCriticalToChunks(markup))
        )
        .join('');

    // Grab the CSS from styled-components
    const styledComponentsTags = sheet.getStyleTags();

    const html = `<!doctype html>
    <html lang="">
    <head ${helmet.htmlAttributes.toString()}>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        ${cssLinksFromAssets(assets, 'client')}
        ${styleTagsAsStr}
        ${styledComponentsTags}
        ${helmet.title.toString()}
        ${helmet.meta.toString()}
        ${helmet.link.toString()}
    </head>
    <body ${helmet.bodyAttributes.toString()}>
        <script>
            window.__FETCH_STATE__=${JSON.stringify(state).replace(
                /</g,
                '\\u003c'
            )};
        </script>
        <div id="root">${markup}</div>
        ${jsScriptTagsFromAssets(assets, 'client', 'defer', 'crossorigin')}
    </body>
    </html>`;

    return { context, html };
}
Example #18
Source File: Marker.js    From FSE-Planner with MIT License 4 votes vote down vote up
function Marker({position, size, color, sim, allJobs, ...props}) {
  let type = 'default';
  if (!sim || (props.icaodata[props.icao] && props.icaodata[props.icao][sim][0] === props.icao)) {
    const a = props.icaodata[props.icao];
    type = a.type + (a.size >= 3500 ? 3 : a.size >= 1000 ? 2 : 1);
  }
  return new AirportIcon(
    position,
    {
      radius: parseInt(size)/2,
      color: '#fff',
      fillColor: color,
      type: type,
      allJobs: allJobs,
    }
  )
    .bindPopup(() => {
      var div = document.createElement('div');
      const root = createRoot(div);
      if (sim) {
        flushSync(() => {
          root.render((
            <ThemeProvider theme={Theme}>
              <Typography variant="h5" style={{padding:'3px 24px 3px 8px'}}>{props.icao}</Typography>
            </ThemeProvider>
          ));
        });
      }
      else {
        flushSync(() => {
          root.render((
            <ThemeProvider theme={Theme}>
              <Popup {...props} />
            </ThemeProvider>
          ));
        });
      }
      return div;
    }, {
      autoPanPadding: new L.Point(30, 30),
      minWidth: sim ? 50 : Math.min(250, window.innerWidth-10),
      maxWidth: Math.max(600, window.innerWidth-10)
    })
    .on('contextmenu', (evt) => {
      L.DomEvent.stopPropagation(evt);
      const actions = [];
      if (!sim) {
        actions.push({
          name: 'Open in FSE',
          onClick: () => {
            let w = window.open('https://server.fseconomy.net/airport.jsp?icao='+props.icao, 'fse');
            w.focus();
          }
        });
        actions.push({
          name: 'View jobs',
          onClick: () => {
            props.actions.current.openTable();
            props.actions.current.goTo(props.icao);
          }
        });
        const isFromIcao = props.actions.current.isFromIcao(props.icao);
        const isToIcao = props.actions.current.isToIcao(props.icao);
        if (isFromIcao) {
          actions.push({
            name: 'Cancel jobs radiating FROM',
            onClick: () => props.actions.current.fromIcao('')
          });
        }
        else {
          actions.push({
            name: 'Jobs radiating FROM',
            onClick: () => {
              if (isToIcao) {
                props.actions.current.toIcao('');
              }
              props.actions.current.fromIcao(props.icao);
            }
          });
        }
        if (isToIcao) {
          actions.push({
            name: 'Cancel jobs radiating TO',
            onClick: () => props.actions.current.toIcao('')
          });
        }
        else {
          actions.push({
            name: 'Jobs radiating TO',
            onClick: () => {
              if (isFromIcao) {
                props.actions.current.fromIcao('');
              }
              props.actions.current.toIcao(props.icao);
            }
          });
        }
        actions.push({
          name: 'Mesure distance from this point',
          onClick: () => props.actions.current.measureDistance(evt.latlng)
        });
        // Custom layers action
        const layers = props.actions.current.getCustomLayers(props.icao);
        if (layers.length) {
          actions.push({
            divider: true
          });
          for (const [id, name, exist] of layers) {
            if (!exist) {
              actions.push({
                name: 'Add to layer "'+name+'"',
                onClick: () => props.actions.current.addToCustomLayer(id, props.icao)
              });
            }
            else {
              actions.push({
                name: 'Remove from layer "'+name+'"',
                onClick: () => props.actions.current.removeFromCustomLayer(id, props.icao)
              });
            }
          }
        }
        // Chart links
        actions.push({
          divider: true
        });
        actions.push({
          name: 'Charts on ChartFox',
          onClick: () => window.open(`https://chartfox.org/${props.icao}`, '_blank')
        });
        actions.push({
          name: 'Airport on SkyVector',
          onClick: () => window.open(`https://skyvector.com/airport/${props.icao}`, '_blank')
        });
      }
      props.actions.current.contextMenu({
        mouseX: evt.originalEvent.clientX,
        mouseY: evt.originalEvent.clientY,
        title: props.icao,
        actions: actions
      });
    });
}