The code powering m.abunchtell.com https://m.abunchtell.com
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

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