@material-ui/core#DialogContentText JavaScript Examples

The following examples show how to use @material-ui/core#DialogContentText. 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: YesNoDialog.js    From acsys with MIT License 6 votes vote down vote up
export default function YesNoDialog(props) {
  return (
    <Dialog
      open={props.open}
      onClose={props.closeDialog}
      aria-labelledby="alert-dialog-title"
      aria-describedby="alert-dialog-description"
    >
      <DialogTitle id="alert-dialog-title">{props.title}</DialogTitle>
      <DialogContent>
        <DialogContentText id="alert-dialog-description">
          {props.message}
        </DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button onClick={props.closeDialog} color="primary">
          No
        </Button>
        <Button
          onClick={props.action}
          color="primary"
          disabled={props.actionProcess}
          autoFocus
        >
          {props.actionProcess && <CircularProgress size={24} />}
          {!props.actionProcess && 'Yes'}
        </Button>
      </DialogActions>
    </Dialog>
  );
}
Example #2
Source File: Dialog.jsx    From module-federation-examples with MIT License 6 votes vote down vote up
function DialogComponent() {
  const [open, setOpen] = React.useState(false);

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  return (
    <div>
      <Button variant="contained" color="primary" onClick={handleClickOpen}>
        Open Dialog
      </Button>
      <Dialog open={open} onClose={handleClose}>
        <DialogTitle>Dialog Example</DialogTitle>
        <DialogContent>
          <DialogContentText>
            This is a dialog from the Material UI app rendered in a React <code>Portal</code>.
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose} variant="contained" color="primary" autoFocus>
            Nice
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}
Example #3
Source File: Dialog.jsx    From mfe-webpack-demo with MIT License 6 votes vote down vote up
function DialogComponent() {
  const [open, setOpen] = React.useState(false);

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  return (
    <div>
      <Button variant="contained" color="primary" onClick={handleClickOpen}>
        Open Dialog
      </Button>
      <Dialog open={open} onClose={handleClose}>
        <DialogTitle>Dialog Example</DialogTitle>
        <DialogContent>
          <DialogContentText>
            This is a dialog from the Material UI app rendered in a React{" "}
            <code>Portal</code>.
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button
            onClick={handleClose}
            variant="contained"
            color="primary"
            autoFocus
          >
            Nice
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}
Example #4
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 #5
Source File: Modal.js    From social-media-strategy-fe with MIT License 6 votes vote down vote up
Modal = (props) => {
	const { open, handleClose, title, content, handleConfirmation } = props;
	return (
		<Dialog open={open} onClose={handleClose} aria-labelledby="dialog-title">
			<div style={{ minWidth: 300 }}>
				<DialogTitle id="dialog-title">{title}</DialogTitle>

				<DialogContent>
					{props.children ? (
						<>{props.children}</>
					) : (
						content && (
							<DialogContentText id="dialog-description">
								{content}
							</DialogContentText>
						)
					)}
				</DialogContent>

				<DialogActions>
					<Button onClick={handleClose} color="primary">
						Cancel
					</Button>
					{handleConfirmation && (
						<Button onClick={handleConfirmation} color="primary" autoFocus>
							Confirm
						</Button>
					)}
				</DialogActions>
			</div>
		</Dialog>
	);
}
Example #6
Source File: Dialog.jsx    From Turnip-Calculator with MIT License 6 votes vote down vote up
CustomDialog = ({
  open,
  onClose,
  title,
  description,
  children,
  actions,
  ...props
}) => {
  const dialogClasses = useDialogStyles();

  return (
    <Dialog
      open={open}
      onClose={onClose}
      classes={dialogClasses}
      aria-labelledby="alert-dialog-title"
      aria-describedby="alert-dialog-description"
      transitionDuration={0}
      {...props}
    >
      {title && <DialogTitle id="alert-dialog-title">{title}</DialogTitle>}
      <DialogContent>
        {description && (
          <DialogContentText id="alert-dialog-description">
            {description}
          </DialogContentText>
        )}
        {children}
      </DialogContent>
      {actions && <DialogActions>{actions}</DialogActions>}
    </Dialog>
  );
}
Example #7
Source File: RemoveDialog.js    From react-storefront-starter-app with Apache License 2.0 6 votes vote down vote up
export default function RemoveDialog({ open, setOpen, name, action }) {
  return (
    <Dialog open={open} onClose={() => setOpen(false)} maxWidth="sm">
      <DialogTitle>{name}</DialogTitle>
      <DialogContent>
        <DialogContentText>Are you sure that you want to remove selected item?</DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button onClick={action}>Remove Item</Button>
        <Button onClick={() => setOpen(false)} color="primary">
          Keep Item
        </Button>
      </DialogActions>
    </Dialog>
  )
}
Example #8
Source File: MessageDialog.js    From acsys with MIT License 6 votes vote down vote up
export default function MessageDialog(props) {
  return (
    <Dialog
      open={props.open}
      onClose={props.closeDialog}
      aria-labelledby="alert-dialog-title"
      aria-describedby="alert-dialog-description"
      maxWidth={'md'}
      style={{
        minHeight: 200,
        minWidth: 1100,
        margin: 'auto',
        overflow: 'hidden',
      }}
    >
      <DialogTitle id="alert-dialog-title">{props.title}</DialogTitle>
      <DialogContent>
        <DialogContentText id="alert-dialog-description">
          {props.message}
        </DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button onClick={props.closeDialog} color="primary">
          Close
        </Button>
      </DialogActions>
    </Dialog>
  );
}
Example #9
Source File: team-member-dialog-display.js    From turinghut-website with BSD Zero Clause License 6 votes vote down vote up
DialogDisplay = ({ person: { name, designation, phoneNumber, emailId, githubProfile, linkedinProfile } }) => {
    const classes = teamMemberStyles();
    const [open, setOpen] = useState(false);
    return (
        <div className={`${classes.tilebar} ${classes.tilebarRootTitle} ${classes.tilebarBottom}`}>
            <div className={`${classes.titlePosRight} ${classes.titleWrap}`}>
                <div className={classes.title}>{name}</div>
                <div><span>{designation}</span></div>
            </div>
            <CardActions onClick={() => setOpen(true)} className={classes.actionItem}><Info /></CardActions>
            <Dialog
                aria-labelledby="simple-dialog-title"
                aria-describedby="simple-dialog-description"
                open={open}
                onClose={() => { setOpen(false) }}
            >
                <DialogContent style={{minWidth:'38vh',minHeight:'25vh'}}>
                    {name ? <DialogContentText className={classes.dialogHeading}>{name}</DialogContentText> : null}
                    {phoneNumber ? <DialogContentText className={classes.dialogContent}><LocalPhone className={classes.icon}/> {phoneNumber}</DialogContentText> : null}
                    {emailId ? <DialogContentText className={classes.dialogContent}><Mail className={classes.icon}/> {emailId}</DialogContentText> : null}
                    {githubProfile ? <a href={githubProfile} alt={"githubProfile"} ><GitHub className={classes.githubIcon} /></a> : null}
                    {linkedinProfile ? <a href={linkedinProfile} alt={"linkedinProfile"}><LinkedIn className={classes.linkedinIcon} /></a> : null}
                </DialogContent>
            </Dialog>
        </div>
    )
}
Example #10
Source File: FindGameDialog.js    From dipact with GNU General Public License v3.0 6 votes vote down vote up
render() {
		return (
			<Dialog
				onEntered={helpers.genOnback(this.close)}
				open={this.state.open}
				className="find-game-dialog"
				disableBackdropClick={false}
				onClose={this.close}
			>
				<DialogTitle>Find game</DialogTitle>
				<DialogContent>
					<DialogContentText>
						Enter any game ID or URL to find it. You can find the
						game URL in the address bar for any opened game, or by
						choosing "Share" in the top right menu of any game.
					</DialogContentText>
					<TextField
						id="find-game-by-id-input-field"
						label="Game ID"
						autoFocus
						margin="dense"
						fullWidth
					/>
					<DialogActions>
						<Button onClick={this.close} color="primary">
							Cancel
						</Button>
						<Button
							onClick={this.onFind}
							color="primary"
						>
							Find
						</Button>
					</DialogActions>
				</DialogContent>
			</Dialog>
		);
	}
Example #11
Source File: WarnDialog.js    From fireshort with MIT License 6 votes vote down vote up
export default function UrlsDialog(props) {
  return (
    <Dialog open={props.state.warnOpen} onClose={props.warnClose} aria-labelledby="form-dialog-title">
      <DialogTitle id="form-dialog-title">Replace?</DialogTitle>
      <DialogContent>
        <DialogContentText>There is already a Short URL with this same name. Do you want to Replace?</DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button onClick={props.warnClose} color="primary">
          Cancel
        </Button>
        <Button onClick={props.handleReplace} color="primary">
          Replace
        </Button>
      </DialogActions>
    </Dialog>
  );
}
Example #12
Source File: DepositDialog.js    From spl-token-wallet with Apache License 2.0 5 votes vote down vote up
function SolletSwapDepositAddress({ balanceInfo, swapInfo, ethAccount }) {
  const [ethBalance] = useAsyncData(
    () => getErc20Balance(ethAccount),
    'ethBalance',
    {
      refreshInterval: 2000,
    },
  );

  const ethFeeData = useAsyncData(
    swapInfo.coin &&
      (() =>
        estimateErc20SwapFees({
          erc20Address: swapInfo.coin.erc20Contract,
          swapAddress: swapInfo.address,
          ethAccount,
        })),
    'depositEthFee',
    {
      refreshInterval: 2000,
    },
  );

  if (!swapInfo) {
    return null;
  }

  const ethFeeEstimate = Array.isArray(ethFeeData[0])
    ? ethFeeData[0].reduce((acc, elem) => acc + elem)
    : ethFeeData[0];
  const insufficientEthBalance =
    typeof ethBalance === 'number' &&
    typeof ethFeeEstimate === 'number' &&
    ethBalance < ethFeeEstimate;

  const { blockchain, address, memo, coin } = swapInfo;
  const { mint, tokenName } = balanceInfo;

  if (blockchain === 'btc' && memo === null) {
    return (
      <>
        <DialogContentText>
          Native BTC can be converted to SPL {tokenName} by sending it to the
          following address:
        </DialogContentText>
        <CopyableDisplay
          value={address}
          label="Native BTC Deposit Address"
          autoFocus
          qrCode={`bitcoin:${address}`}
        />
      </>
    );
  }

  if (false && blockchain === 'eth') {
    return (
      <>
        <DialogContentText>
          {coin.erc20Contract ? 'ERC20' : 'Native'} {coin.ticker} can be
          converted to {mint ? 'SPL' : 'native'} {tokenName} via MetaMask. To
          convert, you must already have SOL in your wallet.
        </DialogContentText>
        <DialogContentText>
          Estimated withdrawal transaction fee:
          <EthFeeEstimate
            ethFeeData={ethFeeData}
            insufficientEthBalance={insufficientEthBalance}
          />
        </DialogContentText>
        <MetamaskDeposit
          swapInfo={swapInfo}
          insufficientEthBalance={insufficientEthBalance}
        />
      </>
    );
  }

  return null;
}
Example #13
Source File: HomePage.jsx    From Corona-tracker with MIT License 5 votes vote down vote up
function DiagnosticContainer(props) {
  const { reminderStatus, setReminderStatus } = props;
  const handleClose = () => {
    setReminderStatus(false);
  };
  const classes = useStyles();
  const { userSession } = useBlockstack();
  const today = new Date();
  const { i18n } = useTranslation();
  const history = useHistory();

  return (
    <div>
      <Typography variant="h5">
        <Trans i18nKey="logSection.text.hello.hello " />
        <b>{userSession.loadUserData().profile.name}</b>
      </Typography>
      <Typography variant="h6">
        <Trans i18nKey="logSection.text.todayIs.todayIs" />:{' '}
        <b>{today.toLocaleDateString(i18n.languages, dateOptions)}</b>{' '}
      </Typography>
      <hr className={classes.hr} />
      <HealthLogToggle />
      <Dialog
        open={reminderStatus}
        onClose={handleClose}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogContent className={classes.dialog}>
          <DialogContentText id="alert-dialog-description">
            <Trans i18nKey="logSection.text.takeSurvey.takeASurvey" />{' '}
          </DialogContentText>
          <DialogActions className={classes.buttonContainer}>
            <Button
              className={classes.button}
              color="default"
              onClick={() => {
                handleClose();
                history.push('/symptomsurvey');
              }}
            >
              <Trans i18nKey="logSection.text.takeSurvey.takeASurvey" />
            </Button>
            <Button onClick={handleClose} color="default">
              <Trans i18nKey="surveySection.text.close.close" />
            </Button>
          </DialogActions>
        </DialogContent>
      </Dialog>
    </div>
  );
}
Example #14
Source File: CloseTokenAccountButton.js    From spl-token-wallet with Apache License 2.0 5 votes vote down vote up
export default function CloseTokenAccountDialog({
  open,
  onClose,
  publicKey,
  balanceInfo,
}) {
  const wallet = useWallet();
  const [sendTransaction, sending] = useSendTransaction();
  const { mint, tokenName } = balanceInfo;

  function onSubmit() {
    sendTransaction(wallet.closeTokenAccount(publicKey), {
      onSuccess: () => {
        refreshWalletPublicKeys(wallet);
        onClose();
      },
    });
  }

  return (
    <DialogForm open={open} onClose={onClose} onSubmit={onSubmit}>
      <DialogTitle>
        Delete {tokenName ?? mint.toBase58()} Address{' '}
        {abbreviateAddress(publicKey)}
      </DialogTitle>
      <DialogContent>
        <DialogContentText>
          Are you sure you want to delete your {tokenName ?? mint.toBase58()}{' '}
          address {publicKey.toBase58()}? This will permanently disable token
          transfers to this address and remove it from your wallet.
        </DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancel</Button>
        <Button type="submit" color="secondary" disabled={sending}>
          Delete
        </Button>
      </DialogActions>
    </DialogForm>
  );
}
Example #15
Source File: Survey.jsx    From Corona-tracker with MIT License 5 votes vote down vote up
Survey = props => {
  const { surveyPage, setSurveyPage, requiredStep } = props;
  const classes = useStyles();
  const [activeStep, setActiveStep] = useState(surveyPage - 1);
  const [showDialog, setShowDialog] = useState(false);
  const contentEl = document.getElementById('content');

  const handleStep = step => {
    const page = step + 1;
    if (page > 2 && !requiredStep) {
      setShowDialog(true);
    } else {
      setActiveStep(step);
      setSurveyPage(page);
    }
  };
  const handleClose = () => {
    setShowDialog(false);
  };

  useEffect(() => {
    if (contentEl) contentEl.scrollTop = 0;
    setActiveStep(surveyPage - 1);
  }, [surveyPage, contentEl]);

  return (
    <div>
      <Stepper
        alternativeLabel
        nonLinear
        activeStep={activeStep}
        connector={<SurveyConnector />}
        className={classes.stepper}
      >
        {[0, 1, 2, 3].map(step => {
          return (
            <Step key={step}>
              <StepButton
                onClick={() => {
                  handleStep(step);
                }}
              >
                <StepLabel StepIconComponent={SurveyStepIcon} />
              </StepButton>
            </Step>
          );
        })}
      </Stepper>
      {surveyPage === 1 && <SurveyPage1 />}
      {surveyPage === 2 && <SurveyPage2 />}
      {surveyPage === 3 && <SurveyPage3 />}
      {surveyPage === 4 && <SurveyPage4 />}
      <Dialog
        open={showDialog}
        onClose={handleClose}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogContent>
          <DialogContentText id="alert-dialog-description">Complete Step 2 before moving on</DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose} color="default" autoFocus>
            Close
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}
Example #16
Source File: CreateChannelDialog.js    From dipact with GNU General Public License v3.0 5 votes vote down vote up
render() {
		return (
			<Dialog
				onEntered={helpers.genOnback(this.close)}
				open={this.state.open}
				disableBackdropClick={false}
				onClose={this.close}
			>
				<DialogTitle>Create channel</DialogTitle>
				<DialogContent>
					<DialogContentText>
						Pick the participants of the new channel.
					</DialogContentText>
					<FormGroup>
						{this.variant.Properties.Nations.map((n) => {
							return (
								<FormControlLabel
									key={n}
									control={
										<Checkbox
											disabled={n === this.member.Nation}
											checked={!!this.state.members[n]}
											onChange={this.toggleMember(n)}
										/>
									}
									label={n}
								/>
							);
						})}
					</FormGroup>
				</DialogContent>
				<DialogActions>
					<Button onClick={this.close} color="primary">
						Cancel
					</Button>
					<Button
						onClick={this.createChannel}
						color="primary"
					>
						Create
					</Button>
				</DialogActions>
			</Dialog>
		);
	}
Example #17
Source File: ContactInfo.js    From app with MIT License 5 votes vote down vote up
function ContactInfo({ requestId }) {
  const classes = useStyles();
  const user = useUser();
  const [
    hasAccess,
    requestAccess,
    addUserToAccessList,
    confirmationDialogOpen,
    closeConfirmationDialog,
  ] = useContactInfo(requestId);

  async function handleOK() {
    await addUserToAccessList();
    closeConfirmationDialog();
  }

  function handleCancel() {
    closeConfirmationDialog();
  }

  return (
    <div className={classes.root}>
      {hasAccess ? (
        <ContactDetails requestId={requestId} />
      ) : (
        <>
          {user ? (
            <Button
              size="small"
              startIcon={<RequestContactIcon />}
              onClick={requestAccess}>
              Show Contact Info...
            </Button>
          ) : (
            <Button
              size="small"
              component={Link}
              to={LOGIN_PATH}
              startIcon={<RequestContactIcon />}>
              Please login to see contact info
            </Button>
          )}
          <Dialog open={confirmationDialogOpen}>
            <DialogTitle>Viewing Contact Details</DialogTitle>
            <DialogContent>
              <DialogContentText>
                This volunteer system is open to public, but to minimize abuse
                we note who looks up the contact information on requests.
              </DialogContentText>
              <DialogContentText>
                We will only ask for this confirmation once per request.
              </DialogContentText>
            </DialogContent>
            <DialogActions>
              <Button onClick={handleCancel}>Cancel</Button>
              <Button onClick={handleOK} color="primary">
                OK
              </Button>
            </DialogActions>
          </Dialog>
        </>
      )}
    </div>
  );
}
Example #18
Source File: DeleteProductModal.js    From beluga with GNU General Public License v3.0 5 votes vote down vote up
function DeleteProductModal(props) {
  const { modalOpen, modalProduct, products } = props;

  const startDeletingProduct = () => {
    fetch(`/product-info/${modalProduct.stripe_id}`)
      .then(res => res.json())
      .then(result => {
        if (result.data && result.data.length) {
          Promise.all(result.data.map(d => deleteSKU(d.id)))
            .then(() => {
              deleteProduct();
            });
        } else {
          deleteProduct();
        }
      })
  }

  const deleteSKU = (id) => {
    return new Promise(function(resolve, reject) {
      fetch(`/delete-sku/${id}`, {
          method: 'POST',
          headers: new Headers({ 'content-type': 'application/json' })
        }).then((response) => response.json())
        .then((json) => {
          if (!json.success) reject();
          resolve(true);
        });
    });
  }

  const deleteProduct = () => {
    fetch(`/delete-product/${modalProduct.stripe_id}`, {
        method: 'POST',
        headers: new Headers({ 'content-type': 'application/json' })
      }).then((response) => response.json())
      .then((json) => {
        // error that is not a missing ID
        if (json.code && json.code !== "resource_missing") {
          console.log(json)
          return;
        }

        const newProducts = [...products];
        const index = newProducts.findIndex(p => p.stripe_id === modalProduct.stripe_id)
        newProducts.splice(index, 1);
        props.handleChange("products", newProducts, true);
        props.setModalProduct(null);
        props.setModalOpen(false);
      });
  }

  return (
    <Dialog
      open={modalOpen}
      onClose={() => props.setModalOpen(false)}
    >
      <DialogTitle>Delete Product</DialogTitle>
      <DialogContent>
        <DialogContentText id="alert-dialog-description">
          Are you sure you want to delete <b>{modalProduct && modalProduct.name}</b>? This cannot be undone.
        </DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button onClick={() => props.setModalOpen(false)} color="primary">
          Cancel
        </Button>
        <Button onClick={startDeletingProduct} color="primary" autoFocus>
          Delete
        </Button>
      </DialogActions>
    </Dialog>
  );
}
Example #19
Source File: EditRoomDialog.js    From virtualdojo-rooms with GNU General Public License v3.0 5 votes vote down vote up
export default function EditRoomDialog({ isOpen, onConfirm, onClose, room }) {
  const { t } = useTranslation("translation");
  const [roomName, setRoomName] = useState(room.roomName || "");
  const [imageUrl, setImageUrl] = useState(room.imageUrl || "");
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    setRoomName(room.roomName || "");
    setImageUrl(room.imageUrl || "");
  }, [room.imageUrl, room.roomName, isOpen]);

  const handleConfirm = useCallback(async () => {
    setIsLoading(true);
    try {
      await onConfirm(roomName.trim(), imageUrl.trim());
    } catch (err) {
      console.log("error ", err);
    }
    setIsLoading(false);
  }, [imageUrl, onConfirm, roomName]);
  return (
    <Dialog open={isOpen} onClose={onClose} aria-labelledby="form-dialog-title">
      <DialogTitle id="form-dialog-title">
        {t("Room settings title")}
      </DialogTitle>
      <DialogContent>
        <DialogContentText>{t("Room settings text")}</DialogContentText>
        <TextField
          autoFocus
          margin="dense"
          id="roomName"
          label={t("Room Name")}
          value={roomName}
          onChange={(event) => setRoomName(event.target.value)}
          fullWidth
        />
        <TextField
          margin="dense"
          id="imageUrl"
          label={t("Room image url")}
          value={imageUrl}
          onChange={(event) => setImageUrl(event.target.value)}
          fullWidth
        />
      </DialogContent>
      <DialogActions>
        {isLoading && <CircularProgress size={20} color={"primary"} />}
        <Button onClick={onClose} color="primary" disabled={isLoading}>
          {t("Cancel")}
        </Button>
        <Button onClick={handleConfirm} color="primary" disabled={isLoading}>
          {t("Confirm")}
        </Button>
      </DialogActions>
    </Dialog>
  );
}
Example #20
Source File: DeleteDialog.js    From to-view-list with MIT License 5 votes vote down vote up
DeleteDialog = ({ handleDelete, title, isMobile }) => {
  const [open, setOpen] = useState(false);
  const classes = useDeleteBtnStyles();

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const handleActionClick = () => {
    handleClose();
    handleDelete();
  };

  return (
    <div>
      {!isMobile ? (
        <Button
          className={classes.deleteButton}
          startIcon={<DeleteIcon />}
          onClick={handleClickOpen}
        >
          Delete
        </Button>
      ) : (
        <IconButton onClick={handleClickOpen} className={classes.deleteButton}>
          <DeleteIcon />
        </IconButton>
      )}
      <Dialog open={open} keepMounted onClose={handleClose}>
        <DialogTitle>Confirm Delete</DialogTitle>
        <DialogContent>
          <DialogContentText>
            {`Are you sure want to delete "${title}" ?`}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose} color="primary">
            Cancel
          </Button>
          <Button onClick={handleActionClick} color="primary">
            Ok
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}
Example #21
Source File: DeleteDialog.js    From stack-underflow with MIT License 5 votes vote down vote up
DeleteDialog = ({ handleDelete, bodyType }) => {
  const [modalOpen, setModalOpen] = useState(false);
  const classes = useQuesPageStyles();

  const handleModalOpen = () => {
    setModalOpen(true);
  };

  const handleModalClose = () => {
    setModalOpen(false);
  };

  const handleDeleteClick = () => {
    handleDelete();
    handleModalClose();
  };

  return (
    <div style={{ display: 'inline' }}>
      {bodyType === 'comment' ? (
        <Button
          size="small"
          color="primary"
          className={classes.commentBtns}
          onClick={handleModalOpen}
        >
          delete
        </Button>
      ) : (
        <Button
          size="small"
          color="primary"
          variant="contained"
          className={classes.bottomBtns}
          onClick={handleModalOpen}
        >
          Delete
        </Button>
      )}
      <Dialog open={modalOpen} onClose={handleModalClose}>
        <DialogTitle>Confirm Delete</DialogTitle>
        <DialogContent>
          <DialogContentText>
            {`Are you sure you want to delete your ${
              bodyType ? bodyType : 'question'
            }?`}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button autoFocus onClick={handleModalClose} color="primary">
            Cancel
          </Button>
          <Button onClick={handleDeleteClick} color="primary">
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}
Example #22
Source File: App.js    From Gameplayer with MIT License 5 votes vote down vote up
render() {
    const { withImage, withName, orderBy, showHelpDialog } = this.state

    return (
      <ApolloProvider client={client}>
        <div className="App">
          <Grid container direction="column">
            <Header onHelp={this.toggleHelpDialog} />
            <Filter
              orderBy={orderBy}
              withImage={withImage}
              withName={withName}
              onOrderBy={field => this.setState(state => ({ ...state, orderBy: field }))}
              onToggleWithImage={() =>
                this.setState(state => ({ ...state, withImage: !state.withImage }))
              }
              onToggleWithName={() =>
                this.setState(state => ({ ...state, withName: !state.withName }))
              }
            />
            <Grid item>
              <Grid container>
                <Query
                  query={GRAVATARS_QUERY}
                  variables={{
                    where: {
                      ...(withImage ? { imageUrl_starts_with: 'http' } : {}),
                      ...(withName ? { displayName_not: '' } : {}),
                    },
                    orderBy: orderBy,
                  }}
                >
                  {({ data, error, loading }) => {
                    return loading ? (
                      <LinearProgress variant="query" style={{ width: '100%' }} />
                    ) : error ? (
                      <Error error={error} />
                    ) : (
                      <Gravatars gravatars={data.gravatars} />
                    )
                  }}
                </Query>
              </Grid>
            </Grid>
          </Grid>
          <Dialog
            fullScreen={false}
            open={showHelpDialog}
            onClose={this.toggleHelpDialog}
            aria-labelledby="help-dialog"
          >
            <DialogTitle id="help-dialog">{'Show Quick Guide?'}</DialogTitle>
            <DialogContent>
              <DialogContentText>
                We have prepared a quick guide for you to get started with The Graph at
                this hackathon. Shall we take you there now?
              </DialogContentText>
            </DialogContent>
            <DialogActions>
              <Button onClick={this.toggleHelpDialog} color="primary">
                Nah, I'm good
              </Button>
              <Button onClick={this.gotoQuickStartGuide} color="primary" autoFocus>
                Yes, pease
              </Button>
            </DialogActions>
          </Dialog>
        </div>
      </ApolloProvider>
    )
  }
Example #23
Source File: Modal.js    From medha-STPC with GNU Affero General Public License v3.0 5 votes vote down vote up
Modal = props => {
  function _onClick(e, close) {
    if (!props.event) {
      return;
    }
    props.event(e);
    props.close(close);
  }

  return (
    <Dialog
      open={props.show}
      onClose={props.close}
      aria-labelledby="alert-dialog-title"
      aria-describedby="alert-dialog-description"
    >
      <DialogTitle id="alert-dialog-title">{props.header}</DialogTitle>
      <DialogContent>
        <DialogContentText id="alert-dialog-description">
          {props.children}
        </DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button
          onClick={props.close}
          style={props.footer.displayClose}
          color="primary"
        >
          {props.footer.footerCloseName}
        </Button>
        <Button
          onClick={_onClick}
          href={props.footer.footerHref}
          style={props.footer.displaySave}
          color="primary"
          autoFocus
        >
          {props.footer.footerSaveName}
        </Button>
      </DialogActions>
    </Dialog>
  );
}
Example #24
Source File: LoginPage.js    From spl-token-wallet with Apache License 2.0 4 votes vote down vote up
function SeedWordsForm({ mnemonicAndSeed, goForward }) {
  const [confirmed, setConfirmed] = useState(false);
  const [downloaded, setDownloaded] = useState(false);
  const [showDialog, setShowDialog] = useState(false);
  const [seedCheck, setSeedCheck] = useState('');

  const downloadMnemonic = (mnemonic) => {
    const url = window.URL.createObjectURL(new Blob([mnemonic]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'sollet.bak');
    document.body.appendChild(link);
    link.click();
  }

  return (
    <>
      <Card>
        <CardContent>
          <Typography variant="h5" gutterBottom>
            Create New Wallet
          </Typography>
          <Typography paragraph>
            Create a new wallet to hold Solana and SPL tokens.
          </Typography>
          <Typography>
            Please write down the following twenty four words and keep them in a
            safe place:
          </Typography>
          {mnemonicAndSeed ? (
            <TextField
              variant="outlined"
              fullWidth
              multiline
              margin="normal"
              value={mnemonicAndSeed.mnemonic}
              label="Seed Words"
              onFocus={(e) => e.currentTarget.select()}
            />
          ) : (
            <LoadingIndicator />
          )}
          <Typography paragraph>
            Your private keys are only stored on your current computer or device.
            You will need these words to restore your wallet if your browser's
            storage is cleared or your device is damaged or lost.
          </Typography>
          <Typography paragraph>
            By default, sollet will use <code>m/44'/501'/0'/0'</code> as the
            derivation path for the main wallet. To use an alternative path, try
            restoring an existing wallet.
          </Typography>
          <Typography paragraph>
            <b>Note:</b> For certain users, Sollet may <b>NOT</b> be secure. See{' '}
            <a
              style={{ color: 'inherit'}}
              href="https://medium.com/metamask/security-notice-extension-disk-encryption-issue-d437d4250863"
              target="__blank"
            >
              this article
            </a>{' '}to understand if you are at risk.
          </Typography>
          <FormControlLabel
            control={
              <Checkbox
                checked={confirmed}
                disabled={!mnemonicAndSeed}
                onChange={(e) => setConfirmed(e.target.checked)}
              />
            }
            label="I have saved these words in a safe place."
          />
          <Typography paragraph>
          <Button variant="contained" color="primary" style={{ marginTop: 20 }} onClick={() => {
            downloadMnemonic(mnemonicAndSeed?.mnemonic);
            setDownloaded(true);
          }}>
            Download Backup Mnemonic File (Required)
          </Button>
          </Typography>
        </CardContent>
        <CardActions style={{ justifyContent: 'flex-end' }}>
          <Button color="primary" disabled={!confirmed || !downloaded} onClick={() => setShowDialog(true)}>
            Continue
          </Button>
        </CardActions>
      </Card>
      <DialogForm
        open={showDialog}
        onClose={() => setShowDialog(false)}
        onSubmit={goForward}
        fullWidth
      >
        <DialogTitle>{'Confirm Mnemonic'}</DialogTitle>
        <DialogContentText style={{ margin: 20 }}>
          <div
            style={{
              display: 'flex',
              flexDirection: 'column',
            }}
          >
            Please re-enter your seed phrase to confirm that you have saved it.
          </div>
          <TextField
            label={`Please type your seed phrase to confirm`}
            fullWidth
            variant="outlined"
            margin="normal"
            value={seedCheck}
            onChange={(e) => setSeedCheck(e.target.value)}
          />
        </DialogContentText>
        <DialogActions>
          <Button onClick={() => setShowDialog(false)}>Close</Button>
          <Button
            type="submit"
            color="secondary"
            disabled={normalizeMnemonic(seedCheck) !== mnemonicAndSeed?.mnemonic}
          >
            Continue
          </Button>
        </DialogActions>
      </DialogForm>
    </>
  );
}
Example #25
Source File: message.js    From js-miniapp with MIT License 4 votes vote down vote up
Message = (props: MessageTypeProps) => {
  const classes = useStyles();
  const messageTypes = props.messageTypes;
  const [message, setMessage] = useState({
    id: messageTypes[0] !== undefined ? messageTypes[0].id : -1,
    contactId: '',
    image: pandaLogo,
    text: defaultTexts.get(MessageTypeId.SINGLE_CONTACT),
    caption: defaultCaption,
    action: defaultAction,
    bannerMessage: 'Win 30 coins from every friends who joins from your invite',
  });
  const [validation, setValidationState] = useState({
    error: false,
    message: '',
  });
  const [messageResponse, setMessageResponse] = useState({
    show: false,
    response: '',
  });
  const validate = () => {
    if (
      messageTypes.map((it) => it.id).findIndex((it) => it === message.id) ===
      -1
    ) {
      setValidationState({ error: true, message: 'select message' });
      return false;
    } else if (message.text === undefined || message.text.trim().length === 0) {
      setValidationState({ error: true, message: 'text cannot be empty' });
      return false;
    } else if (
      message.id === 2 &&
      (message.contactId === undefined || message.contactId.trim().length === 0)
    ) {
      setValidationState({
        error: true,
        message: 'contact id cannot be empty',
      });
      return false;
    } else {
      setValidationState({ error: false, message: '' });
    }
    return true;
  };
  const handleChange = (event) => {
    message.text = defaultTexts.get(event.target.value);
    message.action = defaultAction;
    message.caption = defaultCaption;
    setMessage({ ...message, id: event.target.value });
  };
  const talkToChatbot = () => {
    if (validate()) {
      if (message.id === MessageTypeId.SINGLE_CONTACT) {
        props
          .sendMessageToContact(
            message.image.trim() ?? '',
            message.text !== undefined ? message.text.trim() : '',
            message.caption.trim() ?? '',
            message.action.trim() ?? '',
            message.bannerMessage.trim() ?? ''
          )
          .then((contactId) => {
            let respMsg = 'Message not sent';
            if (contactId !== null)
              respMsg = 'Message is sent to contact Id: ' + contactId;
            setMessageResponse({
              show: true,
              response: respMsg,
            });
          })
          .catch((e) => {
            setMessageResponse({
              show: true,
              response: e,
            });
          });
      } else if (message.id === MessageTypeId.SINGLE_CONTACT_ID) {
        props
          .sendMessageToContactId(
            message.contactId.trim(),
            message.image.trim() ?? '',
            message.text !== undefined ? message.text.trim() : '',
            message.caption.trim() ?? '',
            message.action.trim() ?? ''
          )
          .then((contactId) => {
            let respMsg = 'Message not sent';
            if (contactId !== null && contactId !== undefined)
              respMsg = 'Message is sent to contact Id: ' + contactId;
            setMessageResponse({
              show: true,
              response: respMsg,
            });
          })
          .catch((e) => {
            setMessageResponse({
              show: true,
              response: e,
            });
          });
      } else if (message.id === MessageTypeId.MULTIPLE_CONTACTS) {
        props
          .sendMessageToMultipleContacts(
            message.image.trim() ?? '',
            message.text !== undefined ? message.text.trim() : '',
            message.caption.trim() ?? '',
            message.action.trim() ?? '',
            message.bannerMessage.trim() ?? ''
          )
          .then((contactIds) => {
            let respMsg = 'Message not sent';
            if (contactIds !== null)
              respMsg = contactIds.length + ' contacts sent';
            setMessageResponse({
              show: true,
              response: respMsg,
            });
          })
          .catch((e) => {
            setMessageResponse({
              show: true,
              response: e,
            });
          });
      }
    }
  };

  const onContactIdChange = (event) => {
    setMessage({ ...message, contactId: event.target.value });
  };
  const onImageChange = (event) => {
    setMessage({ ...message, image: event.target.value });
  };
  const onTextChange = (event) => {
    setMessage({ ...message, text: event.target.value });
  };
  const onBannerMessageChange = (event) => {
    setMessage({ ...message, bannerMessage: event.target.value });
  };
  const onCaptionChange = (event) => {
    setMessage({ ...message, caption: event.target.value });
  };
  const onActionChange = (event) => {
    setMessage({ ...message, action: event.target.value });
  };

  const onChatbotClose = () => {
    setMessageResponse({ show: false, response: '' });
  };

  return (
    <div className={classes.scrollable}>
      <Fragment>
        <FormControl className={classes.formControl}>
          <InputLabel id="chatbotLabel">Send Message Type</InputLabel>
          <Select
            labelId="chatbotLabel"
            id="message"
            placeholder="Select Chatbot"
            value={message.id}
            className={classes.fields}
            onChange={handleChange}
          >
            {messageTypes.map((c) => (
              <MenuItem key={c.id} value={c.id}>
                {c.name}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        {message.id === MessageTypeId.SINGLE_CONTACT_ID && (
          <FormControl className={classes.formControl}>
            <TextField
              id="contactId"
              label="Contact ID"
              className={classes.fields}
              onChange={onContactIdChange}
              placeholder="Input contact id receiving a message"
              value={message.contactId}
            />
          </FormControl>
        )}

        <FormControl className={classes.formControl}>
          <TextField
            id="image"
            label="Image"
            className={classes.fields}
            onChange={onImageChange}
            placeholder="Image url or Base64 string"
            value={message.image}
          />
        </FormControl>
        <FormControl className={classes.formControl}>
          <TextField
            id="text"
            label="Text"
            className={classes.fields}
            onChange={onTextChange}
            value={message.text}
            multiline
            rowsMax="4"
          />
        </FormControl>
        {message.id !== MessageTypeId.SINGLE_CONTACT_ID && (
          <FormControl className={classes.formControl}>
            <TextField
              id="bannerMessage"
              label="Banner message"
              className={classes.fields}
              onChange={onBannerMessageChange}
              value={message.bannerMessage}
            />
          </FormControl>
        )}
        <FormControl className={classes.formControl}>
          <TextField
            id="caption"
            label="Caption"
            className={classes.fields}
            onChange={onCaptionChange}
            value={message.caption}
          />
        </FormControl>
        <FormControl className={classes.formControl}>
          <TextField
            id="action"
            label="Action"
            className={classes.fields}
            onChange={onActionChange}
            value={message.action}
          />
        </FormControl>
        {validation.error && (
          <div data-testid="validation-error" className={classes.errorMessage}>
            {validation.message}
          </div>
        )}
        <CardActions className={classes.actions}>
          <Button
            data-testid="send-message"
            variant="contained"
            color="primary"
            fullWidth
            onClick={talkToChatbot}
          >
            SEND MESSAGE
          </Button>
        </CardActions>
        <Dialog
          data-testid="message-response-dialog"
          open={messageResponse.show}
          onClose={onChatbotClose}
          aria-labelledby="max-width-dialog-title"
        >
          <DialogTitle id="max-width-dialog-title">Response</DialogTitle>
          <DialogContent>
            <DialogContentText>{messageResponse.response}</DialogContentText>
          </DialogContent>
          <DialogActions>
            <Button onClick={onChatbotClose} color="primary">
              Close
            </Button>
          </DialogActions>
        </Dialog>
      </Fragment>
    </div>
  );
}
Example #26
Source File: DepositDialog.js    From spl-token-wallet with Apache License 2.0 4 votes vote down vote up
export default function DepositDialog({
  open,
  onClose,
  publicKey,
  balanceInfo,
  swapInfo,
  isAssociatedToken,
}) {
  const ethAccount = useEthAccount();
  const urlSuffix = useSolanaExplorerUrlSuffix();
  const { mint, tokenName, tokenSymbol, owner } = balanceInfo;
  const [tab, setTab] = useState(0);

  // SwapInfos to ignore.
  if (
    swapInfo &&
    swapInfo.coin &&
    swapInfo.coin.erc20Contract === '0x2b2e04bf86978b45bb2edf54aca876973bdd43c0'
  ) {
    swapInfo = null;
  }

  let tabs = null;
  if (swapInfo) {
    let firstTab = `SPL ${tokenSymbol ?? swapInfo.coin.ticker}`;
    let secondTab = swapInfo.coin.ticker;
    if (!mint) {
      firstTab = 'SOL';
    } else {
      if (swapInfo.blockchain !== 'eth') {
        secondTab = `${
          swapInfo.coin.erc20Contract ? 'ERC20' : 'Native'
        } ${secondTab}`;
      } else {
        secondTab = null;
      }
    }
    tabs = (
      <Tabs
        value={tab}
        variant="fullWidth"
        onChange={(e, value) => setTab(value)}
        textColor="primary"
        indicatorColor="primary"
      >
        <Tab label={firstTab} />
        {(!DISABLED_MINTS.has(mint && mint.toString()) ||
          localStorage.getItem('sollet-private')) &&
          secondTab && <Tab label={secondTab} />}
      </Tabs>
    );
  }
  const displaySolAddress = publicKey.equals(owner) || isAssociatedToken;
  const depositAddressStr = displaySolAddress
    ? owner.toBase58()
    : publicKey.toBase58();
  return (
    <DialogForm open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>
        Deposit {tokenName ?? mint.toBase58()}
        {tokenSymbol ? ` (${tokenSymbol})` : null}
        {ethAccount && (
          <div>
            <Typography color="textSecondary" style={{ fontSize: '14px' }}>
              Metamask connected: {ethAccount}
            </Typography>
          </div>
        )}
      </DialogTitle>
      {tabs}
      <DialogContent style={{ paddingTop: 16 }}>
        {tab === 0 ? (
          <>
            {!displaySolAddress && isAssociatedToken === false ? (
              <DialogContentText>
                This address can only be used to receive{' '}
                {tokenSymbol ?? abbreviateAddress(mint)}. Do not send SOL to
                this address.
                <br />
                <b style={{ color: 'red' }}>WARNING</b>: You are using a
                deprecated account type. Please migrate your tokens. Ideally,
                create a new wallet. If you send to this address from a poorly
                implemented wallet, you may burn tokens.
              </DialogContentText>
            ) : (
              <DialogContentText>
                This address can be used to receive{' '}
                {tokenSymbol ?? abbreviateAddress(mint)}.
              </DialogContentText>
            )}
            <CopyableDisplay
              value={depositAddressStr}
              label={'Deposit Address'}
              autoFocus
              qrCode
            />
            <DialogContentText variant="body2">
              <Link
                href={
                  `https://solscan.io/account/${depositAddressStr}` + urlSuffix
                }
                target="_blank"
                rel="noopener"
              >
                View on Solscan
              </Link>
            </DialogContentText>
          </>
        ) : (
          <SolletSwapDepositAddress
            balanceInfo={balanceInfo}
            swapInfo={swapInfo}
            ethAccount={ethAccount}
          />
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Close</Button>
      </DialogActions>
    </DialogForm>
  );
}
Example #27
Source File: CreateProject.js    From eSim-Cloud with GNU General Public License v3.0 4 votes vote down vote up
function CreateProject () {
  const [open, setOpen] = useState(false)
  const classes = useStyles()
  const dispatch = useDispatch()
  const project = useSelector(state => state.projectReducer)
  const auth = useSelector(state => state.authReducer)
  const save_id = useSelector(state => state.saveSchematicReducer.details.save_id)
  const owner = useSelector(state => state.saveSchematicReducer.details.owner)
  const [status, setStatus] = React.useState(null)
  const [versions, setVersions] = React.useState(null)
  const [activeVersion, setActiveVersion] = React.useState('')
  const [activeName, setActiveName] = React.useState(null)
  const [activeSaveTime, setActiveSaveTime] = React.useState(null)
  const [activeSaveDate, setActiveSaveDate] = React.useState(null)
  const [details, setDetails] = useState(
    {
      title: '',
      description: '',
      active_branch: '',
      active_version: ''
    })
  const [fields, setFields] = useState([{ name: 'Procedure', text: '' }, { name: 'Observation', text: '' }, { name: 'Conclusion', text: '' }])
  const [changed, setChanged] = useState(0)
  const [deleteDialogue, setDeleteDialogue] = useState(false)
  const [dcSweepcontrolLine, setDcSweepControlLine] = useState({
    parameter: '',
    sweepType: 'Linear',
    start: '',
    stop: '',
    step: '',
    parameter2: '',
    start2: '',
    stop2: '',
    step2: ''
  })
  const [transientAnalysisControlLine, setTransientAnalysisControlLine] = useState({
    start: '',
    stop: '',
    step: '',
    skipInitial: false
  })

  const [acAnalysisControlLine, setAcAnalysisControlLine] = useState({
    input: 'dec',
    start: '',
    stop: '',
    pointsBydecade: ''
  })

  const [tfAnalysisControlLine, setTfAnalysisControlLine] = useState({
    outputNodes: false,
    outputVoltageSource: '',
    inputVoltageSource: ''
  })
  const [selectedSimulation, setSelectedSimulation] = useState('')
  useEffect(() => {
    if (open && project.details?.project_id) {
      dispatch(getStatus(project.details?.project_id))
      setStatus(project.details?.status_name)
    }
    if (project.details) {
      console.log(project.details)
      setDetails({ title: project.details.title, description: project.details.description, active_version: project.details.active_version, active_branch: project.details.active_branch })
      setFields(project.details.fields)
      if (project.details.dc_sweep) {
        setDcSweepControlLine(project.details.dc_sweep)
      }
      if (project.details.transient_analysis) {
        setTransientAnalysisControlLine(project.details.transient_analysis)
      }
      if (project.details.tf_analysis) {
        setTfAnalysisControlLine(project.details.tf_analysis)
      }
      if (project.details.ac_analysis) {
        setAcAnalysisControlLine(project.details.ac_analysis)
      }
    }
    if (!project.details) {
      setDetails({
        title: '',
        description: '',
        active_branch: '',
        active_version: ''
      })
      setActiveVersion('')
      setFields([{ name: 'Procedure', text: '' }, { name: 'Observation', text: '' }, { name: 'Conclusion', text: '' }])
    }
  }, [open, dispatch, project.details])
  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]) {
      api
        .get(
          'save/versions/' +
          window.location.href.split('?id=')[1].substring(0, 36),
          config
        )
        .then((resp) => {
          for (var i = 0; i < resp.data.length; i++) {
            var d = new Date(resp.data[i].save_time)
            resp.data[i].date = d.getDate() + '/' + parseInt(d.getMonth() + 1) + '/' + d.getFullYear()
            resp.data[i].time = d.getHours() + ':' + d.getMinutes()
            if (d.getMinutes() < 10) {
              resp.data[i].time = d.getHours() + ':0' + d.getMinutes()
            }
          }
          var versionsAccordingFreq = {}
          resp.data.forEach((value) => {
            value.full_time = new Date(value.save_time)
            versionsAccordingFreq[value.branch] ? versionsAccordingFreq[value.branch].push(value) : versionsAccordingFreq[value.branch] = [value]
          })
          var versionsArray = Object.entries(versionsAccordingFreq)
          for (var k = 0; k < versionsArray.length; k++) {
            versionsArray[k][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
          })
          var versionsTemp = []
          for (var j = 0; j < versionsArray.length; j++) {
            versionsTemp = versionsTemp.concat(versionsArray[j][1])
          }
          setVersions(versionsTemp)
        })
        .catch((err) => {
          console.log(err)
        })
    }
  }, [open])
  useEffect(() => {
    if (versions && project.details) {
      for (var i = 0; i < versions.length; i++) {
        if (versions[i].version === project.details.active_version && versions[i].branch === project.details.active_branch) {
          setActiveVersion(`${versions[i].version}-${versions[i].branch}`)
          setActiveName(versions[i].name)
          setActiveSaveTime(versions[i].time)
          setActiveSaveDate(versions[i].date)
          break
        }
      }
    }
  }, [project.details, versions])
  const handleActiveVersion = (e) => {
    if (changed === 0) {
      setChanged(1)
    } else if (changed === 2) {
      setChanged(3)
    }
    setActiveVersion(e.target.value)
    setDetails({ ...details, active_branch: e.target.value.split('-')[1], active_version: e.target.value.split('-')[0] })
  }
  const handleSelectChange = (event) => {
    if (event.target.value !== project.details.status_name) {
      if (changed === 0) {
        setChanged(2)
      } else if (changed === 1) {
        setChanged(3)
      }
    } else {
      if (changed === 2) {
        setChanged(0)
      } else if (changed === 3) {
        setChanged(1)
      }
    }
    setStatus(event.target.value)
  }
  const changeFieldText = (e) => {
    if (changed === 0) {
      setChanged(1)
    } else if (changed === 2) {
      setChanged(3)
    }
    var temp = [...fields]
    if (e.target.name === 'name') {
      temp[e.target.id].name = e.target.value
      setFields(temp)
    } else if (e.target.name === 'text') {
      temp[e.target.id].text = e.target.value
      setFields(temp)
    } else {
      setDetails({ ...details, [e.target.name]: e.target.value })
    }
  }
  const handleClick = () => {
    setOpen(!open)
  }
  const createPub = () => {
    if (details.title !== '' && details.description !== '' && activeVersion !== '') {
      dispatch(createProject(save_id, [details, fields, '', dcSweepcontrolLine, transientAnalysisControlLine, acAnalysisControlLine, tfAnalysisControlLine]))
    }
  }
  const clickChange = () => {
    if (details.title !== '' && details.description !== '' && activeVersion !== '') {
      if (changed === 1) {
        dispatch(createProject(save_id, [details, fields, '', dcSweepcontrolLine, transientAnalysisControlLine, acAnalysisControlLine, tfAnalysisControlLine]))
      } else if (changed === 2) {
        if (status !== project.details.status_name) {
          dispatch(changeStatus(project.details.project_id, status, ''))
        }
      } else if (changed === 3) {
        if (status !== project.details.status_name) {
          dispatch(createProject(save_id, [details, fields, status, dcSweepcontrolLine, transientAnalysisControlLine, acAnalysisControlLine, tfAnalysisControlLine]))
        } else {
          dispatch(createProject(save_id, [details, fields, '', dcSweepcontrolLine, transientAnalysisControlLine, acAnalysisControlLine, tfAnalysisControlLine]))
        }
      }
      setChanged(0)
    }
  }
  const clickPreview = () => {
    const win = window.open()
    win.location.href = '/eda/#/project?save_id=' + project.details.save_id + '&version=' + project.details.active_version + '&branch=' + project.details.active_branch + '&project_id=' + project.details.project_id
    win.focus()
  }
  const addField = () => {
    setFields([...fields, { name: '', text: '' }])
    if (changed === 0) {
      setChanged(1)
    } else if (changed === 2) {
      setChanged(3)
    }
  }
  const onClickShift = (type, index) => {
    if (type === 'above') {
      const temporary = [...fields]
      const current = temporary[index]
      temporary[index] = temporary[index - 1]
      temporary[index - 1] = current
      setFields(temporary)
    } else {
      const temporary = [...fields]
      const current = temporary[index]
      temporary[index] = temporary[index + 1]
      temporary[index + 1] = current
      setFields(temporary)
    }
  }
  const onRemove = (e) => {
    var list = [...fields]
    console.log(e)
    list.splice(e, 1)
    setFields(list)
    if (changed === 0) {
      setChanged(1)
    } else if (changed === 2) {
      setChanged(3)
    }
  }
  const handleDeleteDialogue = () => {
    setDeleteDialogue(!deleteDialogue)
  }
  const deleteProjectFunction = (id) => {
    console.log(id)
    dispatch(deleteProject(id))
    setDeleteDialogue(!deleteDialogue)
    setOpen(false)
  }
  return (
    <div>
      {(window.location.href.split('?id=')[1] && auth.user?.username === owner) &&
        <IconButton
          color='inherit'
          aria-label='open drawer'
          edge='end'
          size="small"
          onClick={handleClick}>
          <Tooltip title="Create Project">
            <PostAddIcon />
          </Tooltip>
        </IconButton>}
      <Dialog fullScreen open={open} TransitionComponent={Transition} onClose={handleClick} PaperProps={{
        style: {
          backgroundColor: '#4d4d4d',
          boxShadow: 'none'
        }
      }}>
        <AppBar className={classes.appBar}>
          <Toolbar>
            <IconButton edge="start" color="inherit" onClick={handleClick} aria-label="close">
              <CloseIcon />
            </IconButton>
            <Typography variant="h6" className={classes.title}>
              Project Details
            </Typography>

            {!project.details && <Button color="inherit" onClick={createPub}>
              Create Project
            </Button>}
            {project.details && <Button color="inherit" onClick={clickPreview}>
              Preview
            </Button>}
            {project.details && changed !== 0 && <Button color="inherit" onClick={clickChange}>
              Update Project
            </Button>}
          </Toolbar>
        </AppBar>

        <Container maxWidth="lg" className={classes.header}>
          <Grid
            container
            spacing={3}
            direction="row"
            justify="center"
            alignItems="flex-start"
          >
            <Grid item xs={12} sm={12}>

              {project.details && <Paper style={{ padding: '.2% 0%', marginBottom: '1%' }}>
                <h3 style={{ textAlign: 'center' }}>Status of the project: {project.details.status_name}  </h3>
                <h3 style={{ textAlign: 'center' }}>Active Version: {activeName} of variation {project.details.active_branch} saved on {activeSaveDate} at {activeSaveTime} hours</h3>
                {project.details.history && project.details.history.slice(0).reverse()[0]?.reviewer_notes && <h4 style={{ textAlign: 'center' }}>Reviewer Notes: {project.details.history.slice(0).reverse()[0]?.reviewer_notes}</h4>}
              </Paper>}
              <Paper className={classes.paper}>
                <h2 style={{ color: 'black' }}>Project Details</h2>
                {versions != null &&
                  ((project.details && project.details.can_edit) || !project.details) && <Grid item xs={12} sm={12}>
                  <FormControl
                    style={{ width: '100%' }}
                    className={classes.formControl}
                    error={!activeVersion}>
                    <InputLabel id="demo-simple-select-label">Select the version you want to use for your project.</InputLabel>
                    <Select
                      labelId="demo-simple-select-label"
                      id="demo-simple-select"
                      value={activeVersion}
                      onChange={handleActiveVersion}
                    >
                      {versions.map(version => {
                        return <MenuItem key={version.version} value={`${version.version}-${version.branch}`}>Version {version.name} from variation {version.branch} saved on {version.date} at {version.time}</MenuItem>
                      })}
                    </Select>
                  </FormControl> </Grid>}
                <TextField
                  color='primary'
                  autoFocus
                  margin="dense"
                  id="title"
                  label="Title"
                  name='title'
                  type="text"
                  fullWidth
                  disabled={project.details && !project.details.can_edit}
                  value={details.title}
                  error={!details.title}
                  onChange={changeFieldText}

                />
                <TextField
                  color='primary'
                  margin="dense"
                  multiline
                  id="description"
                  label="Description"
                  name='description'
                  rows={4}
                  type="text"
                  disabled={project.details && !project.details.can_edit}
                  value={details.description}
                  error={!details.description}
                  onChange={changeFieldText}
                  fullWidth
                />
                {fields && fields.map((item, index) =>
                  (
                    <>
                      <hr />
                      {((project.details && project.details.can_edit) || !project.details) &&
                      <>
                        <Tooltip title="Delete Field">
                          <IconButton style={{ float: 'right' }} onClick={() => onRemove(index)}>
                            <CloseIcon />
                          </IconButton></Tooltip>
                        {index !== fields.length - 1 && <IconButton style={{ float: 'right' }} onClick={() => onClickShift('below', index)}>
                          <Tooltip title="Move Field Down">
                            <KeyboardArrowDownIcon />
                          </Tooltip>
                        </IconButton>}
                        {index !== 0 && <IconButton style={{ float: 'right' }} onClick={() => onClickShift('above', index)}>
                          <Tooltip title="Move Field Up">
                            <KeyboardArrowUpIcon />
                          </Tooltip>
                        </IconButton>}
                      </>}
                      <TextField
                        color='primary'
                        margin="dense"
                        id={index}
                        label={'Title ' + index}
                        type="text"
                        name='name'
                        disabled={project.details && !project.details.can_edit}
                        value={item.name}
                        onChange={changeFieldText}
                        fullWidth
                      />
                      <TextField
                        color='primary'
                        margin="dense"
                        multiline
                        id={index}
                        label={'Text ' + index}
                        rows={4}
                        type="text"
                        name='text'
                        disabled={project.details && !project.details.can_edit}
                        value={item.text}
                        onChange={changeFieldText}
                        fullWidth
                      />
                    </>
                  ))}

                <br />
                {((project.states && project.details) || !project.details) && <Button onClick={addField}>+ Add Field</Button>}
                <h2 style={{ color: 'black' }}>Simulation Parameters</h2>
                <div>
                  <FormControl className={classes.formControl} style={{ width: '100%' }}>
                    <InputLabel id="demo-simple-select-label">Select simulation mode parameters to enter:</InputLabel>
                    <Select
                      style={{ width: '50%' }}
                      onChange={(e) => setSelectedSimulation(e.target.value)}
                      value={selectedSimulation}>
                      <MenuItem value="DC Sweep">DC Sweep</MenuItem>
                      <MenuItem value="Transient Analysis">Transient Analysis</MenuItem>
                      <MenuItem value="Transfer Function Analysis">Transfer Function Analysis</MenuItem>
                      <MenuItem value="AC Analysis">AC Analysis</MenuItem>
                    </Select>
                  </FormControl>
                </div>
                <ProjectSimulationParameters
                  dcSweepcontrolLine={dcSweepcontrolLine}
                  setDcSweepControlLine={setDcSweepControlLine}
                  transientAnalysisControlLine={transientAnalysisControlLine}
                  setTransientAnalysisControlLine={setTransientAnalysisControlLine}
                  acAnalysisControlLine={acAnalysisControlLine}
                  setAcAnalysisControlLine={setAcAnalysisControlLine}
                  tfAnalysisControlLine={tfAnalysisControlLine}
                  setTfAnalysisControlLine={setTfAnalysisControlLine}
                  changed={changed}
                  setChanged={setChanged}
                  selectedSimulation={selectedSimulation}
                />
                {project.details && <>{
                  project.states &&
                  <div style={{ textAlign: 'left' }}>
                    <br />
                    <InputLabel id="demo-simple-select-label">Change Status</InputLabel>
                    <Select
                      labelId="demo-simple-select-label"
                      id="demo-simple-select"
                      style={{ width: '50%' }}
                      onChange={handleSelectChange}
                      value={status}
                    >
                      {project.states.map((item, index) =>
                        (
                          <MenuItem key={item} value={item}>{item}</MenuItem>
                        ))}
                      <MenuItem key={project.details.status_name} value={project.details.status_name}>{project.details.status_name}</MenuItem>
                    </Select>
                  </div>
                }</>}
              </Paper>
            </Grid>
            {project.details && <><Grid item xs={6} sm={6}>
              <Paper style={{ paddingTop: '0%', padding: '2%' }}>
                <List>
                  <h3>List of Approved Reports</h3>
                  {project.reports?.approved[0]
                    ? <>
                      {project.reports.approved.map((item, index) => (
                        <ListItem key={index}>
                          {index + 1}. {item.description}
                        </ListItem>
                      ))}
                    </> : <h4>No approved reports.</h4>}
                </List>
                <List>
                  <h3>List of Reports yet to be evaluated by a Reviewer.</h3>
                  {project.reports?.open[0]
                    ? <>
                      {project.reports.open.map((item, index) => (
                        <ListItem key={index}>
                          {index + 1}. {item.description}
                        </ListItem>
                      ))}
                    </> : <h4>No Unapproved reports.</h4>}
                </List>
              </Paper>
            </Grid>
            <Grid item xs={6} sm={6}>
              <Paper style={{ padding: '2%' }}>
                <List>
                  <h3>History of this Project</h3>
                  {(project.details?.history && project.details?.history[0])
                    ? <>
                      <ProjectTimeline history={project.details.history.slice(0).reverse()} isOwner={auth.user?.username === owner} />
                    </>
                    : <h4>No history of this project.</h4>
                  }
                </List>
              </Paper>
            </Grid></>}
          </Grid>
          {!project.details && <Button color="primary" style={{ width: '100%', marginTop: '2%' }} variant='contained' onClick={createPub}>
            Create Project
          </Button>}
          {project.details && project.details.can_delete && <Button onClick={handleDeleteDialogue} style={{ width: '100%', color: 'white', backgroundColor: 'red', margin: '2% auto auto auto' }}>Delete Project</Button>}
          <Dialog
            open={deleteDialogue}
            onClose={handleDeleteDialogue}
            aria-labelledby="alert-dialog-title"
            aria-describedby="alert-dialog-description"
          >
            <DialogTitle id="alert-dialog-title">{'Are you sure you want to delete the project?'}</DialogTitle>
            <DialogContent>
              <DialogContentText id="alert-dialog-description">
                You cannot revert this.
              </DialogContentText>
            </DialogContent>
            <DialogActions>
              <Button onClick={handleDeleteDialogue} color="primary">
                Disagree
              </Button>
              <Button onClick={() => deleteProjectFunction(project.details.project_id)} color="primary" autoFocus>
                Agree
              </Button>
            </DialogActions>
          </Dialog>
        </Container>
      </Dialog>
    </div>
  )
}
Example #28
Source File: UrlsDialog.js    From fireshort with MIT License 4 votes vote down vote up
export default function UrlsDialog(props) {
    const classes = useStyles(); 
    const [gurl,setGurl]=useState("");  
    function makeid() {
        var length = 10;
        var result = '';
        var characters = 'abcdefghijklmnopqrstuvwxyz';
        var charactersLength = characters.length;
        for ( var i = 0; i < length; i++ ) {
           result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        setGurl(result);
    } 
    function forgetid() {
        setGurl("");
        props.handleClear();
    }
    return (
        <Dialog open={props.state.formopen} onClose={props.handleClose} aria-labelledby="form-dialog-title">
            <DialogTitle id="form-dialog-title">FireShort URL</DialogTitle>
            <DialogContent>
                {props.state.lurl.length === 0 && props.state.curl.length === 0 &&  gurl.length ===0  &&
                    (
                        <DialogContentText>
                            Enter Long and Short URLs.
                        </DialogContentText>
                    )
                }
                 {props.state.lurl.length === 0 && (props.state.curl.length > 0  || gurl.length > 0 )&&
                    (
                        <DialogContentText>
                            Enter Long URL.
                        </DialogContentText>
                    )
                }
                {props.state.lurl.length > 0 && (props.state.curl.length === 0  &&  gurl.length === 0) &&
                    (
                        <DialogContentText>
                            Enter or Generate Short URL.
                        </DialogContentText>
                    )
                }
                 {props.state.lurl.length > 0 && (props.state.curl.length > 0 ||  gurl.length>0) &&
                    (
                        <DialogContentText>
                            Looks good to go!
                        </DialogContentText>
                    )
                }
                {props.state.lurl.length > 0 &&(props.state.curl.length > 0 ||  gurl.length>0) &&  props.state.invalidLurl &&
                    (
                        <DialogContentText style={{color:'red'}}>
                            Invalid Long URL! Please try again.
                        </DialogContentText>
                    )
                }
                <TextField
                    autoFocus
                    margin="dense"
                    id="longurl"
                    label="Long URL"
                    type="url"
                    fullWidth
                    value={props.state.lurl}
                    onChange={props.handleLurlChange}
                />
                <TextField
                    margin="dense"
                    id="customurl"
                    label="Custom URL"
                    type="text"
                    value={gurl.length>0?gurl:props.state.curl}
                    onChange={props.handleCurlChange}
                />
                <Button
                    variant="contained"
                    color="primary"
                    size="medium"
                    className={classes.button}
                    startIcon={<SaveIcon />}
                    onClick = {makeid}
                >
                 Generate
                </Button>
                <Button
                    variant="contained"
                    color="secondary"
                    size="medium"
                    onClick={forgetid}
                    startIcon={<DeleteIcon />}
                   
                >Clear 
                </Button>
                </DialogContent>
            <DialogActions>
                <Button onClick={props.handleClose} color="primary">
                    Cancel
              </Button>
                <Button onClick={props.handleSubmit} color="primary">
                    Shorten
              </Button>
            </DialogActions>
        </Dialog>
    );
}
Example #29
Source File: UrlsDialog.js    From FireShort with MIT License 4 votes vote down vote up
export default function UrlsDialog(props) {
    const [open, setOpen] = React.useState(false);
    const handleClick = () => {
        setOpen(true);
    };

    const handleClose = (event, reason) => {
        if (reason === 'clickaway') {
            return;
        }

        setOpen(false);
    };
    return (
        <Dialog
            open={props.state.formopen}
            onClose={props.handleClose}
            aria-labelledby="form-dialog-title"
        >
            <DialogTitle id="form-dialog-title">FireShort URL</DialogTitle>
            <DialogContent>
                {props.state.lurl.length === 0 && props.state.curl.length === 0 &&
                    (
                        <DialogContentText>
                            Enter Long and Short URLs.
                        </DialogContentText>
                    )
                }
                {props.state.lurl.length === 0 && props.state.curl.length > 0 &&
                    (
                        <DialogContentText>
                            Enter Long URL.
                        </DialogContentText>
                    )
                }
                {props.state.lurl.length > 0 && props.state.curl.length === 0 &&
                    (
                        <DialogContentText>
                            Enter Short URL (optional).
                        </DialogContentText>
                    )
                }
                {props.state.lurl.length > 0 && props.state.curl.length > 0 &&
                    (
                        <DialogContentText>
                            Looks good to go!
                        </DialogContentText>
                    )
                }
                <TextField
                    autoFocus
                    margin="dense"
                    id="longurl"
                    label="Long URL"
                    type="url"
                    fullWidth
                    value={props.state.lurl}
                    onChange={props.handleLurlChange}
                />
                <TextField
                    margin="dense"
                    id="customurl"
                    label="Custom URL"
                    type="text"
                    fullWidth
                    value={props.state.curl}
                    onChange={props.handleCurlChange}
                />
                <Grid
                    component="label"
                    container
                    alignItems="center"
                    spacing={1}
                    style={{ marginTop: "15px", marginBottom: "15px" }}
                >
                    <Grid item><b>Track Link Activity:</b></Grid>
                    {/*<Grid item>Off</Grid>*/}
                    <Grid item>
                        <AntSwitch
                            checked={props.state.track}
                            onChange={props.handleTrackChange} name="checked"
                        />
                    </Grid>
                    {/*<Grid item>On</Grid>*/}
                </Grid>
                <Grid
                    component="label"
                    container
                    alignItems="center"
                    spacing={1}
                    style={{marginBottom: "15px" }}
                >
                    <Grid item><b>Protect Link:</b></Grid>
                    {/*<Grid item>Off</Grid>*/}
                    <Grid item>
                        <AntSwitch
                            checked={props.state.locked}
                            onChange={props.handleProtectChange} name="checked"
                        />
                    </Grid>
                    {
                        props.state.locked ?
                        <Grid item style={{ marginLeft: "15px", padding: "0px"}}>
                            <TextField
                                autoFocus
                                margin="dense"
                                type="password"
                                value={props.state.newPsw}
                                onChange={props.handlePswChange}
                            />
                        </Grid>
                        : null
                    }
                    {/*<Grid item>On</Grid>*/}
                </Grid>
            </DialogContent>
            <DialogActions>
                <Button onClick={props.handleClose} color="primary">
                    Cancel
              </Button>
                <Button onClick={() => {
                    if (isUrl(props.state.lurl) && !hasSpaces(props.state.curl)) {
                        props.handleSubmit()
                    } else {
                        handleClick()
                    }
                }} color="primary">
                    Shorten
              </Button>
                <Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
                    <Alert onClose={handleClose} severity="error" variant="filled">
                        {
                            !isUrl(props.state.lurl) ?
                            "Enter a valid URL to shorten" :
                            "Enter a custom URL without spaces"
                        }
                    </Alert>
                </Snackbar>
            </DialogActions>
        </Dialog>
    );
}