@material-ui/core#MenuItem TypeScript Examples

The following examples show how to use @material-ui/core#MenuItem. 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: Layout.tsx    From Demae with MIT License 6 votes vote down vote up
UserMenuItem = React.forwardRef(({ role }: { role: Role }, ref) => {
	const history = useHistory()
	const [showProcessing] = useProcessing()
	const [showMessage] = useSnackbar()
	const [provider] = useDocumentListen<Provider>(Provider, new Provider(role.id).documentReference)
	return (
		<MenuItem key={role.id} onClick={async () => {
			showProcessing(true)
			const adminAttach = firebase.functions().httpsCallable("commerce-v1-admin-attach")
			try {
				await adminAttach({ providerID: provider!.id })
				showMessage("success", "Change admin")
				history.push(`/admin`)
			} catch (error) {
				showMessage("error", "Error")
				console.error(error)
			}
			showProcessing(false)
		}}>{provider?.name || ""}</MenuItem>
	)
})
Example #2
Source File: index.tsx    From Nishan with MIT License 6 votes vote down vote up
export function BasicSelect(props: Props) {
  const classes = useStyles();
  const { filter_item_label } = useContext(NotionFilterContext)

  return <FormControl className={classes.formControl}>
    {filter_item_label && <InputLabel>{props.label}</InputLabel>}
    <Select
      value={props.value}
      onChange={props.onChange}
    >
      {props.items.map(({ value, label, icon = null }) => <MenuItem key={value} value={value}>{icon} {label}</MenuItem>)}
    </Select>
  </FormControl>
}
Example #3
Source File: branch_setup.tsx    From jupyter-extensions with Apache License 2.0 6 votes vote down vote up
private _renderBranches() {
    if (this.state.branches) {
      return this.state.branches.map(branch => {
        return (
          <MenuItem key={branch} value={branch}>
            {branch}
          </MenuItem>
        );
      });
    } else {
      this.setState({
        currBranch: 'Cannot Switch Branch',
        disabled: true,
      });
      return (
        <MenuItem key="DEFAULT_VAL" value="Cannot Switch Branch"></MenuItem>
      );
    }
  }
Example #4
Source File: DropdownInput.tsx    From ow-mod-manager with MIT License 6 votes vote down vote up
DropdownInput: FunctionComponent<Props> = ({
  value,
  onChange,
  label,
  disabled,
  tooltip = '',
}) => {
  const [mainLabel, falseLabel, trueLabel] = label.split('|');

  return (
    <Tooltip title={tooltip} placement="bottom">
      <ListItem disabled={disabled}>
        <Box mr={2}>
          <Typography>{mainLabel}</Typography>
        </Box>
        <Select
          variant="outlined"
          margin="dense"
          color="secondary"
          value={value ? 'true' : 'false'}
          onChange={(event) => {
            event.preventDefault();
            onChange(event.target.value === 'true');
          }}
        >
          <MenuItem value="false">{falseLabel}</MenuItem>
          <MenuItem value="true">{trueLabel}</MenuItem>
        </Select>
      </ListItem>
    </Tooltip>
  );
}
Example #5
Source File: ControlsOptionsLanguage.tsx    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
_ControlsOptionsLanguage: FunctionComponent<ControlsOptionsLanguageProps> = ({
  overrideLang,
  setOverrideLang,
}) => {
  const classes = useStyles();

  const currentLangCode = overrideLang !== null ? overrideLang : getShortLocale();
  const langOptions = getLanguageOptions(currentLangCode);

  const onLangChange: SelectInputProps['onChange'] = (event) => {
    const langCode = event.target.value;
    if (!distinguishLanguageCode(langCode)) return;

    setOverrideLang(langCode);
  };

  return (
    <BorderBox grow={false} direction="row" alignItems="center">
      <Typography className={classes.label}>{t('language')}</Typography>
      <Select value={currentLangCode} onChange={onLangChange}>
        {_.map(langOptions, (lang) => (
          <MenuItem key={lang.value} value={lang.value}>
            <img className={classes.flag} src={getLanguageFlag(lang.value)} />
            {lang.label}
          </MenuItem>
        ))}
      </Select>
    </BorderBox>
  );
}
Example #6
Source File: index.tsx    From prism-frontend with MIT License 6 votes vote down vote up
export default function SimpleDropdown<OptionValue extends number | string>({
  options,
  value,
  onChange,
  ...rest
}: {
  options: [OptionValue, OptionLabel][];
  value: OptionValue;
  onChange: (value: OptionValue) => void;
}) {
  const { t } = useSafeTranslation();
  return (
    <FormControl {...rest}>
      <Select
        value={value === undefined ? '' : value}
        onChange={e => {
          onChange(e.target.value as OptionValue);
        }}
      >
        {options.map(([val, text]) => (
          <MenuItem key={val} value={val}>
            {t(text)}
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  );
}
Example #7
Source File: AudioSelector.tsx    From Oratio with MIT License 6 votes vote down vote up
export default function AudioSelector() {
  const { t } = useTranslation();
  const [sound, setSound] = React.useState('');

  const handleSoundChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    setSound(event.target.value as string);
    localStorage.setItem('soundFileName', event.target.value as string);
  };

  const classes = useStyles();
  return (
    <div>
      <FormControl className={classes.root}>
        <InputLabel id="demo-simple-select-label">
          {t('Speech Sound')}
        </InputLabel>
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={sound}
          autoWidth
          onChange={handleSoundChange}
        >
          {options.map((option) => (
            <MenuItem key={option} value={option}>
              {option}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </div>
  );
}
Example #8
Source File: index.tsx    From aqualink-app with MIT License 6 votes vote down vote up
SelectRange = ({
  open,
  value,
  setOpen,
  onRangeChange,
  classes,
}: SelectRangeProps) => {
  return (
    <Grid item className={classes.selectorWrapper}>
      <Box display="flex" alignItems="flex-end">
        <Typography variant="h6" color="textSecondary">
          Time range:
        </Typography>
        <Select
          className={classes.selector}
          open={open}
          onClose={() => setOpen(false)}
          onOpen={() => setOpen(true)}
          value={value}
          onChange={onRangeChange}
        >
          <MenuItem value="day">
            <Typography color="textSecondary">One day</Typography>
          </MenuItem>
          <MenuItem value="week">
            <Typography color="textSecondary">One week</Typography>
          </MenuItem>
        </Select>
      </Box>
    </Grid>
  );
}
Example #9
Source File: SortMethodSelector.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
SortMethodSelector = ({
  sortMethodNbr,
  handleSortMethodChange,
}: Props) => {
  const classes = useStyles();
  return (
    <FormControl fullWidth>
      <Select
        className={classes.select}
        disableUnderline
        value={sortMethodNbr}
        onChange={handleSortMethodChange}
      >
        <MenuItem value={0}>Latest updated</MenuItem>
        <MenuItem value={1}>A-Z</MenuItem>
        <MenuItem value={2}>Most members</MenuItem>
      </Select>
    </FormControl>
  );
}
Example #10
Source File: Forms.tsx    From signer with Apache License 2.0 6 votes vote down vote up
SelectFieldWithFormState = observer(
  (props: SelectWithFormStateProps) => {
    const { fieldState, selectItems, ...otherProps } = props;
    return (
      <Select
        value={fieldState?.value}
        onChange={(e: React.ChangeEvent<{ value: unknown }>) => {
          fieldState?.onChange((e.target.value as string) || '');
        }}
        error={fieldState?.hasError}
        {...otherProps}
      >
        {selectItems.map(item => {
          return (
            <MenuItem key={item.value} value={item.value}>
              {item.text}
            </MenuItem>
          );
        })}
      </Select>
    );
  }
)
Example #11
Source File: AutoCompletedResults.tsx    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
AutoCompleteResults: React.FC<Props> = (props) => {
  const { values, ...rest } = props;

  return (
    <Popover {...rest}>
      {values.map((value) => (
        <MenuItem key={value.id.raw}>{value.text.raw}</MenuItem>
      ))}
    </Popover>
  );
}
Example #12
Source File: menus.tsx    From clearflask with Apache License 2.0 6 votes vote down vote up
export function MenuItemHeader(props: {
  insideDrawer?: boolean;
  item: MenuHeader;
}) {
  return (
    <>
      <MenuItem
        key={props.item.title}
        disabled
        style={{
          justifyContent: props.insideDrawer ? 'flex-start' : 'center',
          minHeight: 48,
        }}
      >{props.item.title}</MenuItem>
      <Divider />
    </>
  );
}
Example #13
Source File: index.tsx    From back-home-safe with GNU General Public License v3.0 6 votes vote down vote up
CameraSetting = () => {
  const { t } = useTranslation("camera_setting");
  const { preferredCameraId, setPreferredCameraId, cameraList } = useCamera();

  return (
    <PageWrapper>
      <Header backPath="/" name={t("name")} />
      <FormWrapper>
        <StyledFormControl>
          <InputLabel id="cameraId">{t("form.camera_choice.label")}</InputLabel>
          <Select
            labelId="cameraId"
            id="demo-simple-select"
            value={preferredCameraId}
            onChange={(e) => {
              setPreferredCameraId((e.target.value as string) || "AUTO");
            }}
          >
            <MenuItem value="AUTO">{t("form.camera_choice.auto")}</MenuItem>
            {cameraList.map(({ deviceId, label }) => (
              <MenuItem value={deviceId} key="deviceId">
                {isNil(label) || isEmpty(label) ? deviceId : label}
              </MenuItem>
            ))}
          </Select>
          <FormHelperText>{t("form.camera_choice.explain")}</FormHelperText>
        </StyledFormControl>
      </FormWrapper>
      <VideoContainer>
        <MediaStream suppressError />
      </VideoContainer>
    </PageWrapper>
  );
}
Example #14
Source File: SelectStamp.tsx    From bee-dashboard with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
export default function SimpleMenu({ stamps, selectedStamp, setSelected }: Props): ReactElement | null {
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null)

  if (!stamps) return null

  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    setAnchorEl(event.currentTarget)
  }

  const handleClose = () => setAnchorEl(null)

  return (
    <div>
      <Button variant="contained" aria-haspopup="true" onClick={handleClick}>
        Change
      </Button>
      <Menu anchorEl={anchorEl} keepMounted open={Boolean(anchorEl)} onClose={handleClose}>
        {stamps.map(stamp => (
          <MenuItem
            key={stamp.batchID}
            onClick={() => {
              setSelected(stamp)
              handleClose()
            }}
            selected={stamp.batchID === selectedStamp?.batchID}
          >
            <ListItemIcon>{stamp.usageText}</ListItemIcon>
            <Typography variant="body2">{stamp.batchID.slice(0, 8)}[…]</Typography>
          </MenuItem>
        ))}
      </Menu>
    </div>
  )
}
Example #15
Source File: SelectApplicationView.tsx    From github-deploy-center with MIT License 6 votes vote down vote up
SelectApplicationView = () => {
  const { applicationsById, selectedApplicationId } = useAppState()
  const { selectApplication, editApplication, editDeployment } = useActions()
  const sortedApplications = orderBy(applicationsById, (x) =>
    x.name.toLowerCase()
  )
  return size(sortedApplications) ? (
    <Box display="flex" alignItems="center" style={{ gap: '1rem' }}>
      <FormControl variant="outlined" style={{ flex: 1 }}>
        <InputLabel id="application-select-label">Application</InputLabel>
        <Select
          labelId="application-select-label"
          label="Application"
          onChange={(event) => {
            selectApplication(event.target.value as string)
          }}
          value={selectedApplicationId}>
          {map(sortedApplications, (app) => (
            <MenuItem value={app.id} key={app.id}>
              {app.name}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
      <Button color="secondary" variant="contained" onClick={editApplication}>
        Edit App
      </Button>
      <Button color="secondary" variant="contained" onClick={editDeployment}>
        Edit Deploy
      </Button>
    </Box>
  ) : null
}
Example #16
Source File: HubSortDropdown.tsx    From dashboard with Apache License 2.0 6 votes vote down vote up
HubSortDropdown = ({
  selectedSortOption,
  sortOptions,
  handleSortOption,
}: Props) => {
  return (
    <FormControl>
      <SortLabel shrink>Sort</SortLabel>
      <SortSelect
        value={selectedSortOption}
        onChange={handleSortOption}
        input={<InputBase />}
        data-name={`selectedHubSortDropdown-${selectedSortOption.replaceAll(
          " ",
          "_"
        )}`}
      >
        {sortOptions.map((sortOption) => (
          <MenuItem
            data-name={`sortOptionHubSortDropdown-${sortOption.replaceAll(
              " ",
              "_"
            )}`}
            value={sortOption}
          >
            {sortOption}
          </MenuItem>
        ))}
      </SortSelect>
    </FormControl>
  )
}
Example #17
Source File: LoginIcon.tsx    From cognitive-search-static-web-apps-sample-ui with MIT License 6 votes vote down vote up
render(): JSX.Element {

        const state = this.props.state;

        return (<>

            <Button color={state.isLoggedInAnonymously ? "secondary" : "inherit"}
                onClick={evt => state.menuAnchorElement = evt.currentTarget}
            >
                <Tooltip title={state.isLoggedInAnonymously ? "ANONYMOUS" : state.userName}>
                    <AccountCircle />
                </Tooltip>
            </Button>

            <Menu
                anchorEl={state.menuAnchorElement}
                open={!state.isLoggedInAnonymously && !!state.menuAnchorElement}
                onClose={() => state.menuAnchorElement = undefined}
            >
                <MenuItem onClick={() => state.logout()}>Login under a different name</MenuItem>
            </Menu>
            
        </>);
    }
Example #18
Source File: System.tsx    From TidGi-Desktop with Mozilla Public License 2.0 6 votes vote down vote up
export function System(props: ISectionProps): JSX.Element {
  const { t } = useTranslation();

  const systemPreference = useSystemPreferenceObservable();

  return (
    <>
      <SectionTitle ref={props.sections.system.ref}>{t('Preference.System')}</SectionTitle>
      <Paper elevation={0}>
        <List dense disablePadding>
          {systemPreference === undefined ? (
            <ListItem>{t('Loading')}</ListItem>
          ) : (
            <>
              <PopUpMenuItem
                id="openAtLogin"
                buttonElement={
                  <ListItem button>
                    <ListItemText primary={t('Preference.OpenAtLogin')} secondary={getOpenAtLoginString(systemPreference.openAtLogin)} />
                    <ChevronRightIcon color="action" />
                  </ListItem>
                }>
                <MenuItem dense onClick={async () => await window.service.systemPreference.setSystemPreference('openAtLogin', 'yes')}>
                  {t('Yes')}
                </MenuItem>
                <MenuItem dense onClick={async () => await window.service.systemPreference.setSystemPreference('openAtLogin', 'yes-hidden')}>
                  {t('Preference.OpenAtLoginMinimized')}
                </MenuItem>
                <MenuItem dense onClick={async () => await window.service.systemPreference.setSystemPreference('openAtLogin', 'no')}>
                  {t('No')}
                </MenuItem>
              </PopUpMenuItem>
            </>
          )}
        </List>
      </Paper>
    </>
  );
}
Example #19
Source File: CustomSelect.tsx    From flect-chime-sdk-demo with Apache License 2.0 6 votes vote down vote up
CustomSelect = <T extends string | number | readonly string[] | undefined>(props: CustomSelectProps<T>) => {
    const classes = useCustomSelectStyles({ height: props.height, fontsize: props.fontsize, labelFontsize: props.labelFontsize });
    const [value, setValue] = useState<T | undefined>(props.defaultValue);
    const items = props.items.map((x) => {
        return (
            <MenuItem style={{ fontSize: props.fontsize }} key={x.label} value={x.value}>
                <em>{x.label}</em>
            </MenuItem>
        );
    });

    return (
        <FormControl>
            <InputLabel
                shrink={true}
                classes={{
                    root: classes.inputLabel,
                    focused: classes.inputLabelFocused,
                }}
            >
                {props.label}
            </InputLabel>
            <Select
                onChange={(e) => {
                    props.onChange(e.target.value as T);
                    setValue(e.target.value as T);
                }}
                defaultValue={value}
                inputProps={{
                    classes: {
                        root: classes.input,
                    },
                }}
            >
                {items}
            </Select>
        </FormControl>
    );
}
Example #20
Source File: Layout.tsx    From Demae with MIT License 5 votes vote down vote up
AccountMenu = () => {

	const [user] = useUser()
	const [roles] = useRoles()

	const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
	const menuOpen = Boolean(anchorEl)
	const handleMenu = (event: React.MouseEvent<HTMLElement>) => {
		setAnchorEl(event.currentTarget);
	}
	const handleClose = () => {
		setAnchorEl(null);
	}

	if (user) {
		return (
			<>
				<IconButton
					onClick={handleMenu}
					color="inherit"
				>
					<AccountCircle />
				</IconButton>
				<Menu
					style={{ width: "120px" }}
					anchorEl={anchorEl}
					anchorOrigin={{ vertical: "top", horizontal: "right", }}
					keepMounted
					transformOrigin={{ vertical: "top", horizontal: "right", }}
					open={menuOpen}
					onClose={handleClose}
				>
					{roles.map(role => <UserMenuItem key={role.id} role={role} />)}
					<Divider />
					<MenuItem key={"signout"} onClick={async () => {
						await firebase.auth().signOut()
					}}>SignOut</MenuItem>
				</Menu>
			</>
		)
	} else {
		return (
			<IconButton
				color="inherit"
			>
				<AccountCircle />
			</IconButton>
		)
	}
}
Example #21
Source File: FieldsDropdown.tsx    From firetable with Apache License 2.0 5 votes vote down vote up
/**
 * Returns dropdown component of all available types
 */
export default function FieldsDropdown({
  value,
  onChange,
  className,
  hideLabel = false,
  options: optionsProp,
}: IFieldsDropdownProps) {
  const classes = useStyles();

  const options = optionsProp
    ? Object.values(FieldType).filter(
        (fieldType) => optionsProp.indexOf(fieldType) > -1
      )
    : Object.values(FieldType);

  return (
    <TextField
      fullWidth
      select
      value={value ? value : ""}
      onChange={onChange}
      inputProps={{ name: "type", id: "type" }}
      label={!hideLabel ? "Field Type" : ""}
      aria-label="Field Type"
      hiddenLabel={hideLabel}
      helperText={value && getFieldProp("description", value)}
      FormHelperTextProps={{ classes: { root: classes.helperText } }}
      className={className}
    >
      {options.map((fieldType) => (
        <MenuItem
          key={`select-field-${getFieldProp("name", fieldType)}`}
          id={`select-field-${fieldType}`}
          value={fieldType}
        >
          <ListItemIcon className={classes.listItemIcon}>
            {getFieldProp("icon", fieldType)}
          </ListItemIcon>
          {getFieldProp("name", fieldType)}
        </MenuItem>
      ))}
    </TextField>
  );
}
Example #22
Source File: context_menu.tsx    From jupyter-extensions with Apache License 2.0 5 votes vote down vote up
ContextMenuItem = withStyles({
  root: {
    fontSize: 'var(--jp-ui-font-size1)',
  },
})(MenuItem)
Example #23
Source File: NewsMenu.tsx    From The-TypeScript-Workshop with MIT License 5 votes vote down vote up
NewsMenu = () => {
  const [anchorEl, setAnchorEl] = useState<Element>();
  const history = useHistory();
  const user = useContext(UserContext);

  const handleClick = (
    event: React.MouseEvent<HTMLButtonElement, MouseEvent>
  ) => setAnchorEl(event.currentTarget);

  const handleAdd = () => history.push('/add');

  const handleClose = () => setAnchorEl(undefined);

  const handleLogOut = async () => {
    await auth.signOut();
    history.push('/signin');
  };

  const handleSignIn = () => history.push('/signin');
  const handleSignUp = () => history.push('/signup');

  return (
    <div>
      <Button
        area-controls="simple-menu"
        area-haspopup="true"
        color="inherit"
        onClick={handleClick}
      >
        Menu
      </Button>
      <Menu
        id="simple-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
      >
        {user ? (
          <div>
            <MenuItem onClick={handleAdd}>Add a Story</MenuItem>
            <MenuItem onClick={handleLogOut}>Log Out</MenuItem>
          </div>
        ) : (
          <div>
            <MenuItem onClick={handleSignIn}>Sign In</MenuItem>
            <MenuItem onClick={handleSignUp}>Sign Up</MenuItem>
          </div>
        )}
      </Menu>
    </div>
  );
}
Example #24
Source File: ModNameSelect.tsx    From ow-mod-manager with MIT License 5 votes vote down vote up
ModNameSelect: React.FunctionComponent<Props> = ({
  value,
  onChange,
  logLines,
}) => {
  const styles = useStyles();
  const [modNames, setModNames] = useState<string[]>([]);

  useEffect(() => {
    debugConsole.log('useEffect: ModNameSelect set mod names');
    setModNames(uniq(logLines.map((line) => line.modName)));
  }, [logLines]);

  const handleModNameChange = ({
    target,
  }: React.ChangeEvent<{
    name?: string | undefined;
    value: unknown;
  }>) => {
    onChange(target.value as string);
  };

  return (
    <Select
      variant="outlined"
      margin="dense"
      className={styles.root}
      value={value}
      onChange={handleModNameChange}
      displayEmpty
    >
      <MenuItem value={''}>{logsText.allMods}</MenuItem>
      {modNames.map((modName) => (
        <MenuItem value={modName} key={modName}>
          {modName}
        </MenuItem>
      ))}
    </Select>
  );
}
Example #25
Source File: ControlsSummaryFeatureMenu.tsx    From Teyvat.moe with GNU General Public License v3.0 5 votes vote down vote up
_ControlsSummaryFeatureMenu: FunctionComponent<ControlsSummaryFeatureMenuProps> = ({
  featureKey,

  displayed,

  hideFeature,
  showFeature,
  clearAllFeature,
  clearExpiredFeature,
  locateFeature,
}) => {
  const classes = useStyles();

  const mapFeature = getMapFeature(featureKey);
  const doesExpire = (mapFeature.respawn ?? 'none') !== 'none';

  const [menuAnchor, setMenuAnchor] = useState<HTMLButtonElement | null>(null);

  const handleOpen: React.MouseEventHandler<HTMLButtonElement> = (event) => {
    setMenuAnchor(event.currentTarget);
  };

  const handleClose = () => {
    setMenuAnchor(null);
  };

  return (
    <>
      <Tooltip place="left" />
      <IconButton classes={{ root: classes.menuButtonRoot }} onClick={handleOpen}>
        <MenuIcon />
      </IconButton>

      <Menu
        id="summary-menu"
        anchorEl={menuAnchor}
        open={Boolean(menuAnchor)}
        onClose={handleClose}
        getContentAnchorEl={null}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
        transformOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
      >
        <MenuItem onClick={locateFeature}>{t('map-ui:locate')}</MenuItem>
        {doesExpire ? (
          <MenuItem onClick={clearExpiredFeature}>{t('map-ui:clear-refreshed-markers')}</MenuItem>
        ) : null}
        {displayed ? (
          <MenuItem onClick={hideFeature}>{t('map-ui:hide-feature')}</MenuItem>
        ) : (
          <MenuItem onClick={showFeature}>{t('map-ui:show-feature')}</MenuItem>
        )}
        <MenuItem onClick={clearAllFeature}>{t('map-ui:clear-all')}</MenuItem>
      </Menu>
    </>
  );
}
Example #26
Source File: ProjectSelect.tsx    From frontend with Apache License 2.0 5 votes vote down vote up
ProjectSelect: FunctionComponent<{
  projectId?: string;
  onProjectSelect: (id: string) => void;
}> = ({ projectId, onProjectSelect }) => {
  const classes = useStyles();
  const { projectList, selectedProjectId } = useProjectState();
  const projectDispatch = useProjectDispatch();

  React.useEffect(() => {
    if (projectId && projectId !== selectedProjectId) {
      selectProject(projectDispatch, projectId);
    }
  }, [projectId, selectedProjectId, projectDispatch]);

  return (
    <React.Fragment>
      {projectList.length > 0 && (
        <FormControl className={classes.formControl}>
          <InputLabel id="projectSelect" shrink>
            Project
          </InputLabel>
          <Select
            id="project-select"
            labelId="projectSelect"
            className={classes.input}
            displayEmpty
            value={selectedProjectId ?? ""}
            onChange={(event) => onProjectSelect(event.target.value as string)}
          >
            <MenuItem value="" disabled>
              <em>Select project</em>
            </MenuItem>
            {projectList.map((project) => (
              <MenuItem key={project.id} value={project.id}>
                {project.name}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      )}
    </React.Fragment>
  );
}
Example #27
Source File: index.tsx    From prism-frontend with MIT License 5 votes vote down vote up
ExportMenuItem = withStyles((theme: Theme) => ({
  root: {
    color: theme.palette.common.white,
  },
}))(MenuItem)
Example #28
Source File: DepartmentSelector.tsx    From graphql-ts-client with MIT License 5 votes vote down vote up
DepartmentSelector: FC<{
    value?: string,
    onChange: (value?: string) => void
}> = memo(({value, onChange}) => {

    const [data, setData] = useState<ModelType<typeof DEPARTMENT_LIST_FETCHER>>();
    const [error, setError] = useState<Error>();
    const [loading, setLoading] = useState(false);

    const findDepartments = useCallback(async () => {
        setLoading(true);
        setData(undefined);
        setError(undefined);
        try {
            const data = await execute(DEPARTMENT_LIST_FETCHER);
            setData(data);
        } catch (e) {
            setError(e);
        } finally {
            setLoading(false);
        }
    }, []);

    useEffect(() => {
        findDepartments();
    }, [findDepartments]);

    const onSelectChange = useCallback((e: ChangeEvent<{value: any}>) => {
        const v = e.target.value;
        onChange(v === "" ? undefined : v);
    }, [onChange]);

    return (
        <FormControl fullWidth={true}>
            <InputLabel>
                Department
                { loading && <CircularProgress size="1rem"/> }
                { error && <span style={{color:"red"}}>Load failed...</span>}
            </InputLabel>
            <Select 
            disabled={data === undefined} 
            error={false}
            value={value ?? ""}
            onChange={onSelectChange}
            fullWidth={true}>
                <MenuItem key="Nonde" value="">
                    <em>Unspecified</em>
                </MenuItem>
                {
                    data?.connection?.edges?.map(edge =>
                        <MenuItem key={edge.node.id} value={edge.node.id}>{edge.node.name}</MenuItem>
                    )
                }
            </Select>
        </FormControl>
    );
})
Example #29
Source File: CatalogKindHeader.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
/** @public */
export function CatalogKindHeader(props: CatalogKindHeaderProps) {
  const { initialFilter = 'component', allowedKinds } = props;
  const classes = useStyles();
  const catalogApi = useApi(catalogApiRef);
  const { value: allKinds } = useAsync(async () => {
    return await catalogApi
      .getEntityFacets({ facets: ['kind'] })
      .then(response => response.facets.kind?.map(f => f.value).sort() || []);
  });
  const {
    updateFilters,
    queryParameters: { kind: kindParameter },
  } = useEntityList();

  const queryParamKind = useMemo(
    () => [kindParameter].flat()[0]?.toLocaleLowerCase('en-US'),
    [kindParameter],
  );
  const [selectedKind, setSelectedKind] = useState(
    queryParamKind ?? initialFilter,
  );

  useEffect(() => {
    updateFilters({
      kind: selectedKind ? new EntityKindFilter(selectedKind) : undefined,
    });
  }, [selectedKind, updateFilters]);

  // Set selected Kind on query parameter updates; this happens at initial page load and from
  // external updates to the page location.
  useEffect(() => {
    if (queryParamKind) {
      setSelectedKind(queryParamKind);
    }
  }, [queryParamKind]);

  // Before allKinds is loaded, or when a kind is entered manually in the URL, selectedKind may not
  // be present in allKinds. It should still be shown in the dropdown, but may not have the nice
  // enforced casing from the catalog-backend. This makes a key/value record for the Select options,
  // including selectedKind if it's unknown - but allows the selectedKind to get clobbered by the
  // more proper catalog kind if it exists.
  const availableKinds = [capitalize(selectedKind)].concat(
    allKinds?.filter(k =>
      allowedKinds
        ? allowedKinds.some(
            a => a.toLocaleLowerCase('en-US') === k.toLocaleLowerCase('en-US'),
          )
        : true,
    ) ?? [],
  );
  const options = availableKinds.sort().reduce((acc, kind) => {
    acc[kind.toLocaleLowerCase('en-US')] = kind;
    return acc;
  }, {} as Record<string, string>);

  return (
    <Select
      input={<InputBase value={selectedKind} />}
      value={selectedKind}
      onChange={e => setSelectedKind(e.target.value as string)}
      classes={classes}
    >
      {Object.keys(options).map(kind => (
        <MenuItem value={kind} key={kind}>
          {`${options[kind]}s`}
        </MenuItem>
      ))}
    </Select>
  );
}