@material-ui/core#InputBase JavaScript Examples

The following examples show how to use @material-ui/core#InputBase. 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: WebChatSearchBox.js    From WhatsApp-Clone with MIT License 6 votes vote down vote up
WebChatSearchBox = ({ onSendMessage }) => {
  const [message, setMessage] = useState("");

  function handleKeyDown(event) {
    if (event.key === "Enter") {
      event.preventDefault();
      onSendMessage(message);
      setMessage("");
    }
  } 

  return (
    // <Paper elevation={webConstants.PAPER_ELEVATION}>
    <div style={styles.parentView}>
      <InputBase
        multiline
        rowsMax={5}
        style={styles.userMessage}
        placeholder="Search or start new chat"
        value={message}
        onKeyPress={e => handleKeyDown(e)}
        onChange={event => {
          // onTyping(event);
          setMessage(event.target.value);
        }}
      >
        <Search width={30} />
      </InputBase>
    </div>
    // </Paper>
  );
}
Example #2
Source File: CreateList.js    From social-media-strategy-fe with MIT License 6 votes vote down vote up
export default function CreateList() {
	const dispatch = useDispatch();
	const classes = useStyles();
	const [title, setTitle] = useState("");

	const handleSubmit = (e) => {
		e.preventDefault();
		if (title && title !== "Drafts") {
			dispatch(addList(title));
		}
	};

	const handleTextInput = (e) => {
		setTitle(e.currentTarget.value);
	};

	return (
		<form onSubmit={handleSubmit} className={classes.root}>
			<InputBase
				placeholder="New list…"
				inputProps={{ "aria-label": "add list" }}
				onChange={handleTextInput}
				fullWidth
			/>

			<IconButton
				type="submit"
				className={classes.iconButton}
				aria-label="search"
			>
				<AddIcon />
			</IconButton>
		</form>
	);
}
Example #3
Source File: InputSelect.jsx    From zubhub with GNU Affero General Public License v3.0 6 votes vote down vote up
BootstrapInput = withStyles(theme => ({
  input: {
    borderRadius: 0,
    borderTopLeftRadius: 250,
    borderBottomLeftRadius: 250,
    position: 'relative',
    fontSize: 16,
    padding: '10px 26px 10px 18px',
    backgroundColor: '#00B8C4',
    color: 'white',
    transition: 'background-color 250ms ease',
    textAlign: 'center',
    minHeight: '20px',
    '& ~ svg': {
      color: 'white',
    },
    '&:focus': {
      borderTopLeftRadius: 250,
      borderBottomLeftRadius: 250,
      backgroundColor: '#00B8C4',
    },
    '&[aria-expanded]': {
      borderRadius: 0,
      borderTopLeftRadius: 250,
      borderBottomLeftRadius: 250,
      backgroundColor: 'white',
      color: '#00B8C4',
      '& ~ svg': {
        color: '#00B8C4',
      },
    },
  },
}))(InputBase)
Example #4
Source File: MusicSearch.js    From qasong with ISC License 6 votes vote down vote up
function MusicSearch({ handleSubmitMusicSearch }) {
  const classes = useStyles();
  let history = useHistory();
  const [searchTerm, setSearchTerm] = React.useState();

  const handleSearchTermInput = (e) => {
    setSearchTerm(e.target.value);
  };

  return (
    <div className={classes.search}>
      <div className={classes.searchIcon}>
        <SearchIcon />
      </div>
      <form
        onSubmit={(e) => {
          history.push("/search");
          handleSubmitMusicSearch(e);
        }}
      >
        <InputBase
          id="qasong-search"
          name="qasong-search"
          onChange={handleSearchTermInput}
          placeholder="search music…"
          autoFocus={true}
          value={searchTerm}
          classes={{
            root: classes.inputRoot,
            input: classes.inputInput,
          }}
          inputProps={{ "aria-label": "search" }}
        />
      </form>
    </div>
  );
}
Example #5
Source File: Searchbar.js    From dscbppimt-official-website with MIT License 6 votes vote down vote up
function Searchbar({classes}) {
    return (
        <div>
          <div className={classes.search}>
            <div className={classes.searchIcon}>
              <SearchIcon />
            </div>
            <InputBase
              placeholder="Search…"
              classes={{
                root: classes.inputRoot,
                input: classes.inputInput,
              }}
              inputProps={{ 'aria-label': 'search' }}
            />
          </div>
          <div className={classes.grow} />
        </div>
    )
}
Example #6
Source File: index.js    From AED-Map with MIT License 6 votes vote down vote up
MyInputBase = props => {
  const [field] = useField(props);

  return (
    <InputBase
      className="text-input"
      {...field}
      {...props}
    />
  );
}
Example #7
Source File: CoinField.js    From Alternative-Uniswap-Interface with GNU General Public License v3.0 5 votes vote down vote up
export default function CoinField(props) {
  // This component is used to selecting a token and entering a value, the props are explained below:
  //      onClick - (string) => void - Called when the button is clicked
  //      symbol - string - The text displayed on the button
  //      value - string - The value of the text field
  //      onChange - (e) => void - Called when the text field changes
  //      activeField - boolean - Whether text can be entered into this field or not

  const classes = useStyles();
  const { onClick, symbol, value, onChange, activeField } = props;

  return (
    <div className={classes.container}>
      <Grid
        container
        direction="row"
        justifyContent="space-between"
        alignItems="center"
        className={classes.grid}
      >
        {/* Button */}
        <Grid item xs={3}>
          <Fab
            size="small"
            variant="extended"
            onClick={onClick}
            className={classes.fab}
          >
            {symbol}
            <ExpandMoreIcon />
          </Fab>
        </Grid>

        {/* Text Field */}
        <Grid item xs={9}>
          <InputBase
            value={value}
            onChange={onChange}
            placeholder="0.0"
            disabled={!activeField}
            classes={{ root: classes.input, input: classes.inputBase }}
          />
        </Grid>
      </Grid>
    </div>
  );
}
Example #8
Source File: NavSearch.js    From youtube-clone with MIT License 5 votes vote down vote up
MiddleNav = ({ history }) => {
  const [searchValue, setSearch] = useState("");
  const classes = useStyles();

  const handleSearch = () => {
    if (searchValue) {
      history.push(`/results?search_query=${searchValue}`);
    }
  };

  const handleSearchChange = (e) => {
    setSearch(e.target.value);
  };
  return (
    <div className={classes.searchForm}>
      <InputBase
        fullWidth
        value={searchValue}
        onChange={handleSearchChange}
        className={classes.border}
        classes={{
          input: classes.input,
        }}
        placeholder="Search…"
        inputProps={{ "aria-label": "search" }}
        endAdornment={
          <Tooltip title="Search">
            <Button
              disableRipple
              size="small"
              type="submit"
              className={classes.searchButton}
              onClick={handleSearch}
              aria-label="search"
            >
              <SearchIcon fontSize="small" />
            </Button>
          </Tooltip>
        }
      />
    </div>
  );
}
Example #9
Source File: index.js    From Codelabz with Apache License 2.0 5 votes vote down vote up
function MiniNavbar() {
  const classes = useStyles();

  const history = useHistory();

  return (
    <Headroom>
      <nav
        style={{
          padding: "10px",
          background: "white",
        }}
      >
        <Grid
          container
          direction="row"
          justifyContent="space-between"
          alignItems="center"
        >
          <Grid item>
            <div
              onClick={() => {
                history.push("/");
              }}
            >
              <BrandName />
            </div>
          </Grid>
          <Grid item xs={5}>
            <Paper component={"form"} className={classes.root} elevation={0}>
              <IconButton
                type="submit"
                aria-label="search"
                disableRipple
                className={classes.icon}
              >
                <SearchIcon />
              </IconButton>
              <InputBase className={classes.input} placeholder="Search" />
            </Paper>
          </Grid>
          <Grid item className={classes.grid}>
            <Button
              variant="contained"
              color="primary"
              style={{
                boxShadow: "none",
                color: "white",
              }}
              className={classes.button}
              onClick={() => history.push("/login")}
            >
              Login
            </Button>
            <Button
              variant="outlined"
              color="primary"
              style={{
                boxShadow: "none",
              }}
              className={classes.button}
              onClick={() => history.push("/signup")}
            >
              Sign Up
            </Button>
          </Grid>
        </Grid>
      </nav>
    </Headroom>
  );
}
Example #10
Source File: index.js    From Codelabz with Apache License 2.0 5 votes vote down vote up
function MainNavbar() {
  const classes = useStyles();
  return (
    <Headroom>
      <nav
        style={{
          padding: "10px",
          background: "white",
        }}
      >
        <Grid
          container
          direction="row"
          justifyContent="space-between"
          alignItems="center"
        >
          <Grid item>
            <BrandName />
          </Grid>
          <Grid item xs={5}>
            <Paper component={"form"} className={classes.root} elevation={0}>
              <IconButton
                type="submit"
                aria-label="search"
                disableRipple
                className={classes.icon}
              >
                <SearchIcon />
              </IconButton>
              <InputBase className={classes.input} placeholder="Search" />
            </Paper>
          </Grid>
          <Grid
            item
            container
            direction="row"
            alignItems="center"
            className={classes.grid}
          >
            <Grid item justifyContent="center">
              <LeftMenu />
            </Grid>
            <Grid item>
              <RightMenu />
            </Grid>
          </Grid>
        </Grid>
      </nav>
    </Headroom>
  );
}
Example #11
Source File: TopBar.js    From covid19ph.net with MIT License 5 votes vote down vote up
TopBar = ({
  title,
  onSearchChange,
}) => {
  const classes = useStyles()

  return (
    <div className={classes.grow}>
      <AppBar position="static">
        <Toolbar>
          <Typography className={classes.title} variant="h6" noWrap>
            {title}
          </Typography>
          <div className={classes.search}>
            <div className={classes.searchIcon}>
              <SearchIcon />
            </div>
            <InputBase
              placeholder="Search&hellip;"
              classes={{
                root: classes.inputRoot,
                input: classes.inputInput,
              }}
              inputProps={{ 'aria-label': 'search' }}
              onChange={onSearchChange}
            />
          </div>
          <div className={classes.grow} />
          <div className={classes.sectionDesktop}>
            <ShareButtons />
          </div>
          <div className={classes.sectionMobile}>
            <ShareButtons
              mobile
            />
          </div>
        </Toolbar>
      </AppBar>
    </div>
  )
}
Example #12
Source File: InputCard.js    From Trellis with GNU General Public License v3.0 5 votes vote down vote up
export default function InputItem({
  value,
  changedHandler,
  keyDownHandler,
  itemAdded,
  closeHandler,
  width,
  type,
  btnText,
  placeholder,
  marginLeft,
}) {
  const classes = useStyles({ type, width, marginLeft })
  const divRef = useRef(null)

  useEffect(() => {
    if (divRef.current != null) {
      divRef.current.scrollIntoView({ behaviour: 'smooth' })
    }
  })
  const handleBlur = () => {
    closeHandler()
    itemAdded()
  }
  return (
    <div className={classes.listBackground}>
      <Paper className={`${classes.card} ${classes.width}`}>
        <InputBase
          onChange={changedHandler}
          multiline
          fullWidth
          value={value}
          autoFocus
          placeholder={placeholder}
          onBlur={handleBlur}
          onKeyDown={keyDownHandler}
        />
      </Paper>
      <Button
        ref={divRef}
        className={classes.btn}
        variant="contained"
        onClick={itemAdded}
      >
        {btnText}
      </Button>
      <IconButton className={classes.icon} onClick={closeHandler}>
        <CloseIcon />
      </IconButton>
    </div>
  )
}
Example #13
Source File: EditPostText.js    From social-media-strategy-fe with MIT License 5 votes vote down vote up
EditPostText = (props) => {
	const { text, handleInputText, submit } = props;

	const { form, iconButton, secondColumn } = useStyles();

	const handleBlur = (e) => {
		submit(e);
	};

	return (
		<>
			<form onSubmit={submit} className={form} style={{ width: "100%" }}>
				<InputBase
					autoFocus
					onFocus={(e) => e.target.select()}
					onBlur={handleBlur}
					onChange={handleInputText}
					onKeyDown={handleInputText}
					id="standard-error-helper-text"
					defaultValue={text}
					multiline
					fullWidth
					inputProps={{
						"aria-label": "edit post",
						maxLength: 280,
					}}
				/>
				<div className={secondColumn}>
					<IconButton
						type="submit"
						className={iconButton}
						aria-label="confirm edit"
					>
						<CheckIcon />
					</IconButton>
					<TwitterCharCount text={text} />
				</div>
			</form>
		</>
	);
}
Example #14
Source File: EditList.js    From social-media-strategy-fe with MIT License 5 votes vote down vote up
EditList = (props) => {
	const { listTitle, list, handleInputText, submit } = props;

	const { form, iconButton, divider, input } = useStyles();

	const dispatch = useDispatch();
	const { lists } = useSelector((state) => state.kanban);

	const [modalOpen, setModalOpen] = useState(false);

	const handleDeleteConfirmation = () => {
		dispatch(deleteList(lists, list));
	};

	const handleBlur = (e) => {
		if (!modalOpen) {
			submit(e);
		}
	};

	return (
		<>
			<form onSubmit={submit} className={form} style={{ width: "100%" }}>
				<InputBase
					autoFocus
					onFocus={(e) => e.target.select()}
					onBlur={handleBlur}
					onChange={handleInputText}
					id="standard-error-helper-text"
					defaultValue={listTitle}
					fullWidth
					className={input}
					inputProps={{
						"aria-label": "edit title",
					}}
				/>
				<IconButton
					type="submit"
					className={iconButton}
					aria-label="confirm edit"
				>
					<CheckIcon />
				</IconButton>
				<Divider className={divider} orientation="vertical" />
				<IconButton
					onClick={() => setModalOpen(true)}
					className={iconButton}
					aria-label="delete list"
				>
					<DeleteIcon />
				</IconButton>
			</form>

			<Modal
				open={modalOpen}
				handleClose={() => setModalOpen(false)}
				title={`Would you like to delete the ${listTitle} list?`}
				content={
					"Confirming this action all posts in the list will also be deleted."
				}
				handleConfirmation={handleDeleteConfirmation}
			/>
		</>
	);
}
Example #15
Source File: CoinField.js    From Alternative-Uniswap-Interface with GNU General Public License v3.0 5 votes vote down vote up
export function RemoveLiquidityField1(props) {
  // This component is used to selecting a coin and entering a value, the props are explained below:
  //      onClick - (string) => void - Called when the button is clicked
  //      symbol - string - The text displayed on the button
  //      value - string - The value of the text field
  //      onChange - (e) => void - Called when the text field changes
  //      activeField - boolean - Whether text can be entered into this field or not

  const classes = useStyles();
  const { onClick, symbol, value, onChange, activeField } = props;
  return (
    <div className={classes.container_blank}>
      <Grid
        container
        direction="row"
        justifyContent="space-between"
        alignItems="center"
        className={classes.grid}
      >
        {/* Button */}
        <Grid item xs={3}>
          <Fab
            size="small"
            variant="extended"
            onClick={onClick}
            className={classes.fab}
          >
            {symbol}
            <ExpandMoreIcon />
          </Fab>
        </Grid>
        {/* Text Field */}
        <Grid item xs={9}>
          <InputBase
            value={value}
            onChange={onChange}
            placeholder="0.0"
            disabled={!activeField}
            classes={{
              root: classes.container_input,
              input: classes.inputBase,
            }}
          />
        </Grid>
        {/* </div> */}
      </Grid>
    </div>
  );
}
Example #16
Source File: List.js    From Trellis with GNU General Public License v3.0 4 votes vote down vote up
export default function Column({ column, tasks, index }) {
  const classes = useStyles()
  const [cardTitle, setCardTitle] = useState('')
  const [listTitle, setListTitle] = useState(column.name)
  const [addCardFlag, setAddCardFlag] = useState(false)
  const [editable, setEditable] = useState(false)
  const [list, setList] = useState(true)
  const [showDelete, setShowDelete] = useState(false)
  const { token, user } = useSelector((state) => state.user)
  const dispatch = useDispatch()

  const handleChange = (e) => {
    e.preventDefault()
    setCardTitle(e.target.value)
  }

  const submitHandler = () => {
    if (cardTitle === '') return
    const text = cardTitle.trim().replace(/\s+/g, ' ')
    setCardTitle(text)
    const totalTasks = tasks.length
    const postCardReq = {
      name: text,
      boardId: column.boardId,
      listId: column._id,
      order:
        totalTasks === 0 ? 'n' : midString(tasks[totalTasks - 1].order, ''),
    }
    dispatch(createNewCard(postCardReq, token))
    dispatch(
      createNewActivity(
        {
          text: `${user.username} added ${text} to ${column.name}`,
          boardId: column.boardId,
        },
        token,
      ),
    )
    setCardTitle('')
  }
  const handleAddition = () => {
    setAddCardFlag(true)
  }
  const closeButtonHandler = () => {
    setAddCardFlag(false)
    setCardTitle('')
  }
  const changedHandler = (e) => {
    e.preventDefault()
    setListTitle(e.target.value)
  }
  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault()
      submitHandler()
    }
  }
  const updateListTitle = () => {
    const text = listTitle.trim().replace(/\s+/g, ' ')
    if (text === '') {
      setListTitle(column.name)
      setEditable(false)
      return
    }
    setListTitle(text)
    dispatch(updateListById(column._id, { name: listTitle }))
    // eslint-disable-next-line no-param-reassign
    column.name = text
    setEditable(false)
  }

  return (
    <div className={classes.wrapper}>
      {list && (
        <Draggable draggableId={column._id} index={index}>
          {(provided) => (
            <div {...provided.draggableProps} ref={provided.innerRef}>
              <Paper
                elevation={0}
                onMouseEnter={() => setShowDelete(true)}
                onMouseLeave={() => setShowDelete(false)}
                className={classes.root}
                {...provided.dragHandleProps}
              >
                <div
                  className={classes.title}
                  onClick={() => setEditable(true)}
                >
                  {!editable && (
                    <div style={{ position: 'relative' }}>
                      <div>{column.name}</div>
                      {showDelete && (
                        <IconButton
                          size="small"
                          style={{
                            right: 0,
                            top: 0,
                            position: 'absolute',
                            backgroundColor: '#EBECF0',
                            zIndex: 100,
                          }}
                          onClick={() => {
                            setList(false)
                            dispatch(deleteListById(column._id))
                            const text = `${user.username} deleted list ${column.name}`
                            dispatch(
                              createNewActivity(
                                { text, boardId: column.boardId },
                                token,
                              ),
                            )
                          }}
                        >
                          <DeleteIcon
                            fontSize="small"
                            style={{ backgroundColor: '#EBECF0' }}
                          />
                        </IconButton>
                      )}
                    </div>
                  )}
                  {editable && (
                    <div className={classes.editable}>
                      <InputBase
                        onChange={changedHandler}
                        multiline
                        fullWidth
                        value={listTitle}
                        style={{ fontWeight: 'bold' }}
                        autoFocus
                        onFocus={(e) => {
                          const val = e.target.value
                          e.target.value = ''
                          e.target.value = val
                        }}
                        onBlur={updateListTitle}
                      />
                    </div>
                  )}
                </div>
                <Droppable droppableId={column._id} type="card">
                  {
                    // eslint-disable-next-line no-shadow
                    (provided) => (
                      <div ref={provided.innerRef} {...provided.droppableProps}>
                        <div className={classes.scroll}>
                          {/* eslint-disable-next-line no-shadow */}
                          {tasks.map((task, index) => (
                            <Card key={task._id} task={task} index={index} />
                          ))}
                          {addCardFlag && (
                            <InputCard
                              value={cardTitle}
                              changedHandler={handleChange}
                              itemAdded={submitHandler}
                              closeHandler={closeButtonHandler}
                              keyDownHandler={handleKeyDown}
                              type="card"
                              btnText="Add Card"
                              placeholder="Enter a title for this card..."
                              width="230px"
                            />
                          )}
                          {provided.placeholder}
                        </div>
                        {!addCardFlag && (
                          <AddItem
                            handleClick={handleAddition}
                            icon={<AddIcon />}
                            btnText="Add another card"
                            type="card"
                            width="256px"
                          />
                        )}
                      </div>
                    )
                  }
                </Droppable>
              </Paper>
            </div>
          )}
        </Draggable>
      )}
    </div>
  )
}
Example #17
Source File: Card.js    From Trellis with GNU General Public License v3.0 4 votes vote down vote up
export default function Card({ task, index }) {
  const [editable, setEditable] = useState(false)
  const [title, setTitle] = useState(task.name)
  const [card, setCard] = useState(true)
  const [showDelete, setShowDelete] = useState(false)
  const classes = useStyles()
  const { token, user } = useSelector((state) => state.user)
  const dispatch = useDispatch()
  return (
    <Draggable draggableId={task._id} index={index}>
      {(provided) => (
        <div
          {...provided.draggableProps}
          {...provided.dragHandleProps}
          ref={provided.innerRef}
        >
          {card && (
            <Paper
              className={classes.card}
              onMouseEnter={() => setShowDelete(true)}
              onMouseLeave={() => setShowDelete(false)}
              onClick={() => {
                setEditable(true)
              }}
            >
              {editable ? (
                <InputBase
                  onChange={(e) => {
                    e.preventDefault()
                    setTitle(e.target.value)
                  }}
                  multiline
                  fullWidth
                  value={title}
                  style={{ minHeight: '7px' }}
                  autoFocus
                  onFocus={(e) => {
                    const val = e.target.value
                    e.target.value = ''
                    e.target.value = val
                  }}
                  onBlur={() => {
                    setEditable(false)
                    const text = title.trim().replace(/\s+/g, ' ')
                    if (text === '') {
                      setTitle(task.name)
                      return
                    }
                    setTitle(text)
                    dispatch(updateCardById(task._id, { name: text }))
                    // eslint-disable-next-line no-param-reassign
                    task.name = text
                  }}
                />
              ) : (
                <div style={{ position: 'relative' }}>
                  <div>{task.name}</div>
                  {showDelete && (
                    <IconButton
                      className={classes.delete}
                      size="small"
                      onClick={() => {
                        setCard(false)
                        dispatch(deleteCardById(task._id))
                        const text = `${user.username} deleted card ${task.name}`
                        dispatch(
                          createNewActivity(
                            { text, boardId: task.boardId },
                            token,
                          ),
                        )
                      }}
                    >
                      <DeleteForeverIcon
                        fontSize="small"
                        style={{ backgroundColor: '#EBECF0' }}
                      />
                    </IconButton>
                  )}
                </div>
              )}
            </Paper>
          )}
        </div>
      )}
    </Draggable>
  )
}
Example #18
Source File: Boards.js    From Trellis with GNU General Public License v3.0 4 votes vote down vote up
export default function Boards() {
  const classes = useStyles()
  const [boardTitle, setBoardTitle] = useState('')
  const { boards, newBoard } = useSelector((state) => state.boards)
  const { token, isValid, user, tokenRequest } = useSelector(
    (state) => state.user,
  )
  const [showInput, setShowInput] = useState(false)
  const history = useHistory()
  const dispatch = useDispatch()

  useEffect(() => {
    document.title = `Home | Trellis`
  }, [])

  useEffect(() => {
    if (isValid) {
      dispatch(fetchAllBoards(token))
    }
  }, [token, isValid, dispatch])

  const handleChange = (e) => {
    e.preventDefault()
    setBoardTitle(e.target.value)
  }

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault()
      submitHandler()
    }
  }

  useEffect(() => {
    if (newBoard) {
      dispatch(
        createNewActivity(
          {
            text: `${user.username} created this board`,
            boardId: newBoard._id,
          },
          token,
        ),
      )
    }
  }, [newBoard, dispatch, token, user])

  const submitHandler = () => {
    if (boardTitle === '') return

    const postBoardReq = {
      name: boardTitle,
      userId: user.id,
      image: {
        color: 'white',
        thumb: imageUrls.thumb,
        full: imageUrls.full,
      },
    }
    dispatch(createNewBoard(postBoardReq))
    setBoardTitle('')
    setShowInput(false)
  }

  return (
    <>
      {isValid || tokenRequest ? (
        <div style={{ backgroundColor: '#FAFBFC' }}>
          <Header loggedIn />
          <div style={{ paddingTop: '80px' }}>
            <div className={classes.menuContainer}>
              {boards.map((board) => (
                <div
                  className={classes.card}
                  key={board._id}
                  style={{
                    backgroundColor: `${board.image.color}`,
                    backgroundImage: `url(${board.image.thumb})`,
                    backgroundSize: 'cover',
                    backgroundRepeat: 'no-repeat',
                  }}
                  onClick={(e) => {
                    e.preventDefault()
                    // window.location.href = `/b/${board._id}/${board.name}`
                    history.push(`/b/${board._id}/${board.name}`)
                  }}
                >
                  <div className={classes.title}>{board.name}</div>
                </div>
              ))}

              <div
                className={classes.card}
                style={{ backgroundColor: '#E7E9ED' }}
                onClick={() => setShowInput((prev) => !prev)}
              >
                <div
                  style={{
                    fontSize: '14px',
                    opacity: 0.8,
                    textAlign: 'center',
                    marginTop: '35px',
                  }}
                >
                  Create new board
                </div>
              </div>
              {showInput ? (
                <div className={classes.backdrop}>
                  <div
                    style={{
                      width: '260px',
                      marginLeft: '45%',
                      marginTop: '10%',
                      height: '100px',
                      borderRadius: 5,
                      zIndex: 50,
                      backgroundColor: 'white',
                      backgroundImage: `url(${imageUrls.full})`,
                      backgroundSize: 'cover',
                      backgroundRepeat: 'no-repeat',
                    }}
                  >
                    <InputBase
                      autoFocus
                      // multiline
                      fullWidth
                      value={boardTitle}
                      onChange={handleChange}
                      onKeyDown={handleKeyDown}
                      onBlur={() => {
                        submitHandler()
                        setShowInput(false)
                        setBoardTitle('')
                      }}
                      placeholder="Add board title..."
                      style={{
                        color: 'white',
                        fontWeight: 'bold',
                        width: '240px',
                        margin: '10px',
                        padding: '2px',
                        paddingLeft: '10px',
                        borderRadius: 5,
                        backgroundColor: 'hsla(0,0%,100%,.24)',
                        zIndex: 200,
                      }}
                    />
                    <Button
                      variant="contained"
                      style={{
                        backgroundColor: '#61BD4F',
                        textTransform: 'none',
                        color: '#F2FAF1',
                        padding: '0.65px',
                        marginLeft: '20px',
                      }}
                    >
                      Create
                    </Button>
                  </div>
                </div>
              ) : null}
            </div>
          </div>
        </div>
      ) : (
        <NotFound />
      )}
    </>
  )
}
Example #19
Source File: OftadehAppBar.jsx    From oftadeh-react-admin with MIT License 4 votes vote down vote up
OftadehAppBar = (props) => {
  const classes = useStyles(props);
  const { open, handleDrawerToggle, handleRightPanelOpen } = React.useContext(
    NavigationContext
  );

  const { setThemeName, curThemeName } = React.useContext(ThemeContext);

  return (
    <AppBar
      position="fixed"
      className={clsx(classes.appBar, {
        [classes.appBarShift]: open,
      })}
    >
      <Toolbar>
        <IconButton
          color="inherit"
          aria-label="open drawer"
          onClick={handleDrawerToggle}
          edge="start"
          className={classes.menuButton}
        >
          <MenuIcon />
        </IconButton>
        <div className={classes.search}>
          <div className={classes.searchIcon}>
            <SearchIcon />
          </div>
          <InputBase
            placeholder="Search…"
            classes={{
              root: classes.inputRoot,
              input: classes.inputInput,
            }}
            inputProps={{ "aria-label": "search" }}
          />
        </div>
        <div className={classes.grow} />
        <div className={classes.appbarSection}>
          <IconButton
            aria-haspopup="true"
            onClick={() =>
              curThemeName === "dark"
                ? setThemeName("light")
                : setThemeName("dark")
            }
            color="inherit"
          >
            {curThemeName === "dark" ? (
              <Brightness7Icon />
            ) : (
              <Brightness4Icon />
            )}
          </IconButton>
          <div className={classes.appbarToday}>
            <IconButton
              aria-haspopup="true"
              onClick={(event) => handleRightPanelOpen(event, 0)}
              color="inherit"
            >
              <TodayIcon />
            </IconButton>
            <IconButton
              aria-haspopup="true"
              onClick={(event) => handleRightPanelOpen(event, 2)}
              aria-label="show 4 new messages"
              color="inherit"
            >
              <Badge badgeContent={4} color="secondary">
                <MailIcon />
              </Badge>
            </IconButton>
          </div>
          <IconButton
            aria-haspopup="true"
            onClick={(event) => handleRightPanelOpen(event, 1)}
            aria-label="show 17 new notifications"
            color="inherit"
          >
            <Badge badgeContent={17} color="secondary">
              <NotificationsIcon />
            </Badge>
          </IconButton>
          <OftadehAvatarMenu />
        </div>
      </Toolbar>
    </AppBar>
  );
}
Example #20
Source File: Header.js    From react-code-splitting-2021-04-26 with MIT License 4 votes vote down vote up
export default function Header(props) {
  var classes = useStyles();

  // global
  var layoutState = useLayoutState();
  var layoutDispatch = useLayoutDispatch();
  var userDispatch = useUserDispatch();

  // local
  var [mailMenu, setMailMenu] = useState(null);
  var [isMailsUnread, setIsMailsUnread] = useState(true);
  var [notificationsMenu, setNotificationsMenu] = useState(null);
  var [isNotificationsUnread, setIsNotificationsUnread] = useState(true);
  var [profileMenu, setProfileMenu] = useState(null);
  var [isSearchOpen, setSearchOpen] = useState(false);

  return (
    <AppBar position="fixed" className={classes.appBar}>
      <Toolbar className={classes.toolbar}>
        <IconButton
          color="inherit"
          onClick={() => toggleSidebar(layoutDispatch)}
          className={classNames(
            classes.headerMenuButtonSandwich,
            classes.headerMenuButtonCollapse,
          )}
        >
          {layoutState.isSidebarOpened ? (
            <ArrowBackIcon
              classes={{
                root: classNames(
                  classes.headerIcon,
                  classes.headerIconCollapse,
                ),
              }}
            />
          ) : (
            <MenuIcon
              classes={{
                root: classNames(
                  classes.headerIcon,
                  classes.headerIconCollapse,
                ),
              }}
            />
          )}
        </IconButton>
        <Typography variant="h6" weight="medium" className={classes.logotype}>
          React Material Admin
        </Typography>
        <div className={classes.grow} />
        <Button component={Link} href="https://flatlogic.com/templates/react-material-admin-full" variant={"outlined"} color={"secondary"} className={classes.purchaseBtn}>Unlock full version</Button>
        <div
          className={classNames(classes.search, {
            [classes.searchFocused]: isSearchOpen,
          })}
        >
          <div
            className={classNames(classes.searchIcon, {
              [classes.searchIconOpened]: isSearchOpen,
            })}
            onClick={() => setSearchOpen(!isSearchOpen)}
          >
            <SearchIcon classes={{ root: classes.headerIcon }} />
          </div>
          <InputBase
            placeholder="Search…"
            classes={{
              root: classes.inputRoot,
              input: classes.inputInput,
            }}
          />
        </div>
        <IconButton
          color="inherit"
          aria-haspopup="true"
          aria-controls="mail-menu"
          onClick={e => {
            setNotificationsMenu(e.currentTarget);
            setIsNotificationsUnread(false);
          }}
          className={classes.headerMenuButton}
        >
          <Badge
            badgeContent={isNotificationsUnread ? notifications.length : null}
            color="warning"
          >
            <NotificationsIcon classes={{ root: classes.headerIcon }} />
          </Badge>
        </IconButton>
        <IconButton
          color="inherit"
          aria-haspopup="true"
          aria-controls="mail-menu"
          onClick={e => {
            setMailMenu(e.currentTarget);
            setIsMailsUnread(false);
          }}
          className={classes.headerMenuButton}
        >
          <Badge
            badgeContent={isMailsUnread ? messages.length : null}
            color="secondary"
          >
            <MailIcon classes={{ root: classes.headerIcon }} />
          </Badge>
        </IconButton>
        <IconButton
          aria-haspopup="true"
          color="inherit"
          className={classes.headerMenuButton}
          aria-controls="profile-menu"
          onClick={e => setProfileMenu(e.currentTarget)}
        >
          <AccountIcon classes={{ root: classes.headerIcon }} />
        </IconButton>
        <Menu
          id="mail-menu"
          open={Boolean(mailMenu)}
          anchorEl={mailMenu}
          onClose={() => setMailMenu(null)}
          MenuListProps={{ className: classes.headerMenuList }}
          className={classes.headerMenu}
          classes={{ paper: classes.profileMenu }}
          disableAutoFocusItem
        >
          <div className={classes.profileMenuUser}>
            <Typography variant="h4" weight="medium">
              New Messages
            </Typography>
            <Typography
              className={classes.profileMenuLink}
              component="a"
              color="secondary"
            >
              {messages.length} New Messages
            </Typography>
          </div>
          {messages.map(message => (
            <MenuItem key={message.id} className={classes.messageNotification}>
              <div className={classes.messageNotificationSide}>
                <UserAvatar color={message.variant} name={message.name} />
                <Typography size="sm" color="text" colorBrightness="secondary">
                  {message.time}
                </Typography>
              </div>
              <div
                className={classNames(
                  classes.messageNotificationSide,
                  classes.messageNotificationBodySide,
                )}
              >
                <Typography weight="medium" gutterBottom>
                  {message.name}
                </Typography>
                <Typography color="text" colorBrightness="secondary">
                  {message.message}
                </Typography>
              </div>
            </MenuItem>
          ))}
          <Fab
            variant="extended"
            color="primary"
            aria-label="Add"
            className={classes.sendMessageButton}
          >
            Send New Message
            <SendIcon className={classes.sendButtonIcon} />
          </Fab>
        </Menu>
        <Menu
          id="notifications-menu"
          open={Boolean(notificationsMenu)}
          anchorEl={notificationsMenu}
          onClose={() => setNotificationsMenu(null)}
          className={classes.headerMenu}
          disableAutoFocusItem
        >
          {notifications.map(notification => (
            <MenuItem
              key={notification.id}
              onClick={() => setNotificationsMenu(null)}
              className={classes.headerMenuItem}
            >
              <Notification {...notification} typographyVariant="inherit" />
            </MenuItem>
          ))}
        </Menu>
        <Menu
          id="profile-menu"
          open={Boolean(profileMenu)}
          anchorEl={profileMenu}
          onClose={() => setProfileMenu(null)}
          className={classes.headerMenu}
          classes={{ paper: classes.profileMenu }}
          disableAutoFocusItem
        >
          <div className={classes.profileMenuUser}>
            <Typography variant="h4" weight="medium">
              John Smith
            </Typography>
            <Typography
              className={classes.profileMenuLink}
              component="a"
              color="primary"
              href="https://flatlogic.com"
            >
              Flalogic.com
            </Typography>
          </div>
          <MenuItem
            className={classNames(
              classes.profileMenuItem,
              classes.headerMenuItem,
            )}
          >
            <AccountIcon className={classes.profileMenuIcon} /> Profile
          </MenuItem>
          <MenuItem
            className={classNames(
              classes.profileMenuItem,
              classes.headerMenuItem,
            )}
          >
            <AccountIcon className={classes.profileMenuIcon} /> Tasks
          </MenuItem>
          <MenuItem
            className={classNames(
              classes.profileMenuItem,
              classes.headerMenuItem,
            )}
          >
            <AccountIcon className={classes.profileMenuIcon} /> Messages
          </MenuItem>
          <div className={classes.profileMenuUser}>
            <Typography
              className={classes.profileMenuLink}
              color="primary"
              onClick={() => signOut(userDispatch, props.history)}
            >
              Sign Out
            </Typography>
          </div>
        </Menu>
      </Toolbar>
    </AppBar>
  );
}
Example #21
Source File: HeaderView.js    From react-code-splitting-2021-04-26 with MIT License 4 votes vote down vote up
Header = ({ classes, isSidebarOpened, toggleSidebar, ...props }) => (
  <AppBar position="fixed" className={classes.appBar}>
    <Toolbar className={classes.toolbar}>
      <IconButton
        color="inherit"
        onClick={toggleSidebar}
        className={classNames(
          classes.headerMenuButton,
          classes.headerMenuButtonCollapse
        )}
      >
        {isSidebarOpened ? (
          <ArrowBackIcon
            classes={{
              root: classNames(classes.headerIcon, classes.headerIconCollapse)
            }}
          />
        ) : (
          <MenuIcon
            classes={{
              root: classNames(classes.headerIcon, classes.headerIconCollapse)
            }}
          />
        )}
      </IconButton>
      <Typography variant="h6" weight="medium" className={classes.logotype}>React Material Admin</Typography>
      <div className={classes.grow} />
      <div
        className={classNames(classes.search, {
          [classes.searchFocused]: props.isSearchOpen
        })}
      >
        <div
          className={classNames(classes.searchIcon, {
            [classes.searchIconOpened]: props.isSearchOpen
          })}
          onClick={props.toggleSearch}
        >
          <SearchIcon classes={{ root: classes.headerIcon }} />
        </div>
        <InputBase
          placeholder="Search…"
          classes={{
            root: classes.inputRoot,
            input: classes.inputInput
          }}
        />
      </div>
      <IconButton
        color="inherit"
        aria-haspopup="true"
        aria-controls="mail-menu"
        onClick={props.openNotificationsMenu}
        className={classes.headerMenuButton}
      >
        <Badge
          badgeContent={
            props.isNotificationsUnread ? notifications.length : null
          }
          colortheme="warning"
        >
          <NotificationsIcon classes={{ root: classes.headerIcon }} />
        </Badge>
      </IconButton>
      <IconButton
        color="inherit"
        aria-haspopup="true"
        aria-controls="mail-menu"
        onClick={props.openMailMenu}
        className={classes.headerMenuButton}
      >
        <Badge
          badgeContent={props.isMailsUnread ? messages.length : null}
          color="secondary"
        >
          <MailIcon classes={{ root: classes.headerIcon }} />
        </Badge>
      </IconButton>
      <IconButton
        aria-haspopup="true"
        color="inherit"
        className={classes.headerMenuButton}
        aria-controls="profile-menu"
        onClick={props.openProfileMenu}
      >
        <AccountIcon classes={{ root: classes.headerIcon }} />
      </IconButton>
      <Menu
        id="mail-menu"
        open={Boolean(props.mailMenu)}
        anchorEl={props.mailMenu}
        onClose={props.closeMailMenu}
        MenuListProps={{ className: classes.headerMenuList }}
        className={classes.headerMenu}
        classes={{ paper: classes.profileMenu }}
        disableAutoFocusItem
      >
        <div className={classes.profileMenuUser}>
          <Typography variant="h4" weight="medium">
            New Messages
          </Typography>
          <Typography
            className={classes.profileMenuLink}
            component="a"
            color="secondary"
          >
            {messages.length} New Messages
          </Typography>
        </div>
        {messages.map(message => (
          <MenuItem key={message.id} className={classes.messageNotification}>
            <div className={classes.messageNotificationSide}>
              <UserAvatar color={message.variant} name={message.name} />
              <Typography size="sm" color="textSecondary">
                {message.time}
              </Typography>
            </div>
            <div
              className={classNames(
                classes.messageNotificationSide,
                classes.messageNotificationBodySide
              )}
            >
              <Typography weight="medium" gutterBottom>
                {message.name}
              </Typography>
              <Typography color="textSecondary">{message.message}</Typography>
            </div>
          </MenuItem>
        ))}
        <Fab
          variant="extended"
          color="primary"
          aria-label="Add"
          className={classes.sendMessageButton}
        >
          Send New Message
          <SendIcon className={classes.sendButtonIcon} />
        </Fab>
      </Menu>
      <Menu
        id="notifications-menu"
        open={Boolean(props.notificationsMenu)}
        anchorEl={props.notificationsMenu}
        onClose={props.closeNotificationsMenu}
        className={classes.headerMenu}
        disableAutoFocusItem
      >
        {notifications.map(notification => (
          <MenuItem
            key={notification.id}
            onClick={props.closeNotificationsMenu}
            className={classes.headerMenuItem}
          >
            <Notification {...notification} typographyVariant="inherit" />
          </MenuItem>
        ))}
      </Menu>
      <Menu
        id="profile-menu"
        open={Boolean(props.profileMenu)}
        anchorEl={props.profileMenu}
        onClose={props.closeProfileMenu}
        className={classes.headerMenu}
        classes={{ paper: classes.profileMenu }}
        disableAutoFocusItem
      >
        <div className={classes.profileMenuUser}>
          <Typography variant="h4" weight="medium">
            John Smith
          </Typography>
          <Typography
            className={classes.profileMenuLink}
            component="a"
            color="primary"
            href="https://flatlogic.com"
          >
            Flalogic.com
          </Typography>
        </div>
        <MenuItem
          className={classNames(
            classes.profileMenuItem,
            classes.headerMenuItem
          )}
        >
          <AccountIcon className={classes.profileMenuIcon} /> Profile
        </MenuItem>
        <MenuItem
          className={classNames(
            classes.profileMenuItem,
            classes.headerMenuItem
          )}
        >
          <AccountIcon className={classes.profileMenuIcon} /> Tasks
        </MenuItem>
        <MenuItem
          className={classNames(
            classes.profileMenuItem,
            classes.headerMenuItem
          )}
        >
          <AccountIcon className={classes.profileMenuIcon} /> Messages
        </MenuItem>
        <div className={classes.profileMenuUser}>
          <Typography
            className={classes.profileMenuLink}
            color="primary"
            onClick={props.signOut}
          >
            Sign Out
          </Typography>
        </div>
      </Menu>
    </Toolbar>
  </AppBar>
)
Example #22
Source File: Board.js    From Trellis with GNU General Public License v3.0 4 votes vote down vote up
export default function Board() {
  const classes = useStyles()
  /* eslint-disable-next-line */
  var { id, name } = useParams()
  const { loading, currBoard, error } = useSelector((state) => state.boards)
  const { listLoading, lists } = useSelector((state) => state.lists)
  const { cardLoading, cards } = useSelector((state) => state.cards)
  const { activities } = useSelector((state) => state.activities)
  const { isValid, user, token, tokenRequest } = useSelector(
    (state) => state.user,
  )
  const [initialData, setInitialData] = useState({})
  const [initDone, setInitDone] = useState(false)
  const addFlag = useRef(true)
  const [addListFlag, setAddListFlag] = useState(false)
  const [listTitle, setListTitle] = useState('')
  const [color, setColor] = useState('white')
  const [url, setUrl] = useState('')
  const [editable, setEditable] = useState(false)
  const [boardTitle, setBoardTitle] = useState('')
  const dispatch = useDispatch()

  if (!loading && name !== currBoard.name && currBoard.name !== undefined)
    name = currBoard.name
  else if (name === undefined) name = ''

  useEffect(() => {
    if (isValid && !error) {
      if (id.length === 24) {
        dispatch(fetchBoardById(id, token))
        dispatch(fetchListsFromBoard(id, token))
        dispatch(fetchsCardsFromBoard(id, token))
        dispatch(fetchActivitiesFromBoard(id, token))
      }
    }
  }, [dispatch, id, isValid, token, error])

  useEffect(() => {
    if (!_.isEmpty(currBoard)) {
      setColor(currBoard.image.color)
      setUrl(currBoard.image.full)
      setBoardTitle(currBoard.name)
      document.title = `${currBoard.name} | Trellis`
    }
  }, [currBoard])

  useEffect(() => {
    if (!listLoading && !cardLoading) {
      const prevState = { tasks: {}, columns: {}, columnOrder: [] }
      // eslint-disable-next-line no-shadow
      const getTaskIds = (id) => {
        const filteredTasks = _.filter(cards, { listId: id })
        const sortedTasks = _.orderBy(filteredTasks, ['order'], ['asc'])
        const taskIds = []
        sortedTasks.forEach((task) => taskIds.push(task._id))
        return taskIds
      }

      const setContent = () => {
        cards.forEach((card) => (prevState.tasks[card._id] = card))
        const sortedLists = _.orderBy(lists, ['order'], ['asc'])
        sortedLists.forEach((list) => {
          prevState.columns[list._id] = {
            ...list,
            taskIds: getTaskIds(list._id),
          }
          prevState.columnOrder.push(list._id)
        })
      }
      setContent()
      setInitialData({ ...prevState })
      setInitDone(true)
    }
  }, [setInitDone, listLoading, cardLoading, setInitialData, cards, lists])

  const onDragEnd = (result) => {
    // eslint-disable-next-line no-var
    var newOrder
    const { destination, source, draggableId, type } = result
    if (!destination) return
    if (
      destination.droppableId === source.droppableId &&
      destination.index === source.index
    )
      return

    if (type === 'list') {
      const listOrder = initialData.columnOrder
      if (destination.index === 0) {
        newOrder = midString('', initialData.columns[listOrder[0]].order)
      } else if (destination.index === listOrder.length - 1) {
        newOrder = midString(
          initialData.columns[listOrder[destination.index]].order,
          '',
        )
      } else if (destination.index < source.index) {
        newOrder = midString(
          initialData.columns[listOrder[destination.index - 1]].order,
          initialData.columns[listOrder[destination.index]].order,
        )
      } else {
        newOrder = midString(
          initialData.columns[listOrder[destination.index]].order,
          initialData.columns[listOrder[destination.index + 1]].order,
        )
      }
      dispatch(updateListById(draggableId, { order: newOrder }))
      const newListOrder = Array.from(initialData.columnOrder)
      const destinationColumn = initialData.columns[draggableId]
      destinationColumn.order = newOrder
      newListOrder.splice(source.index, 1)
      newListOrder.splice(destination.index, 0, draggableId)
      const newData = {
        ...initialData,
        columnOrder: newListOrder,
        columns: {
          ...initialData.columns,
          draggableId: destinationColumn,
        },
      }
      setInitialData(newData)
      return
    }
    const startList = initialData.columns[source.droppableId]
    const endList = initialData.columns[destination.droppableId]

    if (startList === endList) {
      const column = startList
      if (destination.index === 0)
        newOrder = midString('', initialData.tasks[column.taskIds[0]].order)
      else if (destination.index === column.taskIds.length - 1)
        newOrder = midString(
          initialData.tasks[column.taskIds[destination.index]].order,
          '',
        )
      else if (destination.index < source.index)
        newOrder = midString(
          initialData.tasks[column.taskIds[destination.index - 1]].order,
          initialData.tasks[column.taskIds[destination.index]].order,
        )
      else
        newOrder = midString(
          initialData.tasks[column.taskIds[destination.index]].order,
          initialData.tasks[column.taskIds[destination.index + 1]].order,
        )

      dispatch(updateCardById(draggableId, { order: newOrder }))
      const newTaskIds = Array.from(column.taskIds)
      newTaskIds.splice(source.index, 1)
      newTaskIds.splice(destination.index, 0, draggableId)
      const destinationTask = initialData.tasks[draggableId]
      destinationTask.order = newOrder
      const newColumn = {
        ...column,
        taskIds: newTaskIds,
      }
      const newData = {
        ...initialData,
        columns: {
          ...initialData.columns,
          [newColumn._id]: newColumn,
        },
        tasks: {
          ...initialData.tasks,
          draggableId: destinationTask,
        },
      }
      setInitialData(newData)
      return
    }

    // Move from one list to another
    if (endList.taskIds.length === 0) newOrder = 'n'
    else if (destination.index === 0) {
      newOrder = midString('', initialData.tasks[endList.taskIds[0]].order)
    } else if (destination.index === endList.taskIds.length)
      newOrder = midString(
        initialData.tasks[endList.taskIds[destination.index - 1]].order,
        '',
      )
    else
      newOrder = midString(
        initialData.tasks[endList.taskIds[destination.index - 1]].order,
        initialData.tasks[endList.taskIds[destination.index]].order,
      )
    dispatch(
      updateCardById(draggableId, { order: newOrder, listId: endList._id }),
    )
    const text = `${user.username} moved ${initialData.tasks[draggableId].name} from ${startList.name} to ${endList.name}`
    const recentActivity = activities[activities.length - 1]
    if (
      recentActivity.text ===
        `${user.username} moved ${initialData.tasks[draggableId].name} from ${endList.name} to ${startList.name}` &&
      moment(recentActivity.createdAt).fromNow().includes('second')
    ) {
      dispatch(deleteActivityById(recentActivity._id))
    } else dispatch(createNewActivity({ text, boardId: currBoard._id }, token))

    const startTaskIds = Array.from(startList.taskIds)
    startTaskIds.splice(source.index, 1)
    const newStartList = {
      ...startList,
      taskIds: startTaskIds,
    }
    const destinationTask = initialData.tasks[draggableId]
    destinationTask.order = newOrder
    const endTaskIds = Array.from(endList.taskIds)
    endTaskIds.splice(destination.index, 0, draggableId)
    const newEndList = {
      ...endList,
      taskIds: endTaskIds,
    }
    const newData = {
      ...initialData,
      columns: {
        ...initialData.columns,
        [newStartList._id]: newStartList,
        [newEndList._id]: newEndList,
      },
      tasks: {
        ...initialData.tasks,
        draggableId: destinationTask,
      },
    }
    setInitialData(newData)
  }

  if (id.length < 24) return <h1>Invalid URL</h1>
  const handleChange = (e) => {
    e.preventDefault()
    setListTitle(e.target.value)
  }

  const submitHandler = () => {
    if (listTitle === '') return
    const text = listTitle.trim().replace(/\s+/g, ' ')
    if (text === '') {
      setListTitle(listTitle)
      return
    }
    const totalLists = initialData.columnOrder.length
    const postListReq = {
      name: text,
      boardId: currBoard._id,
      order:
        totalLists === 0
          ? 'n'
          : midString(
              initialData.columns[initialData.columnOrder[totalLists - 1]]
                .order,
              '',
            ),
    }
    dispatch(createNewList(postListReq, token))
    dispatch(
      createNewActivity(
        {
          text: `${user.username} added ${listTitle} to this board`,
          boardId: currBoard._id,
        },
        token,
      ),
    )
    setListTitle('')
  }

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault()
      submitHandler()
    }
  }

  const closeButtonHandler = () => {
    setAddListFlag(false)
    addFlag.current = true
    setListTitle('')
  }

  const handleAddition = () => {
    setAddListFlag(true)
    addFlag.current = false
  }
  const setBackground = (background) => {
    if (background.thumb) {
      setUrl(background.full)
      setColor('white')
      dispatch(
        updateBoardById(
          currBoard._id,
          {
            image: {
              full: background.full,
              thumb: background.thumb,
              color: 'white',
            },
          },
          token,
        ),
      )
    } else {
      setColor(background)
      setUrl('')
      dispatch(
        updateBoardById(
          currBoard._id,
          {
            image: {
              full: '',
              thumb: '',
              color: background,
            },
          },
          token,
        ),
      )
    }
  }

  return (
    <>
      {isValid || tokenRequest ? (
        <div
          className={classes.root}
          style={{
            backgroundColor: `${color}`,
            backgroundImage: `url(${url})`,
            backgroundSize: 'cover',
            backgroundRepeat: 'no-repeat',
          }}
        >
          <Redirect to={`/b/${id}/${name}`} />
          <Header loggedIn />
          {editable ? (
            <div className={classes.editable}>
              <InputBase
                onChange={(e) => {
                  e.preventDefault()
                  setBoardTitle(e.target.value)
                }}
                fullWidth
                value={boardTitle}
                style={{
                  fontWeight: 'bold',
                  fontFamily: 'sans-serif',
                  fontSize: '20px',
                }}
                autoFocus
                onFocus={(e) => {
                  const val = e.target.value
                  e.target.value = ''
                  e.target.value = val
                }}
                onBlur={() => {
                  setEditable(false)
                  const text = boardTitle.trim().replace(/\s+/g, ' ')
                  if (text === '') {
                    setBoardTitle(currBoard.name)
                    return
                  }
                  dispatch(updateBoardById(id, { name: text }, token))
                  currBoard.name = boardTitle
                }}
              />
            </div>
          ) : (
            <BoardHeader
              title={currBoard.name}
              showEditable={() => setEditable(true)}
            />
          )}
          <DragDropContext onDragEnd={onDragEnd}>
            <Droppable
              droppableId="all-columns"
              direction="horizontal"
              type="list"
            >
              {(provided) => (
                <div
                  className={classes.listContainer}
                  {...provided.droppableProps}
                  ref={provided.innerRef}
                >
                  {initDone &&
                    initialData.columnOrder.map((columnId, index) => {
                      const column = initialData.columns[columnId]
                      const tasks = column.taskIds.map(
                        (taskId) => initialData.tasks[taskId],
                      )
                      return (
                        <List
                          key={column._id}
                          column={column}
                          tasks={tasks}
                          index={index}
                        />
                      )
                    })}
                  <div className={classes.wrapper}>
                    {addFlag.current && (
                      <AddItem
                        handleClick={handleAddition}
                        btnText="Add another list"
                        type="list"
                        icon={<AddIcon />}
                        width="256px"
                        color="white"
                      />
                    )}
                    {addListFlag && (
                      <InputCard
                        value={listTitle}
                        changedHandler={handleChange}
                        itemAdded={submitHandler}
                        closeHandler={closeButtonHandler}
                        keyDownHandler={handleKeyDown}
                        type="list"
                        btnText="Add List"
                        placeholder="Enter list title..."
                        width="230px"
                        marginLeft="1"
                      />
                    )}
                  </div>
                  {provided.placeholder}
                </div>
              )}
            </Droppable>
          </DragDropContext>
          <SideMenu
            setBackground={setBackground}
            board={{ id, color, url, title: boardTitle }}
          />
        </div>
      ) : (
        <NotFound />
      )}
    </>
  )
}
Example #23
Source File: index.js    From Artion-Client with GNU General Public License v3.0 4 votes vote down vote up
ExploreCollections = () => {
  const dispatch = useDispatch();

  const classes = useStyles();
  const [filter, setFilter] = useState('');

  const { collections: collectionItems, collectionsLoading } = useSelector(
    state => state.Collections
  );
  const { collections } = useSelector(state => state.Filter);

  const handleSelectCollection = addr => {
    let newCollections = [];
    if (collections.includes(addr)) {
      newCollections = collections.filter(item => item !== addr);
    } else {
      newCollections = [...collections, addr];
    }
    dispatch(FilterActions.updateCollectionsFilter(newCollections));
  };

  const filteredCollections = () => {
    const selected = [];
    let unselected = [];
    collectionItems.map(item => {
      if (collections.includes(item.address)) {
        selected.push(item);
      } else {
        unselected.push(item);
      }
    });
    unselected = unselected.filter(
      item =>
        (item.name || item.collectionName || '')
          .toLowerCase()
          .indexOf(filter.toLowerCase()) > -1
    );
    return [...selected, ...unselected];
  };

  return (
    <FilterWrapper title="Collections" classes={{ body: classes.body }}>
      <div className={classes.collectionExpandDiv}>
        <SearchIcon className={classes.iconButton} />
        <InputBase
          className={classes.input}
          placeholder="Filter"
          inputProps={{ 'aria-label': 'Filter' }}
          value={filter}
          onChange={e => setFilter(e.target.value)}
        />
      </div>
      <div className={classes.collectionsList}>
        {collectionsLoading &&
          collectionItems.length === 0 &&
          new Array(8)
            .fill(0)
            .map((_, idx) => (
              <Skeleton
                key={idx}
                width="100%"
                height={40}
                className={classes.collection}
              />
            ))}
        {filteredCollections()
          .filter(item => item.isVisible)
          .map((item, idx) => (
            <div
              key={idx}
              className={classes.collection}
              onClick={() => handleSelectCollection(item.address)}
            >
              {collections.includes(item.address) ? (
                <div className={cx(classes.logo, classes.withBorder)}>
                  <img src={iconCheck} />
                </div>
              ) : (
                <img
                  className={classes.logo}
                  src={
                    item.logoImageHash
                      ? `${getRandomIPFS('', true)}${item.logoImageHash}`
                      : collections.includes(item.address)
                      ? nftActiveIcon
                      : nftIcon
                  }
                />
              )}
              <span className={classes.name}>
                {item.name || item.collectionName}
              </span>
              {item.isVerified && (
                <BootstrapTooltip title="Verified Collection" placement="top">
                  <CheckCircleIcon className={classes.checkIcon} />
                </BootstrapTooltip>
              )}
            </div>
          ))}
      </div>
    </FilterWrapper>
  );
}
Example #24
Source File: layout.jsx    From animeworldz with MIT License 4 votes vote down vote up
function Layout({ window, children }) {
  const theme = useTheme();
  const classes = useStyles();
  const history = useHistory();
  const location = useLocation();
  const [searchResult, setSearchResult] = useState([]);
  const [time, setTime] = useState(new Date().toLocaleTimeString());
  const { darkMode, setDarkMode } = useContext(DarkModeContext);
  const [keyword, setKeyword] = useState("");
  const [mobileOpen, setMobileOpen] = React.useState(false);

  useEffect(() => {
    setInterval(() => {
      setTime(new Date().toLocaleTimeString());
    }, 1000);
  }, []);

  const menuItems = [
    {
      text: "HomePage",
      icon: <HomeRounded />,
      path: "/",
    },
    {
      text: "Waifu Pics",
      icon: <ImageRounded />,
      path: "/waifu",
    },
  ];

  const drawer = (
    <div>
      <div>
        <Typography variant="h5" className={classes.title}>
          ANIMEWORLD-Z
        </Typography>
      </div>
      <Divider />
      <List>
        {menuItems.map((menu, i) => (
          <ListItem
            key={i}
            button
            onClick={() => history.push(menu.path)}
            className={location.pathname === menu.path ? classes.active : null}
          >
            <ListItemIcon>{menu.icon}</ListItemIcon>
            <ListItemText primary={menu.text} />
          </ListItem>
        ))}
      </List>
      <div className={classes.footer}>
        <Typography variant="h6" className={classes.version}>
          v2.1
        </Typography>
      </div>
    </div>
  );

  const handleSwitch = (event) => {
    setDarkMode(event.target.checked);
  };

  const handleSearch = (event) => {
    const { value } = event.target;
    setKeyword(value);
  };

  const getSearchAnime = () => {
    if (keyword) {
      axios
        .get(`/api/v1/anime/${keyword}`)
        .then((response) => {
          setSearchResult(response.data);
        })
        .catch((err) => console.log(err));
    } else {
      setSearchResult([]);
    }
  };

  const handleDrawerToggle = () => {
    setMobileOpen(!mobileOpen);
  };

  const handleResetKeyword = () => {
    setKeyword("");
  };

  useEffect(() => {
    let timer = setTimeout(() => getSearchAnime(), 1000);
    return () => clearTimeout(timer);
  }, [keyword]);

  const container =
    window !== undefined ? () => window().document.body : undefined;

  return (
    <div className={classes.root}>
      <CssBaseline />
      {keyword !== "" ? (
        <SearchList
          results={searchResult}
          handleResetKeyword={handleResetKeyword}
        />
      ) : (
        ""
      )}
      <AppBar className={classes.appBar} color="dafault">
        <Toolbar>
          <IconButton
            color="inherit"
            aria-label="open drawer"
            edge="start"
            onClick={handleDrawerToggle}
            className={classes.menuButton}
          >
            <MenuBookRounded />
          </IconButton>
          <Typography className={classes.time}>{time}</Typography>
          <div className={classes.search}>
            <div className={classes.searchIcon}>
              <SearchOutlined />
            </div>
            <InputBase
              placeholder="Search…"
              classes={{
                root: classes.inputRoot,
                input: classes.inputInput,
              }}
              inputProps={{ "aria-label": "search" }}
              onChange={handleSearch}
              value={keyword}
            />
          </div>
          <Switch checked={darkMode} onChange={handleSwitch} />
        </Toolbar>
      </AppBar>
      <nav className={classes.drawer}>
        {/* The implementation can be swapped with js to avoid SEO duplication of links. */}
        <Hidden smUp implementation="css">
          <Drawer
            container={container}
            variant="temporary"
            anchor={theme.direction === "rtl" ? "right" : "left"}
            open={mobileOpen}
            onClose={handleDrawerToggle}
            classes={{
              paper: classes.drawerPaper,
            }}
            ModalProps={{
              keepMounted: true, // Better open performance on mobile.
            }}
          >
            {drawer}
          </Drawer>
        </Hidden>
        <Hidden xsDown implementation="css">
          <Drawer
            classes={{
              paper: classes.drawerPaper,
            }}
            variant="permanent"
            open
          >
            {drawer}
          </Drawer>
        </Hidden>
      </nav>
      <div className={classes.page}>
        <div className={classes.toolbar}></div>
        {children}
      </div>
    </div>
  );
}
Example #25
Source File: SearchInput.js    From covid-19 with MIT License 4 votes vote down vote up
SearchInput = (props) => {
  const classes = useStyles();
  const world = useContext(WorldContext);

  const [results, setResults] = React.useState([]);

  // Force the search index to lazy load
  React.useEffect(() => {
    world.get(Path.root(), SearchIndexComponent);
  });

  const onClose = () => {
    setResults([]);
  };

  const onChange = (e) => {
    const search = world.get(SEARCH_INDEX_PATH, SearchIndexComponent);
    if (!search) {
      return;
    }

    setResults(search.search(e.target.value));
  };

  const onChoice = (e, path) => {
    e.preventDefault();
    setResults([]);
    props.onChoice(path);
  };

  const resultRenderer = ({index, key, style}) => {
    const {name, path} = results[index];

    return (
      <div key={key} style={style} className={classes.result}>
        <MaterialLink href="#" onClick={(e) => onChoice(e, path)}>
          {name}
        </MaterialLink>
      </div>
    );
  };

  return (
    <ClickAwayListener onClickAway={onClose}>
      <div className={`${classes.root} ${props.className || ''}`}>
        <SearchIcon className={classes.searchIcon} />
        <InputBase
            className={classes.input}
            onChange={onChange}
            placerholder="Search..." />
        {props.onGeolocate &&
            <Divider className={classes.divider} />
        }
        {props.onGeolocate &&
            <IconButton
                size="small"
                className={classes.iconButton}
                onClick={props.onGeolocate}>
              <LocationSearchingIcon />
            </IconButton>
        }
        <Paper
            className={
              `${classes.resultsContainer} `
                  + (results.length === 0 ? 'hide' : '')
            }
            elevation={3}>
          <AutoSizer disableHeight>
            {({width}) => (
              <List
                  className={classes.resultsList}
                  rowCount={results.length}
                  rowHeight={RESULT_HEIGHT}
                  rowRenderer={resultRenderer}
                  width={width}
                  height={Math.min(RESULTS_MAX_HEIGHT, RESULT_HEIGHT * results.length)}
              />
            )}
          </AutoSizer>
        </Paper>
      </div>
    </ClickAwayListener>
  );
}