2021-04-28 07:41:20 -04:00
|
|
|
import React, { useState, useEffect } from 'react'
|
|
|
|
import PropTypes from 'prop-types'
|
2021-05-21 07:32:51 -04:00
|
|
|
import { useEditorContext } from '../../../shared/context/editor-context'
|
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-05-21 07:32:51 -04:00
|
|
|
const { projectId } = useEditorContext({
|
|
|
|
projectId: PropTypes.string.isRequired,
|
|
|
|
})
|
|
|
|
|
2021-04-28 07:41:20 -04:00
|
|
|
const [textPreview, setTextPreview] = useState('')
|
|
|
|
const [shouldShowDots, setShouldShowDots] = useState(false)
|
|
|
|
|
|
|
|
useEffect(() => {
|
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}`
|
|
|
|
}
|
|
|
|
fetch(path)
|
|
|
|
.then(response => {
|
|
|
|
response.text().then(text => {
|
|
|
|
if (truncated) {
|
|
|
|
text = text.replace(/\n.*$/, '')
|
|
|
|
}
|
|
|
|
|
|
|
|
setTextPreview(text)
|
|
|
|
onLoad()
|
|
|
|
setShouldShowDots(truncated)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
.catch(err => {
|
|
|
|
onError()
|
|
|
|
console.error(err)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
.catch(err => {
|
|
|
|
onError()
|
|
|
|
})
|
2021-05-21 07:32:51 -04:00
|
|
|
}, [projectId, file.id, onError, onLoad])
|
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,
|
|
|
|
}
|