react-bootstrap#ProgressBar TypeScript Examples

The following examples show how to use react-bootstrap#ProgressBar. 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: BattleActorDisplay.tsx    From apps with MIT License 6 votes vote down vote up
private displayGauge() {
        if (this.props.actor.team === BattleTeam.ENEMY) return null;

        const max = this.props.actor.gaugeLineMax,
            current = this.props.actor.currentGauge,
            level = Math.min(Math.floor(current / max), 2),
            mod = current % max,
            styles = ["info", "warning", "danger"],
            percent = Math.floor((mod / max) * 1000) / 10,
            remaining = 100 - percent;

        return (
            <div>
                <div className="battle-actor-gauge">{percent}%</div>
                <ProgressBar now={percent}>
                    <ProgressBar variant={styles[level]} now={percent} />
                    {remaining > 0 && level > 0 ? <ProgressBar variant={styles[level - 1]} now={remaining} /> : null}
                </ProgressBar>
            </div>
        );
    }
Example #2
Source File: BattleActorDisplay.tsx    From apps with MIT License 6 votes vote down vote up
render() {
        return (
            <div className="battle-actor-display">
                <img className="battle-actor-face" src={this.props.actor.face} alt={this.props.actor.name} />
                <div className="battle-actor-name">
                    ({this.props.actor.id}) {this.props.actor.name}
                </div>
                <div className="battle-actor-health">
                    {this.props.actor.currentHealth} / {this.props.actor.maxHealth}
                </div>
                <ProgressBar variant="success" now={this.props.actor.currentHealth / this.props.actor.maxHealth} />
                {this.displayGauge()}
                {this.shouldDisplaySkills() ? <BattleActorSkillDisplay actor={this.props.actor} /> : null}
                {this.shouldDisplayAttacks() ? <BattleActorAttackDisplay actor={this.props.actor} /> : null}
            </div>
        );
    }
Example #3
Source File: running.tsx    From bada-frame with GNU General Public License v3.0 6 votes vote down vote up
export default function FixCreationTimeRunning({ progressTracker }) {
    return (
        <>
            <div style={{ marginBottom: '10px' }}>
                <ComfySpan>
                    {' '}
                    {progressTracker.current} / {progressTracker.total}{' '}
                </ComfySpan>{' '}
                <span style={{ marginLeft: '10px' }}>
                    {' '}
                    {constants.CREATION_TIME_UPDATED}
                </span>
            </div>
            <div
                style={{
                    width: '100%',
                    marginTop: '10px',
                    marginBottom: '20px',
                }}>
                <ProgressBar
                    now={Math.round(
                        (progressTracker.current * 100) / progressTracker.total
                    )}
                    animated={true}
                    variant="upload-progress-bar"
                />
            </div>
        </>
    );
}
Example #4
Source File: ExportInProgress.tsx    From bada-frame with GNU General Public License v3.0 5 votes vote down vote up
export default function ExportInProgress(props: Props) {
    return (
        <>
            <div
                style={{
                    marginBottom: '30px',
                    padding: '0 5%',
                    display: 'flex',
                    alignItems: 'center',
                    flexDirection: 'column',
                }}>
                <div style={{ marginBottom: '10px' }}>
                    <ComfySpan>
                        {' '}
                        {props.exportProgress.current} /{' '}
                        {props.exportProgress.total}{' '}
                    </ComfySpan>{' '}
                    <span style={{ marginLeft: '10px' }}>
                        {' '}
                        files exported{' '}
                        {props.exportStage === ExportStage.PAUSED && `(paused)`}
                    </span>
                </div>
                <div style={{ width: '100%', marginBottom: '30px' }}>
                    <ProgressBar
                        now={Math.round(
                            (props.exportProgress.current * 100) /
                                props.exportProgress.total
                        )}
                        animated={!(props.exportStage === ExportStage.PAUSED)}
                        variant="upload-progress-bar"
                    />
                </div>
                <div
                    style={{
                        width: '100%',
                        display: 'flex',
                        justifyContent: 'space-around',
                    }}>
                    {props.exportStage === ExportStage.PAUSED ? (
                        <Button
                            block
                            variant={'outline-secondary'}
                            onClick={props.resumeExport}>
                            {constants.RESUME}
                        </Button>
                    ) : (
                        <Button
                            block
                            variant={'outline-secondary'}
                            onClick={props.pauseExport}>
                            {constants.PAUSE}
                        </Button>
                    )}
                    <div style={{ width: '30px' }} />
                    <Button
                        block
                        variant={'outline-danger'}
                        onClick={props.cancelExport}>
                        {constants.CANCEL}
                    </Button>
                </div>
            </div>
        </>
    );
}
Example #5
Source File: UploaderView.tsx    From 3Speak-app with GNU General Public License v3.0 4 votes vote down vote up
export function UploaderView() {
  const videoUpload = useRef<any>()
  const thumbnailUpload = useRef<any>()
  const thumbnailPreview = useRef('')
  const publishForm = useRef()
  const hwaccelOption = useRef()
  const ipfs = useRef<any>()

  const [logData, setLogData] = useState([])
  const [videoSourceFile, setVideoSourceFile] = useState()
  const [encodingInProgress, setEncodingInProgress] = useState(false)
  const [progress, setProgress] = useState<any>({})
  const [statusInfo, setStatusInfo] = useState<any>({ progress: {} })
  const [estimatedTimeRemaining, setEstimatedTimeRemaining] = useState('')
  const [videoInfo, setVideoInfo] = useState<any>({
    path: null,
    size: 0,
    cid: null,
    language: '',
    duration: null,
  })
  const [thumbnailInfo, setThumbnailInfo] = useState({
    path: null,
    size: 0,
    cid: null,
  })
  const [startTime, setStartTime] = useState<number>()
  const [endTime, setEndTime] = useState<number>(0)
  const [publishReady, setPublishReady] = useState(false)
  const [blockedGlobalMessage, setBlockedGlobalMessage] = useState('')

  useEffect(() => {
    ipfs.current = IPFSHTTPClient.create({ host: IPFS_HOST })
  }, [])

  const caluclatePercentage = () => {
    return progress.percent / statusInfo.nstages + statusInfo.stage * (100 / statusInfo.nstages)
  }

  const normalizeSize = () => {
    const size = videoInfo.size + thumbnailInfo.size
    return bytesAsString(size)
  }

  const compileVideoCid = async () => {
    const videoCid = videoInfo.cid
    if (thumbnailInfo.cid) {
      const obj = await ipfs.current.object.stat(thumbnailInfo.cid)
      console.log(obj)
      console.log(thumbnailInfo)
      const output = await ipfs.current.object.patch.addLink(videoCid, {
        name: thumbnailInfo.path,
        size: thumbnailInfo.size,
        cid: thumbnailInfo.cid,
      })
      console.log(output)
      return output.toString()
    }
    return videoCid
  }

  /**
   * Note: example metadata https://hiveblocks.com/hive-181335/@taskmaster4450/tqxwimhy
   */
  const publish = async () => {
    const videoCid = await compileVideoCid()
    const formData = FormUtils.formToObj(new FormData(publishForm.current))
    let tags: string[] = []
    if (formData.tags) {
      tags = formData.tags.replace(/\s/g, '').split(',')
    }

    console.log(`thumbnail info`, thumbnailInfo)

    const sourceMap = []
    if (thumbnailInfo.path) {
      sourceMap.push({
        type: 'thumbnail',
        url: `ipfs://${videoCid}/${thumbnailInfo.path}`,
      })
    }

    if (videoInfo) {
      sourceMap.push({
        type: 'video',
        url: `ipfs://${videoCid}/${videoInfo.path}`,
        format: 'm3u8',
      })
    }
    const permlink = `speak-${randomstring
      .generate({
        length: 8,
        charset: 'alphabetic',
      })
      .toLowerCase()}`
    //     console.log(permlink)
    console.log(`source map`)
    console.log(sourceMap)
    //     console.log(videoInfo)
    //     console.log(typeof formData.description)
    //     console.log(videoCid)
    setBlockedGlobalMessage('Publishing')

    const filesize = videoInfo.size + thumbnailInfo.size

    console.log(`formdata is `, formData)

    formData.title = formData.title || 'no form data'
    formData.description = formData.description || 'no form data'

    console.log(`publish form is `, publishForm.current)

    try {
      const [reflink] = await AccountService.postComment({
        accountType: 'hive',
        title: formData.title,
        body: formData.description,
        permlink,
        tags,
        json_metadata: {
          title: formData.title,
          description: formData.description,
          tags,
          sourceMap,
          filesize,
          created: new Date(),
          lang: videoInfo.language,
          video: {
            duration: videoInfo.duration,
          },
          app: '3speak/app-beta',
          type: '3speak/video',
        },
      })

      setTimeout(() => {
        location.hash = `#/watch/${reflink}`
        setBlockedGlobalMessage('done')
      }, 15000)
    } catch (error) {
      console.error(`Error in postComment operation ${error.message}`)
      throw error
    }
  }

  const handleVideoSelect = async (e) => {
    const file = e.target.files[0]
    setVideoSourceFile(file.path)
    setLogData([...logData, `Selected: ${videoInfo.path}`])
  }

  const handleThumbnailSelect = async (e) => {
    console.log(`handling thumbnail selectr`)

    const file = e.target.files[0]
    const imgblob = URL.createObjectURL(file)
    const size = file.size

    console.log(`uploading file with size ${size}`)

    thumbnailPreview.current = imgblob

    const fileDetails = {
      path: e.target.files[0].name,
      content: e.target.files[0],
    }

    const ipfsOut = await ipfs.current.add(fileDetails, { pin: false })
    console.log(`setting thumbnail info to cid`, ipfsOut.cid.toString())

    setThumbnailInfo({
      size,
      path: `thumbnail.${file.type.split('/')[1]}`,
      cid: ipfsOut.cid.toString(),
    })
  }

  const handleStartEncode = async (event) => {
    event.preventDefault()
    if (videoSourceFile === null) {
      NotificationManager.error('No video source file selected')
      return
    }
    if (!Fs.existsSync(videoSourceFile)) {
      NotificationManager.error('Source file does not exist')
      return
    }
    setEncodingInProgress(true)
    setStartTime(new Date().getTime())
    setEndTime(null)

    const jobInfo = (await PromiseIpc.send('encoder.createJob', {
      sourceUrl: videoSourceFile,
      profiles: [
        {
          name: '1080p',
          size: '1920x1080',
        },
        {
          name: '720p',
          size: '1080x720',
        },
        {
          name: '480p',
          size: '720x480',
        },
      ],
      options: {
        hwaccel:
          hwaccelOption.current !== '' && hwaccelOption.current !== 'none'
            ? hwaccelOption.current
            : undefined,
      },
    } as any)) as any
    NotificationManager.success('Encoding Started.')

    let savePct = 0
    const progressTrack = async () => {
      const status = (await PromiseIpc.send('encoder.status', jobInfo.id)) as any

      console.log(`Encoder status: `, status)

      setProgress(status.progress || {})
      setStatusInfo(status)

      const val = caluclatePercentage()
      const diffPct = val - savePct
      savePct = val
      const pctPerSec = diffPct / 3
      const totalTimeRemaining = (100 - val) / pctPerSec

      setEstimatedTimeRemaining(secondsAsString(totalTimeRemaining))
      setEndTime(new Date().getTime())
    }

    const pid = setInterval(progressTrack, 3000)
    void progressTrack()

    const encodeOutput = (await PromiseIpc.send('encoder.getjoboutput', jobInfo.id)) as any
    console.log(`got encode output`)
    console.log(encodeOutput)

    setVideoInfo({
      size: encodeOutput.size,
      cid: encodeOutput.ipfsHash,
      path: encodeOutput.path,
      duration: Number(DateTime.parse(encodeOutput.duration, 'hh:mm:ss.SS', true)) / 1000,
    })

    clearInterval(pid)

    setEncodingInProgress(false)
    setEstimatedTimeRemaining(null)
    setEndTime(new Date().getTime())
    setPublishReady(true)

    NotificationManager.success('Encoding complete.')
  }

  if (blockedGlobalMessage) {
    return (
      <LoadingMessage
        loadingMessage={blockedGlobalMessage}
        subtitle="Note: you will need to keep the app open for your video to play for other users. A process called 'shunting' will be released in the future to relieve this issue."
      />
    )
  }

  return (
    <div style={{ width: '95%', marginRight: 'auto', marginLeft: 'auto' }}>
      <Row style={{ marginTop: '1.45rem' }}>
        <div>
          <div
            className="d-table-cell align-middle card dz-clickable"
            onClick={() => videoUpload.current.click()}
            style={{
              width: '4000px',
              textAlign: 'center',
              height: '150px',
              fontSize: '16px',
              fontWeight: 'bold',
              cursor: 'pointer',
            }}
          >
            Drop a file or click to start the upload <br />
            <p>
              Selected: <kbd>{videoSourceFile}</kbd>
            </p>
            <input
              accept="video/*"
              type="file"
              id="video"
              className="d-none"
              ref={videoUpload}
              onChange={handleVideoSelect}
            />
          </div>
        </div>
      </Row>
      <Row style={{ marginTop: '15px' }}>
        <Col xl={6} sm={12} style={{ paddingLeft: '0px' }}>
          <div className="card" style={{ padding: '10px' }}>
            <Form ref={publishForm.current}>
              <Form.Group>
                <Form.Label>Title</Form.Label>
                <Form.Control type="text" name="title"></Form.Control>
              </Form.Group>
              <Form.Group>
                <Form.Label>Description</Form.Label>
                <textarea className="form-control" name="description"></textarea>
              </Form.Group>
              <Form.Group>
                <Form.Label>Tags</Form.Label>
                <Form.Control type="text" name="tags"></Form.Control>
                <small className="text-muted">
                  Separate multiple tags with a <kbd>,</kbd>{' '}
                </small>
              </Form.Group>
              <Form.Group>
                <Form.Label>Language</Form.Label>
                <select disabled={false} name="language" className="form-control mb-4">
                  <option selected={false} value="en">
                    English
                  </option>
                  <option value="de">Deutsch</option>
                  <option value="fr">Français</option>
                  <option value="es">Español</option>
                  <option value="nl">Nederlands</option>
                  <option value="ko">한국어</option>
                  <option value="ru">русский</option>
                  <option value="hu">Magyar</option>
                  <option value="ro">Română</option>
                  <option value="cs">čeština</option>
                  <option value="pl">Polskie</option>
                  <option value="in">bahasa Indonesia</option>
                  <option value="bn">Bangla</option>
                  <option value="it">Italian</option>
                </select>
              </Form.Group>
              <span className="form-check mb-3">
                <input
                  type="checkbox"
                  className="form-check-input"
                  id="nsfwContent"
                  name="nsfwContent"
                />
                <label className="form-check-label" htmlFor="nsfwContent">
                  Content is graphic and/or NSFW
                  <span className="text-danger">
                    &nbsp;Warning: you should check this option if your content is&nbsp;
                    <a href="https://en.wikipedia.org/wiki/Not_safe_for_work">NSFW</a>.
                  </span>
                </label>
              </span>
              <Form.Group>
                <Form.Label>Thumbnail</Form.Label>
                <div></div>
                <img
                  src={thumbnailPreview.current || DefaultThumbnail}
                  style={{
                    width: '720px',
                    aspectRatio: '16/9',
                    cursor: 'pointer',
                  }}
                  alt=""
                  onClick={() => thumbnailUpload.current.click()}
                />
                <input
                  accept="image/*"
                  type="file"
                  id="thumbnail_input"
                  className="d-none"
                  ref={thumbnailUpload}
                  onChange={handleThumbnailSelect}
                />
                <p>Click the thumbnail to change it</p>
                <p>Recommended 5MB. Ideally 1280px×720px.</p>
              </Form.Group>
              <Button onClick={handleStartEncode}>Start Encode</Button>
              <Button
                style={{ marginLeft: '5px' }}
                onClick={publish}
                disabled={encodingInProgress || !publishReady}
              >
                Publish
              </Button>
            </Form>
          </div>
        </Col>
        <Col style={{ paddingRight: '0px', paddingLeft: '0px' }}>
          <Card>
            <Card.Header>Encoder status</Card.Header>
            <Card.Body>
              <Card.Text>This area will show live encoding statistics</Card.Text>
              <Button style={{ marginBottom: '5px' }} variant="primary">
                FPS: {progress.currentFps}
              </Button>{' '}
              <br />
              <Button variant="primary">Video Size: {normalizeSize()}</Button>
              <ProgressBar
                style={{
                  display: encodingInProgress ? '' : 'none',
                }}
                striped
                variant="success"
                now={caluclatePercentage()}
                label={progress.percent ? `${Math.round(caluclatePercentage())}%` : null}
              />
              <div
                style={{
                  display: encodingInProgress ? '' : 'none',
                }}
              >
                Time Remaining:{' '}
                {estimatedTimeRemaining !== 'NaNns' ? estimatedTimeRemaining : 'Calculating'}
              </div>
              <div style={{ display: endTime ? '' : 'none' }}>
                Total Time (so far):{' '}
                {endTime !== 0 ? millisecondsAsString(endTime - startTime) : 'Calculating'}
              </div>
            </Card.Body>
          </Card>
          <div className="card" style={{ marginTop: '15px' }}>
            <div className="card-header">
              <h5>Control Panel</h5>
            </div>
            <Tabs style={{ background: 'white' }} defaultActiveKey="encode">
              <Tab
                style={{ background: 'white', padding: '10px' }}
                eventKey="encode"
                title="Encode Settings"
              >
                <Form.Group>
                  <Form.Label>
                    <strong>Format</strong>
                  </Form.Label>
                  <select
                    style={{ width: '6em' }}
                    disabled={encodingInProgress}
                    id="language"
                    className="form-control mb-4"
                  >
                    <option selected={false} value="hls">
                      HLS
                    </option>
                  </select>
                </Form.Group>
                <Form.Group>
                  <Form.Label>
                    <strong>Hardware Accel</strong>
                  </Form.Label>
                  <Form.Text>
                    Use hardware acceleration to speed up video encode. Not available on all
                    systems, results may vary.
                  </Form.Text>
                  <select
                    style={{ width: '6em' }}
                    ref={hwaccelOption}
                    disabled={encodingInProgress}
                    id="language"
                    className="form-control mb-4"
                  >
                    <option selected={false} value="none">
                      none
                    </option>
                    <option value="qsv">QSV</option>
                    <option value="nvenc">nvenc</option>
                  </select>
                </Form.Group>
              </Tab>
              <Tab eventKey="info" title="Info" style={{ padding: '10px' }}>
                <Form.Group>
                  <Form.Label>Video IpfsPath</Form.Label>
                  <Form.Control
                    type="text"
                    name="vidoeHash"
                    disabled
                    value={videoInfo.cid}
                  ></Form.Control>
                </Form.Group>
                <Form.Group>
                  <Form.Label>Thumbnail IpfsPath</Form.Label>
                  <Form.Control
                    type="text"
                    name="thumbnailHash"
                    disabled
                    value={thumbnailInfo.cid}
                  ></Form.Control>
                </Form.Group>
                <Form.Group>
                  <Form.Label>Total Size</Form.Label>
                  <Form.Control
                    style={{ width: '15%' }}
                    type="text"
                    name="videoSize"
                    value={normalizeSize()}
                    disabled
                  ></Form.Control>
                </Form.Group>
              </Tab>
              {/*<Tab eventKey="networks" title="Networks">
                                <Table striped bordered hover size="sm">
                                    <thead>
                                        <tr>
                                            <th>Enabled</th>
                                            <th>ID</th>
                                            <th>Username</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td><Form.Check/></td>
                                            <td>Hive</td>
                                            <td>vaultec</td>
                                        </tr>
                                    </tbody>
                                </Table>
                                
                            </Tab>*/}

              <Tab eventKey="log" title="Log" style={{ padding: '10px' }}>
                <textarea
                  disabled
                  className="form-control"
                  value={(() => logData.join('\n'))()}
                ></textarea>
              </Tab>
            </Tabs>
          </div>
        </Col>
      </Row>
    </div>
  )
}
Example #6
Source File: FixLargeThumbnail.tsx    From bada-frame with GNU General Public License v3.0 4 votes vote down vote up
export default function FixLargeThumbnails(props: Props) {
    const [fixState, setFixState] = useState(FIX_STATE.NOT_STARTED);
    const [progressTracker, setProgressTracker] = useState({
        current: 0,
        total: 0,
    });
    const [largeThumbnailFiles, setLargeThumbnailFiles] = useState<number[]>(
        []
    );

    const init = (): FIX_STATE => {
        let fixState = getData(LS_KEYS.THUMBNAIL_FIX_STATE)?.state;
        if (!fixState || fixState === FIX_STATE.RUNNING) {
            fixState = FIX_STATE.NOT_STARTED;
            updateFixState(fixState);
        }
        if (fixState === FIX_STATE.COMPLETED) {
            fixState = FIX_STATE.NOOP;
            updateFixState(fixState);
        }
        setFixState(fixState);
        return fixState;
    };

    const fetchLargeThumbnail = async () => {
        const largeThumbnailFiles = (await getLargeThumbnailFiles()) ?? [];
        setLargeThumbnailFiles(largeThumbnailFiles);
        return largeThumbnailFiles;
    };

    const main = async () => {
        const largeThumbnailFiles = await fetchLargeThumbnail();
        if (
            fixState === FIX_STATE.NOT_STARTED &&
            largeThumbnailFiles.length > 0
        ) {
            props.show();
        }
        if (
            (fixState === FIX_STATE.COMPLETED || fixState === FIX_STATE.NOOP) &&
            largeThumbnailFiles.length > 0
        ) {
            updateFixState(FIX_STATE.NOT_STARTED);
            logError(Error(), 'large thumbnail files left after migration');
        }
        if (largeThumbnailFiles.length === 0 && fixState !== FIX_STATE.NOOP) {
            updateFixState(FIX_STATE.NOOP);
        }
    };
    useEffect(() => {
        if (props.isOpen && fixState !== FIX_STATE.RUNNING) {
            main();
        }
    }, [props.isOpen]);

    useEffect(() => {
        const fixState = init();
        if (fixState === FIX_STATE.NOT_STARTED) {
            main();
        }
    }, []);
    const startFix = async (newlyFetchedLargeThumbnailFiles?: number[]) => {
        updateFixState(FIX_STATE.RUNNING);
        const completedWithError = await replaceThumbnail(
            setProgressTracker,
            new Set(
                newlyFetchedLargeThumbnailFiles ?? largeThumbnailFiles ?? []
            )
        );
        if (typeof completedWithError !== 'undefined') {
            updateFixState(
                completedWithError
                    ? FIX_STATE.COMPLETED_WITH_ERRORS
                    : FIX_STATE.COMPLETED
            );
        }
        await fetchLargeThumbnail();
    };

    const updateFixState = (fixState: FIX_STATE) => {
        setFixState(fixState);
        setData(LS_KEYS.THUMBNAIL_FIX_STATE, { state: fixState });
    };
    return (
        <MessageDialog
            show={props.isOpen}
            onHide={props.hide}
            attributes={{
                title: constants.FIX_LARGE_THUMBNAILS,
                staticBackdrop: true,
            }}>
            <div
                style={{
                    marginBottom: '20px',
                    padding: '0 5%',
                    display: 'flex',
                    alignItems: 'center',
                    flexDirection: 'column',
                }}>
                <Message fixState={fixState} />

                {fixState === FIX_STATE.RUNNING && (
                    <>
                        <div style={{ marginBottom: '10px' }}>
                            <ComfySpan>
                                {' '}
                                {progressTracker.current} /{' '}
                                {progressTracker.total}{' '}
                            </ComfySpan>{' '}
                            <span style={{ marginLeft: '10px' }}>
                                {' '}
                                {constants.THUMBNAIL_REPLACED}
                            </span>
                        </div>
                        <div
                            style={{
                                width: '100%',
                                marginTop: '10px',
                                marginBottom: '20px',
                            }}>
                            <ProgressBar
                                now={Math.round(
                                    (progressTracker.current * 100) /
                                        progressTracker.total
                                )}
                                animated={true}
                                variant="upload-progress-bar"
                            />
                        </div>
                    </>
                )}
                <div
                    style={{
                        width: '100%',
                        display: 'flex',
                        justifyContent: 'space-around',
                    }}>
                    {fixState === FIX_STATE.NOT_STARTED ||
                    fixState === FIX_STATE.FIX_LATER ? (
                        <Button
                            block
                            variant={'outline-secondary'}
                            onClick={() => {
                                updateFixState(FIX_STATE.FIX_LATER);
                                props.hide();
                            }}>
                            {constants.FIX_THUMBNAIL_LATER}
                        </Button>
                    ) : (
                        <Button
                            block
                            variant={'outline-secondary'}
                            onClick={props.hide}>
                            {constants.CLOSE}
                        </Button>
                    )}
                    {(fixState === FIX_STATE.NOT_STARTED ||
                        fixState === FIX_STATE.FIX_LATER ||
                        fixState === FIX_STATE.COMPLETED_WITH_ERRORS) && (
                        <>
                            <div style={{ width: '30px' }} />

                            <Button
                                block
                                variant={'outline-success'}
                                onClick={() => startFix()}>
                                {constants.FIX_THUMBNAIL}
                            </Button>
                        </>
                    )}
                </div>
            </div>
        </MessageDialog>
    );
}
Example #7
Source File: UploadProgress.tsx    From bada-frame with GNU General Public License v3.0 4 votes vote down vote up
export default function UploadProgress(props: Props) {
    const appContext = useContext(AppContext);

    const fileProgressStatuses = [] as FileProgresses[];
    const fileUploadResultMap = new Map<FileUploadResults, number[]>();
    let filesNotUploaded = false;
    let sectionInfo = null;
    if (props.fileProgress) {
        for (const [localID, progress] of props.fileProgress) {
            fileProgressStatuses.push({
                fileID: localID,
                progress,
            });
        }
    }
    if (props.uploadResult) {
        for (const [localID, progress] of props.uploadResult) {
            if (!fileUploadResultMap.has(progress)) {
                fileUploadResultMap.set(progress, []);
            }
            if (
                progress !== FileUploadResults.UPLOADED &&
                progress !== FileUploadResults.UPLOADED_WITH_STATIC_THUMBNAIL
            ) {
                filesNotUploaded = true;
            }
            const fileList = fileUploadResultMap.get(progress);

            fileUploadResultMap.set(progress, [...fileList, localID]);
        }
    }
    if (props.hasLivePhotos) {
        sectionInfo = constants.LIVE_PHOTOS_DETECTED();
    }

    function handleHideModal(): () => void {
        return props.uploadStage !== UPLOAD_STAGES.FINISH
            ? () => {
                  appContext.setDialogMessage({
                      title: constants.STOP_UPLOADS_HEADER,
                      content: constants.STOP_ALL_UPLOADS_MESSAGE,
                      proceed: {
                          text: constants.YES_STOP_UPLOADS,
                          variant: 'danger',
                          action: props.cancelUploads,
                      },
                      close: {
                          text: constants.NO,
                          variant: 'secondary',
                          action: () => {},
                      },
                  });
              }
            : props.closeModal;
    }

    return (
        <>
            <Modal
                show={props.show}
                aria-labelledby="contained-modal-title-vcenter"
                centered
                backdrop={fileProgressStatuses?.length !== 0 ? 'static' : true}>
                <Modal.Header
                    style={{
                        display: 'flex',
                        justifyContent: 'center',
                        textAlign: 'center',
                        borderBottom: 'none',
                        paddingTop: '30px',
                        paddingBottom: '0px',
                    }}>
                    <h4 style={{ width: '100%' }}>
                        {props.uploadStage === UPLOAD_STAGES.UPLOADING
                            ? constants.UPLOAD[props.uploadStage](
                                  props.fileCounter
                              )
                            : constants.UPLOAD[props.uploadStage]}
                    </h4>
                    <IoMdClose
                        size={30}
                        onClick={handleHideModal()}
                        style={{ cursor: 'pointer' }}
                    />
                </Modal.Header>
                <Modal.Body>
                    {(props.uploadStage ===
                        UPLOAD_STAGES.READING_GOOGLE_METADATA_FILES ||
                        props.uploadStage ===
                            UPLOAD_STAGES.EXTRACTING_METADATA ||
                        props.uploadStage === UPLOAD_STAGES.UPLOADING) && (
                        <ProgressBar
                            now={props.now}
                            animated
                            variant="upload-progress-bar"
                        />
                    )}
                    {props.uploadStage === UPLOAD_STAGES.UPLOADING && (
                        <InProgressSection
                            filenames={props.filenames}
                            fileProgressStatuses={fileProgressStatuses}
                            sectionTitle={constants.INPROGRESS_UPLOADS}
                            sectionInfo={sectionInfo}
                        />
                    )}

                    <ResultSection
                        filenames={props.filenames}
                        fileUploadResultMap={fileUploadResultMap}
                        fileUploadResult={FileUploadResults.UPLOADED}
                        sectionTitle={constants.SUCCESSFUL_UPLOADS}
                    />
                    <ResultSection
                        filenames={props.filenames}
                        fileUploadResultMap={fileUploadResultMap}
                        fileUploadResult={
                            FileUploadResults.UPLOADED_WITH_STATIC_THUMBNAIL
                        }
                        sectionTitle={
                            constants.THUMBNAIL_GENERATION_FAILED_UPLOADS
                        }
                        sectionInfo={constants.THUMBNAIL_GENERATION_FAILED_INFO}
                    />

                    {props.uploadStage === UPLOAD_STAGES.FINISH &&
                        filesNotUploaded && (
                            <NotUploadSectionHeader>
                                {constants.FILE_NOT_UPLOADED_LIST}
                            </NotUploadSectionHeader>
                        )}

                    <ResultSection
                        filenames={props.filenames}
                        fileUploadResultMap={fileUploadResultMap}
                        fileUploadResult={FileUploadResults.BLOCKED}
                        sectionTitle={constants.BLOCKED_UPLOADS}
                        sectionInfo={constants.ETAGS_BLOCKED(
                            getOSSpecificDesktopAppDownloadLink()
                        )}
                    />
                    <ResultSection
                        filenames={props.filenames}
                        fileUploadResultMap={fileUploadResultMap}
                        fileUploadResult={FileUploadResults.FAILED}
                        sectionTitle={constants.FAILED_UPLOADS}
                    />
                    <ResultSection
                        filenames={props.filenames}
                        fileUploadResultMap={fileUploadResultMap}
                        fileUploadResult={FileUploadResults.ALREADY_UPLOADED}
                        sectionTitle={constants.SKIPPED_FILES}
                        sectionInfo={constants.SKIPPED_INFO}
                    />
                    <ResultSection
                        filenames={props.filenames}
                        fileUploadResultMap={fileUploadResultMap}
                        fileUploadResult={
                            FileUploadResults.LARGER_THAN_AVAILABLE_STORAGE
                        }
                        sectionTitle={
                            constants.LARGER_THAN_AVAILABLE_STORAGE_UPLOADS
                        }
                        sectionInfo={
                            constants.LARGER_THAN_AVAILABLE_STORAGE_INFO
                        }
                    />
                    <ResultSection
                        filenames={props.filenames}
                        fileUploadResultMap={fileUploadResultMap}
                        fileUploadResult={FileUploadResults.UNSUPPORTED}
                        sectionTitle={constants.UNSUPPORTED_FILES}
                        sectionInfo={constants.UNSUPPORTED_INFO}
                    />
                    <ResultSection
                        filenames={props.filenames}
                        fileUploadResultMap={fileUploadResultMap}
                        fileUploadResult={FileUploadResults.TOO_LARGE}
                        sectionTitle={constants.TOO_LARGE_UPLOADS}
                        sectionInfo={constants.TOO_LARGE_INFO}
                    />
                </Modal.Body>
                {props.uploadStage === UPLOAD_STAGES.FINISH && (
                    <Modal.Footer style={{ border: 'none' }}>
                        {props.uploadStage === UPLOAD_STAGES.FINISH &&
                            (fileUploadResultMap?.get(FileUploadResults.FAILED)
                                ?.length > 0 ||
                            fileUploadResultMap?.get(FileUploadResults.BLOCKED)
                                ?.length > 0 ? (
                                <Button
                                    variant="outline-success"
                                    style={{ width: '100%' }}
                                    onClick={props.retryFailed}>
                                    {constants.RETRY_FAILED}
                                </Button>
                            ) : (
                                <Button
                                    variant="outline-secondary"
                                    style={{ width: '100%' }}
                                    onClick={props.closeModal}>
                                    {constants.CLOSE}
                                </Button>
                            ))}
                    </Modal.Footer>
                )}
            </Modal>
        </>
    );
}