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.

281 lines
9.4 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. import { Component, linkEvent } from 'inferno';
  2. import { CommentNode as CommentNodeI, CommentForm as CommentFormI, SearchForm, SearchType, SortType, UserOperation, SearchResponse } from '../interfaces';
  3. import { Subscription } from "rxjs";
  4. import { capitalizeFirstLetter, mentionDropdownFetchLimit, msgOp, mdToHtml, randomStr, markdownHelpUrl } from '../utils';
  5. import { WebSocketService, UserService } from '../services';
  6. import * as autosize from 'autosize';
  7. import { i18n } from '../i18next';
  8. import { T } from 'inferno-i18next';
  9. import Tribute from 'tributejs/src/Tribute.js';
  10. import * as emojiShortName from 'emoji-short-name';
  11. interface CommentFormProps {
  12. postId?: number;
  13. node?: CommentNodeI;
  14. onReplyCancel?(): any;
  15. edit?: boolean;
  16. disabled?: boolean;
  17. }
  18. interface CommentFormState {
  19. commentForm: CommentFormI;
  20. buttonTitle: string;
  21. previewMode: boolean;
  22. imageLoading: boolean;
  23. }
  24. export class CommentForm extends Component<CommentFormProps, CommentFormState> {
  25. private id = `comment-form-${randomStr()}`;
  26. private userSub: Subscription;
  27. private communitySub: Subscription;
  28. private tribute: any;
  29. private emptyState: CommentFormState = {
  30. commentForm: {
  31. auth: null,
  32. content: null,
  33. post_id: this.props.node ? this.props.node.comment.post_id : this.props.postId,
  34. creator_id: UserService.Instance.user ? UserService.Instance.user.id : null,
  35. },
  36. buttonTitle: !this.props.node ? capitalizeFirstLetter(i18n.t('post')) : this.props.edit ? capitalizeFirstLetter(i18n.t('edit')) : capitalizeFirstLetter(i18n.t('reply')),
  37. previewMode: false,
  38. imageLoading: false,
  39. }
  40. constructor(props: any, context: any) {
  41. super(props, context);
  42. this.tribute = new Tribute({
  43. collection: [
  44. // Emojis
  45. {
  46. trigger: ':',
  47. menuItemTemplate: (item: any) => {
  48. let emoji = `:${item.original.key}:`;
  49. return `${item.original.val} ${emoji}`;
  50. },
  51. selectTemplate: (item: any) => {
  52. return `:${item.original.key}:`;
  53. },
  54. values: Object.entries(emojiShortName).map(e => {return {'key': e[1], 'val': e[0]}}),
  55. allowSpaces: false,
  56. autocompleteMode: true,
  57. menuItemLimit: mentionDropdownFetchLimit,
  58. },
  59. // Users
  60. {
  61. trigger: '@',
  62. selectTemplate: (item: any) => {
  63. return `[/u/${item.original.key}](/u/${item.original.key})`;
  64. },
  65. values: (text: string, cb: any) => {
  66. this.userSearch(text, (users: any) => cb(users));
  67. },
  68. allowSpaces: false,
  69. autocompleteMode: true,
  70. menuItemLimit: mentionDropdownFetchLimit,
  71. },
  72. // Communities
  73. {
  74. trigger: '#',
  75. selectTemplate: (item: any) => {
  76. return `[/c/${item.original.key}](/c/${item.original.key})`;
  77. },
  78. values: (text: string, cb: any) => {
  79. this.communitySearch(text, (communities: any) => cb(communities));
  80. },
  81. allowSpaces: false,
  82. autocompleteMode: true,
  83. menuItemLimit: mentionDropdownFetchLimit,
  84. }
  85. ]
  86. });
  87. this.state = this.emptyState;
  88. if (this.props.node) {
  89. if (this.props.edit) {
  90. this.state.commentForm.edit_id = this.props.node.comment.id;
  91. this.state.commentForm.parent_id = this.props.node.comment.parent_id;
  92. this.state.commentForm.content = this.props.node.comment.content;
  93. this.state.commentForm.creator_id = this.props.node.comment.creator_id;
  94. } else {
  95. // A reply gets a new parent id
  96. this.state.commentForm.parent_id = this.props.node.comment.id;
  97. }
  98. }
  99. }
  100. componentDidMount() {
  101. var textarea: any = document.getElementById(this.id);
  102. autosize(textarea);
  103. this.tribute.attach(textarea);
  104. textarea.addEventListener('tribute-replaced', () => {
  105. this.state.commentForm.content = textarea.value;
  106. this.setState(this.state);
  107. autosize.update(textarea);
  108. });
  109. }
  110. render() {
  111. return (
  112. <div class="mb-3">
  113. <form onSubmit={linkEvent(this, this.handleCommentSubmit)}>
  114. <div class="form-group row">
  115. <div className={`col-sm-12`}>
  116. <textarea id={this.id} className={`form-control ${this.state.previewMode && 'd-none'}`} value={this.state.commentForm.content} onInput={linkEvent(this, this.handleCommentContentChange)} required disabled={this.props.disabled} rows={2} maxLength={10000} />
  117. {this.state.previewMode &&
  118. <div className="md-div" dangerouslySetInnerHTML={mdToHtml(this.state.commentForm.content)} />
  119. }
  120. </div>
  121. </div>
  122. <div class="row">
  123. <div class="col-sm-12">
  124. <button type="submit" class="btn btn-sm btn-secondary mr-2" disabled={this.props.disabled}>{this.state.buttonTitle}</button>
  125. {this.state.commentForm.content &&
  126. <button className={`btn btn-sm mr-2 btn-secondary ${this.state.previewMode && 'active'}`} onClick={linkEvent(this, this.handlePreviewToggle)}><T i18nKey="preview">#</T></button>
  127. }
  128. {this.props.node && <button type="button" class="btn btn-sm btn-secondary mr-2" onClick={linkEvent(this, this.handleReplyCancel)}><T i18nKey="cancel">#</T></button>}
  129. <a href={markdownHelpUrl} target="_blank" class="d-inline-block float-right text-muted small font-weight-bold"><T i18nKey="formatting_help">#</T></a>
  130. <form class="d-inline-block mr-2 float-right text-muted small font-weight-bold">
  131. <label htmlFor={`file-upload-${this.id}`} class="pointer"><T i18nKey="upload_image">#</T></label>
  132. <input id={`file-upload-${this.id}`} type="file" accept="image/*,video/*" name="file" class="d-none" onChange={linkEvent(this, this.handleImageUpload)} />
  133. </form>
  134. {this.state.imageLoading &&
  135. <svg class="icon icon-spinner spin"><use xlinkHref="#icon-spinner"></use></svg>
  136. }
  137. </div>
  138. </div>
  139. </form>
  140. </div>
  141. );
  142. }
  143. handleCommentSubmit(i: CommentForm, event: any) {
  144. event.preventDefault();
  145. if (i.props.edit) {
  146. WebSocketService.Instance.editComment(i.state.commentForm);
  147. } else {
  148. WebSocketService.Instance.createComment(i.state.commentForm);
  149. }
  150. i.state.previewMode = false;
  151. i.state.commentForm.content = undefined;
  152. event.target.reset();
  153. i.setState(i.state);
  154. if (i.props.node) {
  155. i.props.onReplyCancel();
  156. }
  157. autosize.update(document.querySelector('textarea'));
  158. }
  159. handleCommentContentChange(i: CommentForm, event: any) {
  160. i.state.commentForm.content = event.target.value;
  161. i.setState(i.state);
  162. }
  163. handlePreviewToggle(i: CommentForm, event: any) {
  164. event.preventDefault();
  165. i.state.previewMode = !i.state.previewMode;
  166. i.setState(i.state);
  167. }
  168. handleReplyCancel(i: CommentForm) {
  169. i.props.onReplyCancel();
  170. }
  171. handleImageUpload(i: CommentForm, event: any) {
  172. event.preventDefault();
  173. let file = event.target.files[0];
  174. const imageUploadUrl = `/pictshare/api/upload.php`;
  175. const formData = new FormData();
  176. formData.append('file', file);
  177. i.state.imageLoading = true;
  178. i.setState(i.state);
  179. fetch(imageUploadUrl, {
  180. method: 'POST',
  181. body: formData,
  182. })
  183. .then(res => res.json())
  184. .then(res => {
  185. let url = `${window.location.origin}/pictshare/${res.url}`;
  186. let markdown = (res.filetype == 'mp4') ? `[vid](${url}/raw)` : `![](${url})`;
  187. let content = i.state.commentForm.content;
  188. content = (content) ? `${content} ${markdown}` : markdown;
  189. i.state.commentForm.content = content;
  190. i.state.imageLoading = false;
  191. i.setState(i.state);
  192. })
  193. .catch((error) => {
  194. i.state.imageLoading = false;
  195. i.setState(i.state);
  196. alert(error);
  197. })
  198. }
  199. userSearch(text: string, cb: any) {
  200. if (text) {
  201. let form: SearchForm = {
  202. q: text,
  203. type_: SearchType[SearchType.Users],
  204. sort: SortType[SortType.TopAll],
  205. page: 1,
  206. limit: mentionDropdownFetchLimit,
  207. };
  208. WebSocketService.Instance.search(form);
  209. this.userSub = WebSocketService.Instance.subject
  210. .subscribe(
  211. (msg) => {
  212. let op: UserOperation = msgOp(msg);
  213. if (op == UserOperation.Search) {
  214. let res: SearchResponse = msg;
  215. let users = res.users.map(u => {return {key: u.name}});
  216. cb(users);
  217. this.userSub.unsubscribe();
  218. }
  219. },
  220. (err) => console.error(err),
  221. () => console.log('complete')
  222. );
  223. } else {
  224. cb([]);
  225. }
  226. }
  227. communitySearch(text: string, cb: any) {
  228. if (text) {
  229. let form: SearchForm = {
  230. q: text,
  231. type_: SearchType[SearchType.Communities],
  232. sort: SortType[SortType.TopAll],
  233. page: 1,
  234. limit: mentionDropdownFetchLimit,
  235. };
  236. WebSocketService.Instance.search(form);
  237. this.communitySub = WebSocketService.Instance.subject
  238. .subscribe(
  239. (msg) => {
  240. let op: UserOperation = msgOp(msg);
  241. if (op == UserOperation.Search) {
  242. let res: SearchResponse = msg;
  243. let communities = res.communities.map(u => {return {key: u.name}});
  244. cb(communities);
  245. this.communitySub.unsubscribe();
  246. }
  247. },
  248. (err) => console.error(err),
  249. () => console.log('complete')
  250. );
  251. } else {
  252. cb([]);
  253. }
  254. }
  255. }