2021-06-23 05:37:08 -04:00
|
|
|
import { useState, useEffect } from 'react'
|
2021-04-28 07:41:20 -04:00
|
|
|
import PropTypes from 'prop-types'
|
2021-06-25 04:13:17 -04:00
|
|
|
import { useProjectContext } from '../../../shared/context/project-context'
|
2023-09-27 05:45:49 -04:00
|
|
|
import { debugConsole } from '@/utils/debugging'
|
2021-04-28 07:41:20 -04:00
|
|
|
|
|
|
|
const MAX_FILE_SIZE = 2 * 1024 * 1024
|
|
|
|
|
2021-06-10 07:26:04 -04:00
|
|
|
export default function FileViewText({ file, onLoad, onError }) {
|
2021-06-25 04:13:17 -04:00
|
|
|
const { _id: projectId } = useProjectContext({
|
|
|
|
_id: PropTypes.string.isRequired,
|
2021-05-21 07:32:51 -04:00
|
|
|
})
|
|
|
|
|
2021-04-28 07:41:20 -04:00
|
|
|
const [textPreview, setTextPreview] = useState('')
|
|
|
|
const [shouldShowDots, setShouldShowDots] = useState(false)
|
2021-07-27 04:45:24 -04:00
|
|
|
const [inFlight, setInFlight] = useState(false)
|
2021-04-28 07:41:20 -04:00
|
|
|
|
|
|
|
useEffect(() => {
|
2021-07-27 04:45:24 -04:00
|
|
|
if (inFlight) {
|
|
|
|
return
|
|
|
|
}
|
2021-05-21 07:32:51 -04:00
|
|
|
let path = `/project/${projectId}/file/${file.id}`
|
2021-04-28 07:41:20 -04:00
|
|
|
fetch(path, { method: 'HEAD' })
|
|
|
|
.then(response => {
|
|
|
|
if (!response.ok) throw new Error('HTTP Error Code: ' + response.status)
|
|
|
|
return response.headers.get('Content-Length')
|
|
|
|
})
|
|
|
|
.then(fileSize => {
|
|
|
|
let truncated = false
|
|
|
|
let maxSize = null
|
|
|
|
if (fileSize > MAX_FILE_SIZE) {
|
|
|
|
truncated = true
|
|
|
|
maxSize = MAX_FILE_SIZE
|
|
|
|
}
|
|
|
|
|
|
|
|
if (maxSize != null) {
|
|
|
|
path += `?range=0-${maxSize}`
|
|
|
|
}
|
2021-07-27 04:45:24 -04:00
|
|
|
return fetch(path).then(response => {
|
|
|
|
return response.text().then(text => {
|
|
|
|
if (truncated) {
|
|
|
|
text = text.replace(/\n.*$/, '')
|
|
|
|
}
|
2021-04-28 07:41:20 -04:00
|
|
|
|
2021-07-27 04:45:24 -04:00
|
|
|
setTextPreview(text)
|
|
|
|
onLoad()
|
|
|
|
setShouldShowDots(truncated)
|
2021-04-28 07:41:20 -04:00
|
|
|
})
|
2021-07-27 04:45:24 -04:00
|
|
|
})
|
2021-04-28 07:41:20 -04:00
|
|
|
})
|
|
|
|
.catch(err => {
|
2023-09-27 05:45:49 -04:00
|
|
|
debugConsole.error(err)
|
2021-04-28 07:41:20 -04:00
|
|
|
onError()
|
|
|
|
})
|
2021-07-27 04:45:24 -04:00
|
|
|
.finally(() => {
|
|
|
|
setInFlight(false)
|
|
|
|
})
|
|
|
|
}, [projectId, file.id, onError, onLoad, inFlight])
|
2021-04-28 07:41:20 -04:00
|
|
|
return (
|
|
|
|
<div>
|
|
|
|
{textPreview && (
|
|
|
|
<div className="text-preview">
|
|
|
|
<div className="scroll-container">
|
|
|
|
<p>{textPreview}</p>
|
|
|
|
{shouldShowDots && <p>...</p>}
|
|
|
|
</div>
|
|
|
|
</div>
|
|
|
|
)}
|
|
|
|
</div>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2021-06-10 07:26:04 -04:00
|
|
|
FileViewText.propTypes = {
|
2021-04-28 07:41:20 -04:00
|
|
|
file: PropTypes.shape({ id: PropTypes.string }).isRequired,
|
|
|
|
onLoad: PropTypes.func.isRequired,
|
|
|
|
onError: PropTypes.func.isRequired,
|
|
|
|
}
|