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.

532 lines
19 KiB

  1. import {
  2. COMPOSE_MOUNT,
  3. COMPOSE_UNMOUNT,
  4. COMPOSE_CHANGE,
  5. COMPOSE_REPLY,
  6. COMPOSE_REPLY_CANCEL,
  7. COMPOSE_DIRECT,
  8. COMPOSE_MENTION,
  9. COMPOSE_SUBMIT_REQUEST,
  10. COMPOSE_SUBMIT_SUCCESS,
  11. COMPOSE_SUBMIT_FAIL,
  12. COMPOSE_UPLOAD_REQUEST,
  13. COMPOSE_UPLOAD_SUCCESS,
  14. COMPOSE_UPLOAD_FAIL,
  15. COMPOSE_UPLOAD_UNDO,
  16. COMPOSE_UPLOAD_PROGRESS,
  17. COMPOSE_UPLOAD_PROCESSING,
  18. THUMBNAIL_UPLOAD_REQUEST,
  19. THUMBNAIL_UPLOAD_SUCCESS,
  20. THUMBNAIL_UPLOAD_FAIL,
  21. THUMBNAIL_UPLOAD_PROGRESS,
  22. COMPOSE_SUGGESTIONS_CLEAR,
  23. COMPOSE_SUGGESTIONS_READY,
  24. COMPOSE_SUGGESTION_SELECT,
  25. COMPOSE_SUGGESTION_IGNORE,
  26. COMPOSE_SUGGESTION_TAGS_UPDATE,
  27. COMPOSE_TAG_HISTORY_UPDATE,
  28. COMPOSE_SENSITIVITY_CHANGE,
  29. COMPOSE_SPOILERNESS_CHANGE,
  30. COMPOSE_SPOILER_TEXT_CHANGE,
  31. COMPOSE_VISIBILITY_CHANGE,
  32. COMPOSE_LANGUAGE_CHANGE,
  33. COMPOSE_COMPOSING_CHANGE,
  34. COMPOSE_EMOJI_INSERT,
  35. COMPOSE_UPLOAD_CHANGE_REQUEST,
  36. COMPOSE_UPLOAD_CHANGE_SUCCESS,
  37. COMPOSE_UPLOAD_CHANGE_FAIL,
  38. COMPOSE_RESET,
  39. COMPOSE_POLL_ADD,
  40. COMPOSE_POLL_REMOVE,
  41. COMPOSE_POLL_OPTION_ADD,
  42. COMPOSE_POLL_OPTION_CHANGE,
  43. COMPOSE_POLL_OPTION_REMOVE,
  44. COMPOSE_POLL_SETTINGS_CHANGE,
  45. INIT_MEDIA_EDIT_MODAL,
  46. COMPOSE_CHANGE_MEDIA_DESCRIPTION,
  47. COMPOSE_CHANGE_MEDIA_FOCUS,
  48. COMPOSE_SET_STATUS,
  49. } from '../actions/compose';
  50. import { TIMELINE_DELETE } from '../actions/timelines';
  51. import { STORE_HYDRATE } from '../actions/store';
  52. import { REDRAFT } from '../actions/statuses';
  53. import { Map as ImmutableMap, List as ImmutableList, OrderedSet as ImmutableOrderedSet, fromJS } from 'immutable';
  54. import uuid from '../uuid';
  55. import { me } from '../initial_state';
  56. import { unescapeHTML } from '../utils/html';
  57. const initialState = ImmutableMap({
  58. mounted: 0,
  59. sensitive: false,
  60. spoiler: false,
  61. spoiler_text: '',
  62. privacy: null,
  63. id: null,
  64. text: '',
  65. focusDate: null,
  66. caretPosition: null,
  67. preselectDate: null,
  68. in_reply_to: null,
  69. is_composing: false,
  70. is_submitting: false,
  71. is_changing_upload: false,
  72. is_uploading: false,
  73. progress: 0,
  74. isUploadingThumbnail: false,
  75. thumbnailProgress: 0,
  76. media_attachments: ImmutableList(),
  77. pending_media_attachments: 0,
  78. poll: null,
  79. suggestion_token: null,
  80. suggestions: ImmutableList(),
  81. default_privacy: 'public',
  82. default_sensitive: false,
  83. default_language: 'en',
  84. resetFileKey: Math.floor((Math.random() * 0x10000)),
  85. idempotencyKey: null,
  86. tagHistory: ImmutableList(),
  87. media_modal: ImmutableMap({
  88. id: null,
  89. description: '',
  90. focusX: 0,
  91. focusY: 0,
  92. dirty: false,
  93. }),
  94. });
  95. const initialPoll = ImmutableMap({
  96. options: ImmutableList(['', '']),
  97. expires_in: 24 * 3600,
  98. multiple: false,
  99. });
  100. function statusToTextMentions(state, status) {
  101. let set = ImmutableOrderedSet([]);
  102. if (status.getIn(['account', 'id']) !== me) {
  103. set = set.add(`@${status.getIn(['account', 'acct'])} `);
  104. }
  105. return set.union(status.get('mentions').filterNot(mention => mention.get('id') === me).map(mention => `@${mention.get('acct')} `)).join('');
  106. }
  107. function clearAll(state) {
  108. return state.withMutations(map => {
  109. map.set('id', null);
  110. map.set('text', '');
  111. map.set('spoiler', false);
  112. map.set('spoiler_text', '');
  113. map.set('is_submitting', false);
  114. map.set('is_changing_upload', false);
  115. map.set('in_reply_to', null);
  116. map.set('privacy', state.get('default_privacy'));
  117. map.set('sensitive', state.get('default_sensitive'));
  118. map.set('language', state.get('default_language'));
  119. map.update('media_attachments', list => list.clear());
  120. map.set('poll', null);
  121. map.set('idempotencyKey', uuid());
  122. });
  123. }
  124. function appendMedia(state, media, file) {
  125. const prevSize = state.get('media_attachments').size;
  126. return state.withMutations(map => {
  127. if (media.get('type') === 'image') {
  128. media = media.set('file', file);
  129. }
  130. map.update('media_attachments', list => list.push(media.set('unattached', true)));
  131. map.set('is_uploading', false);
  132. map.set('is_processing', false);
  133. map.set('resetFileKey', Math.floor((Math.random() * 0x10000)));
  134. map.set('idempotencyKey', uuid());
  135. map.update('pending_media_attachments', n => n - 1);
  136. if (prevSize === 0 && (state.get('default_sensitive') || state.get('spoiler'))) {
  137. map.set('sensitive', true);
  138. }
  139. });
  140. }
  141. function removeMedia(state, mediaId) {
  142. const prevSize = state.get('media_attachments').size;
  143. return state.withMutations(map => {
  144. map.update('media_attachments', list => list.filterNot(item => item.get('id') === mediaId));
  145. map.set('idempotencyKey', uuid());
  146. if (prevSize === 1) {
  147. map.set('sensitive', false);
  148. }
  149. });
  150. }
  151. const insertSuggestion = (state, position, token, completion, path) => {
  152. return state.withMutations(map => {
  153. map.updateIn(path, oldText => `${oldText.slice(0, position)}${completion} ${oldText.slice(position + token.length)}`);
  154. map.set('suggestion_token', null);
  155. map.set('suggestions', ImmutableList());
  156. if (path.length === 1 && path[0] === 'text') {
  157. map.set('focusDate', new Date());
  158. map.set('caretPosition', position + completion.length + 1);
  159. }
  160. map.set('idempotencyKey', uuid());
  161. });
  162. };
  163. const ignoreSuggestion = (state, position, token, completion, path) => {
  164. return state.withMutations(map => {
  165. map.updateIn(path, oldText => `${oldText.slice(0, position + token.length)} ${oldText.slice(position + token.length)}`);
  166. map.set('suggestion_token', null);
  167. map.set('suggestions', ImmutableList());
  168. map.set('focusDate', new Date());
  169. map.set('caretPosition', position + token.length + 1);
  170. map.set('idempotencyKey', uuid());
  171. });
  172. };
  173. const sortHashtagsByUse = (state, tags) => {
  174. const personalHistory = state.get('tagHistory').map(tag => tag.toLowerCase());
  175. const tagsWithLowercase = tags.map(t => ({ ...t, lowerName: t.name.toLowerCase() }));
  176. const sorted = tagsWithLowercase.sort((a, b) => {
  177. const usedA = personalHistory.includes(a.lowerName);
  178. const usedB = personalHistory.includes(b.lowerName);
  179. if (usedA === usedB) {
  180. return 0;
  181. } else if (usedA && !usedB) {
  182. return -1;
  183. } else {
  184. return 1;
  185. }
  186. });
  187. sorted.forEach(tag => delete tag.lowerName);
  188. return sorted;
  189. };
  190. const insertEmoji = (state, position, emojiData, needsSpace) => {
  191. const oldText = state.get('text');
  192. const emoji = needsSpace ? ' ' + emojiData.native : emojiData.native;
  193. return state.merge({
  194. text: `${oldText.slice(0, position)}${emoji} ${oldText.slice(position)}`,
  195. focusDate: new Date(),
  196. caretPosition: position + emoji.length + 1,
  197. idempotencyKey: uuid(),
  198. });
  199. };
  200. const privacyPreference = (a, b) => {
  201. const order = ['public', 'unlisted', 'private', 'direct'];
  202. return order[Math.max(order.indexOf(a), order.indexOf(b), 0)];
  203. };
  204. const hydrate = (state, hydratedState) => {
  205. state = clearAll(state.merge(hydratedState));
  206. if (hydratedState.get('text')) {
  207. state = state.set('text', hydratedState.get('text')).set('focusDate', new Date());
  208. }
  209. return state;
  210. };
  211. const domParser = new DOMParser();
  212. const expandMentions = status => {
  213. const fragment = domParser.parseFromString(status.get('content'), 'text/html').documentElement;
  214. status.get('mentions').forEach(mention => {
  215. fragment.querySelector(`a[href="${mention.get('url')}"]`).textContent = `@${mention.get('acct')}`;
  216. });
  217. return fragment.innerHTML;
  218. };
  219. const expiresInFromExpiresAt = expires_at => {
  220. if (!expires_at) return 24 * 3600;
  221. const delta = (new Date(expires_at).getTime() - Date.now()) / 1000;
  222. return [300, 1800, 3600, 21600, 86400, 259200, 604800].find(expires_in => expires_in >= delta) || 24 * 3600;
  223. };
  224. const mergeLocalHashtagResults = (suggestions, prefix, tagHistory) => {
  225. prefix = prefix.toLowerCase();
  226. if (suggestions.length < 4) {
  227. const localTags = tagHistory.filter(tag => tag.toLowerCase().startsWith(prefix) && !suggestions.some(suggestion => suggestion.type === 'hashtag' && suggestion.name.toLowerCase() === tag.toLowerCase()));
  228. return suggestions.concat(localTags.slice(0, 4 - suggestions.length).toJS().map(tag => ({ type: 'hashtag', name: tag })));
  229. } else {
  230. return suggestions;
  231. }
  232. };
  233. const normalizeSuggestions = (state, { accounts, emojis, tags, token }) => {
  234. if (accounts) {
  235. return accounts.map(item => ({ id: item.id, type: 'account' }));
  236. } else if (emojis) {
  237. return emojis.map(item => ({ ...item, type: 'emoji' }));
  238. } else {
  239. return mergeLocalHashtagResults(sortHashtagsByUse(state, tags.map(item => ({ ...item, type: 'hashtag' }))), token.slice(1), state.get('tagHistory'));
  240. }
  241. };
  242. const updateSuggestionTags = (state, token) => {
  243. const prefix = token.slice(1);
  244. const suggestions = state.get('suggestions').toJS();
  245. return state.merge({
  246. suggestions: ImmutableList(mergeLocalHashtagResults(suggestions, prefix, state.get('tagHistory'))),
  247. suggestion_token: token,
  248. });
  249. };
  250. export default function compose(state = initialState, action) {
  251. switch(action.type) {
  252. case STORE_HYDRATE:
  253. return hydrate(state, action.state.get('compose'));
  254. case COMPOSE_MOUNT:
  255. return state.set('mounted', state.get('mounted') + 1);
  256. case COMPOSE_UNMOUNT:
  257. return state
  258. .set('mounted', Math.max(state.get('mounted') - 1, 0))
  259. .set('is_composing', false);
  260. case COMPOSE_SENSITIVITY_CHANGE:
  261. return state.withMutations(map => {
  262. if (!state.get('spoiler')) {
  263. map.set('sensitive', !state.get('sensitive'));
  264. }
  265. map.set('idempotencyKey', uuid());
  266. });
  267. case COMPOSE_SPOILERNESS_CHANGE:
  268. return state.withMutations(map => {
  269. map.set('spoiler', !state.get('spoiler'));
  270. map.set('idempotencyKey', uuid());
  271. if (!state.get('sensitive') && state.get('media_attachments').size >= 1) {
  272. map.set('sensitive', true);
  273. }
  274. });
  275. case COMPOSE_SPOILER_TEXT_CHANGE:
  276. if (!state.get('spoiler')) return state;
  277. return state
  278. .set('spoiler_text', action.text)
  279. .set('idempotencyKey', uuid());
  280. case COMPOSE_VISIBILITY_CHANGE:
  281. return state
  282. .set('privacy', action.value)
  283. .set('idempotencyKey', uuid());
  284. case COMPOSE_CHANGE:
  285. return state
  286. .set('text', action.text)
  287. .set('idempotencyKey', uuid());
  288. case COMPOSE_COMPOSING_CHANGE:
  289. return state.set('is_composing', action.value);
  290. case COMPOSE_REPLY:
  291. return state.withMutations(map => {
  292. map.set('id', null);
  293. map.set('in_reply_to', action.status.get('id'));
  294. map.set('text', statusToTextMentions(state, action.status));
  295. map.set('privacy', privacyPreference(action.status.get('visibility'), state.get('default_privacy')));
  296. map.set('focusDate', new Date());
  297. map.set('caretPosition', null);
  298. map.set('preselectDate', new Date());
  299. map.set('idempotencyKey', uuid());
  300. map.update('media_attachments', list => list.filter(media => media.get('unattached')));
  301. if (action.status.get('language') && !action.status.has('translation')) {
  302. map.set('language', action.status.get('language'));
  303. } else {
  304. map.set('language', state.get('default_language'));
  305. }
  306. if (action.status.get('spoiler_text').length > 0) {
  307. map.set('spoiler', true);
  308. map.set('spoiler_text', action.status.get('spoiler_text'));
  309. if (map.get('media_attachments').size >= 1) {
  310. map.set('sensitive', true);
  311. }
  312. } else {
  313. map.set('spoiler', false);
  314. map.set('spoiler_text', '');
  315. }
  316. });
  317. case COMPOSE_SUBMIT_REQUEST:
  318. return state.set('is_submitting', true);
  319. case COMPOSE_UPLOAD_CHANGE_REQUEST:
  320. return state.set('is_changing_upload', true);
  321. case COMPOSE_REPLY_CANCEL:
  322. case COMPOSE_RESET:
  323. case COMPOSE_SUBMIT_SUCCESS:
  324. return clearAll(state);
  325. case COMPOSE_SUBMIT_FAIL:
  326. return state.set('is_submitting', false);
  327. case COMPOSE_UPLOAD_CHANGE_FAIL:
  328. return state.set('is_changing_upload', false);
  329. case COMPOSE_UPLOAD_REQUEST:
  330. return state.set('is_uploading', true).update('pending_media_attachments', n => n + 1);
  331. case COMPOSE_UPLOAD_PROCESSING:
  332. return state.set('is_processing', true);
  333. case COMPOSE_UPLOAD_SUCCESS:
  334. return appendMedia(state, fromJS(action.media), action.file);
  335. case COMPOSE_UPLOAD_FAIL:
  336. return state.set('is_uploading', false).set('is_processing', false).update('pending_media_attachments', n => n - 1);
  337. case COMPOSE_UPLOAD_UNDO:
  338. return removeMedia(state, action.media_id);
  339. case COMPOSE_UPLOAD_PROGRESS:
  340. return state.set('progress', Math.round((action.loaded / action.total) * 100));
  341. case THUMBNAIL_UPLOAD_REQUEST:
  342. return state.set('isUploadingThumbnail', true);
  343. case THUMBNAIL_UPLOAD_PROGRESS:
  344. return state.set('thumbnailProgress', Math.round((action.loaded / action.total) * 100));
  345. case THUMBNAIL_UPLOAD_FAIL:
  346. return state.set('isUploadingThumbnail', false);
  347. case THUMBNAIL_UPLOAD_SUCCESS:
  348. return state
  349. .set('isUploadingThumbnail', false)
  350. .update('media_attachments', list => list.map(item => {
  351. if (item.get('id') === action.media.id) {
  352. return fromJS(action.media);
  353. }
  354. return item;
  355. }));
  356. case INIT_MEDIA_EDIT_MODAL:
  357. const media = state.get('media_attachments').find(item => item.get('id') === action.id);
  358. return state.set('media_modal', ImmutableMap({
  359. id: action.id,
  360. description: media.get('description') || '',
  361. focusX: media.getIn(['meta', 'focus', 'x'], 0),
  362. focusY: media.getIn(['meta', 'focus', 'y'], 0),
  363. dirty: false,
  364. }));
  365. case COMPOSE_CHANGE_MEDIA_DESCRIPTION:
  366. return state.setIn(['media_modal', 'description'], action.description).setIn(['media_modal', 'dirty'], true);
  367. case COMPOSE_CHANGE_MEDIA_FOCUS:
  368. return state.setIn(['media_modal', 'focusX'], action.focusX).setIn(['media_modal', 'focusY'], action.focusY).setIn(['media_modal', 'dirty'], true);
  369. case COMPOSE_MENTION:
  370. return state.withMutations(map => {
  371. map.update('text', text => [text.trim(), `@${action.account.get('acct')} `].filter((str) => str.length !== 0).join(' '));
  372. map.set('focusDate', new Date());
  373. map.set('caretPosition', null);
  374. map.set('idempotencyKey', uuid());
  375. });
  376. case COMPOSE_DIRECT:
  377. return state.withMutations(map => {
  378. map.update('text', text => [text.trim(), `@${action.account.get('acct')} `].filter((str) => str.length !== 0).join(' '));
  379. map.set('privacy', 'direct');
  380. map.set('focusDate', new Date());
  381. map.set('caretPosition', null);
  382. map.set('idempotencyKey', uuid());
  383. });
  384. case COMPOSE_SUGGESTIONS_CLEAR:
  385. return state.update('suggestions', ImmutableList(), list => list.clear()).set('suggestion_token', null);
  386. case COMPOSE_SUGGESTIONS_READY:
  387. return state.set('suggestions', ImmutableList(normalizeSuggestions(state, action))).set('suggestion_token', action.token);
  388. case COMPOSE_SUGGESTION_SELECT:
  389. return insertSuggestion(state, action.position, action.token, action.completion, action.path);
  390. case COMPOSE_SUGGESTION_IGNORE:
  391. return ignoreSuggestion(state, action.position, action.token, action.completion, action.path);
  392. case COMPOSE_SUGGESTION_TAGS_UPDATE:
  393. return updateSuggestionTags(state, action.token);
  394. case COMPOSE_TAG_HISTORY_UPDATE:
  395. return state.set('tagHistory', fromJS(action.tags));
  396. case TIMELINE_DELETE:
  397. if (action.id === state.get('in_reply_to')) {
  398. return state.set('in_reply_to', null);
  399. } else if (action.id === state.get('id')) {
  400. return state.set('id', null);
  401. } else {
  402. return state;
  403. }
  404. case COMPOSE_EMOJI_INSERT:
  405. return insertEmoji(state, action.position, action.emoji, action.needsSpace);
  406. case COMPOSE_UPLOAD_CHANGE_SUCCESS:
  407. return state
  408. .set('is_changing_upload', false)
  409. .setIn(['media_modal', 'dirty'], false)
  410. .update('media_attachments', list => list.map(item => {
  411. if (item.get('id') === action.media.id) {
  412. return fromJS(action.media).set('unattached', !action.attached);
  413. }
  414. return item;
  415. }));
  416. case REDRAFT:
  417. return state.withMutations(map => {
  418. map.set('text', action.raw_text || unescapeHTML(expandMentions(action.status)));
  419. map.set('in_reply_to', action.status.get('in_reply_to_id'));
  420. map.set('privacy', action.status.get('visibility'));
  421. map.set('media_attachments', action.status.get('media_attachments').map((media) => media.set('unattached', true)));
  422. map.set('focusDate', new Date());
  423. map.set('caretPosition', null);
  424. map.set('idempotencyKey', uuid());
  425. map.set('sensitive', action.status.get('sensitive'));
  426. map.set('language', action.status.get('language'));
  427. map.set('id', null);
  428. if (action.status.get('spoiler_text').length > 0) {
  429. map.set('spoiler', true);
  430. map.set('spoiler_text', action.status.get('spoiler_text'));
  431. } else {
  432. map.set('spoiler', false);
  433. map.set('spoiler_text', '');
  434. }
  435. if (action.status.get('poll')) {
  436. map.set('poll', ImmutableMap({
  437. options: action.status.getIn(['poll', 'options']).map(x => x.get('title')),
  438. multiple: action.status.getIn(['poll', 'multiple']),
  439. expires_in: expiresInFromExpiresAt(action.status.getIn(['poll', 'expires_at'])),
  440. }));
  441. }
  442. });
  443. case COMPOSE_SET_STATUS:
  444. return state.withMutations(map => {
  445. map.set('id', action.status.get('id'));
  446. map.set('text', action.text);
  447. map.set('in_reply_to', action.status.get('in_reply_to_id'));
  448. map.set('privacy', action.status.get('visibility'));
  449. map.set('media_attachments', action.status.get('media_attachments'));
  450. map.set('focusDate', new Date());
  451. map.set('caretPosition', null);
  452. map.set('idempotencyKey', uuid());
  453. map.set('sensitive', action.status.get('sensitive'));
  454. map.set('language', action.status.get('language'));
  455. if (action.spoiler_text.length > 0) {
  456. map.set('spoiler', true);
  457. map.set('spoiler_text', action.spoiler_text);
  458. } else {
  459. map.set('spoiler', false);
  460. map.set('spoiler_text', '');
  461. }
  462. if (action.status.get('poll')) {
  463. map.set('poll', ImmutableMap({
  464. options: action.status.getIn(['poll', 'options']).map(x => x.get('title')),
  465. multiple: action.status.getIn(['poll', 'multiple']),
  466. expires_in: expiresInFromExpiresAt(action.status.getIn(['poll', 'expires_at'])),
  467. }));
  468. }
  469. });
  470. case COMPOSE_POLL_ADD:
  471. return state.set('poll', initialPoll);
  472. case COMPOSE_POLL_REMOVE:
  473. return state.set('poll', null);
  474. case COMPOSE_POLL_OPTION_ADD:
  475. return state.updateIn(['poll', 'options'], options => options.push(action.title));
  476. case COMPOSE_POLL_OPTION_CHANGE:
  477. return state.setIn(['poll', 'options', action.index], action.title);
  478. case COMPOSE_POLL_OPTION_REMOVE:
  479. return state.updateIn(['poll', 'options'], options => options.delete(action.index));
  480. case COMPOSE_POLL_SETTINGS_CHANGE:
  481. return state.update('poll', poll => poll.set('expires_in', action.expiresIn).set('multiple', action.isMultiple));
  482. case COMPOSE_LANGUAGE_CHANGE:
  483. return state.set('language', action.language);
  484. default:
  485. return state;
  486. }
  487. }