You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

431 lines
14 KiB

6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. import {
  2. COMPOSE_MOUNT,
  3. COMPOSE_UNMOUNT,
  4. COMPOSE_CHANGE,
  5. COMPOSE_CYCLE_ELEFRIEND,
  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_SUGGESTIONS_CLEAR,
  19. COMPOSE_SUGGESTIONS_READY,
  20. COMPOSE_SUGGESTION_SELECT,
  21. COMPOSE_SUGGESTION_TAGS_UPDATE,
  22. COMPOSE_TAG_HISTORY_UPDATE,
  23. COMPOSE_ADVANCED_OPTIONS_CHANGE,
  24. COMPOSE_SENSITIVITY_CHANGE,
  25. COMPOSE_SPOILERNESS_CHANGE,
  26. COMPOSE_SPOILER_TEXT_CHANGE,
  27. COMPOSE_VISIBILITY_CHANGE,
  28. COMPOSE_EMOJI_INSERT,
  29. COMPOSE_UPLOAD_CHANGE_REQUEST,
  30. COMPOSE_UPLOAD_CHANGE_SUCCESS,
  31. COMPOSE_UPLOAD_CHANGE_FAIL,
  32. COMPOSE_DOODLE_SET,
  33. COMPOSE_RESET,
  34. } from 'flavours/glitch/actions/compose';
  35. import { TIMELINE_DELETE } from 'flavours/glitch/actions/timelines';
  36. import { STORE_HYDRATE } from 'flavours/glitch/actions/store';
  37. import { REDRAFT } from 'flavours/glitch/actions/statuses';
  38. import { Map as ImmutableMap, List as ImmutableList, OrderedSet as ImmutableOrderedSet, fromJS } from 'immutable';
  39. import uuid from 'flavours/glitch/util/uuid';
  40. import { privacyPreference } from 'flavours/glitch/util/privacy_preference';
  41. import { me } from 'flavours/glitch/util/initial_state';
  42. import { overwrite } from 'flavours/glitch/util/js_helpers';
  43. import { unescapeHTML } from 'flavours/glitch/util/html';
  44. import { recoverHashtags } from 'flavours/glitch/util/hashtag';
  45. const totalElefriends = 3;
  46. // ~4% chance you'll end up with an unexpected friend
  47. // glitch-soc/mastodon repo created_at date: 2017-04-20T21:55:28Z
  48. const glitchProbability = 1 - 0.0420215528;
  49. const initialState = ImmutableMap({
  50. mounted: false,
  51. advanced_options: ImmutableMap({
  52. do_not_federate: false,
  53. threaded_mode: false,
  54. }),
  55. sensitive: false,
  56. elefriend: Math.random() < glitchProbability ? Math.floor(Math.random() * totalElefriends) : totalElefriends,
  57. spoiler: false,
  58. spoiler_text: '',
  59. privacy: null,
  60. text: '',
  61. focusDate: null,
  62. caretPosition: null,
  63. preselectDate: null,
  64. in_reply_to: null,
  65. is_submitting: false,
  66. is_uploading: false,
  67. is_changing_upload: false,
  68. progress: 0,
  69. media_attachments: ImmutableList(),
  70. suggestion_token: null,
  71. suggestions: ImmutableList(),
  72. default_advanced_options: ImmutableMap({
  73. do_not_federate: false,
  74. threaded_mode: null, // Do not reset
  75. }),
  76. default_privacy: 'public',
  77. default_sensitive: false,
  78. resetFileKey: Math.floor((Math.random() * 0x10000)),
  79. idempotencyKey: null,
  80. tagHistory: ImmutableList(),
  81. doodle: ImmutableMap({
  82. fg: 'rgb( 0, 0, 0)',
  83. bg: 'rgb(255, 255, 255)',
  84. swapped: false,
  85. mode: 'draw',
  86. size: 'normal',
  87. weight: 2,
  88. opacity: 1,
  89. adaptiveStroke: true,
  90. smoothing: false,
  91. }),
  92. });
  93. function statusToTextMentions(state, status) {
  94. let set = ImmutableOrderedSet([]);
  95. if (status.getIn(['account', 'id']) !== me) {
  96. set = set.add(`@${status.getIn(['account', 'acct'])} `);
  97. }
  98. return set.union(status.get('mentions').filterNot(mention => mention.get('id') === me).map(mention => `@${mention.get('acct')} `)).join('');
  99. };
  100. function apiStatusToTextMentions (state, status) {
  101. let set = ImmutableOrderedSet([]);
  102. if (status.account.id !== me) {
  103. set = set.add(`@${status.account.acct} `);
  104. }
  105. return set.union(status.mentions.filter(
  106. mention => mention.id !== me
  107. ).map(
  108. mention => `@${mention.acct} `
  109. )).join('');
  110. }
  111. function apiStatusToTextHashtags (state, status) {
  112. const text = unescapeHTML(status.content);
  113. return ImmutableOrderedSet([]).union(recoverHashtags(status.tags, text).map(
  114. (name) => `#${name} `
  115. )).join('');
  116. }
  117. function clearAll(state) {
  118. return state.withMutations(map => {
  119. map.set('text', '');
  120. map.set('spoiler', false);
  121. map.set('spoiler_text', '');
  122. map.set('is_submitting', false);
  123. map.set('is_changing_upload', false);
  124. map.set('in_reply_to', null);
  125. map.update(
  126. 'advanced_options',
  127. map => map.mergeWith(overwrite, state.get('default_advanced_options'))
  128. );
  129. map.set('privacy', state.get('default_privacy'));
  130. map.set('sensitive', false);
  131. map.update('media_attachments', list => list.clear());
  132. map.set('idempotencyKey', uuid());
  133. });
  134. };
  135. function continueThread (state, status) {
  136. return state.withMutations(function (map) {
  137. let text = apiStatusToTextMentions(state, status);
  138. text = text + apiStatusToTextHashtags(state, status);
  139. map.set('text', text);
  140. if (status.spoiler_text) {
  141. map.set('spoiler', true);
  142. map.set('spoiler_text', status.spoiler_text);
  143. } else {
  144. map.set('spoiler', false);
  145. map.set('spoiler_text', '');
  146. }
  147. map.set('is_submitting', false);
  148. map.set('in_reply_to', status.id);
  149. map.update(
  150. 'advanced_options',
  151. map => map.merge(new ImmutableMap({ do_not_federate: /👁\ufe0f?\u200b?(?:<\/p>)?$/.test(status.content) }))
  152. );
  153. map.set('privacy', status.visibility);
  154. map.set('sensitive', false);
  155. map.update('media_attachments', list => list.clear());
  156. map.set('idempotencyKey', uuid());
  157. map.set('focusDate', new Date());
  158. map.set('caretPosition', null);
  159. map.set('preselectDate', new Date());
  160. });
  161. }
  162. function appendMedia(state, media) {
  163. const prevSize = state.get('media_attachments').size;
  164. return state.withMutations(map => {
  165. map.update('media_attachments', list => list.push(media));
  166. map.set('is_uploading', false);
  167. map.set('resetFileKey', Math.floor((Math.random() * 0x10000)));
  168. map.set('idempotencyKey', uuid());
  169. if (prevSize === 0 && (state.get('default_sensitive') || state.get('spoiler'))) {
  170. map.set('sensitive', true);
  171. }
  172. });
  173. };
  174. function removeMedia(state, mediaId) {
  175. const prevSize = state.get('media_attachments').size;
  176. return state.withMutations(map => {
  177. map.update('media_attachments', list => list.filterNot(item => item.get('id') === mediaId));
  178. map.set('idempotencyKey', uuid());
  179. if (prevSize === 1) {
  180. map.set('sensitive', false);
  181. }
  182. });
  183. };
  184. const insertSuggestion = (state, position, token, completion) => {
  185. return state.withMutations(map => {
  186. map.update('text', oldText => `${oldText.slice(0, position)}${completion}${completion[0] === ':' ? '\u200B' : ' '}${oldText.slice(position + token.length)}`);
  187. map.set('suggestion_token', null);
  188. map.update('suggestions', ImmutableList(), list => list.clear());
  189. map.set('focusDate', new Date());
  190. map.set('caretPosition', position + completion.length + 1);
  191. map.set('idempotencyKey', uuid());
  192. });
  193. };
  194. const updateSuggestionTags = (state, token) => {
  195. const prefix = token.slice(1);
  196. return state.merge({
  197. suggestions: state.get('tagHistory')
  198. .filter(tag => tag.toLowerCase().startsWith(prefix.toLowerCase()))
  199. .slice(0, 4)
  200. .map(tag => '#' + tag),
  201. suggestion_token: token,
  202. });
  203. };
  204. const insertEmoji = (state, position, emojiData) => {
  205. const emoji = emojiData.native;
  206. return state.withMutations(map => {
  207. map.update('text', oldText => `${oldText.slice(0, position)}${emoji}\u200B${oldText.slice(position)}`);
  208. map.set('focusDate', new Date());
  209. map.set('caretPosition', position + emoji.length + 1);
  210. map.set('idempotencyKey', uuid());
  211. });
  212. };
  213. const hydrate = (state, hydratedState) => {
  214. state = clearAll(state.merge(hydratedState));
  215. if (hydratedState.has('text')) {
  216. state = state.set('text', hydratedState.get('text'));
  217. }
  218. return state;
  219. };
  220. const domParser = new DOMParser();
  221. const expandMentions = status => {
  222. const fragment = domParser.parseFromString(status.get('content'), 'text/html').documentElement;
  223. status.get('mentions').forEach(mention => {
  224. fragment.querySelector(`a[href="${mention.get('url')}"]`).textContent = `@${mention.get('acct')}`;
  225. });
  226. return fragment.innerHTML;
  227. };
  228. export default function compose(state = initialState, action) {
  229. switch(action.type) {
  230. case STORE_HYDRATE:
  231. return hydrate(state, action.state.get('compose'));
  232. case COMPOSE_MOUNT:
  233. return state.set('mounted', true);
  234. case COMPOSE_UNMOUNT:
  235. return state.set('mounted', false);
  236. case COMPOSE_ADVANCED_OPTIONS_CHANGE:
  237. return state
  238. .set('advanced_options', state.get('advanced_options').set(action.option, !!overwrite(!state.getIn(['advanced_options', action.option]), action.value)))
  239. .set('idempotencyKey', uuid());
  240. case COMPOSE_SENSITIVITY_CHANGE:
  241. return state.withMutations(map => {
  242. if (!state.get('spoiler')) {
  243. map.set('sensitive', !state.get('sensitive'));
  244. }
  245. map.set('idempotencyKey', uuid());
  246. });
  247. case COMPOSE_SPOILERNESS_CHANGE:
  248. return state.withMutations(map => {
  249. map.set('spoiler_text', '');
  250. map.set('spoiler', !state.get('spoiler'));
  251. map.set('idempotencyKey', uuid());
  252. if (!state.get('sensitive') && state.get('media_attachments').size >= 1) {
  253. map.set('sensitive', true);
  254. }
  255. });
  256. case COMPOSE_SPOILER_TEXT_CHANGE:
  257. return state
  258. .set('spoiler_text', action.text)
  259. .set('idempotencyKey', uuid());
  260. case COMPOSE_VISIBILITY_CHANGE:
  261. return state
  262. .set('privacy', action.value)
  263. .set('idempotencyKey', uuid());
  264. case COMPOSE_CHANGE:
  265. return state
  266. .set('text', action.text)
  267. .set('idempotencyKey', uuid());
  268. case COMPOSE_CYCLE_ELEFRIEND:
  269. return state
  270. .set('elefriend', (state.get('elefriend') + 1) % totalElefriends);
  271. case COMPOSE_REPLY:
  272. return state.withMutations(map => {
  273. map.set('in_reply_to', action.status.get('id'));
  274. map.set('text', statusToTextMentions(state, action.status));
  275. map.set('privacy', privacyPreference(action.status.get('visibility'), state.get('default_privacy')));
  276. map.update(
  277. 'advanced_options',
  278. map => map.merge(new ImmutableMap({ do_not_federate: /👁\ufe0f?\u200b?(?:<\/p>)?$/.test(action.status.get('content')) }))
  279. );
  280. map.set('focusDate', new Date());
  281. map.set('caretPosition', null);
  282. map.set('preselectDate', new Date());
  283. map.set('idempotencyKey', uuid());
  284. if (action.status.get('spoiler_text').length > 0) {
  285. let spoiler_text = action.status.get('spoiler_text');
  286. if (!spoiler_text.match(/^re[: ]/i)) {
  287. spoiler_text = 're: '.concat(spoiler_text);
  288. }
  289. map.set('spoiler', true);
  290. map.set('spoiler_text', spoiler_text);
  291. } else {
  292. map.set('spoiler', false);
  293. map.set('spoiler_text', '');
  294. }
  295. });
  296. case COMPOSE_REPLY_CANCEL:
  297. state = state.setIn(['advanced_options', 'threaded_mode'], false);
  298. case COMPOSE_RESET:
  299. return state.withMutations(map => {
  300. map.set('in_reply_to', null);
  301. map.set('text', '');
  302. map.set('spoiler', false);
  303. map.set('spoiler_text', '');
  304. map.set('privacy', state.get('default_privacy'));
  305. map.update(
  306. 'advanced_options',
  307. map => map.mergeWith(overwrite, state.get('default_advanced_options'))
  308. );
  309. map.set('idempotencyKey', uuid());
  310. });
  311. case COMPOSE_SUBMIT_REQUEST:
  312. return state.set('is_submitting', true);
  313. case COMPOSE_UPLOAD_CHANGE_REQUEST:
  314. return state.set('is_changing_upload', true);
  315. case COMPOSE_SUBMIT_SUCCESS:
  316. return action.status && state.getIn(['advanced_options', 'threaded_mode']) ? continueThread(state, action.status) : clearAll(state);
  317. case COMPOSE_SUBMIT_FAIL:
  318. return state.set('is_submitting', false);
  319. case COMPOSE_UPLOAD_CHANGE_FAIL:
  320. return state.set('is_changing_upload', false);
  321. case COMPOSE_UPLOAD_REQUEST:
  322. return state.set('is_uploading', true);
  323. case COMPOSE_UPLOAD_SUCCESS:
  324. return appendMedia(state, fromJS(action.media));
  325. case COMPOSE_UPLOAD_FAIL:
  326. return state.set('is_uploading', false);
  327. case COMPOSE_UPLOAD_UNDO:
  328. return removeMedia(state, action.media_id);
  329. case COMPOSE_UPLOAD_PROGRESS:
  330. return state.set('progress', Math.round((action.loaded / action.total) * 100));
  331. case COMPOSE_MENTION:
  332. return state.withMutations(map => {
  333. map.update('text', text => [text.trim(), `@${action.account.get('acct')} `].filter((str) => str.length !== 0).join(' '));
  334. map.set('focusDate', new Date());
  335. map.set('caretPosition', null);
  336. map.set('idempotencyKey', uuid());
  337. });
  338. case COMPOSE_DIRECT:
  339. return state.withMutations(map => {
  340. map.update('text', text => [text.trim(), `@${action.account.get('acct')} `].filter((str) => str.length !== 0).join(' '));
  341. map.set('privacy', 'direct');
  342. map.set('focusDate', new Date());
  343. map.set('caretPosition', null);
  344. map.set('idempotencyKey', uuid());
  345. });
  346. case COMPOSE_SUGGESTIONS_CLEAR:
  347. return state.update('suggestions', ImmutableList(), list => list.clear()).set('suggestion_token', null);
  348. case COMPOSE_SUGGESTIONS_READY:
  349. return state.set('suggestions', ImmutableList(action.accounts ? action.accounts.map(item => item.id) : action.emojis)).set('suggestion_token', action.token);
  350. case COMPOSE_SUGGESTION_SELECT:
  351. return insertSuggestion(state, action.position, action.token, action.completion);
  352. case COMPOSE_SUGGESTION_TAGS_UPDATE:
  353. return updateSuggestionTags(state, action.token);
  354. case COMPOSE_TAG_HISTORY_UPDATE:
  355. return state.set('tagHistory', fromJS(action.tags));
  356. case TIMELINE_DELETE:
  357. if (action.id === state.get('in_reply_to')) {
  358. return state.set('in_reply_to', null);
  359. } else {
  360. return state;
  361. }
  362. case COMPOSE_EMOJI_INSERT:
  363. return insertEmoji(state, action.position, action.emoji);
  364. case COMPOSE_UPLOAD_CHANGE_SUCCESS:
  365. return state
  366. .set('is_changing_upload', false)
  367. .update('media_attachments', list => list.map(item => {
  368. if (item.get('id') === action.media.id) {
  369. return fromJS(action.media);
  370. }
  371. return item;
  372. }));
  373. case COMPOSE_DOODLE_SET:
  374. return state.mergeIn(['doodle'], action.options);
  375. case REDRAFT:
  376. return state.withMutations(map => {
  377. map.set('text', unescapeHTML(expandMentions(action.status)));
  378. map.set('in_reply_to', action.status.get('in_reply_to_id'));
  379. map.set('privacy', action.status.get('visibility'));
  380. map.set('media_attachments', action.status.get('media_attachments'));
  381. map.set('focusDate', new Date());
  382. map.set('caretPosition', null);
  383. map.set('idempotencyKey', uuid());
  384. if (action.status.get('spoiler_text').length > 0) {
  385. map.set('spoiler', true);
  386. map.set('spoiler_text', action.status.get('spoiler_text'));
  387. } else {
  388. map.set('spoiler', false);
  389. map.set('spoiler_text', '');
  390. }
  391. });
  392. default:
  393. return state;
  394. }
  395. };