@material-ui/icons#Delete JavaScript Examples

The following examples show how to use @material-ui/icons#Delete. 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: App.js    From covid-vaccine-notification-system with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
tableIcons = {
  Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
  Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
  Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
  Delete: forwardRef((props, ref) => <Delete {...props} ref={ref} />),
  DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
  Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
  Export: forwardRef((props, ref) => <Save {...props} ref={ref} />),
  Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
  FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
  LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
  NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
  PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />),
  ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
  Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
  SortArrow: forwardRef((props, ref) => <ArrowUpward {...props} ref={ref} />),
  ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
  ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />),
}
Example #2
Source File: ConfirmDelete.jsx    From Edlib with GNU General Public License v3.0 6 votes vote down vote up
ConfirmDelete = ({ accessTokenToDelete, onClose, onDeleted }) => {
    const { id: applicationId } = React.useContext(ApplicationContext);
    const request = useRequestWithToken();
    const { status: deleteAccessTokenStatus, action: deleteAccessToken } =
        useRequestAction(() =>
            request(
                `/common/applications/${applicationId}/access_tokens/${accessTokenToDelete}`,
                'DELETE'
            )
        );

    return (
        <Dialog open={!!accessTokenToDelete} fullWidth maxWidth="xs">
            <DialogTitle>Delete application access token?</DialogTitle>
            <DialogContent>
                Are you sure you want to delete this access token? Application
                using this token will loose access to the API.
            </DialogContent>
            <DialogActions>
                <Button onClick={onClose} color="primary">
                    Cancel
                </Button>
                <Button
                    onClick={() => deleteAccessToken('', () => onDeleted())}
                    color="error"
                    disabled={deleteAccessTokenStatus.loading}
                    startIcon={<Delete />}
                >
                    Delete
                </Button>
            </DialogActions>
        </Dialog>
    );
}
Example #3
Source File: AnalysisCard.js    From jobtriage with MIT License 6 votes vote down vote up
AnalysisCard = props => {
  const classes = useStyles();
  const {
    content, onEdit, onDelete,
  } = props;

  return (
    <div className={`${classes.root} ql-editor`}>
      <div className={classes.contentDiv}>
        {parse(content)}
      </div>
      <div className={classes.menu}>
        {onDelete
          ? (
            <IconButton aria-label="Delete time log" component="span" onClick={onDelete}>
              <Delete color="error" />
            </IconButton>
          )
          : ''}

        <IconButton aria-label="Edit time log" component="span" onClick={onEdit}>
          <Edit color="primary" />
        </IconButton>
      </div>
    </div>
  );
}
Example #4
Source File: ActivitiesDataModule.js    From ehr with GNU Affero General Public License v3.0 5 votes vote down vote up
constructor(props) {
        super(props);

        this.state = {
            loading: true,
            filters: {
                dateRange: {
                    begin: moment()
                        .clone()
                        .subtract(1, 'month'),
                    end: moment(),
                },
            },
            page: 0,
            rowsPerPage: 25,
            data: [],
            columns: [
                {
                    label: '',
                    key: 'datePeriodFormatted',
                },
                {
                    label: t('ehr', 'Steps'),
                    key: 'steps',
                },
                {
                    label: t('ehr', 'Distance'),
                    key: 'distance',
                },
                {
                    label: t('ehr', 'Calories'),
                    key: 'calories',
                },
            ],
            activitiesDataToUpdate: null,
            savingActivities: false,
        };

        this.contextMenuOptions = [
            {
                label: t('ehr', 'Edit'),
                icon: <Edit fontSize="small" />,
                onClick: this.onEditActivities,
            },
            {
                label: t('ehr', 'Delete'),
                icon: <Delete fontSize="small" />,
                onClick: this.handleDelete,
            },
        ];

        this.activitiesService = new ActivitiesService();

        this.activitiesEditModalRef = React.createRef();
    }
Example #5
Source File: DiabetesDataModule.js    From ehr with GNU Affero General Public License v3.0 5 votes vote down vote up
constructor(props) {
        super(props);

        this.state = {
            loading: false,
            filters: {
                dateRange: {
                    begin: moment()
                        .clone()
                        .subtract(1, 'month'),
                    end: moment(),
                },
            },
            page: 0,
            rowsPerPage: 25,
            data: [],
            columns: [
                {
                    label: '',
                    key: 'date',
                },
                {
                    label: t('ehr', 'Glucose Value'),
                    key: 'glucoseValue',
                },
                {
                    label: t('ehr', 'Glucose Measurer'),
                    key: 'glucoseMeasurer',
                },
            ],
            diabetesToUpdate: null,
            savingDiabetes: false,
        };

        this.contextMenuOptions = [
            {
                label: t('ehr', 'Edit'),
                icon: <Edit fontSize="small" />,
                onClick: this.onEditDiabetesData,
            },
            {
                label: t('ehr', 'Delete'),
                icon: <Delete fontSize="small" />,
                onClick: this.handleDelete,
            },
        ];

        this.diabetesDataService = new DiabetesDataService();

        this.diabetesDataEditModalRef = React.createRef();
    }
Example #6
Source File: LabsDataModule.js    From ehr with GNU Affero General Public License v3.0 5 votes vote down vote up
constructor(props) {
        super(props);

        this.state = {
            loading: true,
            filters: {
                dateRange: {
                    begin: moment()
                        .clone()
                        .subtract(1, 'month'),
                    end: moment(),
                },
            },
            page: 0,
            rowsPerPage: 25,
            data: [],
            columns: [
                {
                    label: '',
                    key: 'date',
                },
                {
                    label: t('ehr', 'Leukocytes'),
                    key: 'leukocytes',
                },
                {
                    label: t('ehr', 'Hemoglobin'),
                    key: 'hemoglobin',
                },
                {
                    label: t('ehr', 'Platelets'),
                    key: 'platelets',
                },
                {
                    label: t('ehr', 'Lymphocytes'),
                    key: 'lymphocytes',
                },
                {
                    label: t('ehr', 'Neutrophils'),
                    key: 'neutrophils',
                },
                {
                    label: t('ehr', 'Eosinophils'),
                    key: 'eosinophils',
                },
                {
                    label: t('ehr', 'Basophils'),
                    key: 'basophils',
                },
                {
                    label: t('ehr', 'Monocytes'),
                    key: 'monocytes',
                },
            ],
            labsDataToUpdate: null,
            savingLabs: false,
        };

        this.contextMenuOptions = [
            {
                label: t('ehr', 'Edit'),
                icon: <Edit fontSize="small" />,
                onClick: this.onEditLabs,
            },
            {
                label: t('ehr', 'Delete'),
                icon: <Delete fontSize="small" />,
                onClick: this.handleDelete,
            },
        ];

        this.laboratoryService = new LaboratoryService();

        this.labsEditModalRef = React.createRef();
    }
Example #7
Source File: PhysicalDataModule.js    From ehr with GNU Affero General Public License v3.0 5 votes vote down vote up
constructor(props) {
        super(props);

        this.state = {
            loading: false,
            filters: {
                dateRange: {
                    begin: moment()
                        .clone()
                        .subtract(19, 'month'),
                    end: moment(),
                },
            },
            page: 0,
            rowsPerPage: 25,
            data: [],
            columns: [
                {
                    label: '',
                    key: 'date',
                },
                {
                    label: t('ehr', 'Age'),
                    key: 'age',
                },
                {
                    label: t('ehr', 'Body Height'),
                    key: 'bodyHeight',
                },
                {
                    label: t('ehr', 'Body Weight'),
                    key: 'bodyWeight',
                },
                {
                    label: t('ehr', 'Body Mass Index'),
                    key: 'bmi',
                },
            ],
            physicalDataToUpdate: null,
            savingPhysicalData: false,
        };

        this.contextMenuOptions = [
            {
                label: t('ehr', 'Edit'),
                icon: <Edit fontSize="small" />,
                onClick: this.onEditPhysicalData,
            },
            {
                label: t('ehr', 'Delete'),
                icon: <Delete fontSize="small" />,
                onClick: this.handleDelete,
            },
        ];

        this.physicalDataService = new PhysicalDataService();

        this.physicalDataEditModalRef = React.createRef();
    }
Example #8
Source File: VitalsDataModule.js    From ehr with GNU Affero General Public License v3.0 5 votes vote down vote up
constructor(props) {
        super(props);

        this.state = {
            loading: true,
            filters: {
                dateRange: {
                    begin: moment()
                        .clone()
                        .subtract(1, 'month'),
                    end: moment(),
                },
            },
            page: 0,
            rowsPerPage: 25,
            data: [],
            columns: [
                {
                    label: '',
                    key: 'date',
                },
                {
                    label: t('ehr', 'Systolic Blood Pressure'),
                    key: 'systolicBloodPressure',
                },
                {
                    label: t('ehr', 'Diastolic Blood Pressure'),
                    key: 'diastolicBloodPressure',
                },
                {
                    label: t('ehr', 'Heart Rate'),
                    key: 'heartRate',
                },
                {
                    label: t('ehr', 'Body Temperature'),
                    key: 'bodyTemperature',
                },
                {
                    label: t('ehr', 'Oxygen Saturation (SpO2)'),
                    key: 'oxygenSaturation',
                },
            ],
            vitalsDataToUpdate: null,
            savingVitals: false,
        };

        this.contextMenuOptions = [
            {
                label: t('ehr', 'Edit'),
                icon: <Edit fontSize="small" />,
                onClick: this.onEditVitals,
            },
            {
                label: t('ehr', 'Delete'),
                icon: <Delete fontSize="small" />,
                onClick: this.handleDelete,
            },
        ];

        this.vitalsService = new VitalsService();

        this.vitalsEditModalRef = React.createRef();
    }
Example #9
Source File: QuestionsTable.js    From quizdom with MIT License 5 votes vote down vote up
EnhancedTableToolbar = (props) => {
  const classes = useToolbarStyles();
  const {
    numSelected,
    selected,
    setSelected,
    questionArray,
    setQuestionArray,
  } = props;

  const deleteRow = () => {
    const temp = [...questionArray];
    // Delete the selected rows from QuestionsArray
    selected.forEach((element) => {
      const target = temp.findIndex((e) => e.title === element);
      temp.splice(target, 1);
    });

    setQuestionArray(temp);
    setSelected([]);
  };

  return (
    <Toolbar
      className={clsx(classes.root, {
        [classes.highlight]: numSelected > 0,
      })}
    >
      {numSelected > 0 ? (
        <Typography
          className={classes.title}
          color="inherit"
          variant="subtitle1"
          component="div"
        >
          {numSelected} selected
        </Typography>
      ) : (
        <Typography
          className={classes.title}
          variant="h6"
          id="tableTitle"
          component="div"
        >
          QUESTIONS
        </Typography>
      )}

      {numSelected > 0 ? (
        <IconButton onClick={deleteRow} aria-label="delete">
          <Delete />
        </IconButton>
      ) : null}
    </Toolbar>
  );
}
Example #10
Source File: TimeLog.js    From jobtriage with MIT License 5 votes vote down vote up
TimeLogItem = props => {
  const classes = useStyles();
  const {
    note, time, type, applicationId, id, onUpdate,
  } = props;
  const [openAddTimeLog, setOpenAddTimeLog] = useState(false);
  const dayJS = new DayJsAdapter();
  const formatedTime = dayJS.format(dayJS.date(time), 'MMM DD YYYY, hh:mm a');

  const handleDelete = () => {
    APIService.deleteTimeLog(applicationId, id).then(onUpdate);
  };

  const handleAddTimeLogOpen = () => {
    setOpenAddTimeLog(true);
  };

  const handleAddTimeLogClose = () => {
    setOpenAddTimeLog(false);
  };


  const FormatedNote = React.forwardRef((innerProps, ref) => (
    <div {...innerProps} ref={ref}>
      <Typography variant="body2">
        {note.length > 35 ? `${note.substring(0, 37)}...` : note}
      </Typography>
    </div>
  ));

  return (
    <Paper className={classes.timeLogItem} elevation={3}>
      <Typography variant="body2" style={{ width: '20%' }}>
        {formatedTime}
      </Typography>
      <Typography variant="body2" style={{ width: '10%' }}>
        {type.toUpperCase()}
      </Typography>
      <BootstrapTooltip title={note} style={{ width: '40%' }} arrow placement="top">
        <FormatedNote />
      </BootstrapTooltip>
      <div className={classes.displayFlex} style={{ justifyContent: 'space-between' }}>
        <a href={getCalenderLink(type, time, note)} label="Add to calender" target="_blank" rel="noopener noreferrer">
          <IconButton aria-label="Add to calender" component="span">
            <CalendarTodayOutlined />
          </IconButton>
        </a>
        <IconButton aria-label="Edit time log" component="span" onClick={handleAddTimeLogOpen}>
          <Edit color="primary" />
        </IconButton>
        <IconButton aria-label="Delete time log" component="span" onClick={handleDelete}>
          <Delete color="error" />
        </IconButton>
      </div>

      <TimeLogForm
        open={openAddTimeLog}
        onClose={handleAddTimeLogClose}
        onChange={onUpdate}
        applicationId={applicationId}
        timeLogId={id}
        time={time}
        note={note}
        type={type}
      />
    </Paper>
  );
}
Example #11
Source File: SelfAnalysis.js    From jobtriage with MIT License 5 votes vote down vote up
AnalysesCard = (props) => {
  const {
    title, content, analysisId, reload,
  } = props;
  const classes = useStyles();
  const [openAddAnalysis, setOpenAddAnalysis] = useState(false);

  const handleAddAnalysisOpen = () => {
    setOpenAddAnalysis(true);
  };

  const handleAddAnalysisClose = () => {
    setOpenAddAnalysis(false);
  };

  const loadState = () => {
    setOpenAddAnalysis(false);
    reload();
  };

  const deleteAnalysis = () => {
    APIService.deleteAnalysis(analysisId).then(reload);
  };

  return (
    <div className={classes.card}>
      <div className={classes.cardContent} onClick={handleAddAnalysisOpen}>
        <Typography variant="h6" gutterBottom color="primary">
          {title}
        </Typography>
        <div className="ql-editor">
          {parse(content)}
        </div>
      </div>
      <div className={classes.cardAction}>
        <IconButton aria-label="Delete analysis" component="span" onClick={deleteAnalysis}>
          <Delete />
        </IconButton>
      </div>
      <AnalysisForm
        open={openAddAnalysis}
        onClose={handleAddAnalysisClose}
        onChange={loadState}
        title={title}
        content={content}
        analysisId={analysisId}
      />
    </div>
  );
}
Example #12
Source File: Notes.js    From jobtriage with MIT License 5 votes vote down vote up
NotesCard = (props) => {
  const classes = useStyles();
  const [openAddNote, setOpenAddNote] = useState(false);
  const {
    title, content, onDelete, id, applicationId, onUpdate,
  } = props;

  const handleAddNoteOpen = () => {
    setOpenAddNote(true);
  };

  const handleAddNoteClose = () => {
    setOpenAddNote(false);
  };

  return (
    <div className={classes.card}>
      <div className={classes.cardContent} onClick={handleAddNoteOpen}>
        <Typography variant="h6" gutterBottom>
          {title.substring(0, 15)}
        </Typography>
        <Typography variant="body1" gutterBottom>
          {content}
        </Typography>
      </div>
      <div className={classes.cardAction}>
        <Delete
          style={{ cursor: 'pointer' }}
          onClick={() => onDelete(id)}
        />
      </div>
      <NoteForm
        open={openAddNote}
        onClose={handleAddNoteClose}
        onChange={onUpdate}
        applicationId={applicationId}
        title={title}
        content={content}
        id={id}
        label="Edit Note"
      />
    </div>
  );
}
Example #13
Source File: ExternalApplicationDetails.jsx    From Edlib with GNU General Public License v3.0 4 votes vote down vote up
ExternalApplicationDetails = ({
    applicationTokensFetchData,
    onCreate,
    createStatus,
    token,
    application,
    onDeleteRequest,
}) => {
    return (
        <Container maxWidth={false}>
            <Grid component={Box} container paddingY={2}>
                <Grid item>
                    <Breadcrumbs aria-label="breadcrumb">
                        <Link to="/">Edlib admin</Link>
                        <Link to="/settings">Settings</Link>
                        <Link to="/settings/external-applications">
                            External applications
                        </Link>
                        <Typography color="textPrimary">
                            {application.name}
                        </Typography>
                    </Breadcrumbs>
                </Grid>
            </Grid>
            <Grid container component={Box} paddingBottom={2}>
                <Grid item md={12}>
                    <Typography variant="h2">{application.name}</Typography>
                </Grid>
            </Grid>
            <Grid container>
                <Grid item md={6}>
                    <Paper>
                        <Box padding={2}>
                            <strong>Application ID: </strong> {application.id}
                        </Box>
                        <Box padding={2}>
                            <Button
                                variant="contained"
                                color="primary"
                                onClick={() => onCreate()}
                                disabled={createStatus.loading}
                            >
                                Create new
                            </Button>
                        </Box>
                        {token && (
                            <Alert>Created new access token: {token}</Alert>
                        )}
                        <DefaultHookQuery
                            fetchData={applicationTokensFetchData}
                        >
                            {({ response: accessTokens }) => (
                                <Table>
                                    <TableHead>
                                        <TableRow>
                                            <TableCell>Id</TableCell>
                                            <TableCell>Name</TableCell>
                                            <TableCell>Delete</TableCell>
                                        </TableRow>
                                    </TableHead>
                                    <TableBody>
                                        {accessTokens.map(({ id, name }) => (
                                            <TableRow key={id}>
                                                <TableCell width={260}>
                                                    {id}
                                                </TableCell>
                                                <TableCell>{name}</TableCell>
                                                <TableCell>
                                                    <Button
                                                        startIcon={<Delete />}
                                                        color="error"
                                                        onClick={() =>
                                                            onDeleteRequest(id)
                                                        }
                                                    >
                                                        Delete
                                                    </Button>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            )}
                        </DefaultHookQuery>
                    </Paper>
                </Grid>
            </Grid>
        </Container>
    );
}
Example #14
Source File: Toolbox.jsx    From doc2pen with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
function VerticalTabs(props) {
	const {
		color,
		setColor,
		fillColor,
		setFillColor,
		fillOpacity,
		setFillOpacity,
		setBowing,
		setFillStyle,
		setFillWeight,
		setHachureAngle,
		setHachureGap,
		bowing,
		fillStyle,
		fillWeight,
		hachureAngle,
		hachureGap,
		background,
		setBackground,
		width,
		setWidth,
		stroke,
		setStroke,
		roughness,
		setRoughness,
		type,
		setType,
		fontSize,
		setFontSize,
		fontStyle,
		setFontStyle,
		fontFamily,
		setFontFamily,
		edge,
		setEdge,
		clear,
		download,
		initiateLoadSaved,
		loadLastState,
		saveInstance,
	} = props;
	const [displayColorPicker, setDisplayColorPicker] = useState(false);
	const ColorPicker = props => {
		const { width, name, color, onColorChange } = props;
		return (
			<div className={styles.root}>
				<div className={styles.swatch}>
					<div
						className={styles.colorIndicator}
						style={{
							backgroundColor: props.color || "#fff",
						}}
						onMouseDown={() => {
							setDisplayColorPicker(true);
						}}
					/>
				</div>
				{displayColorPicker ? (
					<ClickAwayListener
						onClickAway={() => {
							setDisplayColorPicker(false);
						}}
					>
						<div className={styles.popover}>
							<ChromePicker
								width={width}
								name={name}
								color={color}
								onChangeComplete={color => onColorChange(color.hex)}
							/>
						</div>
					</ClickAwayListener>
				) : null}
			</div>
		);
	};

	const classes = useStyles();
	const [value, setValue] = React.useState(0);
	const handleChange = (event, newValue) => {
		setValue(newValue);
	};

	function Feature({ title, children, classname }) {
		return (
			<ListItem>
				<div className={styles.feature + " " + classname}>
					<ListItemText className={styles.title}>{title}</ListItemText>
					<div className={styles.body}>{children}</div>
				</div>
			</ListItem>
		);
	}

	function Shape({ type_, id, label, children }) {
		return (
			<label style={{ marginTop: "3px" }} htmlFor={id} title={label}>
				<div
					className={`${styles.feature} ${
						type === type_ && styles.active_feature
					}`}
					onClick={() => setType(type_)}
					id={id}
				>
					{children}
				</div>
			</label>
		);
	}

	return (
		<div className={styles.toolbox_root}>
			<div className={styles.canvas_toolbox}>
				<div className={classes.root}>
					<Tabs
						orientation="vertical"
						variant="scrollable"
						value={value}
						onChange={handleChange}
						className={classes.tabs}
					>
						<Tab
							onClick={() => setType("pen")}
							label={
								<label title="Project">
									<AccountTree />
								</label>
							}
							{...a11yProps(0)}
						/>
						<Tab
							onClick={() => setType("pen")}
							label={
								<label title="Canvas Setup">
									<RiFileSettingsLine size={25} />
								</label>
							}
							{...a11yProps(1)}
						/>
						<Tab
							onClick={() => setType("pen")}
							label={
								<label title="Shapes & Tools">
									<FaShapes size={25} />
								</label>
							}
							{...a11yProps(2)}
						/>
						<Tab
							onClick={() => setType("text")}
							label={
								<label title="Text">
									<TextFields />
								</label>
							}
							{...a11yProps(3)}
						/>
						<Tab
							onClick={() => {
								setType("pen");
							}}
							label={
								<label title="Icon Library">
									<Apps />
								</label>
							}
							{...a11yProps(4)}
						/>
						<Tab
							onClick={() => setType("pen")}
							label={
								<label title="Minimize Sidebar">
									<Close />
								</label>
							}
							{...a11yProps(5)}
						/>
					</Tabs>
					<TabPanel value={value} index={0}>
						<List component="div">
							<ListItem button onClick={clear}>
								<ListItemIcon>
									<Delete />
								</ListItemIcon>
								<ListItemText primary="Clear Canvas" />
							</ListItem>
							<ListItem button onClick={download}>
								<ListItemIcon>
									<SaveAlt />
								</ListItemIcon>
								<ListItemText primary="Download PNG" />
							</ListItem>
							<ListItem
								button
								onClick={() => initiateLoadSaved("img-file-selector")}
							>
								<ListItemIcon>
									<PhotoLibrary />
									<input
										type="file"
										id="img-file-selector"
										style={{ display: "none" }}
										accept="image/*"
										onChange={event => loadLastState(event)}
									/>
								</ListItemIcon>
								<ListItemText primary="Place Image" />
							</ListItem>
							<ListItem
								button
								onClick={() => saveInstance("savedProgress.d2ps")}
							>
								<ListItemIcon>
									<Save />
								</ListItemIcon>
								<ListItemText primary="Save & download Progress" />
							</ListItem>
							<ListItem
								button
								onClick={() => initiateLoadSaved("file-selector")}
							>
								<ListItemIcon style={{ width: 0 }}>
									<D2psIcon
										style={{
											transform: "scale(0.6) translateX(-30px)",
										}}
									/>
									<input
										type="file"
										id="file-selector"
										style={{ display: "none" }}
										accept=".d2ps"
										onChange={event => loadLastState(event)}
									/>
								</ListItemIcon>
								<ListItemText primary="Load Previous Progress" />
							</ListItem>
						</List>
					</TabPanel>
					<TabPanel value={value} index={1}>
						<List component="div">
							<Feature title="Canvas Setup">
								<div className={styles.colorPicker}>
									<ColorPicker
										width={200}
										name="canvas_bg_color"
										color={background}
										onColorChange={setBackground}
									/>
									<input
										className={styles.hexInput}
										placeholder="#"
										type="text"
										value={background}
										onInput={e => setBackground(e.target.value)}
									/>
								</div>
							</Feature>
						</List>
					</TabPanel>
					<TabPanel value={value} index={2}>
						<List component="div">
							<Feature title="Shapes and Tools">
								<Shape type_="pen" id="sketch-shapes-pen" label="Pen">
									<FaPencilAlt size={12} />
								</Shape>
								<Shape type_="line" id="sketch-shapes-line" label="Line">
									<FaSlash size={10} />
								</Shape>
								<Shape type_="square" id="sketch-shapes-square" label="Square">
									<FaRegSquare size={10} />
								</Shape>
								<Shape type_="circle" id="sketch-shapes-circle" label="Circle">
									<FaRegCircle size={10} />
								</Shape>
								<Shape
									type_="triangle"
									id="sketch-shapes-triangle"
									label="Triangle"
								>
									<GiTriangleTarget size={12} />
								</Shape>
								<Shape type_="arrow" id="sketch-shapes-arrow" label="Arrow">
									<BsArrowUpRight size={12} />
								</Shape>
								<Shape
									type_="diamond"
									id="sketch-shapes-diamond"
									label="Diamond"
								>
									<BsDiamond size={10} />
								</Shape>
								<Shape
									type_="biShapeTriangle"
									id="sketch-shapes-biShapeTriangle"
									label="Bi Shape Triangle"
								>
									<BiShapeTriangle size={12} />
								</Shape>
							</Feature>
							<Divider />
							{!["text", "pen", "line"].includes(type) && (
								<>
									<Feature title="Fill Style">
										<select
											name="shape_fill_style"
											value={fillStyle}
											onChange={e => setFillStyle(e.target.value)}
										>
											<option value="none">none</option>
											<option value="solid">solid</option>
											<option value="hachure">hachure</option>
											<option value="zigzag">zigzag</option>
											<option value="cross-hatch">cross-hatch</option>
											<option value="dots">dots</option>
											<option value="dashed">dashed</option>
											<option value="zigzag-line">zigzag-line</option>
										</select>
									</Feature>
									{fillStyle !== "none" && (
										<>
											<Feature title="Fill Color">
												<div className={styles.colorPicker}>
													<ColorPicker
														width={200}
														name="canvas_pen_color"
														color={fillColor}
														onColorChange={setFillColor}
													/>
													<input
														className={styles.hexInput}
														placeholder="#"
														type="text"
														value={fillColor}
														onInput={e => setFillColor(e.target.value)}
													/>
												</div>
											</Feature>
											<Feature
												classname={styles.sliderWrapper}
												title={"Fill Opacity"}
											>
												<input
													className={styles.slider}
													type="range"
													min={0}
													max={1}
													step={0.1}
													value={fillOpacity}
													onChange={e => setFillOpacity(e.target.value)}
												/>
											</Feature>
										</>
									)}
									{!["none", "solid"].includes(fillStyle) && (
										<>
											<Feature
												classname={styles.sliderWrapper}
												title={"Fill Weight"}
											>
												<input
													className={styles.slider}
													type="range"
													min={1}
													max={10}
													step={0.1}
													value={fillWeight}
													onChange={e => setFillWeight(e.target.value)}
												/>
											</Feature>
											<Feature
												classname={styles.sliderWrapper}
												title={"Fill Hachure Angle"}
											>
												<input
													className={styles.slider}
													type="range"
													min={0}
													max={360}
													step={1}
													value={hachureAngle + 180}
													onChange={e => setHachureAngle(e.target.value - 180)}
												/>
											</Feature>
											<Feature
												classname={styles.sliderWrapper}
												title={"Fill Hachure Gap"}
											>
												<input
													className={styles.slider}
													type="range"
													min={1}
													max={10}
													step={0.1}
													value={hachureGap}
													onChange={e => setHachureGap(e.target.value)}
												/>
											</Feature>
										</>
									)}
									<Divider />
								</>
							)}

							<Feature title="Stroke">
								<div className={styles.colorPicker}>
									<ColorPicker
										width={200}
										name="canvas_pen_color"
										color={color}
										onColorChange={setColor}
									/>
									<input
										className={styles.hexInput}
										placeholder="#"
										type="text"
										value={color}
										onInput={e => setColor(e.target.value)}
									/>
								</div>
							</Feature>
							<Feature classname={styles.sliderWrapper} title={"Roughness"}>
								<input
									className={styles.slider}
									type="range"
									min={0}
									max={5}
									step={0.1}
									value={roughness}
									onChange={e => setRoughness(e.target.value)}
								/>
							</Feature>
							<Feature classname={styles.sliderWrapper} title={"Stroke Bowing"}>
								<input
									className={styles.slider}
									type="range"
									min={0}
									max={10}
									step={0.1}
									value={bowing}
									onChange={e => setBowing(e.target.value)}
								/>
							</Feature>
							<Feature title="Stroke Width">
								<select
									name="canvas_pen_width"
									value={width}
									onChange={e => setWidth(e.target.value)}
								>
									<option value="1">1px</option>
									<option value="2">2px</option>
									<option value="3">3px</option>
									<option value="4">4px</option>
									<option value="5">5px</option>
									<option value="6">6px</option>
									<option value="7">7px</option>
									<option value="8">8px</option>
									<option value="9">9px</option>
									<option value="10">10px</option>
									<option value="11">11px</option>
								</select>
							</Feature>
							<Feature title="Stroke Style">
								<div
									className={`${styles.feature_box} ${
										stroke === "none" && styles.active_feature_box
									}`}
									onClick={() => setStroke("none")}
								>
									<AiOutlineLine size={20} />
								</div>
								<div
									className={`${styles.feature_box} ${
										stroke === "small" && styles.active_feature_box
									}`}
									onClick={() => setStroke("small")}
								>
									<AiOutlineSmallDash size={20} />
								</div>
								<div
									className={`${styles.feature_box} ${
										stroke === "big" && styles.active_feature_box
									}`}
									onClick={() => setStroke("big")}
								>
									<AiOutlineDash size={20} />
								</div>
							</Feature>
							<Feature title="Edge">
								<select value={edge} onChange={e => setEdge(e.target.value)}>
									<option value="round">Round</option>
									<option value="bevel">Bevel</option>
									<option value="miter">Miter</option>
								</select>
							</Feature>
						</List>
					</TabPanel>
					<TabPanel value={value} index={3}>
						<List component="div">
							<Feature title="Stroke">
								<div className={styles.colorPicker}>
									<ColorPicker
										width={200}
										name="canvas_pen_color"
										color={color}
										onColorChange={setColor}
									/>
									<input
										className={styles.hexInput}
										placeholder="#"
										type="text"
										value={color}
										onInput={e => setColor(e.target.value)}
									/>
								</div>
							</Feature>
							<Feature
								classname={styles.sliderWrapper}
								title={`Font [ ${fontSize} ]`}
							>
								<input
									className={styles.slider}
									type="range"
									min="10"
									max="20"
									value={fontSize * 10}
									onChange={e => setFontSize(e.target.value / 10)}
								/>
							</Feature>
							<Feature title="Font Style">
								<div
									className={`${styles.feature_box} ${
										fontStyle === "normal" && styles.active_feature_box
									}`}
									onClick={() => setFontStyle("normal")}
								>
									<BsFonts size={20} />
								</div>
								<div
									className={`${styles.feature_box} ${
										fontStyle === "italic" && styles.active_feature_box
									}`}
									onClick={() => setFontStyle("italic")}
								>
									<FaItalic size={15} />
								</div>
								<div
									className={`${styles.feature_box} ${
										fontStyle === "bold" && styles.active_feature_box
									}`}
									onClick={() => setFontStyle("bold")}
								>
									<FaBold size={15} />
								</div>
							</Feature>
							<Feature title="Font Family">
								<select
									value={fontFamily}
									onChange={e => setFontFamily(e.target.value)}
								>
									<option value="cursive">Cursive</option>
									<option value="Courier New">Courier New</option>
									<option value="serif">Serif</option>
								</select>
							</Feature>
						</List>
					</TabPanel>
					<TabPanel value={value} index={4}>
						<List component="div">
							<IconsLibrary />
						</List>
					</TabPanel>
					<TabPanel
						className={classes.tabPanelClose}
						value={value}
						index={5}
					></TabPanel>
				</div>
			</div>
		</div>
	);
}
Example #15
Source File: images-preview-container.js    From horondi_admin with MIT License 4 votes vote down vote up
ImagesPreviewContainer = ({ src, labels, multiple, imageHandler }) => {
  const style = useStyles();
  const [primaryImageIndex, setPrimaryImageIndex] = useState(0);
  const [arrItems, setArrItems] = useState([]);
  useEffect(() => {
    setArrItems(Array(8).fill({ src: preview, checked: false }));
    !!src.length &&
      src.forEach((item, index) => {
        const image = item?.src?.large
          ? {
              ...item,
              src: config.imagePrefix + item.src.large
            }
          : item;
        setArrItems((prev) => {
          const clone = [...prev];
          clone.splice(index, 1, { ...image, index });
          return clone;
        });
        if (item?.primary) setPrimaryImageIndex(index);
      });
  }, [src]);

  const checkedList = useMemo(
    () => arrItems.filter((item) => item.checked === true),
    [arrItems]
  );

  const disabledPrimary = checkedList.length !== 1;

  const handleChange = (e) => {
    setArrItems((prev) => {
      const clone = [...prev];
      clone[e.target.name] = {
        ...prev[e.target.name],
        checked: e.target.checked
      };
      return clone;
    });
  };

  const handlePrimaryImage = () => {
    imageHandler((prev) => {
      const clone = [...prev];
      clone[primaryImageIndex] = {
        ...clone[primaryImageIndex],
        primary: false
      };
      clone[checkedList[0].index] = {
        ...clone[checkedList[0].index],
        primary: true
      };
      return clone;
    });
  };

  const handleDelete = () => {
    imageHandler((prev) => {
      const newArr = [...prev].filter((item, idx) => {
        const check = checkedList.filter(({ index }) => index === idx);
        const img = item.src.large
          ? config.imagePrefix + item.src.large
          : item.src.preview;
        return img !== check[0]?.src;
      });
      checkedList.forEach((item) => {
        if (item.primary && prev.length !== 1 && newArr.length)
          newArr[0].primary = true;
      });
      return newArr;
    });
  };

  const handlePreviewPage = () => {
    // handler for preview product page
  };

  const list = arrItems.length
    ? arrItems.map((file, index) => (
        <Grid item className={style.item} key={index}>
          <div className={style.thumb}>
            <div className={style.thumbInner}>
              <img
                src={file.src}
                className={style.img}
                alt={utils.alt.preview}
              />
            </div>
          </div>
          <div className={style.checkbox}>
            <Checkbox
              checked={arrItems[index]?.checked || false}
              onChange={handleChange}
              inputProps={{ 'aria-label': 'controlled' }}
              disabled={file.src === preview}
              name={file.index}
            />
          </div>
        </Grid>
      ))
    : null;

  if (src.length === 0) return null;

  return (
    <>
      <Grid container spacing={4}>
        <Grid item margin={10}>
          <Typography variant='h4'>{labels.primary}</Typography>
          <Box className={style.primary} data-cy={utils.dataCy.preview}>
            <div className={style.imagePrimaryInner}>
              <img
                src={arrItems[primaryImageIndex]?.src}
                className={style.img}
                alt={utils.alt.preview}
              />
            </div>
          </Box>
        </Grid>
        <Grid item margin={10}>
          <Typography variant='h4'>{labels.additional}</Typography>
          <Box className={style.listContainer}>{multiple && list}</Box>
        </Grid>
      </Grid>
      <Box className={style.buttonContainer}>
        <Box className={style.buttonGroup}>
          <FormControlLabel
            className={style.deleteLabel}
            control={<Delete color='error' />}
            onClick={handleDelete}
            label='Видалити'
          />
          <FormControlLabel
            control={
              <Checkbox
                name='primary'
                onChange={handlePrimaryImage}
                checked={
                  (checkedList.length &&
                    arrItems[checkedList[0].index]?.primary) ||
                  false
                }
                disabled={disabledPrimary}
              />
            }
            label='Встановити як основне фото продукту'
          />
        </Box>
        <Box>
          <Button
            variant={materialUiConstants.contained}
            color={materialUiConstants.primary}
            onClick={handlePreviewPage}
            size='medium'
            disabled
          >
            Попередній перегляд
          </Button>
        </Box>
      </Box>
    </>
  );
}
Example #16
Source File: EditQuiz.js    From Quizzie with MIT License 4 votes vote down vote up
function EditQuiz(props) {
	const quizId = props.match.params.id;

	const [loading, setLoading] = useState(true);
	const [redirect, setRedirect] = useState(false);

	const [quizDetails, setQuizDetails] = useState({});
	const [quizQuestions, setQuizQuestions] = useState([]);

	const [fileError, setFileError] = useState(false);
	const [serverError, setServerError] = useState(false);
	const [popoverAnchor, setPopoverAnchor] = useState(null);
	const popoverOpen = Boolean(popoverAnchor);

	const [questionModal, setQuestionModal] = useState(false);
	const [newQuestion, setNewQuestion] = useState("");
	const [newQuestionError, setNewQuestionError] = useState(false);

	const [option1, setOption1] = useState("");
	const [option1Error, setOption1Error] = useState(false);
	const [option2, setOption2] = useState("");
	const [option2Error, setOption2Error] = useState(false);
	const [option3, setOption3] = useState("");
	const [option3Error, setOption3Error] = useState(false);
	const [option4, setOption4] = useState("");
	const [option4Error, setOption4Error] = useState(false);
	const [correctOption, setCorrectOption] = useState(-1);
	const [correctOptionError, setCorrectOptionError] = useState(false);

	const [update, setUpdate] = useState(false);
	const [updateId, setUpdateId] = useState(null);

	const [deleteModal, setDeleteModal] = useState(false);
	const [deleteQuestionModal, setDeleteQuestionModal] = useState(false);

	const [quizRestartModal, setQuizRestartModal] = useState(false);
	const [closeQuizModal, setCloseQuizModal] = useState(false);

	const [responses, setResponses] = useState([]);

	const [searchData, setSearchData] = useState(responses);
	const [searchText, setSearchText] = useState("");
	const [sortBy, setSortBy] = useState(-1);

	const { executeRecaptcha } = useGoogleReCaptcha();

	const onCloseHandle = () => {
		setQuestionModal(false);
		if (update) {
			setUpdate(false);
			setUpdateId(null);
			clearModal();
		}
	};

	const handlePopover = (event) => {
		setPopoverAnchor(event.currentTarget);
	};

	const handlePopoverClose = () => {
		setPopoverAnchor(null);
	};

	const onQuestionChange = (event) => {
		setNewQuestion(event.target.value);
	};

	const handleOptionChange1 = (event) => {
		setOption1(event.target.value);
	};
	const handleOptionChange2 = (event) => {
		setOption2(event.target.value);
	};
	const handleOptionChange3 = (event) => {
		setOption3(event.target.value);
	};
	const handleOptionChange4 = (event) => {
		setOption4(event.target.value);
	};

	const handleCorrectOption = (event) => {
		setCorrectOption(event.target.value);
	};

	const clearModal = () => {
		setNewQuestion("");
		setNewQuestionError(false);
		setOption1("");
		setOption1Error(false);
		setOption2("");
		setOption2Error(false);
		setOption3("");
		setOption3Error(false);
		setOption4("");
		setOption4Error(false);
		setCorrectOption(-1);
		setCorrectOptionError(false);
	};

	const handleFileDrop = (files) => {
		const reader = new FileReader();

		let questions = [];

		reader.onabort = () => {
			setFileError(true);
			return;
		};
		reader.onerror = () => {
			setFileError(true);
			return;
		};

		reader.onload = () => {
			csv.parse(reader.result, (err, data) => {
				if (data === undefined) {
					setFileError(true);
					return;
				}
				data.map((question) => {
					if (question[0].trim() === "") {
						return null;
					}
					let obj = {
						quizId: quizId,
						description: question[0],
						options: [
							{ text: question[1] },
							{ text: question[2] },
							{ text: question[3] },
							{ text: question[4] },
						],
						correctAnswer: question[5],
					};

					questions.push(obj);
				});
				submitCSV(questions);
			});
		};

		reader.readAsBinaryString(files[0]);
	};

	const submitCSV = async (questions) => {
		setLoading(true);
		let token = localStorage.getItem("authToken");
		let url = "https://quizzie-api.herokuapp.com/question/csv";

		let captcha = await executeRecaptcha("submit_csv");

		let data = {
			questions: questions,
			captcha: captcha,
		};

		try {
			await axios
				.post(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					console.log(res);
					setLoading(false);
					clearModal();
					onCloseHandle();
					getQuizDetails();
				});
		} catch (error) {
			setServerError(true);
			console.log(error);
		}
	};

	const handleSearchChange = (event) => {
		setSearchText(event.target.value);

		let newRes = responses.filter(
			(response) =>
				response.userId.name
					.toLowerCase()
					.search(event.target.value.trim().toLowerCase()) !== -1 ||
				String(response.marks) ===
					event.target.value.trim().toLowerCase()
		);
		let sorted = sortByFunc(sortBy, newRes);

		setSearchData(sorted);
	};

	const handleSortChange = (event) => {
		setSortBy(event.target.value);

		let newRes = sortByFunc(event.target.value, searchData);

		setSearchData(newRes);
	};

	const sortByFunc = (by, array) => {
		if (by === "score") {
			return array.sort(function (a, b) {
				return b.marks - a.marks;
			});
		} else if (by === "name") {
			return array.sort(function (a, b) {
				return a.userId.name - b.userId.name;
			});
		} else if (by === "recent") {
			return array.sort(function (a, b) {
				return b.timeEnded - a.timeEnded;
			});
		} else {
			return array;
		}
	};

	const handleRestart = async () => {
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/restart`;

		let captcha = await executeRecaptcha("restart_quiz");

		let data = {
			quizId: quizId,
			captcha: captcha,
		};

		try {
			await axios
				.patch(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setQuizRestartModal(false);
					getQuizDetails();
				});
		} catch (error) {
			console.log(error);
		}
	};

	const handleQuizClose = async () => {
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/close`;

		let captcha = await executeRecaptcha("quiz_close");

		let data = {
			quizId: quizId,
			captcha: captcha,
		};

		try {
			await axios
				.patch(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setCloseQuizModal(false);
					getQuizDetails();
				});
		} catch (error) {
			console.log(error);
		}
	};

	const handleQuestionEditBtn = (question) => {
		setUpdate(true);
		setUpdateId(question._id);
		setNewQuestion(question.description);
		setOption1(question.options[0].text);
		setOption2(question.options[1].text);
		setOption3(question.options[2].text);
		setOption4(question.options[3].text);
		setCorrectOption(question.correctAnswer);
		setQuestionModal(true);
	};

	const handleQuestionDeleteBtn = (question) => {
		setUpdateId(question._id);
		setDeleteQuestionModal(true);
	};

	const handleQuestionModalClose = () => {
		setUpdateId(null);
		setDeleteQuestionModal(false);
	};

	const handleDeleteBtn = () => {
		setDeleteModal(true);
	};

	const handleDeleteQuestion = async () => {
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/question/${updateId}`;

		// let captcha = executeRecaptcha("delete_quiz");

		try {
			await axios
				.delete(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setUpdateId(null);
					setDeleteQuestionModal(false);
					getQuizDetails();
				});
		} catch (error) {
			console.log(error);
		}
	};

	const handleDelete = async () => {
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/delete`;

		let data = {
			quizId: quizId,
		};

		try {
			await axios
				.delete(url, {
					headers: {
						"auth-token": token,
					},
					data: data,
				})
				.then((res) => {
					setRedirect(true);
				});
		} catch (error) {
			console.log(error);
		}
	};

	const handleQuestionUpdate = async () => {
		if (!validate()) return;

		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/question/update/${updateId}`;

		let captcha = await executeRecaptcha("question_update");

		let updateOps = [
			{ propName: "description", value: newQuestion },
			{
				propName: "options",
				value: [
					{
						text: option1,
					},
					{
						text: option2,
					},
					{
						text: option3,
					},
					{
						text: option4,
					},
				],
			},
			{ propName: "correctAnswer", value: correctOption },
		];

		let data = {
			updateOps: updateOps,
			captcha: captcha,
		};

		try {
			await axios
				.patch(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					onCloseHandle();
					getQuizDetails();
				});
		} catch (error) {
			console.log(error);
		}
	};

	const validate = () => {
		if (newQuestion.trim().length === 0) {
			setNewQuestionError(true);
			return false;
		}

		if (option1.trim().length === 0) {
			setOption1Error(true);
			return false;
		}
		if (option2.trim().length === 0) {
			setOption2Error(true);
			return false;
		}
		if (option3.trim().length === 0) {
			setOption3Error(true);
			return false;
		}
		if (option4.trim().length === 0) {
			setOption4Error(true);
			return false;
		}

		if (correctOption === -1) {
			setCorrectOptionError(true);
			return false;
		}

		return true;
	};

	const handleQuestionSubmit = async () => {
		//TODO: Handle Validation

		if (!validate()) return;

		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/question/add`;

		let captcha = await executeRecaptcha("submit_question");

		let options = [
			{ text: option1 },
			{ text: option2 },
			{ text: option3 },
			{ text: option4 },
		];

		let data = {
			quizId: quizId,
			description: newQuestion,
			options: options,
			correctAnswer: correctOption,
			captcha: captcha,
		};

		try {
			await axios
				.post(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					clearModal();
					getQuizDetails();
					setQuestionModal(false);
				});
		} catch (error) {
			console.log(error);
		}
	};

	const isOwnerOfQuiz = async () => {
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/checkAdmin/${quizId}`;

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					return true;
				});
		} catch (error) {
			setRedirect(true);
			return;
		}
	};

	const getQuizDetails = async () => {
		setLoading(true);
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/${quizId}`;

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setQuizDetails(res.data.result);
				});
		} catch (error) {
			console.log(error);
		}

		url = `https://quizzie-api.herokuapp.com/question/all/${quizId}`;

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setQuizQuestions(res.data.result);
				});
		} catch (error) {
			console.log(error);
		}

		url = `https://quizzie-api.herokuapp.com/admin/allStudentsQuizResult/${quizId}`;

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setResponses(res.data.userResults);
					setSearchData(res.data.userResults);
					setLoading(false);
				});
		} catch (error) {
			console.log(error);
		}
	};

	useEffect(() => {
		let token = localStorage.getItem("authToken");
		if (token === null) {
			setLoading(false);
			setRedirect(true);
			return;
		}

		isOwnerOfQuiz();
		getQuizDetails();
	}, []);

	if (loading) {
		return <Loading />;
	} else if (redirect) {
		return <Redirect to="/dashboard" />;
	} else {
		return (
			<Container className="edit-quiz-page">
				<Typography
					variant="h3"
					className="dash-head p-top edit-quiz-head"
				>
					Edit Quiz
				</Typography>
				<div className="edit-btn-bar">
					<Button
						className="edit-details-btn"
						component={Link}
						to={`/updateQuizDetails/${quizId}`}
					>
						<Create className="edit-icon" />
						Edit Details
					</Button>
					<Button
						className="edit-details-btn delete-btn"
						onClick={handleDeleteBtn}
					>
						<Delete className="edit-icon" />
						Delete Quiz
					</Button>
					{quizDetails.quizStatus === 1 ? (
						<Button
							className="edit-details-btn"
							style={{ marginLeft: "3%" }}
							onClick={() => setCloseQuizModal(true)}
						>
							<Replay className="edit-quiz" />
							Close Quiz
						</Button>
					) : quizDetails.quizStatus === 2 ? (
						<Button
							className="edit-details-btn"
							style={{ marginLeft: "3%" }}
							onClick={() => setQuizRestartModal(true)}
						>
							<Replay className="edit-quiz" />
							Restart Quiz
						</Button>
					) : null}
				</div>
				<div className="quiz-details-sec">
					<Typography variant="h6" className="quiz-detail-param">
						Name:{" "}
						<span className="quiz-detail-text">
							{quizDetails.quizName}
						</span>
					</Typography>
					<Typography variant="h6" className="quiz-detail-param">
						Date:{" "}
						<span className="quiz-detail-text">
							{new Date(
								Number(quizDetails.scheduledFor)
							).toDateString()}
						</span>
					</Typography>
					<Typography variant="h6" className="quiz-detail-param">
						Time:{" "}
						<span className="quiz-detail-text">
							{new Date(
								Number(quizDetails.scheduledFor)
							).toLocaleTimeString()}
						</span>
					</Typography>
					<Typography variant="h6" className="quiz-detail-param">
						Duration:{" "}
						<span className="quiz-detail-text">
							{quizDetails.quizDuration} minutes
						</span>
					</Typography>
					<Typography variant="h6" className="quiz-detail-param">
						Type:{" "}
						<span className="quiz-detail-text">
							{quizDetails.quizType}
						</span>
					</Typography>
					{quizDetails.quizType === "private" ? (
						<Typography variant="h6" className="quiz-detail-param">
							Quiz Code:{" "}
							<span className="quiz-detail-text">
								{quizDetails.quizCode}
							</span>
						</Typography>
					) : null}
				</div>
				<div className="quiz-questions-sec">
					<Typography variant="h4" className="quiz-questions-head">
						Questions
					</Typography>
					<div className="quiz-questions-display">
						<div className="add-question-bar">
							<Button
								className="add-question-btn"
								onClick={() => setQuestionModal(true)}
							>
								Add a question
							</Button>
						</div>
						{quizQuestions.length === 0 ? (
							<p style={{ textAlign: "center" }}>
								No questions added yet!
							</p>
						) : (
							<div className="questions-list-display">
								{quizQuestions.map((question) => (
									<ExpansionPanel
										elevation={3}
										className="expansion"
										key={question._id}
									>
										<ExpansionPanelSummary
											className="question-summary"
											expandIcon={<ExpandMore />}
											aria-controls="question-content"
											aria-label="Expand"
										>
											<FormControlLabel
												style={{ marginRight: "0" }}
												aria-label="Edit"
												control={
													<IconButton>
														<Create />
													</IconButton>
												}
												// label={question.description}
												onClick={() =>
													handleQuestionEditBtn(
														question
													)
												}
											/>
											<FormControlLabel
												aria-label="Edit"
												control={
													<IconButton>
														<Delete />
													</IconButton>
												}
												// label={question.description}
												onClick={() =>
													handleQuestionDeleteBtn(
														question
													)
												}
											/>
											<Typography className="question-label">
												{question.description}
											</Typography>
										</ExpansionPanelSummary>
										<ExpansionPanelDetails>
											<List
												component="nav"
												className="options-display"
											>
												{question.options.map(
													(option) => (
														<ListItem
															button
															key={option._id}
														>
															<ListItemIcon>
																<Adjust
																	style={{
																		color:
																			question.correctAnswer ===
																			option.text
																				? "green"
																				: "black",
																	}}
																/>
															</ListItemIcon>
															<ListItemText
																style={{
																	color:
																		question.correctAnswer ===
																		option.text
																			? "green"
																			: "black",
																}}
																primary={
																	option.text
																}
															/>
														</ListItem>
													)
												)}
											</List>
										</ExpansionPanelDetails>
									</ExpansionPanel>
								))}
							</div>
						)}
					</div>
					<Typography
						variant="h4"
						className="quiz-questions-head m-top"
					>
						Submissions
					</Typography>
					<div className="quiz-students-list">
						<div className="add-question-bar">
							<Button
								className="add-question-btn stats-btn"
								component={
									responses.length !== 0 ? Link : Button
								}
								to={{
									pathname: "/quizStats",
									state: { responses: responses },
								}}
							>
								<BarChart />
								View Stats
							</Button>
						</div>
						{responses.length === 0 ? (
							<p
								style={{
									textAlign: "center",
									margin: "0",
									paddingTop: "3%",
									paddingBottom: "3%",
								}}
							>
								No responses yet!
							</p>
						) : (
							<>
								<div className="search-bar">
									<TextField
										placeholder="Search by name or score"
										type="text"
										onChange={handleSearchChange}
										className="search-input"
										value={searchText}
									/>
									<div style={{ marginLeft: "3%" }}>
										<InputLabel id="sort-by">
											Sort by
										</InputLabel>
										<Select
											labelId="sort-by"
											id="sort-select"
											value={sortBy}
											onChange={handleSortChange}
										>
											<MenuItem value={-1}>
												<em>None</em>
											</MenuItem>
											<MenuItem value="recent">
												Recent
											</MenuItem>
											<MenuItem value="score">
												Score
											</MenuItem>
											<MenuItem value="name">
												Name
											</MenuItem>
										</Select>
									</div>
								</div>
								<List aria-label="responses list">
									{searchData.map((response) => (
										<ListItem
											button
											key={response._id}
											component={Link}
											to={{
												pathname: `/studentResponse`,
												state: { response: response },
											}}
										>
											<ListItemText
												primary={response.userId.name}
												secondary={`Scored: ${response.marks}`}
											/>
										</ListItem>
									))}
								</List>
							</>
						)}
					</div>
				</div>
				<Dialog
					open={questionModal}
					onClose={onCloseHandle}
					aria-labelledby="add-question-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "#333",
							minWidth: "50%",
						},
					}}
					style={{ width: "100%" }}
				>
					<div className="add-ques-heading">
						<Typography
							variant="h6"
							style={{ textAlign: "center", margin: "2% 5%" }}
						>
							New Question{" "}
						</Typography>
						{!update ? (
							<IconButton onClick={handlePopover}>
								<Info className="add-info-icon" />
							</IconButton>
						) : null}
						<Popover
							id="file-upload-popover"
							open={popoverOpen}
							anchorEl={popoverAnchor}
							onClose={handlePopoverClose}
							anchorOrigin={{
								vertical: "bottom",
								horizontal: "left",
							}}
							disableRestoreFocus
							useLayerForClickAway={false}
							PaperProps={{ style: { maxWidth: "400px" } }}
						>
							<p className="popover-text">
								You can upload a <strong>.csv</strong> file with
								questions. The format should be: the{" "}
								<strong>
									first column should contain the question
									text.
								</strong>{" "}
								The next 4 columns must contain the{" "}
								<strong>four options.</strong> And the sixth
								column should contain{" "}
								<strong>
									the correct answer (it should match one of
									the four options)
								</strong>
								. <br />
								<br />
								<strong>
									NOTE: THE FILE SHOULD EXACTLY MATCH THE
									GIVEN FORMAT.
								</strong>{" "}
								You will be able to see and edit all the
								question though.
							</p>
						</Popover>
					</div>
					{!update ? (
						<>
							<div className="dropzone">
								<Dropzone
									onDrop={(acceptedFiles) =>
										handleFileDrop(acceptedFiles)
									}
								>
									{({ getRootProps, getInputProps }) => (
										<section>
											<div {...getRootProps()}>
												<input {...getInputProps()} />
												<AddCircle className="drop-icon" />
												<p
													style={{
														color:
															"rgb(110, 110, 110)",
													}}
												>
													Drag 'n' drop or click to
													select files
												</p>
											</div>
										</section>
									)}
								</Dropzone>
							</div>
							<p className="manual-head">
								<span>Or manually add the question</span>
							</p>
						</>
					) : null}
					<div className="new-question-form">
						<TextInput
							error={newQuestionError}
							helperText={
								newQuestionError ? "This cannot be empty" : null
							}
							className="new-ques-input"
							variant="outlined"
							label="Question Text"
							value={newQuestion}
							onChange={onQuestionChange}
						/>
						<hr style={{ width: "100%", marginBottom: "3%" }} />
						<Grid container spacing={1}>
							<Grid item xs={12} sm={6}>
								<TextInput
									error={option1Error}
									helperText={
										option1Error
											? "This cannot be empty"
											: null
									}
									className="new-ques-input"
									variant="outlined"
									label="Option 1"
									value={option1}
									onChange={handleOptionChange1}
								/>
							</Grid>
							<Grid item xs={12} sm={6}>
								<TextInput
									error={option2Error}
									helperText={
										option2Error
											? "This cannot be empty"
											: null
									}
									className="new-ques-input"
									variant="outlined"
									label="Option 2"
									value={option2}
									onChange={handleOptionChange2}
								/>
							</Grid>
						</Grid>
						<Grid container spacing={1}>
							<Grid item xs={12} sm={6}>
								<TextInput
									error={option3Error}
									helperText={
										option3Error
											? "This cannot be empty"
											: null
									}
									className="new-ques-input"
									variant="outlined"
									label="Option 3"
									value={option3}
									onChange={handleOptionChange3}
								/>
							</Grid>
							<Grid item xs={12} sm={6}>
								<TextInput
									error={option4Error}
									helperText={
										option4Error
											? "This cannot be empty"
											: null
									}
									className="new-ques-input"
									variant="outlined"
									label="Option 4"
									value={option4}
									onChange={handleOptionChange4}
								/>
							</Grid>
						</Grid>
						<hr style={{ width: "100%", marginBottom: "3%" }} />
						<InputLabel id="correct-option">
							Correct Option
						</InputLabel>
						<Select
							error={correctOptionError}
							className="correct-answer-select"
							style={{ width: "50%" }}
							labelId="correct-option"
							value={correctOption}
							onChange={handleCorrectOption}
						>
							<MenuItem value={-1}>None</MenuItem>
							{option1.trim().length !== 0 ? (
								<MenuItem value={option1}>{option1}</MenuItem>
							) : null}
							{option2.trim().length !== 0 ? (
								<MenuItem value={option2}>{option2}</MenuItem>
							) : null}
							{option3.trim().length !== 0 ? (
								<MenuItem value={option3}>{option3}</MenuItem>
							) : null}
							{option4.trim().length !== 0 ? (
								<MenuItem value={option4}>{option4}</MenuItem>
							) : null}
						</Select>
						{!update ? (
							<Button
								className="add-question-submit"
								onClick={handleQuestionSubmit}
							>
								Add Question
							</Button>
						) : (
							<Button
								className="add-question-submit"
								onClick={handleQuestionUpdate}
							>
								Update Question
							</Button>
						)}
					</div>
				</Dialog>
				<Dialog
					open={deleteModal}
					onClose={() => setDeleteModal(false)}
					aria-labelledby="delete-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "black",
							minWidth: "10%",
						},
					}}
				>
					<DialogTitle>
						Are you sure you want to delete this quiz?
					</DialogTitle>
					<div className="btn-div">
						<Button
							className="logout-btn m-right bg-red-btn"
							onClick={handleDelete}
						>
							Yes
						</Button>
						<Button
							className="cancel-btn m-left"
							onClick={() => setDeleteModal(false)}
						>
							No
						</Button>
					</div>
				</Dialog>
				<Dialog
					open={deleteQuestionModal}
					onClose={handleQuestionModalClose}
					aria-labelledby="delete-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "black",
							minWidth: "10%",
						},
					}}
				>
					<DialogTitle>
						Are you sure you want to delete this question?
					</DialogTitle>
					<div className="btn-div">
						<Button
							className="logout-btn m-right bg-red-btn"
							onClick={handleDeleteQuestion}
						>
							Yes
						</Button>
						<Button
							className="cancel-btn m-left"
							onClick={handleQuestionModalClose}
						>
							No
						</Button>
					</div>
				</Dialog>
				<Dialog
					open={quizRestartModal}
					onClose={() => setQuizRestartModal(false)}
					aria-labelledby="restart-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "black",
							minWidth: "10%",
						},
					}}
				>
					<DialogTitle>
						Are you sure you want to restart this quiz?
					</DialogTitle>
					<div className="btn-div">
						<Button
							className="logout-btn m-right bg-green-btn"
							onClick={handleRestart}
						>
							Yes
						</Button>
						<Button
							className="cancel-btn m-left bg-red-btn"
							onClick={() => setQuizRestartModal(false)}
						>
							No
						</Button>
					</div>
				</Dialog>
				<Dialog
					open={closeQuizModal}
					onClose={() => setCloseQuizModal(false)}
					aria-labelledby="restart-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "black",
							minWidth: "10%",
						},
					}}
				>
					<DialogTitle>
						Are you sure you want to close this quiz?
					</DialogTitle>
					<div className="btn-div">
						<Button
							className="logout-btn m-right bg-green-btn"
							onClick={handleQuizClose}
						>
							Yes
						</Button>
						<Button
							className="cancel-btn m-left bg-red-btn"
							onClick={() => setCloseQuizModal(false)}
						>
							No
						</Button>
					</div>
				</Dialog>
				<Snackbar
					open={fileError}
					autoHideDuration={3000}
					onClose={() => setFileError(false)}
					anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setFileError(false)}
					>
						There was some problem with the file. Try again...
					</Alert>
				</Snackbar>
				<Snackbar
					open={serverError}
					autoHideDuration={3000}
					onClose={() => setServerError(false)}
					anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setServerError(false)}
					>
						There was some problem with the server. Try again...
					</Alert>
				</Snackbar>
			</Container>
		);
	}
}
Example #17
Source File: Storage.js    From acsys with MIT License 4 votes vote down vote up
Storage = (props) => {
  const [locked, setLocked] = useState(true);
  const [isDialog, setIsDialog] = useState(false);
  const [mode, setMode] = useState('');
  const [imgUrl, setImgUrl] = useState(undefined);
  const [con, setCon] = useState(true);
  const [fileName, setFileName] = useState('');
  const [currentDir, setCurrentDir] = useState('');
  const [newFolderName, setNewFolderName] = useState('');
  const [files, setFiles] = useState([]);
  const [uploadFile, setUploadFile] = useState('');
  const [page, setPage] = useState(0);
  const [rowsPerPage] = useState(15);
  const [openMessage, setOpenMessage] = useState(false);
  const [loading, setLoading] = useState(false);
  const [syncing, setSyncing] = useState(false);
  const [newFolder, setNewFolder] = useState(false);
  const [isOpenImage, setIsOpenImage] = useState(false);
  const [messageTitle, setMessageTitle] = useState('');
  const [message, setMessage] = useState('');
  const [setError] = useState('');
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [previousDir, setPreviousDir] = useState('');

  const set = (name, ref) => {
    try {
      props.setFile(name, ref);
    } catch (error) {}
  };

  const closeMessage = () => {
    setOpenMessage(false);
  };

  const openDir = async (dir) => {
    setLoading(true);
    const parentDir = files[0].parent;
    const filesTemp = await Acsys.getData('acsys_storage_items', [
      ['parent', '=', dir],
    ]);
    for (var i = 0; i < filesTemp.length; i++) {
      await Acsys.getStorageURL(filesTemp[i].acsys_id)
        .then((result) => {
          filesTemp[i]['url'] = result;
        })
        .catch((error) => console.log(error));
    }
    filesTemp.sort((a, b) => (a.file_order > b.file_order ? 1 : -1));
    setLoading(false);
    setPreviousDir(parentDir);
    setCurrentDir('/' + dir);
    setFiles(filesTemp);
  };

  const openDirPage = async (dir) => {
    props.history.push('/Storage?' + dir);
    setLocked(false);
  };

  const previousDirFunc = async () => {
    setLoading(true);
    let parentFile = '/';
    let currentDir;
    let files;
    if (previousDir !== '/') {
      const parent = await Acsys.getData(
        'acsys_storage_items',
        [['acsys_id', '=', previousDir]],
        1
      );
      parentFile = parent[0].parent;
      currentDir = '/' + previousDir;
      files = await Acsys.getData('acsys_storage_items', [
        ['parent', '=', previousDir],
      ]);
    } else {
      currentDir = previousDir;
      files = await Acsys.getData('acsys_storage_items', [
        ['parent', '=', '/'],
      ]);
    }
    for (var i = 0; i < files.length; i++) {
      await Acsys.getStorageURL(files[i].acsys_id)
        .then((result) => {
          files[i]['url'] = result;
        })
        .catch((error) => console.log(error));
    }
    files.sort((a, b) => (a.file_order > b.file_order ? 1 : -1));

    setLoading(false);
    setPreviousDir(parentFile);
    setCurrentDir(currentDir);
    setFiles(files);
  };

  const setRef = (ref) => {
    setUploadFile(ref);
  };

  const uploadFileFunc = async () => {
    try {
      setLoading(true);
      await Acsys.uploadFile(uploadFile.files[0], currentDir).then(async () => {
        await loadFiles();
      });
      setLoading(false);
    } catch (error) {}
  };

  const syncFiles = async () => {
    handleSyncClose();
    setLoading(true);
    await Acsys.syncFiles();
    let files = await Acsys.getData('acsys_storage_items', [
      ['parent', '=', '/'],
    ]);
    for (var i = 0; i < files.length; i++) {
      await Acsys.getStorageURL(files[i].acsys_id)
        .then((result) => {
          files[i]['url'] = result;
        })
        .catch((error) => console.log(error));
    }
    files.sort((a, b) => (a.file_order > b.file_order ? 1 : -1));
    setLoading(false);
    setFiles(files);
  };

  const handleSyncOpen = () => {
    setSyncing(true);
  };

  const handleSyncClose = () => {
    setSyncing(false);
  };

  const openImg = (url) => {
    setIsOpenImage(true);
    setImgUrl(url);
  };

  const handleImgClose = () => {
    setIsOpenImage(false);
  };

  const handleChange = (event) => {
    setNewFolderName(event);
  };

  const newFolderOpen = () => {
    setNewFolder(true);
  };

  const newFolderClose = () => {
    setNewFolder(false);
  };

  const createNewFolder = async () => {
    if (newFolderName.indexOf(' ') >= 0) {
      setNewFolder(false);
      setOpenMessage(true);
      setMessageTitle('Error');
      setMessage('Folder name cannot contain spaces.');
    } else {
      setLoading(true);
      setNewFolder(false);
      await Acsys.createNewFolder(newFolderName, currentDir);
      await loadFiles();
      setLoading(false);
    }
  };

  const makeFilePublic = async (fileName) => {
    setLoading(true);
    await Acsys.makeFilePublic(fileName)
      .then(async () => {
        await loadFiles();
      })
      .catch((error) => setError(error));
    setLoading(false);
  };

  const makeFilePrivate = async (fileName) => {
    setLoading(true);
    await Acsys.makeFilePrivate(fileName)
      .then(async () => {
        await loadFiles();
      })
      .catch((error) => setError(error));
    setLoading(false);
  };

  const deleteFile = async () => {
    setDeleteLoading(true);
    await Acsys.deleteFile(fileName)
      .then(async () => {
        await loadFiles();
      })
      .catch((error) => setError(error));
    handleDeleteClose();
  };

  const handleDeleteOpen = async (fileName) => {
    setDeleting(true);
    setFileName(fileName);
  };

  const handleDeleteClose = () => {
    setDeleting(false);
    setDeleteLoading(false);
  };

  const loadFiles = async () => {
    setTimeout(() => {}, 1000);
    let dir = currentDir;
    if (dir !== '/') {
      dir = dir.substring(1, dir.length);
    }
    const files = await Acsys.getData('acsys_storage_items', [
      ['parent', '=', dir],
    ]);
    for (var i = 0; i < files.length; i++) {
      await Acsys.getStorageURL(files[i].acsys_id)
        .then((result) => {
          files[i]['url'] = result;
        })
        .catch((error) => console.log(error));
    }
    files.sort((a, b) => (a.file_order > b.file_order ? 1 : -1));
    setFiles(files);
  };

  const handleChangePage = (event, page) => {
    setPage(page);
  };

  useEffect(async () => {
    try {
      if (
        props.location.search.substring(1) !== currentDir.substring(1) &&
        !locked
      ) {
        let newDir = props.location.search.substring(1);
        if (newDir.length < 1) {
          newDir = '/';
        }
        setLocked(true);
        setLoading(true);
        setIsOpenImage(false);
        const files = await Acsys.getData('acsys_storage_items', [
          ['parent', '=', newDir],
        ]).catch();
        for (var i = 0; i < files.length; i++) {
          await Acsys.getStorageURL(files[i].acsys_id)
            .then((result) => {
              files[i]['url'] = result;
            })
            .catch((error) => console.log(error));
        }
        files.sort((a, b) => (a.file_order > b.file_order ? 1 : -1));
        let currentDir = '/';
        if (newDir !== '/') {
          currentDir += newDir;
        }
        setLocked(false);
        setLoading(false);
        setCurrentDir(currentDir);
        setFiles(files);
      }
    } catch (error) {}
  }, [locked, currentDir, props.location]);

  useEffect(async () => {
    setLoading(true);
    let parent = '/';
    let mode = 'standard';

    try {
      if (props.mode.length > 0) {
        mode = props.mode;
      }
    } catch (error) {
      props.setHeader('Storage');
    }
    let con;
    let files;
    try {
      con = await Acsys.isStorageConnected();
      if (!con) {
        setLoading(false);
        setCon(con);
      }
      files = await Acsys.getData('acsys_storage_items', [
        ['parent', '=', parent],
      ]);
      for (var i = 0; i < files.length; i++) {
        await Acsys.getStorageURL(files[i].acsys_id)
          .then((result) => {
            files[i]['url'] = result;
          })
          .catch((error) => console.log(error));
      }
      files.sort((a, b) => (a.file_order > b.file_order ? 1 : -1));
    } catch (error) {}
    setLoading(false);
    setIsDialog(isDialog);
    setMode(mode);
    setCon(con);
    setFiles(files);
  }, []);

  const getPrevButton = () => {
    return mode !== 'standard' ? (
      <Grid item>
        <Tooltip title="Back">
          <IconButton onClick={() => previousDirFunc()}>
            <KeyboardArrowLeft color="inherit" />
          </IconButton>
        </Tooltip>
      </Grid>
    ) : (
      <div></div>
    );
  };
  const renderIcon = (content_type, url) => {
    if (content_type === 'Folder') {
      return (
        <TableCell style={{ width: 40, paddingRight: 0 }}>
          <FolderOpen />
        </TableCell>
      );
    } else if (content_type.includes('image')) {
      return (
        <TableCell style={{ width: 40, paddingRight: 0 }}>
          <img
            src={url}
            style={{ cursor: 'pointer', height: 40, width: 40, margin: 0 }}
            onClick={() => openImg(url)}
          />
        </TableCell>
      );
    } else {
      return (
        <TableCell style={{ width: 40, paddingRight: 0 }}>
          <Description
            style={{ cursor: 'pointer', height: 40, width: 40, margin: 0 }}
            onClick={() => window.open(url, '_blank')}
          />
        </TableCell>
      );
    }
  };
  const renderName = (id, content_type, name) => {
    if (content_type === 'Folder') {
      if (mode === 'standard') {
        return (
          <TableCell>
            <a onClick={() => openDirPage(id)} style={{ cursor: 'pointer' }}>
              {name}
            </a>
          </TableCell>
        );
      } else {
        return (
          <TableCell>
            <a onClick={() => openDir(id)} style={{ cursor: 'pointer' }}>
              {name}
            </a>
          </TableCell>
        );
      }
    } else {
      if (mode === 'standard') {
        return (
          <TableCell>
            <a>{name}</a>
          </TableCell>
        );
      } else {
        return (
          <TableCell>
            <a onClick={() => set(name, id)} style={{ cursor: 'pointer' }}>
              {name}
            </a>
          </TableCell>
        );
      }
    }
  };
  const renderTableData = () => {
    return files
      .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
      .map((file, index) => {
        const { acsys_id, name, content_type, updated, is_public, url } = file;
        if (name.length > 0) {
          return (
            <TableRow key={index}>
              {renderIcon(content_type, url, name)}
              {renderName(acsys_id, content_type, name)}
              <TableCell>{content_type}</TableCell>
              <TableCell>{updated}</TableCell>
              {Acsys.getMode() !== 'Viewer' ? (
                <TableCell style={{ minWidth: 100 }} align="right">
                  {is_public ? (
                    <Tooltip title="Public To Internet">
                      <IconButton
                        edge="start"
                        color="inherit"
                        aria-label="make private"
                        onClick={() => makeFilePrivate(acsys_id)}
                        style={{ marginRight: 10 }}
                      >
                        <LockOpen />
                      </IconButton>
                    </Tooltip>
                  ) : (
                    <Tooltip title="Not Public">
                      <IconButton
                        edge="start"
                        color="inherit"
                        aria-label="make public"
                        onClick={() => makeFilePublic(acsys_id)}
                        style={{ marginRight: 10 }}
                      >
                        <Lock />
                      </IconButton>
                    </Tooltip>
                  )}
                  <Tooltip title="Delete File">
                    <IconButton
                      edge="start"
                      color="inherit"
                      aria-label="delete"
                      onClick={() => handleDeleteOpen(acsys_id)}
                    >
                      <Delete />
                    </IconButton>
                  </Tooltip>
                </TableCell>
              ) : (
                <div />
              )}
            </TableRow>
          );
        } else {
          return <div />;
        }
      });
  };

  if (con) {
    try {
      return (
        <div>
          <Paper style={{ margin: 'auto', overflow: 'hidden', clear: 'both' }}>
            <AppBar
              position="static"
              elevation={0}
              style={{
                backgroundColor: '#fafafa',
                borderBottom: '1px solid #dcdcdc',
              }}
            >
              <Toolbar style={{ margin: 4, paddingLeft: 12, paddingRight: 12 }}>
                {Acsys.getMode() !== 'Viewer' ? (
                  <Grid container spacing={1}>
                    <Grid item xs style={{ overflow: 'hidden' }}>
                      <Typography
                        align="left"
                        variant="subtitle2"
                        noWrap
                        style={{ marginTop: 10, color: '#000000' }}
                      >
                        {currentDir}
                      </Typography>
                    </Grid>
                    {getPrevButton()}
                    <Grid item style={{ minWidth: 20 }}>
                      <Tooltip title="Scan For File Updates">
                        <Button
                          variant="contained"
                          color="primary"
                          onClick={handleSyncOpen}
                        >
                          Scan
                        </Button>
                      </Tooltip>
                    </Grid>
                    <Grid item style={{ minWidth: 20 }}>
                      <input
                        id="contained-button-file"
                        type="file"
                        style={{ display: 'none' }}
                        ref={setRef}
                        onChange={uploadFileFunc}
                      />
                      <label htmlFor="contained-button-file">
                        <Tooltip title="Upload File">
                          <Button
                            variant="contained"
                            color="primary"
                            component="span"
                          >
                            Upload
                          </Button>
                        </Tooltip>
                      </label>
                    </Grid>
                    <Grid item style={{ minWidth: 20 }}>
                      <Tooltip title="New Folder">
                        <Button
                          variant="contained"
                          color="primary"
                          onClick={newFolderOpen}
                        >
                          New Folder
                        </Button>
                      </Tooltip>
                    </Grid>
                  </Grid>
                ) : (
                  <Grid container spacing={1}>
                    <Grid item xs style={{ overflow: 'hidden' }}>
                      <Typography
                        align="left"
                        variant="subtitle2"
                        noWrap
                        style={{ marginTop: 10, color: '#000000' }}
                      >
                        {currentDir}
                      </Typography>
                    </Grid>
                    {getPrevButton()}
                  </Grid>
                )}
              </Toolbar>
            </AppBar>
            <div style={{ margin: 'auto', overflow: 'auto' }}>
              <Table>
                <TableHead style={{ backgroundColor: '#fafafa' }}>
                  <TableRow>
                    <TableCell
                      colSpan={2}
                      style={{
                        paddingLeft: 16,
                        paddingRight: 16,
                        paddingTop: 5,
                        paddingBottom: 5,
                      }}
                    >
                      NAME
                    </TableCell>
                    <TableCell
                      style={{
                        paddingLeft: 16,
                        paddingRight: 16,
                        paddingTop: 5,
                        paddingBottom: 5,
                        width: 100,
                      }}
                    >
                      TYPE
                    </TableCell>
                    <TableCell
                      style={{
                        paddingLeft: 16,
                        paddingRight: 16,
                        paddingTop: 5,
                        paddingBottom: 5,
                        width: 110,
                      }}
                    >
                      LAST MODIFIED
                    </TableCell>
                    {Acsys.getMode() !== 'Viewer' ? (
                      <TableCell
                        style={{
                          paddingLeft: 16,
                          paddingRight: 16,
                          paddingTop: 5,
                          paddingBottom: 5,
                          width: 100,
                        }}
                        align="right"
                      >
                        ACTIONS
                      </TableCell>
                    ) : (
                      <div />
                    )}
                  </TableRow>
                </TableHead>
                <TableBody>{renderTableData()}</TableBody>
              </Table>
            </div>
            <TablePagination
              rowsPerPageOptions={[25]}
              component="div"
              count={files.length}
              rowsPerPage={rowsPerPage}
              page={page}
              backIconButtonProps={{
                'aria-label': 'previous page',
              }}
              nextIconButtonProps={{
                'aria-label': 'next page',
              }}
              onChangePage={handleChangePage}
              // onChangeRowsPerPage={handleChangeRowsPerPage}
            />
            <LoadingDialog loading={loading} message={'Loading'} />
            <MessageDialog
              open={openMessage}
              closeDialog={closeMessage}
              title={messageTitle}
              message={message}
            />
            <YesNoDialog
              open={syncing}
              closeDialog={handleSyncClose}
              title={'Sync files?'}
              message={
                'Are you sure you want to resync files? This operation can require multiple writes.'
              }
              action={syncFiles}
            />
            <ImageDialog
              open={isOpenImage}
              closeDialog={handleImgClose}
              imgUrl={imgUrl}
            />
            <NewFolderDialog
              open={newFolder}
              closeDialog={newFolderClose}
              handleChange={handleChange}
              createNewFolder={createNewFolder}
            />
            <YesNoDialog
              open={deleting}
              closeDialog={handleDeleteClose}
              title={'Delete file?'}
              message={'Are you sure you want to delete this file?'}
              action={deleteFile}
              actionProcess={deleteLoading}
            />
          </Paper>
        </div>
      );
    } catch (error) {
      console.log('error', error);
      return (
        <div style={{ maxWidth: 1236, margin: 'auto' }}>
          <Paper style={{ height: 40 }}>
            <div style={{ padding: 10, margin: 'auto' }}>
              Please make sure database has been created.
            </div>
          </Paper>
        </div>
      );
    }
  } else {
    return (
      <div style={{ maxWidth: 1236, margin: 'auto' }}>
        <Paper style={{ height: 40 }}>
          <div style={{ padding: 10, margin: 'auto' }}>
            Please configure storage.
          </div>
        </Paper>
      </div>
    );
  }
}
Example #18
Source File: OwnerQuizDetails.js    From Quizzie with MIT License 4 votes vote down vote up
function OwnerQuizDetails(props) {
	const quizId = props.match.params.id;

	const [loading, setLoading] = useState(true);
	const [redirect, setRedirect] = useState(false);
	const [redirectD, setRedirectD] = useState(false);

	const [quizDetails, setQuizDetails] = useState({});
	const [quizQuestions, setQuizQuestions] = useState([]);
	const [responses, setResponses] = useState([]);

	const [deleteModal, setDeleteModal] = useState(false);
	const [deleteSnack, setDeleteSnack] = useState(false);

	const handleDeleteBtn = () => {
		setDeleteModal(true);
	};

	const validate = async () => {
		let token = localStorage.getItem("authToken");
		let url = "https://quizzie-api.herokuapp.com/general/checkUser";

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					if (res.data.result.userType !== "Owner") {
						setRedirectD(true);
						return;
					}
				});
		} catch (error) {
			console.log(error);
		}
	};

	const handleDelete = async () => {
		setDeleteSnack(true);
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/owner/quiz/${quizId}`;

		try {
			await axios
				.delete(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setRedirect(true);
				});
		} catch (error) {
			console.log(error);
		}
	};

	const getQuizDetails = async () => {
		setLoading(true);
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/${quizId}`;

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setQuizDetails(res.data.result);
				});
		} catch (error) {
			console.log(error);
		}

		url = `https://quizzie-api.herokuapp.com/question/all/${quizId}`;

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setQuizQuestions(res.data.result);
					setLoading(false);
				});
		} catch (error) {
			console.log(error);
		}

		// url = `https://quizzie-api.herokuapp.com/admin/allStudentsQuizResult/${quizId}`;

		// try {
		// 	await axios.get(url, {
		// 		headers: {
		// 			"auth-token": token
		// 		}
		// 	}).then(res => {
		// 		console.log(res);
		// 		setResponses(res.data.userResults);
		// 		setLoading(false);
		// 	})
		// } catch(error) {
		// 	console.log(error);
		// }
	};

	useEffect(() => {
		let token = localStorage.getItem("authToken");
		if (token === null) {
			setLoading(false);
			setRedirect(true);
			return;
		}
		validate();
		getQuizDetails();
	}, []);

	if (loading) {
		return <Loading />;
	} else if (redirect) {
		return <Redirect to="/coronilOP" />;
	} else if (redirectD) {
		return <Redirect to="/dashboard" />;
	} else {
		return (
			<Container className="edit-quiz-page">
				<Typography
					variant="h3"
					className="dash-head p-top edit-quiz-head"
				>
					Quiz Details
				</Typography>
				<div className="edit-btn-bar">
					<Button
						className="edit-details-btn delete-btn"
						onClick={handleDeleteBtn}
					>
						<Delete className="edit-icon" />
						Delete Quiz
					</Button>
				</div>
				<div className="quiz-details-sec">
					<Typography variant="h6" className="quiz-detail-param">
						Name:{" "}
						<span className="quiz-detail-text">
							{quizDetails.quizName}
						</span>
					</Typography>
					<Typography variant="h6" className="quiz-detail-param">
						Date:{" "}
						<span className="quiz-detail-text">
							{new Date(
								Number(quizDetails.scheduledFor)
							).toDateString()}
						</span>
					</Typography>
					<Typography variant="h6" className="quiz-detail-param">
						Time:{" "}
						<span className="quiz-detail-text">
							{new Date(
								Number(quizDetails.scheduledFor)
							).toLocaleTimeString()}
						</span>
					</Typography>
					<Typography variant="h6" className="quiz-detail-param">
						Duration:{" "}
						<span className="quiz-detail-text">
							{quizDetails.quizDuration} minutes
						</span>
					</Typography>
					<Typography variant="h6" className="quiz-detail-param">
						Type:{" "}
						<span className="quiz-detail-text">
							{quizDetails.quizType}
						</span>
					</Typography>
					{quizDetails.quizType === "private" ? (
						<Typography variant="h6" className="quiz-detail-param">
							Quiz Code:{" "}
							<span className="quiz-detail-text">
								{quizDetails.quizCode}
							</span>
						</Typography>
					) : null}
				</div>
				<div className="quiz-questions-sec">
					<Typography variant="h4" className="quiz-questions-head">
						Questions
					</Typography>
					<div className="quiz-questions-display">
						{quizQuestions.length === 0 ? (
							<p style={{ textAlign: "center" }}>
								No questions added yet!
							</p>
						) : (
							<div className="questions-list-display">
								{quizQuestions.map((question) => (
									<ExpansionPanel
										elevation={3}
										className="expansion"
										key={question._id}
									>
										<ExpansionPanelSummary
											className="question-summary"
											expandIcon={<ExpandMore />}
											aria-controls="question-content"
											aria-label="Expand"
										>
											<Typography className="question-label">
												{question.description}
											</Typography>
										</ExpansionPanelSummary>
										<ExpansionPanelDetails>
											<List
												component="nav"
												className="options-display"
											>
												{question.options.map(
													(option) => (
														<ListItem
															button
															key={option._id}
														>
															<ListItemIcon>
																<Adjust
																	style={{
																		color:
																			question.correctAnswer ===
																			option.text
																				? "green"
																				: "black",
																	}}
																/>
															</ListItemIcon>
															<ListItemText
																style={{
																	color:
																		question.correctAnswer ===
																		option.text
																			? "green"
																			: "black",
																}}
																primary={
																	option.text
																}
															/>
														</ListItem>
													)
												)}
											</List>
										</ExpansionPanelDetails>
									</ExpansionPanel>
								))}
							</div>
						)}
					</div>
					{/* <Typography variant="h4" className="quiz-questions-head m-top">Submissions</Typography>
					<div className="quiz-students-list">
						{responses.length === 0? <p style={{ textAlign: 'center' }}>No responses yet!</p>
						: 
						<List aria-label="responses list">
							{responses.map((response) => (
								<ListItem button key={response._id}>
									<ListItemText primary={response.userId.name} secondary={`Scored: ${response.marks}`} />
								</ListItem>
							))}
						</List>
						}
					</div> */}
				</div>
				<Dialog
					open={deleteModal}
					onClose={() => setDeleteModal(false)}
					aria-labelledby="delete-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "black",
							minWidth: "10%",
						},
					}}
				>
					<DialogTitle>
						Are you sure you want to delete this quiz?
					</DialogTitle>
					<div className="btn-div">
						<Button
							className="logout-btn m-right bg-red-btn"
							onClick={handleDelete}
						>
							Yes
						</Button>
						<Button
							className="cancel-btn m-left"
							onClick={() => setDeleteModal(false)}
						>
							No
						</Button>
					</div>
				</Dialog>
				<Snackbar
					open={deleteSnack}
					autoHideDuration={5000}
					onClose={() => setDeleteSnack(false)}
				>
					<Alert
						variant="filled"
						severity="info"
						onClose={() => setDeleteSnack(false)}
					>
						Processing... Please Wait!
					</Alert>
				</Snackbar>
			</Container>
		);
	}
}