lbry-desktop/ui/component/postEditor/view.jsx

117 lines
2.7 KiB
React
Raw Normal View History

// @flow
import React, { useEffect } from 'react';
import { FF_MAX_CHARS_IN_POST } from 'constants/form-field';
import { FormField } from 'component/common/form';
type Props = {
uri: ?string,
label: ?string,
disabled: ?boolean,
filePath: string | WebFile,
fileText: ?string,
fileMimeType: ?string,
2020-07-30 22:00:22 +02:00
streamingUrl: ?string,
isStillEditing: boolean,
2020-07-30 22:00:22 +02:00
fetchStreamingUrl: string => void,
setPrevFileText: string => void,
updatePublishForm: ({}) => void,
setCurrentFileType: string => void,
};
2020-07-29 22:30:26 +02:00
function PostEditor(props: Props) {
const {
uri,
label,
disabled,
filePath,
fileText,
2020-07-30 22:00:22 +02:00
streamingUrl,
fileMimeType,
isStillEditing,
setPrevFileText,
2020-07-30 22:00:22 +02:00
fetchStreamingUrl,
updatePublishForm,
setCurrentFileType,
} = props;
const editing = isStillEditing && uri;
const [ready, setReady] = React.useState(!editing);
const [loading, setLoading] = React.useState(false);
2020-07-30 22:00:22 +02:00
useEffect(() => {
if (editing && uri) {
2020-07-30 22:00:22 +02:00
fetchStreamingUrl(uri);
}
2020-12-01 18:56:59 +01:00
}, [uri, editing, fetchStreamingUrl]);
2020-07-30 22:00:22 +02:00
// Ready to edit content
useEffect(() => {
if (!ready && !loading && fileText && streamingUrl) {
setReady(true);
}
}, [ready, loading, fileText, streamingUrl]);
useEffect(() => {
if (fileText && loading) {
setLoading(false);
} else if (!fileText && loading) {
setLoading(true);
}
}, [fileText, loading, setLoading]);
useEffect(() => {
function readFileStream(url) {
return fetch(url).then(res => res.text());
}
async function updateEditorText(url) {
try {
const text = await readFileStream(url);
if (text) {
// Store original content
setPrevFileText(text);
// Update text editor form
updatePublishForm({ fileText: text });
}
} catch (error) {
2020-12-01 18:56:59 +01:00
console.error(error); // eslint-disable-line
}
}
if (editing) {
// Editing same file (previously published)
// User can use a different file to replace the content
if (!ready && !filePath && !fileText && streamingUrl && fileMimeType === 'text/markdown') {
setCurrentFileType(fileMimeType);
updateEditorText(streamingUrl);
}
}
2020-07-28 08:11:28 +02:00
}, [
ready,
editing,
2020-07-28 08:11:28 +02:00
fileText,
filePath,
fileMimeType,
2020-07-28 08:11:28 +02:00
streamingUrl,
setPrevFileText,
updatePublishForm,
setCurrentFileType,
]);
return (
<FormField
type={'markdown'}
2020-07-29 22:30:26 +02:00
name="content_post"
label={label}
2020-07-29 22:30:26 +02:00
placeholder={__('My content for this post...')}
value={ready ? fileText : __('Loading...')}
disabled={!ready || disabled}
onChange={value => updatePublishForm({ fileText: value })}
textAreaMaxLength={FF_MAX_CHARS_IN_POST}
/>
);
}
2020-07-29 22:30:26 +02:00
export default PostEditor;