compose.js 19 KB

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