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.

83 lines
2.0 KiB

  1. import {
  2. SEARCH_CHANGE,
  3. SEARCH_SUGGESTIONS_READY,
  4. SEARCH_RESET
  5. } from '../actions/search';
  6. import Immutable from 'immutable';
  7. const initialState = Immutable.Map({
  8. value: '',
  9. loaded_value: '',
  10. suggestions: []
  11. });
  12. const normalizeSuggestions = (state, value, accounts, hashtags, statuses) => {
  13. let newSuggestions = [];
  14. if (accounts.length > 0) {
  15. newSuggestions.push({
  16. title: 'account',
  17. items: accounts.map(item => ({
  18. type: 'account',
  19. id: item.id,
  20. value: item.acct
  21. }))
  22. });
  23. }
  24. if (value.indexOf('@') === -1 && value.indexOf(' ') === -1 || hashtags.length > 0) {
  25. let hashtagItems = hashtags.map(item => ({
  26. type: 'hashtag',
  27. id: item,
  28. value: `#${item}`
  29. }));
  30. if (value.indexOf('@') === -1 && value.indexOf(' ') === -1 && !value.startsWith('http://') && !value.startsWith('https://') && hashtags.indexOf(value) === -1) {
  31. hashtagItems.unshift({
  32. type: 'hashtag',
  33. id: value,
  34. value: `#${value}`
  35. });
  36. }
  37. if (hashtagItems.length > 0) {
  38. newSuggestions.push({
  39. title: 'hashtag',
  40. items: hashtagItems
  41. });
  42. }
  43. }
  44. if (statuses.length > 0) {
  45. newSuggestions.push({
  46. title: 'status',
  47. items: statuses.map(item => ({
  48. type: 'status',
  49. id: item.id,
  50. value: item.id
  51. }))
  52. });
  53. }
  54. return state.withMutations(map => {
  55. map.set('suggestions', newSuggestions);
  56. map.set('loaded_value', value);
  57. });
  58. };
  59. export default function search(state = initialState, action) {
  60. switch(action.type) {
  61. case SEARCH_CHANGE:
  62. return state.set('value', action.value);
  63. case SEARCH_SUGGESTIONS_READY:
  64. return normalizeSuggestions(state, action.value, action.accounts, action.hashtags, action.statuses);
  65. case SEARCH_RESET:
  66. return state.withMutations(map => {
  67. map.set('suggestions', []);
  68. map.set('value', '');
  69. map.set('loaded_value', '');
  70. });
  71. default:
  72. return state;
  73. }
  74. };