@material-ui/core#TextareaAutosize JavaScript Examples

The following examples show how to use @material-ui/core#TextareaAutosize. 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: MnemonicTextarea.js    From akashlytics-deploy with GNU General Public License v3.0 6 votes vote down vote up
export function MnemonicTextarea({ mnemonic }) {
  const classes = useStyles();
  const { enqueueSnackbar } = useSnackbar();

  const onCopyClick = () => {
    copyTextToClipboard(mnemonic);
    enqueueSnackbar(<Snackbar title="Mnemonic copied to clipboard!" iconVariant="success" />, {
      variant: "success",
      autoHideDuration: 2000
    });
  };

  return (
    <Box position="relative">
      <TextareaAutosize value={mnemonic} className={classes.textArea} rowsMin={5} contentEditable={false} />

      <IconButton onClick={onCopyClick} className={classes.copyButton} size="small">
        <FileCopyIcon fontSize="small" />
      </IconButton>
    </Box>
  );
}
Example #2
Source File: ToolbarExtension.js    From eSim-Cloud with GNU General Public License v3.0 6 votes vote down vote up
// Dialog box to display generated netlist
export function NetlistModal ({ open, close, netlist }) {
  const netfile = useSelector(state => state.netlistReducer)
  const createNetlistFile = () => {
    const titleA = netfile.title.split(' ')[1]
    const blob = new Blob([netlist], { type: 'text/plain;charset=utf-8' })
    FileSaver.saveAs(blob, `${titleA}_eSim_on_cloud.cir`)
  }
  return (
    <Dialog
      open={open}
      onClose={close}
      TransitionComponent={Transition}
      keepMounted
      aria-labelledby="generate-netlist"
      aria-describedby="generate-netlist-description"
    >
      <DialogTitle id="generate-netlist-title">{'Netlist Generator'}</DialogTitle>
      <DialogContent dividers>
        <DialogContentText id="generate-netlist-description">
          Current Netlist for given schematic...<br /><br />
          <TextareaAutosize aria-label="empty textarea" rowsMin={20} rowsMax={50} style={{ minWidth: '500px' }} value={netlist} />
        </DialogContentText>
      </DialogContent>
      <DialogActions>
        {/* Button to download the netlist */}
        <Button color="primary" onClick={createNetlistFile}>
          Download
        </Button>
        <Button onClick={close} color="primary" autoFocus>
          Close
        </Button>
      </DialogActions>
    </Dialog>
  )
}
Example #3
Source File: RequestDataModal.js    From ehr with GNU Affero General Public License v3.0 5 votes vote down vote up
render() {
        return (
            <Dialog fullWidth={true} open={this.props.isOpen}>
                <DialogTitle>
                    <Box display="flex" alignItems="center">
                        <Box flexGrow={1}>{t('ehr', 'Request Data')}</Box>
                        <Box>
                            <IconButton onClick={this.props.onClose}>
                                <CloseIcon />
                            </IconButton>
                        </Box>
                    </Box>
                </DialogTitle>
                <DialogContent>
                    <Grid container direction="column">
                        <Grid item xs={6}>
                            <KailonaTextField
                                inputRef={this.toEmailRef}
                                id="providerEmail"
                                type="text"
                                label={t('ehr', 'Email')}
                                style={{ width: '100%' }}
                            />
                        </Grid>
                        <Grid item xs={12} style={{ marginTop: '20px' }}>
                            <Grid container direction="column">
                                <Grid item>
                                    <Typography variant="body2">{t('ehr', 'Message to Provider:')}</Typography>
                                </Grid>
                                <Grid item>
                                    <TextareaAutosize
                                        ref={this.emailBodyRef}
                                        rowsMin={5}
                                        defaultValue={this.defaultEmailBody}
                                        style={{ width: '100%', resize: 'vertical' }}
                                    />
                                </Grid>
                            </Grid>
                        </Grid>
                    </Grid>
                </DialogContent>
                <DialogActions>
                    <KailonaButton
                        class="default"
                        title={t('ehr', 'Cancel')}
                        onClick={this.props.onClose}
                        disabled={this.state.loading}
                    />
                    <KailonaButton
                        class="primary"
                        title={t('ehr', 'Send Request')}
                        onClick={this.sendRequest}
                        loading={this.state.loading}
                        disabled={this.state.loading}
                    />
                </DialogActions>
            </Dialog>
        );
    }
Example #4
Source File: Job.jsx    From Edlib with GNU General Public License v3.0 5 votes vote down vote up
Job = ({
    start,
    status,
    name,
    onStop,
    showKillButton,
    showResumeButton,
    showInput,
    onResume,
    data,
    setData,
}) => {
    return (
        <>
            <h2>{name}</h2>
            {showInput && (
                <Box>
                    <TextareaAutosize
                        value={data}
                        onChange={(e) => setData(e.target.value)}
                    />
                </Box>
            )}
            {status.loading && (
                <>
                    <div>
                        <CircularProgress />
                    </div>
                    <div>
                        <LinearProgress
                            variant="determinate"
                            value={status.percentDone || 0}
                        />
                    </div>
                    <div>{status.message}</div>
                    {!status.killingStarted && showKillButton && (
                        <div>
                            <Button variant="contained" onClick={onStop}>
                                Stop
                            </Button>
                        </div>
                    )}
                </>
            )}
            {status.done && <Alert severity="success">{status.message}</Alert>}
            {status.error && <Alert severity="error">{status.message}</Alert>}
            {!status.loading && (
                <Button
                    onClick={start}
                    disabled={showInput && data === ''}
                    variant="contained"
                    color="primary"
                >
                    Start
                </Button>
            )}
            {!status.loading &&
                !status.done &&
                !status.error &&
                showResumeButton && <Button onClick={onResume}>Resume</Button>}
        </>
    );
}
Example #5
Source File: CommentForm.js    From youtube-clone with MIT License 5 votes vote down vote up
CommentForm = ({ videoId, commentTo, handleReplyComment }) => {
  const [comment, setComment] = useState("");
  const dispatch = useDispatch();
  const isAuth = useSelector(({ channel }) => channel.isAuth);
  const userId = useSelector(({ channel }) => channel.id);
  const channelImg = useSelector(({ channel }) => channel.image);
  const classes = useStyles();

  const handleChange = (e) => setComment(e.target.value);
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (isAuth) {
      const data = {
        videoId,
        content: comment,
        commentBy: userId,
        commentTo,
      };
      setComment("");
      try {
        const {
          data: { comment: newComment },
        } = await api.post("/api/comments", data);
        handleReplyComment();
        dispatch(addComment(newComment));
      } catch (err) {
        console.log(err);
      }
    } else {
      window.location.assign(urlJoin(BACKEND_URL, "/api/auth/google"));
    }
  };

  return (
    <form className={classes.root}>
      <Avatar alt="Avatar" src={channelImg} />
      <TextareaAutosize
        onChange={handleChange}
        value={comment}
        rowsMin={2}
        className={classes.textArea}
        placeholder="Add a public comment..."
      />
      <Button
        disableElevation
        disableFocusRipple
        disableRipple
        variant="contained"
        color="secondary"
        className={classes.commentBtn}
        type="submit"
        onClick={handleSubmit}
        disabled={!comment}
      >
        Comment
      </Button>
    </form>
  );
}
Example #6
Source File: WebChatTextInput.js    From WhatsApp-Clone with MIT License 5 votes vote down vote up
ChatTextInput = ({ onSendMessage, onTyping }) => {
  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}>
      <div style={styles.smileView}>
        <Mood style={styles.menuIcons} />
      </div>
      {/* <div style={{ width: "90%", justifyContent: "center", maxHeight: 120 }}>  */}
      <TextareaAutosize
        style={styles.userMessage}
        placeholder="Type a message ..."
        value={message}
        onKeyPress={e => handleKeyDown(e)}
        onChange={event => {
          onTyping(event);
          setMessage(event.target.value);
        }}
      />
      {/* <TextareaAutosize  aria-label="empty textarea" placeholder="Empty" /> */}
      {/* </div> */}
      <div style={styles.sendIconView}>
        <Avatar
          style={{
            backgroundColor: HEADER_COLOR
          }}
        >
          <Mic style={styles.sendIcon} />
        </Avatar>
      </div>
    </div>
    // </Paper>
  );
}
Example #7
Source File: ComponentProperties.js    From eSim-Cloud with GNU General Public License v3.0 4 votes vote down vote up
export default function ComponentProperties () {
  // component properties that are displayed on the right side bar when user clicks on a component on the grid.

  const properties = useSelector(state => state.componentPropertiesReducer.compProperties)
  const isOpen = useSelector(state => state.componentPropertiesReducer.isPropertiesWindowOpen)
  const id = useSelector(state => state.componentPropertiesReducer.id)
  let x = useSelector(state => state.componentPropertiesReducer.x) + 50
  let y = useSelector(state => state.componentPropertiesReducer.y)
  const [height, setHeight] = useState(0)
  const [width, setWidth] = useState(0)
  const [val, setVal] = useState(properties)

  useEffect(() => {
    if (isOpen) {
      const temp = document.getElementById('properties-modal').clientHeight
      const temp2 = document.getElementById('properties-modal').clientWidth
      console.log(window.screen.width, temp2)
      console.log(x)
      if (0.6 * window.screen.height - 260 - y < temp) {
        if (temp + 100 >= y) {
          // eslint-disable-next-line
          y = 100 
        }
        else {
          // eslint-disable-next-line
          y = y - temp 
        }
      }
      if (x > window.screen.width - 547) {
        // eslint-disable-next-line
        x = x - 380
      }
      setHeight(y)
      setWidth(x)
    }
  }, [isOpen])

  const dispatch = useDispatch()

  useEffect(() => {
    setVal(properties)
  }, [properties])

  const getInputValues = (evt) => {
    const value = evt.target.value
    setVal({
      ...val,
      [evt.target.id]: value
    })
  }

  const setProps = () => {
    dispatch(setCompProperties(id, val))
  }

  return (
    isOpen &&
    <div id="properties-modal" style={{ position: 'absolute', left: `${width}px`, top: `${height}px` }}>
      <Draggable handle=".handle" bounds={{ left: 250 - width, right: window.screen.width - 550 - width, top: 100 - height, bottom: window.screen.height - 762 }}>
        <Paper>
          <List style={{ maxHeight: 500, maxWidth: 270, overflowY: 'scroll', overflowX: 'scroll' }}>
            <ListItem className="handle">
              <ListItemText style={{ cursor: 'move' }} primary='Component Properties' secondary={properties.NAME} />
            </ListItem>
            {
              Object.keys(properties).map((keyName, i) => {
                if (keyName === 'MODEL') {
                  return <ListItem key={i}>
                    <TextareaAutosize rowsMax={4} id={keyName} label={keyName} value={val[keyName] || ''} rowsMin={4} aria-label={keyName} onChange={getInputValues} placeholder={keyName} style={{ width: '100%' }} />
                  </ListItem>
                  // eslint-disable-next-line brace-style
                }
                else if (keyName === 'EXTRA_EXPRESSION') {
                  return <ListItem key={i}>
                    <TextareaAutosize rowsMax={4} id={keyName} label={keyName} value={val[keyName] || ''} rowsMin={4} aria-label={keyName} onChange={getInputValues} placeholder={'EXPRESSION'} style={{ width: '100%' }} />
                  </ListItem>
                }
                else if (keyName.charAt(0) === 'N' && keyName !== 'NAME') {
                  return <span key={i} />
                } else if (keyName.includes('UNIT')) {
                  return <span key={i} />
                }
                else if (keyName === 'PREFIX') {
                  return (
                    <ListItem key={i}>
                      <TextField id={keyName} label='LABEL' value={val[keyName] || ''} size='small' variant="outlined" onChange={getInputValues} />
                    </ListItem>)
                }
                else if (keyName === 'NAME') {
                  return (
                    <ListItem key={i}>
                      <TextField disabled id={keyName} label='COMPONENT NAME' value={val[keyName] || ''} size='small' variant="outlined" onChange={getInputValues} />
                    </ListItem>)
                }
                return (
                  <ListItem key={i}>
                    <TextField id={keyName} label={keyName} value={val[keyName] || ''} size='small' variant="outlined" onChange={getInputValues} />
                    {val[`${keyName}_UNIT`] && <span style={{ marginLeft: '10px' }}>{val[`${keyName}_UNIT`] || ''}</span>}
                  </ListItem>)
              })
            }
            <ListItem>
              <Button size='small' variant="contained" color="primary" onClick={setProps}>SET PARAMETERS</Button>
            </ListItem>
          </List>
        </Paper>
      </Draggable>
    </div>
  )
}
Example #8
Source File: PropertiesSidebar.js    From eSim-Cloud with GNU General Public License v3.0 4 votes vote down vote up
export default function PropertiesSidebar ({ gridRef, outlineRef }) {
  const classes = useStyles()

  const schSave = useSelector(state => state.saveSchematicReducer)

  const [description, setDescription] = React.useState(schSave.description)
  const [versions, setVersions] = React.useState(null)
  const [branchOpen, setBranchOpen] = React.useState(null)
  const [branchName, setBranchName] = React.useState('')
  const [dialogOpen, setDialogOpen] = React.useState(false)

  const [projectBranch, setProjectBranch] = React.useState(null)
  const [projectVersion, setProjectVersion] = React.useState(null)

  const [anchorEl, setAnchorEl] = React.useState(null)

  const [popoverOpen, setPopoverOpen] = React.useState(null)

  React.useEffect(() => {
    const config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }
    const token = localStorage.getItem('esim_token')
    // If token available add to headers
    if (token) {
      config.headers.Authorization = `Token ${token}`
    }
    if (window.location.href.split('?id=')[1] && !window.location.href.split('?id=')[1].includes('gallery')) {
      api
        .get(
          'save/versions/' +
          window.location.href.split('?id=')[1].substring(0, 36),
          config
        )
        .then((resp) => {
          if (resp.data.length > 0) {
            setProjectBranch(resp.data[0].project_branch)
            setProjectVersion(resp.data[0].project_version)
          }
          const versionsAccordingFreq = {}
          resp.data.forEach((value) => {
            const d = new Date(value.save_time)
            value.full_time = d
            value.date =
              d.getDate() + '/' + parseInt(d.getMonth() + 1) + '/' + d.getFullYear()
            value.time = d.getHours() + ':' + d.getMinutes()
            if (d.getMinutes() < 10) {
              value.time = d.getHours() + ':0' + d.getMinutes()
            }
            versionsAccordingFreq[value.branch] ? versionsAccordingFreq[value.branch].push(value) : versionsAccordingFreq[value.branch] = [value]
          })
          const versionsArray = Object.entries(versionsAccordingFreq)
          for (let i = 0; i < versionsArray.length; i++) {
            versionsArray[i][1].sort((a, b) => {
              return b.full_time - a.full_time
            })
          }
          versionsArray.sort((a, b) => {
            return b[1][b[1].length - 1].full_time - a[1][a[1].length - 1].full_time
          })
          setVersions(versionsArray)
          const temp = []
          for (let j = 0; j < versionsArray.length; j++) {
            if (decodeURI(window.location.href.split('branch=')[1]) === versionsArray[j][0]) { temp.push(true) } else { temp.push(false) }
          }
          const popoverTemp = new Array(versionsArray.length)
          popoverTemp.fill(false)
          setPopoverOpen(popoverTemp)
          setBranchOpen(temp)
        })
        .catch((err) => {
          console.log(err)
        })
    }
  }, [])

  const dispatch = useDispatch()

  const getInputValues = (evt) => {
    setDescription(`${evt.target.value}`)
    dispatch(setSchDescription(evt.target.value))
  }

  async function exportImage (type) {
    const svg = document.querySelector('#divGrid > svg').cloneNode(true)
    svg.removeAttribute('style')
    svg.setAttribute('width', gridRef.current.scrollWidth)
    svg.setAttribute('height', gridRef.current.scrollHeight)
    const canvas = document.createElement('canvas')
    canvas.width = gridRef.current.scrollWidth
    canvas.height = gridRef.current.scrollHeight
    canvas.style.width = canvas.width + 'px'
    canvas.style.height = canvas.height + 'px'
    const images = svg.getElementsByTagName('image')
    for (const image of images) {
      const data = await fetch(image.getAttribute('xlink:href')).then((v) => {
        return v.text()
      })
      image.removeAttribute('xlink:href')
      image.setAttribute(
        'href',
        'data:image/svg+xml;base64,' + window.btoa(data)
      )
    }
    const ctx = canvas.getContext('2d')
    ctx.mozImageSmoothingEnabled = true
    ctx.webkitImageSmoothingEnabled = true
    ctx.msImageSmoothingEnabled = true
    ctx.imageSmoothingEnabled = true
    const pixelRatio = window.devicePixelRatio || 1
    ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0)
    return new Promise((resolve) => {
      if (type === 'SVG') {
        const svgdata = new XMLSerializer().serializeToString(svg)
        resolve('<?xml version="1.0" encoding="UTF-8"?>' + svgdata)
        return
      }
      const v = Canvg.fromString(ctx, svg.outerHTML)
      v.render().then(() => {
        let image = ''
        if (type === 'JPG') {
          const imgdata = ctx.getImageData(0, 0, canvas.width, canvas.height)
          for (let i = 0; i < imgdata.data.length; i += 4) {
            if (imgdata.data[i + 3] === 0) {
              imgdata.data[i] = 255
              imgdata.data[i + 1] = 255
              imgdata.data[i + 2] = 255
              imgdata.data[i + 3] = 255
            }
          }
          ctx.putImageData(imgdata, 0, 0)
          image = canvas.toDataURL('image/jpeg', 1.0)
        } else {
          if (type === 'PNG') {
            image = canvas.toDataURL('image/png')
          }
        }
        resolve(image)
      })
    })
  }

  const handleBranch = (branchName) => {
    setDialogOpen(false)
    exportImage('PNG').then((res) => {
      console.log(schSave.project_id)
      dispatch(saveSchematic(schSave.title, schSave.description, schSave.xmlData, res, true, branchName, setVersions, false, versions, branchOpen, setBranchOpen))
    })
    setBranchName('')
  }

  const handleClick = (index) => {
    console.log(index)
    let left = branchOpen.slice(0, index)
    const right = branchOpen.slice(index + 1)
    const temp = !branchOpen[index]
    left.push(temp)
    left = left.concat(right)
    console.log(left)
    setBranchOpen(left)
  }

  const handleDelete = (branchName, index) => {
    const temp = popoverOpen
    temp.fill(false)
    setPopoverOpen(temp)
    const config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }
    const token = localStorage.getItem('esim_token')
    if (token) {
      config.headers.Authorization = `Token ${token}`
    }
    const saveId = window.location.href.split('id=')[1].substr(0, 36)
    api.delete(`/save/versions/${saveId}/${branchName}`, config).then(resp => {
      const temp = versions.filter(version => version[0] !== branchName)
      const tempBranch = branchOpen
      tempBranch.splice(index, 1)
      setBranchOpen(tempBranch)
      setVersions(temp)
      const tempPopover = popoverOpen.filter(popoverIndex => popoverIndex !== true)
      setPopoverOpen(tempPopover)
    }).catch(err => {
      console.log(err)
    })
  }

  const handleClickPopover = (e, index) => {
    setAnchorEl(e.currentTarget)
    let left = popoverOpen.slice(0, index)
    const right = popoverOpen.slice(index + 1)
    const temp = !popoverOpen[index]
    left.push(temp)
    left = left.concat(right)
    setPopoverOpen(left)
  }

  const handleClosePopover = (index) => {
    setAnchorEl(null)
    let left = popoverOpen.slice(0, index)
    const right = popoverOpen.slice(index + 1)
    const temp = !popoverOpen[index]
    left.push(temp)
    left = left.concat(right)
    setPopoverOpen(left)
  }

  const checkActiveOrProject = (branch) => {
    if (decodeURI(window.location.href.split('branch=')[1]) === branch) return false
    if (branch === projectBranch) return false
    return true
  }

  const handleBranchName = (e) => {
    setBranchName(e.target.value)
  }

  const handleDialogOpen = () => {
    setDialogOpen(true)
  }

  const handleDialogClose = () => {
    setBranchName('')
    setDialogOpen(false)
  }

  return (
    <>
      <Hidden mdDown>
        <div className={classes.toolbar} />
      </Hidden>

      <List>
        <ListItem button divider>
          <h2 style={{ margin: '5px' }}>Properties</h2>
        </ListItem>
        <div>
          <GridProperties gridRef={gridRef} />

          {/* Display component position box */}
          <ListItem>
            <ListItemText primary="Components Position" />
          </ListItem>
          <ListItem style={{ padding: '0px' }} divider>
            <div className="outline-container" ref={outlineRef} id="outlineContainer" />
          </ListItem>

          {/* Input form field for schematic description */}
          <ListItem>
            <ListItemText primary="Schematic Description" />
          </ListItem>
          <ListItem style={{ padding: '0px 7px 7px 7px' }} divider>
            <TextareaAutosize id='Description' label='Description' value={ schSave.description === '' ? description || '' : schSave.description } onChange={getInputValues} rowsMin={6} aria-label='Description' placeholder={'Add Schematic Description'} style={{ width: '100%', minWidth: '234px', maxHeight: '250px' }} />
          </ListItem>
        </div>
      </List>
      <List>
        <ListItem button divider>
          <h2 style={{ margin: '5px', width: '90%' }}>History</h2>
          {versions && <IconButton
            className="new-branch"
            size="small"
            onClick={handleDialogOpen}
          >
            <CreateNewFolderOutlinedIcon fontSize="small" />
          </IconButton>}
          <Dialog onClose={handleDialogClose} aria-labelledby="simple-dialog-title" open={dialogOpen}>
            <DialogTitle id="simple-dialog-title">Create new Variation</DialogTitle>
            <DialogContent>
              <TextField
                id="branch-name"
                label="Variation Name"
                onChange={handleBranchName}
                value={branchName}
                style={{ width: '100%' }}/>
              <br/>
              <Button
                style={{ marginTop: '20px', marginBottom: '10px' }}
                variant="contained"
                color="primary"
                onClick={() => handleBranch(branchName) }>
                Create Variation
              </Button>
            </DialogContent>
          </Dialog>
        </ListItem>
        {(versions && branchOpen && popoverOpen)
          ? <>
            {versions.map((branch, index) => {
              return (
                <>
                  <div style={{ display: 'flex' }}>
                    <ListItem style={{ width: '80%' }} button onClick={() => handleClick(index)}>
                      <ListItemText primary={'Variation ' + (versions.length - index) + ' : ' + branch[0]} />
                    </ListItem>
                    {checkActiveOrProject(branch[0]) &&
                    <>
                      <Button key={branch[0]} onClick={(e) => handleClickPopover(e, index)}>
                        <DeleteIcon />
                      </Button>
                      <Popover
                        open={popoverOpen[index]}
                        anchorEl={anchorEl}
                        onClose={() => handleClosePopover(index)}
                        anchorOrigin={{
                          vertical: 'bottom',
                          horizontal: 'center'
                        }}
                        transformOrigin={{
                          vertical: 'top',
                          horizontal: 'center'
                        }}
                      >
                        <Typography className={classes.typography}>
                          <b>Are you sure you want to delete variation {branch[0]}?</b>
                        </Typography>
                        <Button style={{ marginLeft: '5%', backgroundColor: 'transparent' }} onClick={() => handleDelete(branch[0], index)}>
                          Delete Variation
                        </Button>
                      </Popover>
                    </>}
                  </div>
                  <Collapse in={branchOpen[index]} timeout="auto" unmountOnExit>
                    {
                      branch[1].map((version) =>
                        <VersionComponent
                          key={version.name}
                          name={version.name}
                          date={version.date}
                          time={version.time}
                          save_id={version.save_id}
                          version={version.version}
                          branch={version.branch}
                          setVersions={setVersions}
                          setBranchOpen={setBranchOpen}
                          projectBranch={projectBranch}
                          projectVersion={projectVersion}
                          ltiId={version.lti_id} />
                      )
                    }
                  </Collapse>
                </>
              )
            }
            )
            }
          </>
          : <ListItemText>No History Available</ListItemText>
        }
      </List>
    </>
  )
}