compose.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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');
  175. return tags.sort((a, b) => {
  176. const usedA = personalHistory.includes(a.name);
  177. const usedB = personalHistory.includes(b.name);
  178. if (usedA === usedB) {
  179. return 0;
  180. } else if (usedA && !usedB) {
  181. return -1;
  182. } else {
  183. return 1;
  184. }
  185. });
  186. };
  187. const insertEmoji = (state, position, emojiData, needsSpace) => {
  188. const oldText = state.get('text');
  189. const emoji = needsSpace ? ' ' + emojiData.native : emojiData.native;
  190. return state.merge({
  191. text: `${oldText.slice(0, position)}${emoji} ${oldText.slice(position)}`,
  192. focusDate: new Date(),
  193. caretPosition: position + emoji.length + 1,
  194. idempotencyKey: uuid(),
  195. });
  196. };
  197. const privacyPreference = (a, b) => {
  198. const order = ['public', 'unlisted', 'private', 'direct'];
  199. return order[Math.max(order.indexOf(a), order.indexOf(b), 0)];
  200. };
  201. const hydrate = (state, hydratedState) => {
  202. state = clearAll(state.merge(hydratedState));
  203. if (hydratedState.has('text')) {
  204. state = state.set('text', hydratedState.get('text'));
  205. }
  206. return state;
  207. };
  208. const domParser = new DOMParser();
  209. const expandMentions = status => {
  210. const fragment = domParser.parseFromString(status.get('content'), 'text/html').documentElement;
  211. status.get('mentions').forEach(mention => {
  212. fragment.querySelector(`a[href="${mention.get('url')}"]`).textContent = `@${mention.get('acct')}`;
  213. });
  214. return fragment.innerHTML;
  215. };
  216. const expiresInFromExpiresAt = expires_at => {
  217. if (!expires_at) return 24 * 3600;
  218. const delta = (new Date(expires_at).getTime() - Date.now()) / 1000;
  219. return [300, 1800, 3600, 21600, 86400, 259200, 604800].find(expires_in => expires_in >= delta) || 24 * 3600;
  220. };
  221. const mergeLocalHashtagResults = (suggestions, prefix, tagHistory) => {
  222. prefix = prefix.toLowerCase();
  223. if (suggestions.length < 4) {
  224. const localTags = tagHistory.filter(tag => tag.toLowerCase().startsWith(prefix) && !suggestions.some(suggestion => suggestion.type === 'hashtag' && suggestion.name.toLowerCase() === tag.toLowerCase()));
  225. return suggestions.concat(localTags.slice(0, 4 - suggestions.length).toJS().map(tag => ({ type: 'hashtag', name: tag })));
  226. } else {
  227. return suggestions;
  228. }
  229. };
  230. const normalizeSuggestions = (state, { accounts, emojis, tags, token }) => {
  231. if (accounts) {
  232. return accounts.map(item => ({ id: item.id, type: 'account' }));
  233. } else if (emojis) {
  234. return emojis.map(item => ({ ...item, type: 'emoji' }));
  235. } else {
  236. return mergeLocalHashtagResults(sortHashtagsByUse(state, tags.map(item => ({ ...item, type: 'hashtag' }))), token.slice(1), state.get('tagHistory'));
  237. }
  238. };
  239. const updateSuggestionTags = (state, token) => {
  240. const prefix = token.slice(1);
  241. const suggestions = state.get('suggestions').toJS();
  242. return state.merge({
  243. suggestions: ImmutableList(mergeLocalHashtagResults(suggestions, prefix, state.get('tagHistory'))),
  244. suggestion_token: token,
  245. });
  246. };
  247. export default function compose(state = initialState, action) {
  248. switch(action.type) {
  249. case STORE_HYDRATE:
  250. return hydrate(state, action.state.get('compose'));
  251. case COMPOSE_MOUNT:
  252. return state.set('mounted', state.get('mounted') + 1);
  253. case COMPOSE_UNMOUNT:
  254. return state
  255. .set('mounted', Math.max(state.get('mounted') - 1, 0))
  256. .set('is_composing', false);
  257. case COMPOSE_SENSITIVITY_CHANGE:
  258. return state.withMutations(map => {
  259. if (!state.get('spoiler')) {
  260. map.set('sensitive', !state.get('sensitive'));
  261. }
  262. map.set('idempotencyKey', uuid());
  263. });
  264. case COMPOSE_SPOILERNESS_CHANGE:
  265. return state.withMutations(map => {
  266. map.set('spoiler', !state.get('spoiler'));
  267. map.set('idempotencyKey', uuid());
  268. if (!state.get('sensitive') && state.get('media_attachments').size >= 1) {
  269. map.set('sensitive', true);
  270. }
  271. });
  272. case COMPOSE_SPOILER_TEXT_CHANGE:
  273. if (!state.get('spoiler')) return state;
  274. return state
  275. .set('spoiler_text', action.text)
  276. .set('idempotencyKey', uuid());
  277. case COMPOSE_VISIBILITY_CHANGE:
  278. return state
  279. .set('privacy', action.value)
  280. .set('idempotencyKey', uuid());
  281. case COMPOSE_CHANGE:
  282. return state
  283. .set('text', action.text)
  284. .set('idempotencyKey', uuid());
  285. case COMPOSE_COMPOSING_CHANGE:
  286. return state.set('is_composing', action.value);
  287. case COMPOSE_REPLY:
  288. return state.withMutations(map => {
  289. map.set('id', null);
  290. map.set('in_reply_to', action.status.get('id'));
  291. map.set('text', statusToTextMentions(state, action.status));
  292. map.set('privacy', privacyPreference(action.status.get('visibility'), state.get('default_privacy')));
  293. map.set('focusDate', new Date());
  294. map.set('caretPosition', null);
  295. map.set('preselectDate', new Date());
  296. map.set('idempotencyKey', uuid());
  297. if (action.status.get('language')) {
  298. map.set('language', action.status.get('language'));
  299. }
  300. if (action.status.get('spoiler_text').length > 0) {
  301. map.set('spoiler', true);
  302. map.set('spoiler_text', action.status.get('spoiler_text'));
  303. } else {
  304. map.set('spoiler', false);
  305. map.set('spoiler_text', '');
  306. }
  307. });
  308. case COMPOSE_SUBMIT_REQUEST:
  309. return state.set('is_submitting', true);
  310. case COMPOSE_UPLOAD_CHANGE_REQUEST:
  311. return state.set('is_changing_upload', true);
  312. case COMPOSE_REPLY_CANCEL:
  313. case COMPOSE_RESET:
  314. case COMPOSE_SUBMIT_SUCCESS:
  315. return clearAll(state);
  316. case COMPOSE_SUBMIT_FAIL:
  317. return state.set('is_submitting', false);
  318. case COMPOSE_UPLOAD_CHANGE_FAIL:
  319. return state.set('is_changing_upload', false);
  320. case COMPOSE_UPLOAD_REQUEST:
  321. return state.set('is_uploading', true).update('pending_media_attachments', n => n + 1);
  322. case COMPOSE_UPLOAD_PROCESSING:
  323. return state.set('is_processing', true);
  324. case COMPOSE_UPLOAD_SUCCESS:
  325. return appendMedia(state, fromJS(action.media), action.file);
  326. case COMPOSE_UPLOAD_FAIL:
  327. return state.set('is_uploading', false).set('is_processing', false).update('pending_media_attachments', n => n - 1);
  328. case COMPOSE_UPLOAD_UNDO:
  329. return removeMedia(state, action.media_id);
  330. case COMPOSE_UPLOAD_PROGRESS:
  331. return state.set('progress', Math.round((action.loaded / action.total) * 100));
  332. case THUMBNAIL_UPLOAD_REQUEST:
  333. return state.set('isUploadingThumbnail', true);
  334. case THUMBNAIL_UPLOAD_PROGRESS:
  335. return state.set('thumbnailProgress', Math.round((action.loaded / action.total) * 100));
  336. case THUMBNAIL_UPLOAD_FAIL:
  337. return state.set('isUploadingThumbnail', false);
  338. case THUMBNAIL_UPLOAD_SUCCESS:
  339. return state
  340. .set('isUploadingThumbnail', false)
  341. .update('media_attachments', list => list.map(item => {
  342. if (item.get('id') === action.media.id) {
  343. return fromJS(action.media);
  344. }
  345. return item;
  346. }));
  347. case INIT_MEDIA_EDIT_MODAL:
  348. const media = state.get('media_attachments').find(item => item.get('id') === action.id);
  349. return state.set('media_modal', ImmutableMap({
  350. id: action.id,
  351. description: media.get('description') || '',
  352. focusX: media.getIn(['meta', 'focus', 'x'], 0),
  353. focusY: media.getIn(['meta', 'focus', 'y'], 0),
  354. dirty: false,
  355. }));
  356. case COMPOSE_CHANGE_MEDIA_DESCRIPTION:
  357. return state.setIn(['media_modal', 'description'], action.description).setIn(['media_modal', 'dirty'], true);
  358. case COMPOSE_CHANGE_MEDIA_FOCUS:
  359. return state.setIn(['media_modal', 'focusX'], action.focusX).setIn(['media_modal', 'focusY'], action.focusY).setIn(['media_modal', 'dirty'], true);
  360. case COMPOSE_MENTION:
  361. return state.withMutations(map => {
  362. map.update('text', text => [text.trim(), `@${action.account.get('acct')} `].filter((str) => str.length !== 0).join(' '));
  363. map.set('focusDate', new Date());
  364. map.set('caretPosition', null);
  365. map.set('idempotencyKey', uuid());
  366. });
  367. case COMPOSE_DIRECT:
  368. return state.withMutations(map => {
  369. map.update('text', text => [text.trim(), `@${action.account.get('acct')} `].filter((str) => str.length !== 0).join(' '));
  370. map.set('privacy', 'direct');
  371. map.set('focusDate', new Date());
  372. map.set('caretPosition', null);
  373. map.set('idempotencyKey', uuid());
  374. });
  375. case COMPOSE_SUGGESTIONS_CLEAR:
  376. return state.update('suggestions', ImmutableList(), list => list.clear()).set('suggestion_token', null);
  377. case COMPOSE_SUGGESTIONS_READY:
  378. return state.set('suggestions', ImmutableList(normalizeSuggestions(state, action))).set('suggestion_token', action.token);
  379. case COMPOSE_SUGGESTION_SELECT:
  380. return insertSuggestion(state, action.position, action.token, action.completion, action.path);
  381. case COMPOSE_SUGGESTION_IGNORE:
  382. return ignoreSuggestion(state, action.position, action.token, action.completion, action.path);
  383. case COMPOSE_SUGGESTION_TAGS_UPDATE:
  384. return updateSuggestionTags(state, action.token);
  385. case COMPOSE_TAG_HISTORY_UPDATE:
  386. return state.set('tagHistory', fromJS(action.tags));
  387. case TIMELINE_DELETE:
  388. if (action.id === state.get('in_reply_to')) {
  389. return state.set('in_reply_to', null);
  390. } else {
  391. return state;
  392. }
  393. case COMPOSE_EMOJI_INSERT:
  394. return insertEmoji(state, action.position, action.emoji, action.needsSpace);
  395. case COMPOSE_UPLOAD_CHANGE_SUCCESS:
  396. return state
  397. .set('is_changing_upload', false)
  398. .setIn(['media_modal', 'dirty'], false)
  399. .update('media_attachments', list => list.map(item => {
  400. if (item.get('id') === action.media.id) {
  401. return fromJS(action.media).set('unattached', true);
  402. }
  403. return item;
  404. }));
  405. case REDRAFT:
  406. return state.withMutations(map => {
  407. map.set('text', action.raw_text || unescapeHTML(expandMentions(action.status)));
  408. map.set('in_reply_to', action.status.get('in_reply_to_id'));
  409. map.set('privacy', action.status.get('visibility'));
  410. map.set('media_attachments', action.status.get('media_attachments').map((media) => media.set('unattached', true)));
  411. map.set('focusDate', new Date());
  412. map.set('caretPosition', null);
  413. map.set('idempotencyKey', uuid());
  414. map.set('sensitive', action.status.get('sensitive'));
  415. map.set('language', action.status.get('language'));
  416. map.set('id', null);
  417. if (action.status.get('spoiler_text').length > 0) {
  418. map.set('spoiler', true);
  419. map.set('spoiler_text', action.status.get('spoiler_text'));
  420. } else {
  421. map.set('spoiler', false);
  422. map.set('spoiler_text', '');
  423. }
  424. if (action.status.get('poll')) {
  425. map.set('poll', ImmutableMap({
  426. options: action.status.getIn(['poll', 'options']).map(x => x.get('title')),
  427. multiple: action.status.getIn(['poll', 'multiple']),
  428. expires_in: expiresInFromExpiresAt(action.status.getIn(['poll', 'expires_at'])),
  429. }));
  430. }
  431. });
  432. case COMPOSE_SET_STATUS:
  433. return state.withMutations(map => {
  434. map.set('id', action.status.get('id'));
  435. map.set('text', action.text);
  436. map.set('in_reply_to', action.status.get('in_reply_to_id'));
  437. map.set('privacy', action.status.get('visibility'));
  438. map.set('media_attachments', action.status.get('media_attachments'));
  439. map.set('focusDate', new Date());
  440. map.set('caretPosition', null);
  441. map.set('idempotencyKey', uuid());
  442. map.set('sensitive', action.status.get('sensitive'));
  443. map.set('language', action.status.get('language'));
  444. if (action.spoiler_text.length > 0) {
  445. map.set('spoiler', true);
  446. map.set('spoiler_text', action.spoiler_text);
  447. } else {
  448. map.set('spoiler', false);
  449. map.set('spoiler_text', '');
  450. }
  451. if (action.status.get('poll')) {
  452. map.set('poll', ImmutableMap({
  453. options: action.status.getIn(['poll', 'options']).map(x => x.get('title')),
  454. multiple: action.status.getIn(['poll', 'multiple']),
  455. expires_in: expiresInFromExpiresAt(action.status.getIn(['poll', 'expires_at'])),
  456. }));
  457. }
  458. });
  459. case COMPOSE_POLL_ADD:
  460. return state.set('poll', initialPoll);
  461. case COMPOSE_POLL_REMOVE:
  462. return state.set('poll', null);
  463. case COMPOSE_POLL_OPTION_ADD:
  464. return state.updateIn(['poll', 'options'], options => options.push(action.title));
  465. case COMPOSE_POLL_OPTION_CHANGE:
  466. return state.setIn(['poll', 'options', action.index], action.title);
  467. case COMPOSE_POLL_OPTION_REMOVE:
  468. return state.updateIn(['poll', 'options'], options => options.delete(action.index));
  469. case COMPOSE_POLL_SETTINGS_CHANGE:
  470. return state.update('poll', poll => poll.set('expires_in', action.expiresIn).set('multiple', action.isMultiple));
  471. case COMPOSE_LANGUAGE_CHANGE:
  472. return state.set('language', action.language);
  473. default:
  474. return state;
  475. }
  476. };