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.

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