You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

303 lines
11 KiB

  1. import React from 'react';
  2. import CharacterCounter from './character_counter';
  3. import Button from '../../../components/button';
  4. import ImmutablePropTypes from 'react-immutable-proptypes';
  5. import PropTypes from 'prop-types';
  6. import ReplyIndicatorContainer from '../containers/reply_indicator_container';
  7. import AutosuggestTextarea from '../../../components/autosuggest_textarea';
  8. import AutosuggestInput from '../../../components/autosuggest_input';
  9. import PollButtonContainer from '../containers/poll_button_container';
  10. import UploadButtonContainer from '../containers/upload_button_container';
  11. import { defineMessages, injectIntl } from 'react-intl';
  12. import SpoilerButtonContainer from '../containers/spoiler_button_container';
  13. import PrivacyDropdownContainer from '../containers/privacy_dropdown_container';
  14. import EmojiPickerDropdown from '../containers/emoji_picker_dropdown_container';
  15. import PollFormContainer from '../containers/poll_form_container';
  16. import UploadFormContainer from '../containers/upload_form_container';
  17. import WarningContainer from '../containers/warning_container';
  18. import LanguageDropdown from '../containers/language_dropdown_container';
  19. import ImmutablePureComponent from 'react-immutable-pure-component';
  20. import { length } from 'stringz';
  21. import { countableText } from '../util/counter';
  22. import Icon from 'mastodon/components/icon';
  23. import { maxChars } from '../../../initial_state';
  24. const allowedAroundShortCode = '><\u0085\u0020\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\u0009\u000a\u000b\u000c\u000d';
  25. const messages = defineMessages({
  26. placeholder: { id: 'compose_form.placeholder', defaultMessage: 'What is on your mind?' },
  27. spoiler_placeholder: { id: 'compose_form.spoiler_placeholder', defaultMessage: 'Write your warning here' },
  28. publish: { id: 'compose_form.publish', defaultMessage: 'Publish' },
  29. publishLoud: { id: 'compose_form.publish_loud', defaultMessage: '{publish}!' },
  30. saveChanges: { id: 'compose_form.save_changes', defaultMessage: 'Save changes' },
  31. });
  32. class ComposeForm extends ImmutablePureComponent {
  33. static contextTypes = {
  34. router: PropTypes.object,
  35. };
  36. static propTypes = {
  37. intl: PropTypes.object.isRequired,
  38. text: PropTypes.string.isRequired,
  39. suggestions: ImmutablePropTypes.list,
  40. spoiler: PropTypes.bool,
  41. privacy: PropTypes.string,
  42. spoilerText: PropTypes.string,
  43. focusDate: PropTypes.instanceOf(Date),
  44. caretPosition: PropTypes.number,
  45. preselectDate: PropTypes.instanceOf(Date),
  46. isSubmitting: PropTypes.bool,
  47. isChangingUpload: PropTypes.bool,
  48. isEditing: PropTypes.bool,
  49. isUploading: PropTypes.bool,
  50. onChange: PropTypes.func.isRequired,
  51. onSubmit: PropTypes.func.isRequired,
  52. onClearSuggestions: PropTypes.func.isRequired,
  53. onFetchSuggestions: PropTypes.func.isRequired,
  54. onSuggestionSelected: PropTypes.func.isRequired,
  55. onChangeSpoilerText: PropTypes.func.isRequired,
  56. onPaste: PropTypes.func.isRequired,
  57. onPickEmoji: PropTypes.func.isRequired,
  58. autoFocus: PropTypes.bool,
  59. anyMedia: PropTypes.bool,
  60. isInReply: PropTypes.bool,
  61. singleColumn: PropTypes.bool,
  62. lang: PropTypes.string,
  63. };
  64. static defaultProps = {
  65. autoFocus: false,
  66. };
  67. handleChange = (e) => {
  68. this.props.onChange(e.target.value);
  69. };
  70. handleKeyDown = (e) => {
  71. if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) {
  72. this.handleSubmit();
  73. }
  74. };
  75. getFulltextForCharacterCounting = () => {
  76. return [this.props.spoiler? this.props.spoilerText: '', countableText(this.props.text)].join('');
  77. };
  78. canSubmit = () => {
  79. const { isSubmitting, isChangingUpload, isUploading, anyMedia } = this.props;
  80. const fulltext = this.getFulltextForCharacterCounting();
  81. const isOnlyWhitespace = fulltext.length !== 0 && fulltext.trim().length === 0;
  82. return !(isSubmitting || isUploading || isChangingUpload || length(fulltext) > maxChars || (isOnlyWhitespace && !anyMedia));
  83. };
  84. handleSubmit = (e) => {
  85. if (this.props.text !== this.autosuggestTextarea.textarea.value) {
  86. // Something changed the text inside the textarea (e.g. browser extensions like Grammarly)
  87. // Update the state to match the current text
  88. this.props.onChange(this.autosuggestTextarea.textarea.value);
  89. }
  90. if (!this.canSubmit()) {
  91. return;
  92. }
  93. this.props.onSubmit(this.context.router ? this.context.router.history : null);
  94. if (e) {
  95. e.preventDefault();
  96. }
  97. };
  98. onSuggestionsClearRequested = () => {
  99. this.props.onClearSuggestions();
  100. };
  101. onSuggestionsFetchRequested = (token) => {
  102. this.props.onFetchSuggestions(token);
  103. };
  104. onSuggestionSelected = (tokenStart, token, value) => {
  105. this.props.onSuggestionSelected(tokenStart, token, value, ['text']);
  106. };
  107. onSpoilerSuggestionSelected = (tokenStart, token, value) => {
  108. this.props.onSuggestionSelected(tokenStart, token, value, ['spoiler_text']);
  109. };
  110. handleChangeSpoilerText = (e) => {
  111. this.props.onChangeSpoilerText(e.target.value);
  112. };
  113. handleFocus = () => {
  114. if (this.composeForm && !this.props.singleColumn) {
  115. const { left, right } = this.composeForm.getBoundingClientRect();
  116. if (left < 0 || right > (window.innerWidth || document.documentElement.clientWidth)) {
  117. this.composeForm.scrollIntoView();
  118. }
  119. }
  120. };
  121. componentDidMount () {
  122. this._updateFocusAndSelection({ });
  123. }
  124. componentDidUpdate (prevProps) {
  125. this._updateFocusAndSelection(prevProps);
  126. }
  127. _updateFocusAndSelection = (prevProps) => {
  128. // This statement does several things:
  129. // - If we're beginning a reply, and,
  130. // - Replying to zero or one users, places the cursor at the end of the textbox.
  131. // - Replying to more than one user, selects any usernames past the first;
  132. // this provides a convenient shortcut to drop everyone else from the conversation.
  133. if (this.props.focusDate && this.props.focusDate !== prevProps.focusDate) {
  134. let selectionEnd, selectionStart;
  135. if (this.props.preselectDate !== prevProps.preselectDate && this.props.isInReply) {
  136. selectionEnd = this.props.text.length;
  137. selectionStart = this.props.text.search(/\s/) + 1;
  138. } else if (typeof this.props.caretPosition === 'number') {
  139. selectionStart = this.props.caretPosition;
  140. selectionEnd = this.props.caretPosition;
  141. } else {
  142. selectionEnd = this.props.text.length;
  143. selectionStart = selectionEnd;
  144. }
  145. // Because of the wicg-inert polyfill, the activeElement may not be
  146. // immediately selectable, we have to wait for observers to run, as
  147. // described in https://github.com/WICG/inert#performance-and-gotchas
  148. Promise.resolve().then(() => {
  149. this.autosuggestTextarea.textarea.setSelectionRange(selectionStart, selectionEnd);
  150. this.autosuggestTextarea.textarea.focus();
  151. }).catch(console.error);
  152. } else if(prevProps.isSubmitting && !this.props.isSubmitting) {
  153. this.autosuggestTextarea.textarea.focus();
  154. } else if (this.props.spoiler !== prevProps.spoiler) {
  155. if (this.props.spoiler) {
  156. this.spoilerText.input.focus();
  157. } else if (prevProps.spoiler) {
  158. this.autosuggestTextarea.textarea.focus();
  159. }
  160. }
  161. };
  162. setAutosuggestTextarea = (c) => {
  163. this.autosuggestTextarea = c;
  164. };
  165. setSpoilerText = (c) => {
  166. this.spoilerText = c;
  167. };
  168. setRef = c => {
  169. this.composeForm = c;
  170. };
  171. handleEmojiPick = (data) => {
  172. const { text } = this.props;
  173. const position = this.autosuggestTextarea.textarea.selectionStart;
  174. const needsSpace = data.custom && position > 0 && !allowedAroundShortCode.includes(text[position - 1]);
  175. this.props.onPickEmoji(position, data, needsSpace);
  176. };
  177. render () {
  178. const { intl, onPaste, autoFocus } = this.props;
  179. const disabled = this.props.isSubmitting;
  180. let publishText = '';
  181. if (this.props.isEditing) {
  182. publishText = intl.formatMessage(messages.saveChanges);
  183. } else if (this.props.privacy === 'private' || this.props.privacy === 'direct') {
  184. publishText = <span className='compose-form__publish-private'><Icon id='lock' /> {intl.formatMessage(messages.publish)}</span>;
  185. } else {
  186. publishText = this.props.privacy !== 'unlisted' ? intl.formatMessage(messages.publishLoud, { publish: intl.formatMessage(messages.publish) }) : intl.formatMessage(messages.publish);
  187. }
  188. return (
  189. <form className='compose-form' onSubmit={this.handleSubmit}>
  190. <WarningContainer />
  191. <ReplyIndicatorContainer />
  192. <div className={`spoiler-input ${this.props.spoiler ? 'spoiler-input--visible' : ''}`} ref={this.setRef} aria-hidden={!this.props.spoiler}>
  193. <AutosuggestInput
  194. placeholder={intl.formatMessage(messages.spoiler_placeholder)}
  195. value={this.props.spoilerText}
  196. onChange={this.handleChangeSpoilerText}
  197. onKeyDown={this.handleKeyDown}
  198. disabled={!this.props.spoiler}
  199. ref={this.setSpoilerText}
  200. suggestions={this.props.suggestions}
  201. onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
  202. onSuggestionsClearRequested={this.onSuggestionsClearRequested}
  203. onSuggestionSelected={this.onSpoilerSuggestionSelected}
  204. searchTokens={[':']}
  205. id='cw-spoiler-input'
  206. className='spoiler-input__input'
  207. lang={this.props.lang}
  208. spellCheck
  209. />
  210. </div>
  211. <AutosuggestTextarea
  212. ref={this.setAutosuggestTextarea}
  213. placeholder={intl.formatMessage(messages.placeholder)}
  214. disabled={disabled}
  215. value={this.props.text}
  216. onChange={this.handleChange}
  217. suggestions={this.props.suggestions}
  218. onFocus={this.handleFocus}
  219. onKeyDown={this.handleKeyDown}
  220. onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
  221. onSuggestionsClearRequested={this.onSuggestionsClearRequested}
  222. onSuggestionSelected={this.onSuggestionSelected}
  223. onPaste={onPaste}
  224. autoFocus={autoFocus}
  225. lang={this.props.lang}
  226. >
  227. <EmojiPickerDropdown onPickEmoji={this.handleEmojiPick} />
  228. <div className='compose-form__modifiers'>
  229. <UploadFormContainer />
  230. <PollFormContainer />
  231. </div>
  232. </AutosuggestTextarea>
  233. <div className='compose-form__buttons-wrapper'>
  234. <div className='compose-form__buttons'>
  235. <UploadButtonContainer />
  236. <PollButtonContainer />
  237. <PrivacyDropdownContainer disabled={this.props.isEditing} />
  238. <SpoilerButtonContainer />
  239. <LanguageDropdown />
  240. </div>
  241. <div className='character-counter__wrapper'>
  242. <CharacterCounter max={maxChars} text={this.getFulltextForCharacterCounting()} />
  243. </div>
  244. </div>
  245. <div className='compose-form__publish'>
  246. <div className='compose-form__publish-button-wrapper'>
  247. <Button
  248. type='submit'
  249. text={publishText}
  250. disabled={!this.canSubmit()}
  251. block
  252. />
  253. </div>
  254. </div>
  255. </form>
  256. );
  257. }
  258. }
  259. export default injectIntl(ComposeForm);