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

453 lines
14 KiB
React
Raw Normal View History

2018-03-26 23:32:43 +02:00
// @flow
/*
On submit, this component calls publish, which dispatches doPublishDesktop.
doPublishDesktop calls lbry-redux Lbry publish method using lbry-redux publish state as params.
Publish simply instructs the SDK to find the file path on disk and publish it with the provided metadata.
On web, the Lbry publish method call is overridden in platform/web/api-setup, using a function in platform/web/publish.
File upload is carried out in the background by that function.
*/
2020-07-28 21:10:07 +02:00
2020-07-24 18:20:25 +02:00
import { SITE_NAME } from 'config';
import { CHANNEL_NEW, CHANNEL_ANONYMOUS } from 'constants/claim';
2020-07-30 00:55:48 +02:00
import React, { useEffect, useState } from 'react';
2019-07-24 20:21:34 +02:00
import { buildURI, isURIValid, isNameValid, THUMBNAIL_STATUSES } from 'lbry-redux';
2018-03-26 23:32:43 +02:00
import Button from 'component/button';
2019-12-06 20:42:44 +01:00
import SelectChannel from 'component/selectChannel';
2018-03-26 23:32:43 +02:00
import classnames from 'classnames';
import TagsSelect from 'component/tagsSelect';
import PublishDescription from 'component/publishDescription';
import PublishPrice from 'component/publishPrice';
import PublishFile from 'component/publishFile';
2019-12-06 20:42:44 +01:00
import PublishName from 'component/publishName';
import PublishAdditionalOptions from 'component/publishAdditionalOptions';
import PublishFormErrors from 'component/publishFormErrors';
import SelectThumbnail from 'component/selectThumbnail';
2019-09-27 20:56:15 +02:00
import Card from 'component/common/card';
import I18nMessage from 'component/i18nMessage';
import * as PUBLISH_MODES from 'constants/publish_types';
2020-07-28 21:10:07 +02:00
// @if TARGET='app'
import fs from 'fs';
import tempy from 'tempy';
2020-07-28 21:10:07 +02:00
// @endif
const MODES = Object.values(PUBLISH_MODES);
2018-03-26 23:32:43 +02:00
const MODE_TO_I18N_STR = {
[PUBLISH_MODES.FILE]: 'File',
[PUBLISH_MODES.POST]: 'Post --[noun, markdown post tab button]--',
};
2018-03-26 23:32:43 +02:00
type Props = {
2019-10-28 19:53:59 +01:00
disabled: boolean,
tags: Array<Tag>,
publish: (source?: string | File, ?boolean) => void,
2020-08-11 03:26:44 +02:00
filePath: string | File,
fileText: string,
2018-03-26 23:32:43 +02:00
bid: ?number,
bidError: ?string,
2018-03-26 23:32:43 +02:00
editingURI: ?string,
title: ?string,
thumbnail: ?string,
uploadThumbnailStatus: ?string,
2018-06-08 06:05:45 +02:00
thumbnailPath: ?string,
2018-03-26 23:32:43 +02:00
description: ?string,
language: string,
nsfw: boolean,
contentIsFree: boolean,
fee: {
amount: string,
2018-03-26 23:32:43 +02:00
currency: string,
},
channel: string,
name: ?string,
nameError: ?string,
isResolvingUri: boolean,
winningBidForClaimUri: number,
2019-04-24 16:02:08 +02:00
myClaimForUri: ?StreamClaim,
2018-03-26 23:32:43 +02:00
licenseType: string,
otherLicenseDescription: ?string,
licenseUrl: ?string,
useLBRYUploader: ?boolean,
2018-03-26 23:32:43 +02:00
publishing: boolean,
balance: number,
2018-06-12 07:11:17 +02:00
isStillEditing: boolean,
2018-03-26 23:32:43 +02:00
clearPublish: () => void,
resolveUri: string => void,
scrollToTop: () => void,
2018-10-13 17:49:47 +02:00
prepareEdit: (claim: any, uri: string) => void,
resetThumbnailStatus: () => void,
2018-09-25 02:17:08 +02:00
amountNeededForTakeover: ?number,
// Add back type
updatePublishForm: any => void,
checkAvailability: string => void,
ytSignupPending: boolean,
modal: { id: string, modalProps: {} },
enablePublishPreview: boolean,
2018-03-26 23:32:43 +02:00
};
function PublishForm(props: Props) {
const [mode, setMode] = React.useState(PUBLISH_MODES.FILE);
const [autoSwitchMode, setAutoSwitchMode] = React.useState(true);
2020-07-30 06:03:56 +02:00
// Used to checl if the url name has changed:
// A new file needs to be provided
const [prevName, setPrevName] = React.useState(false);
// Used to checl if the file has been modified by user
const [fileEdited, setFileEdited] = React.useState(false);
const [prevFileText, setPrevFileText] = React.useState('');
const {
thumbnail,
name,
channel,
editingURI,
myClaimForUri,
resolveUri,
title,
bid,
bidError,
uploadThumbnailStatus,
resetThumbnailStatus,
updatePublishForm,
filePath,
fileText,
publishing,
clearPublish,
isStillEditing,
tags,
publish,
2019-10-28 19:53:59 +01:00
disabled = false,
checkAvailability,
ytSignupPending,
modal,
enablePublishPreview,
} = props;
2020-07-30 00:55:48 +02:00
// Used to check if name should be auto-populated from title
const [autoPopulateNameFromTitle, setAutoPopulateNameFromTitle] = useState(!isStillEditing);
2020-03-05 22:35:01 +01:00
const TAGS_LIMIT = 5;
const fileFormDisabled = mode === PUBLISH_MODES.FILE && !filePath;
2020-07-29 22:30:26 +02:00
const emptyPostError = mode === PUBLISH_MODES.POST && (!fileText || fileText.trim() === '');
const formDisabled = (fileFormDisabled && !editingURI) || emptyPostError || publishing;
const isInProgress = filePath || editingURI || name || title;
2020-07-30 06:03:56 +02:00
// Editing content info
const uri = myClaimForUri ? myClaimForUri.permanent_url : undefined;
2020-10-26 19:56:38 +01:00
const fileMimeType =
myClaimForUri && myClaimForUri.value && myClaimForUri.value.source
? myClaimForUri.value.source.media_type
: undefined;
2020-07-30 06:03:56 +02:00
const nameEdited = isStillEditing && name !== prevName;
// If they are editing, they don't need a new file chosen
2019-07-24 20:21:34 +02:00
const formValidLessFile =
name &&
isNameValid(name, false) &&
title &&
bid &&
!bidError &&
2020-07-29 22:30:26 +02:00
!emptyPostError &&
!(uploadThumbnailStatus === THUMBNAIL_STATUSES.IN_PROGRESS);
const isOverwritingExistingClaim = !editingURI && myClaimForUri;
const formValid = isOverwritingExistingClaim
? false
: editingURI && !filePath
? isStillEditing && formValidLessFile
: formValidLessFile;
const [previewing, setPreviewing] = React.useState(false);
useEffect(() => {
if (!modal) {
setTimeout(() => {
setPreviewing(false);
}, 250);
}
}, [modal]);
let submitLabel;
if (isStillEditing) {
submitLabel = !publishing ? __('Save') : __('Saving...');
} else if (previewing) {
submitLabel = __('Preparing...');
} else {
2020-07-23 19:02:07 +02:00
submitLabel = !publishing ? __('Upload') : __('Uploading...');
2018-03-26 23:32:43 +02:00
}
useEffect(() => {
2018-07-17 19:43:43 +02:00
if (!thumbnail) {
resetThumbnailStatus();
2018-06-13 06:19:39 +02:00
}
}, [thumbnail, resetThumbnailStatus]);
2020-07-30 06:03:56 +02:00
// Save current name of the editing claim
useEffect(() => {
if (isStillEditing && (!prevName || !prevName.trim() === '')) {
if (name !== prevName) {
setPrevName(name);
}
}
}, [name, prevName, setPrevName, isStillEditing]);
// Check for content changes on the text editor
useEffect(() => {
if (!fileEdited && fileText !== prevFileText && fileText !== '') {
setFileEdited(true);
} else if (fileEdited && fileText === prevFileText) {
setFileEdited(false);
}
}, [fileText, prevFileText, fileEdited]);
// Every time the channel or name changes, resolve the uris to find winning bid amounts
useEffect(() => {
// If they are midway through a channel creation, treat it as anonymous until it completes
const channelName = channel === CHANNEL_ANONYMOUS || channel === CHANNEL_NEW ? '' : channel;
2018-03-26 23:32:43 +02:00
2018-09-25 02:17:08 +02:00
// We are only going to store the full uri, but we need to resolve the uri with and without the channel name
let uri;
try {
2019-11-01 18:27:01 +01:00
uri = name && buildURI({ streamName: name, channelName });
} catch (e) {}
if (channelName && name) {
// resolve without the channel name so we know the winning bid for it
2019-07-02 06:49:21 +02:00
try {
const uriLessChannel = buildURI({ streamName: name });
2019-07-02 06:49:21 +02:00
resolveUri(uriLessChannel);
} catch (e) {}
}
2019-07-03 16:49:28 +02:00
const isValid = isURIValid(uri);
if (uri && isValid && checkAvailability && name) {
resolveUri(uri);
checkAvailability(name);
updatePublishForm({ uri });
}
}, [name, channel, resolveUri, updatePublishForm, checkAvailability]);
useEffect(() => {
updatePublishForm({ isMarkdownPost: mode === PUBLISH_MODES.POST });
}, [mode, updatePublishForm]);
function handleChannelNameChange(channel) {
updatePublishForm({ channel });
}
2020-07-28 21:10:07 +02:00
// @if TARGET='web'
function createWebFile() {
if (fileText) {
2020-07-29 22:30:26 +02:00
const fileName = name || title;
2020-08-11 03:26:44 +02:00
if (fileName) {
return new File([fileText], `${fileName}.md`, { type: 'text/markdown' });
}
}
}
2020-07-28 21:10:07 +02:00
// @endif
2020-07-28 21:10:07 +02:00
// @if TARGET='app'
// Save file changes locally ( desktop )
function saveFileChanges() {
2020-08-11 03:26:44 +02:00
let output;
if (!output || output === '') {
// Generate a temporary file:
2020-07-29 22:30:26 +02:00
output = tempy.file({ name: 'post.md' });
2020-08-11 03:26:44 +02:00
} else if (typeof filePath === 'string') {
// Use current file
output = filePath;
}
// Create a temporary file and save file changes
2020-08-11 03:26:44 +02:00
if (output && output !== '') {
// Save file changes
return new Promise((resolve, reject) => {
fs.writeFile(output, fileText, (error, data) => {
// Handle error, cant save changes or create file
error ? reject(error) : resolve(output);
});
});
}
}
2020-07-28 21:10:07 +02:00
// @endif
async function handlePublish() {
2020-08-12 03:59:23 +02:00
let outputFile = filePath;
let runPublish = false;
2020-07-29 22:30:26 +02:00
// Publish post:
// If here is no file selected yet on desktop, show file dialog and let the
// user choose a file path. On web a new File is created
if (mode === PUBLISH_MODES.POST && !emptyPostError) {
2020-07-30 06:03:56 +02:00
// If user modified content on the text editor or editing name has changed:
2020-07-30 06:07:00 +02:00
// Save changes and update file path
2020-07-30 06:03:56 +02:00
if (fileEdited || nameEdited) {
// @if TARGET='app'
outputFile = await saveFileChanges();
// @endif
// @if TARGET='web'
outputFile = createWebFile();
// @endif
// New content stored locally and is not empty
if (outputFile) {
updatePublishForm({ filePath: outputFile });
2020-08-12 03:59:23 +02:00
runPublish = true;
}
} else {
// Only metadata has changed.
2020-08-12 03:59:23 +02:00
runPublish = true;
}
}
// Publish file
if (mode === PUBLISH_MODES.FILE) {
2020-08-12 03:59:23 +02:00
runPublish = true;
}
if (runPublish) {
if (enablePublishPreview) {
setPreviewing(true);
2020-08-12 03:59:23 +02:00
publish(outputFile, true);
} else {
2020-08-12 03:59:23 +02:00
publish(outputFile, false);
}
}
}
// Update mode on editing
useEffect(() => {
if (autoSwitchMode && editingURI && myClaimForUri) {
2020-07-29 22:30:26 +02:00
// Change publish mode to "post" if editing content type is markdown
if (fileMimeType === 'text/markdown' && mode !== PUBLISH_MODES.POST) {
setMode(PUBLISH_MODES.POST);
// Prevent forced mode
setAutoSwitchMode(false);
}
}
}, [autoSwitchMode, editingURI, fileMimeType, myClaimForUri, mode, setMode, setAutoSwitchMode]);
// Editing claim uri
return (
<div className="card-stack">
<PublishFile
uri={uri}
mode={mode}
fileMimeType={fileMimeType}
disabled={disabled || publishing}
inProgress={isInProgress}
setPublishMode={setMode}
setPrevFileText={setPrevFileText}
2020-07-30 00:55:48 +02:00
autoPopulateName={autoPopulateNameFromTitle}
2020-07-30 06:03:56 +02:00
setAutoPopulateName={setAutoPopulateNameFromTitle}
header={
2020-08-05 19:19:15 +02:00
<>
{MODES.map((modeName, index) => (
<Button
key={index}
icon={modeName}
label={__(MODE_TO_I18N_STR[String(modeName)] || '---')}
button="alt"
onClick={() => {
setMode(modeName);
}}
className={classnames('button-toggle', { 'button-toggle--active': mode === modeName })}
/>
))}
2020-08-05 19:19:15 +02:00
</>
}
/>
{!publishing && (
<div className={classnames({ 'card--disabled': formDisabled })}>
{mode === PUBLISH_MODES.FILE && <PublishDescription disabled={formDisabled} />}
<Card actions={<SelectThumbnail />} />
<TagsSelect
suggestMature
disableAutoFocus
hideHeader
label={__('Selected Tags')}
empty={__('No tags added')}
limitSelect={TAGS_LIMIT}
help={__(
2020-07-23 19:11:53 +02:00
"Add tags that are relevant to your content so those who're looking for it can find it more easily. If mature content, ensure it is tagged mature. Tag abuse and missing mature tags will not be tolerated."
)}
placeholder={__('gaming, crypto')}
onSelect={newTags => {
const validatedTags = [];
newTags.forEach(newTag => {
if (!tags.some(tag => tag.name === newTag.name)) {
validatedTags.push(newTag);
}
});
updatePublishForm({ tags: [...tags, ...validatedTags] });
}}
onRemove={clickedTag => {
const newTags = tags.slice().filter(tag => tag.name !== clickedTag.name);
updatePublishForm({ tags: newTags });
}}
tagsChosen={tags}
/>
2019-09-27 20:56:15 +02:00
<Card
actions={
<React.Fragment>
<SelectChannel channel={channel} onChannelChange={handleChannelNameChange} />
<p className="help">
{__('This is a username or handle that your content can be found under.')}{' '}
{__('Ex. @Marvel, @TheBeatles, @BooksByJoe')}
</p>
</React.Fragment>
}
/>
2020-07-30 00:55:48 +02:00
<PublishName
disabled={isStillEditing || formDisabled}
2020-07-30 00:55:48 +02:00
autoPopulateName={autoPopulateNameFromTitle}
setAutoPopulateName={setAutoPopulateNameFromTitle}
/>
<PublishPrice disabled={formDisabled} />
<PublishAdditionalOptions disabled={formDisabled} />
</div>
)}
<section>
<div className="card__actions">
<Button
button="primary"
onClick={handlePublish}
label={submitLabel}
disabled={
formDisabled ||
!formValid ||
uploadThumbnailStatus === THUMBNAIL_STATUSES.IN_PROGRESS ||
ytSignupPending ||
previewing
}
/>
<Button button="link" onClick={clearPublish} label={__('Cancel')} />
</div>
<p className="help">
2020-07-08 00:24:24 +02:00
{!formDisabled && !formValid ? (
<PublishFormErrors mode={mode} />
2020-07-08 00:24:24 +02:00
) : (
<I18nMessage
tokens={{
lbry_terms_of_service: (
<Button
button="link"
href="https://www.lbry.com/termsofservice"
2020-07-24 18:20:25 +02:00
label={__('%site_name% Terms of Service', { site_name: SITE_NAME })}
2020-07-08 00:24:24 +02:00
/>
),
}}
>
By continuing, you accept the %lbry_terms_of_service%.
</I18nMessage>
)}
</p>
</section>
</div>
);
}
export default PublishForm;