compose.js 18 KB

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