binary-file-text.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import React, { useState, useEffect } from 'react'
  2. import PropTypes from 'prop-types'
  3. import { useEditorContext } from '../../../shared/context/editor-context'
  4. const MAX_FILE_SIZE = 2 * 1024 * 1024
  5. export default function BinaryFileText({ file, onLoad, onError }) {
  6. const { projectId } = useEditorContext({
  7. projectId: PropTypes.string.isRequired,
  8. })
  9. const [textPreview, setTextPreview] = useState('')
  10. const [shouldShowDots, setShouldShowDots] = useState(false)
  11. useEffect(() => {
  12. let path = `/project/${projectId}/file/${file.id}`
  13. fetch(path, { method: 'HEAD' })
  14. .then(response => {
  15. if (!response.ok) throw new Error('HTTP Error Code: ' + response.status)
  16. return response.headers.get('Content-Length')
  17. })
  18. .then(fileSize => {
  19. let truncated = false
  20. let maxSize = null
  21. if (fileSize > MAX_FILE_SIZE) {
  22. truncated = true
  23. maxSize = MAX_FILE_SIZE
  24. }
  25. if (maxSize != null) {
  26. path += `?range=0-${maxSize}`
  27. }
  28. fetch(path)
  29. .then(response => {
  30. response.text().then(text => {
  31. if (truncated) {
  32. text = text.replace(/\n.*$/, '')
  33. }
  34. setTextPreview(text)
  35. onLoad()
  36. setShouldShowDots(truncated)
  37. })
  38. })
  39. .catch(err => {
  40. onError()
  41. console.error(err)
  42. })
  43. })
  44. .catch(err => {
  45. onError()
  46. })
  47. }, [projectId, file.id, onError, onLoad])
  48. return (
  49. <div>
  50. {textPreview && (
  51. <div className="text-preview">
  52. <div className="scroll-container">
  53. <p>{textPreview}</p>
  54. {shouldShowDots && <p>...</p>}
  55. </div>
  56. </div>
  57. )}
  58. </div>
  59. )
  60. }
  61. BinaryFileText.propTypes = {
  62. file: PropTypes.shape({ id: PropTypes.string }).isRequired,
  63. onLoad: PropTypes.func.isRequired,
  64. onError: PropTypes.func.isRequired,
  65. }