The code powering m.abunchtell.com https://m.abunchtell.com
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

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