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.

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