compose.js 19 KB

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