Example #1
0
export default function reports(state = initialState, action) {
  switch(action.type) {
  case REPORT_INIT:
    return state.withMutations(map => {
      map.setIn(['new', 'isSubmitting'], false);
      map.setIn(['new', 'account_id'], action.account.get('id'));

      if (state.getIn(['new', 'account_id']) !== action.account.get('id')) {
        map.setIn(['new', 'status_ids'], action.status ? ImmutableSet([action.status.getIn(['reblog', 'id'], action.status.get('id'))]) : ImmutableSet());
        map.setIn(['new', 'comment'], '');
      } else if (action.status) {
        map.updateIn(['new', 'status_ids'], ImmutableSet(), set => set.add(action.status.getIn(['reblog', 'id'], action.status.get('id'))));
      }
    });
  case REPORT_STATUS_TOGGLE:
    return state.updateIn(['new', 'status_ids'], ImmutableSet(), set => {
      if (action.checked) {
        return set.add(action.statusId);
      }

      return set.remove(action.statusId);
    });
  case REPORT_COMMENT_CHANGE:
    return state.setIn(['new', 'comment'], action.comment);
  case REPORT_FORWARD_CHANGE:
    return state.setIn(['new', 'forward'], action.forward);
  case REPORT_SUBMIT_REQUEST:
    return state.setIn(['new', 'isSubmitting'], true);
  case REPORT_SUBMIT_FAIL:
    return state.setIn(['new', 'isSubmitting'], false);
  case REPORT_CANCEL:
  case REPORT_SUBMIT_SUCCESS:
    return state.withMutations(map => {
      map.setIn(['new', 'account_id'], null);
      map.setIn(['new', 'status_ids'], ImmutableSet());
      map.setIn(['new', 'comment'], '');
      map.setIn(['new', 'isSubmitting'], false);
    });
  default:
    return state;
  }
};
 updateAccountIds() {
     var new_account_ids = Immutable.Set().withMutations(new_ids => {
         var updatePubkey = public_string => {
             var chain_account_ids = ChainStore.getAccountRefsOfKey(
                 public_string
             );
             if (chain_account_ids)
                 chain_account_ids.forEach(chain_account_id => {
                     new_ids.add(chain_account_id);
                 });
         };
         this.derived_keys.forEach(derived_key =>
             updatePubkey(derived_key.public_string)
         );
     });
     if (!new_account_ids.equals(this.state.account_ids)) {
         this.state.account_ids = new_account_ids;
         this.setState({account_ids: new_account_ids});
     }
 }
  resetInitialFilters = (filterId, parameterName) => {
    let { initialValuesNulled } = this.state;
    let filterParams = initialValuesNulled.get(filterId);

    if (!filterParams && parameterName) {
      filterParams = Set([parameterName]);
    } else if (filterParams && parameterName) {
      filterParams = filterParams.add(parameterName);
    }

    if (!parameterName) {
      initialValuesNulled = initialValuesNulled.delete(filterId);
    } else {
      initialValuesNulled = initialValuesNulled.set(filterId, filterParams);
    }

    this.setState({
      initialValuesNulled,
    });
  };
Example #4
0
export function* findSigningKey({opType, username, password}) {
    let authTypes
    if (postingOps.has(opType))
        authTypes = 'posting, active'
    else
        authTypes = 'active, owner'
    authTypes = authTypes.split(', ')

    const currentUser = yield select(state => state.user.get('current'))
    const currentUsername = currentUser && currentUser.get('username')

    username = username || currentUsername
    if (!username) return null

    const private_keys = currentUsername === username ? currentUser.get('private_keys') : Map()

    const account = yield call(getAccount, username);
    if (!account) throw new Error('Account not found')

    for (const authType of authTypes) {
        let private_key
        if (password) {
            try {
                private_key = PrivateKey.fromWif(password)
            } catch (e) {
                private_key = PrivateKey.fromSeed(username + authType + password)
            }
        } else {
            if(private_keys)
                private_key = private_keys.get(authType + '_private')
        }
        if (private_key) {
            const pubkey = private_key.toPublicKey().toString()
            const pubkeys = Set([pubkey])
            const authority = account.get(authType)
            const auth = yield call(authorityLookup, {pubkeys, authority, authType})
            if (auth === 'full') return private_key
        }
    }
    return null
}
Example #5
0
        _loadHistoryState: function (payload) {
            // TODO validate that count and next are not crazy values
            var documentID = payload.documentID,
                count = payload.count || 0,
                history = this._history.get(documentID),
                current = this._current.get(documentID),
                nextIndex,
                nextState;

            if (!history || !current) {
                throw new Error("Trying to change history, but none is found for document: " + documentID);
            }

            nextIndex = payload.index ? payload.index : (current + count);
            nextState = history.get(nextIndex);
            if (!nextState) {
                throw new Error("No history state found at index " + nextIndex);
            }

            // update the current pointer
            this._current = this._current.set(documentID, nextIndex);

            if (!nextState.document) {
                throw new Error("Could not find a valid document for the requested state");
            } else {
                var nextDocument = nextState.document;

                if (payload.selectedIndices) {
                    var selectedLayers = Immutable.Set(payload.selectedIndices.map(function (index) {
                            return nextDocument.layers.byIndex(index + 1).id;
                        })),
                        nextLayers = nextDocument.layers.updateSelection(selectedLayers);
                        
                    nextDocument = nextDocument.set("layers", nextLayers);
                }

                // this will emit its own change
                this.flux.store("document").setDocument(nextDocument);
                this.emit("timetravel");
            }
        },
Example #6
0
export function loadState(reactorState, state) {
  let dirtyStores = []
  const stateToLoad = toImmutable({}).withMutations(stateToLoad => {
    each(state, (serializedStoreState, storeId) => {
      const store = reactorState.getIn(['stores', storeId])
      if (store) {
        const storeState = store.deserialize(serializedStoreState)
        if (storeState !== undefined) {
          stateToLoad.set(storeId, storeState)
          dirtyStores.push(storeId)
        }
      }
    })
  })

  const dirtyStoresSet = Immutable.Set(dirtyStores)
  return reactorState
    .update('state', state => state.merge(stateToLoad))
    .update('dirtyStores', stores => stores.union(dirtyStoresSet))
    .update('storeStates', storeStates => incrementStoreStates(storeStates, dirtyStores))
}
Example #7
0
  (selectedNodeId, nodes) => {
    if (!selectedNodeId || nodes.isEmpty()) {
      return [];
    }

    // The selected node always goes in focus.
    let focusedNodes = makeSet([selectedNodeId]);

    // Add all the nodes the selected node is connected to...
    focusedNodes = focusedNodes.merge(nodes.getIn([selectedNodeId, 'adjacency']) || makeList());

    // ... and also all the nodes that connect to the selected one.
    nodes.forEach((node, nodeId) => {
      const adjacency = node.get('adjacency') || makeList();
      if (adjacency.includes(selectedNodeId)) {
        focusedNodes = focusedNodes.add(nodeId);
      }
    });

    return focusedNodes.toArray();
  }
Example #8
0
  constructor(props) {
    super(props)

    this.state = {
      moments: Map(),
      locations: Map(),
      places: Map(),
      users: Map(),
      visibleMoments: Set(),
      lastMomentTimestamp: null,
      isLoading: false,
    }

    this.resetState = this.resetState.bind(this)
    this.refreshTimeline = this.refreshTimeline.bind(this)
    this.fetchTimeline = this.fetchTimeline.bind(this)
    this.fetchMoment = this.fetchMoment.bind(this)
    this.mergeTimeline = this.mergeTimeline.bind(this)
    this.handleLoadMore = this.handleLoadMore.bind(this)
    this.handleVisibilityChange = this.handleVisibilityChange.bind(this)
  }
const getBlockMapSupportedTags = (
  blockRenderMap: DraftBlockRenderMap,
): Array<string> => {
  const unstyledElement = blockRenderMap.get('unstyled').element;
  let tags = Set([]);

  blockRenderMap.forEach((draftBlock: DraftBlockRenderConfig) => {
    if (draftBlock.aliasedElements) {
      draftBlock.aliasedElements.forEach(tag => {
        tags = tags.add(tag);
      });
    }

    tags = tags.add(draftBlock.element);
  });

  return tags
    .filter(tag => tag && tag !== unstyledElement)
    .toArray()
    .sort();
};
const defaultProps = (props = {}) => (
  Object.assign({
    outcomeGroup: {
      id: 10,
      title: 'My group'
    },
    outcomes: [
      {
        id: 1,
        expansionId: 100,
        mastered: false,
        mastery_points: 3,
        points_possible: 5,
        calculation_method: 'highest',
        ratings: [
          { description: 'My first rating' },
          { description: 'My second rating' }
        ],
        results: [
          {
            id: 1,
            score: 1,
            percent: 0.1,
            assignment: {
              id: 1,
              html_url: 'http://foo',
              name: 'My assignment',
              submission_types: 'online_quiz'
            }
          }
        ],
        title: 'My outcome'
      }
    ],
    expanded: false,
    expandedOutcomes: Set(),
    onExpansionChange: () => {}
  }, props)
)
Example #11
0
File: db.js Project: joewang704/cow
 return Promise.all([getGroups(), getItems()]).then(([groups, items]) => {
   const groupKeys = Object.keys(groups).map(
     key => parseInt(key)
   )
   const todoKeys = Object.keys(items).map(
     key => parseInt(key)
   ).filter((key) => items[key].checkable)
   const eventKeys = Object.keys(items).map(
     key => parseInt(key)
   ).filter((key) => items[key].startTime)
   return {
     entities: fromJS({
       blocks: { nextBlockId: 0 },
       groups,
       items,
     }),
     groups: List(groupKeys),
     todos: OrderedSet(todoKeys),
     events: Set(eventKeys),
     sidebar: fromJS({})
   }
 })
Example #12
0
 loadData: function (data) {
     _data = data.configuration;
     _probes = data.configuration.probes;
     _taskToProbe = Immutable.Map(
         _.chain(_probes)
         .map(function(p) {return _.map(p.tasks, function(t) {return [t.id, p.id]})})
         .flatten()
         .value());
     _taskToRecordingTask = Immutable.Map(
         _.chain(_probes)
         .pluck('tasks')
         .flatten()
         .map(function(t) {return [t.id, t.relatedRecordingTaskId]})
         .value());
     _alertReports = data.parameterStates;
     _disabledGroups = Immutable.Set();
     _channelId = data.channelId;
     _channelName = data.channelName;
     _interval = {start: data.startDate, end: data.endDate};
     _selectedInterval = _interval;
     _isDataLoaded = true;
     this.emitChange();
 },
const mapStateToProps = (state) => {
  const activities = state.get('daySelectorReducer').get('activities');
  const uniqueDates = Set(activities.map((a) => moment(a.date).clone().startOf('day')))
    .toArray()
    .filter((d) => moment().startOf('day').diff(d) <= 0)
    .sort((left, right) => {
      return left.diff(right)
    })
  uniqueDates.forEach((x) => console.log(x));
  const dateSelected = state.get('daySelectorReducer').get('dateSelected');
  const selectedDayActivities = activities.filter((a) => {
    const startOfIterDate = a.date.clone().startOf('day');
    const startOfDateSelected = dateSelected.clone().startOf('day');
    return startOfDateSelected.diff(startOfIterDate) === 0;
  })
  return {
    title: state.get('daySelectorReducer').get('title'),
    activities,
    dateSelected,
    selectedDayActivities,
    uniqueDates,
  };
};
Example #14
0
  it('renders notes on the judgement line when the scroll offset matches the note offset', () => {
    const offsetPositionYPercent = 0.9;
    const offset = 20 * 24 + 12;

    const note = new Note({
      col: 0,
      totalOffset: offset,
    });

    const ctx = new MockContext();

    const offsetBarY = (1 - offsetPositionYPercent) * HEIGHT;

    renderNotes(ctx, {
      colors: playerColors,
      notes: I.Set([note]),
      beatSpacing: 160,
      offset,
      offsetBarY,
    });

    expect(ctx.fillRect.calls.length).toEqual(1);
    expect(ctx.fillRect.calls[0].arguments[1]).toEqual(offsetBarY - (NOTE_HEIGHT / 2));
  });
 _migrateUnfollowedAccounts(state) {
     try {
         let unfollowed_accounts = accountStorage.get(
             "unfollowed_accounts",
             []
         );
         let hiddenAccounts = accountStorage.get(
             this._getStorageKey("hiddenAccounts", state),
             []
         );
         if (unfollowed_accounts.length && !hiddenAccounts.length) {
             accountStorage.set(
                 this._getStorageKey("hiddenAccounts", state),
                 unfollowed_accounts
             );
             accountStorage.remove("unfollowed_accounts");
             this.setState({
                 myHiddenAccounts: Immutable.Set(unfollowed_accounts)
             });
         }
     } catch (err) {
         console.error(err);
     }
 }
Example #16
0
 (parameters, resources, environment) => {
   return (
     resources
       // get list of resources from environment resource_registry
       .filter(r => environment.resourceRegistry.keySeq().includes(r.type))
       // collect parameter names from those resources
       .reduce(
         (result, resource) =>
           result.union(
             _extractParameters(
               resource.parameters,
               resource.resources,
               resources
             )
           ),
         Set()
       )
       // add parameters from environment's 'parameters' section to the list
       .union(environment.parameterDefaults.keySeq())
       .toMap()
       // convert list of parameter names to map of actual parameter records
       .update(filterParameters(parameters))
   );
 }
Example #17
0
 constructor () {
   super()
   this.onChangeSearch = this.onChangeSearch.bind(this)
   this.onClearSearchText = this.onClearSearchText.bind(this)
   this.clearBrowsingDataNow = this.clearBrowsingDataNow.bind(this)
   this.clearSelection = this.clearSelection.bind(this)
   this.onClick = this.onClick.bind(this)
   this.state = {
     history: Immutable.List(),
     search: '',
     settings: Immutable.Map(),
     languageCodes: Immutable.Map(),
     selection: Immutable.Set(),
     updatedStamp: undefined
   }
   ipc.on(messages.HISTORY_UPDATED, (e, detail) => {
     const aboutHistory = Immutable.fromJS(detail || {})
     const updatedStamp = aboutHistory.get('updatedStamp')
     // Only update if the data has changed.
     if (typeof updatedStamp === 'number' &&
         typeof this.state.updatedStamp === 'number' &&
         updatedStamp === this.state.updatedStamp) {
       return
     }
     this.setState({
       history: aboutHistory.get('entries') || new Immutable.List(),
       updatedStamp: updatedStamp
     })
   })
   ipc.on(messages.SETTINGS_UPDATED, (e, settings) => {
     this.setState({ settings: Immutable.fromJS(settings || {}) })
   })
   ipc.on(messages.LANGUAGE, (e, {languageCodes}) => {
     this.setState({ languageCodes })
   })
 }
Example #18
0
export default function stubImmutableSet() {
  return Set([])
}
Example #19
0
it ('isMessageSuitedForFilters', () => {
	const message = {
		shortGroupName: 'c.f.s.SearchEngine',
		host: 'http://search-coord2.akod.loc',
		thread: 'qtp-123'
	};

	const shouldBeSuited = filters => expect(isMessageSuitedForFilters(message, filters)).toBeTruthy();
	const shouldNotBeSuited = filters => expect(isMessageSuitedForFilters(message, filters)).toBeFalsy();

	[
		emptyFilters(),
		buildFilters(Set(['http://search-coord2.akod.loc']), Set(['c.f.s.SearchEngine']), Set(['qtp-123']))
	].forEach(fs => shouldBeSuited(fs));

	[
		buildFilters(Set(['http://anotherHost']), Set(), Set()),
		buildFilters(Set(), Set(['another_package']), Set()),
		buildFilters(Set(), Set(), Set(['another_thread']))
	].forEach(fs => shouldNotBeSuited(fs));
});
Example #20
0
 it('supports a sequence of values from Immutable.Set', () => {
   expect(Immutable.Seq(Immutable.Set([0, 1, 2]))).toPrettyPrintTo(
     'Immutable.Seq [\n  0,\n  1,\n  2,\n]',
   );
 });
Example #21
0
import { fork, call, put, select, takeEvery } from 'redux-saga/effects';
import {Set, Map, fromJS, List} from 'immutable'
import user from 'app/redux/User'
import {getAccount} from 'app/redux/SagaShared'
import {PrivateKey} from 'golos-js/lib/auth/ecc';
import {api} from 'golos-js';

// operations that require only posting authority
const postingOps = Set(`vote, comment, delete_comment, custom_json, account_metadata`.trim().split(/,\s*/))

export function* authWatches() {
    yield fork(watchForAuth) 
}

function* watchForAuth() {
    yield takeEvery('user/ACCOUNT_AUTH_LOOKUP', accountAuthLookup);
}

export function* accountAuthLookup({payload: {account, private_keys, login_owner_pubkey}}) {
    account = fromJS(account)
    private_keys = fromJS(private_keys)
    // console.log('accountAuthLookup', account.name)
    const stateUser = yield select(state => state.user)
    let keys
    if (private_keys)
        keys = private_keys
    else
        keys = stateUser.getIn(['current', 'private_keys'])

    if (!keys || !keys.has('posting_private')) return
    const toPub = k => k ? k.toPublicKey().toString() : '-'
Example #22
0
function* usernamePasswordLogin2({payload: {username, password, saveLogin,
        operationType /*high security*/, afterLoginRedirectToAccount
}}) {
    // login, using saved password
    let autopost, memoWif, login_owner_pubkey, login_wif_owner_pubkey
    if (!username && !password) {
        const data = localStorage.getItem('autopost2')
        if (data) { // auto-login with a low security key (like a posting key)
            autopost = true; // must use simi-colon
            // The 'password' in this case must be the posting private wif .. See setItme('autopost')
            [username, password, memoWif, login_owner_pubkey] = new Buffer(data, 'hex').toString().split('\t');
            memoWif = clean(memoWif);
            login_owner_pubkey = clean(login_owner_pubkey);
        }
    }
    // no saved password
    if (!username || !password) return

    let userProvidedRole // login via:  username/owner
    if (username.indexOf('/') > -1) {
        // "alice/active" will login only with Alices active key
        [username, userProvidedRole] = username.split('/')
    }
    const highSecurityLogin =
        /owner|active/.test(userProvidedRole) ||
        isHighSecurityOperations.indexOf(operationType) !== -1

    const isRole = (role, fn) => (!userProvidedRole || role === userProvidedRole ? fn() : undefined)

    const account = yield call(getAccount, username)
    if (!account) {
        yield put(user.actions.loginError({ error: 'Username does not exist' }))
        return
    }

    let private_keys
    try {
        const private_key = PrivateKey.fromWif(password)
        login_wif_owner_pubkey = private_key.toPublicKey().toString()
        private_keys = fromJS({
            posting_private: isRole('posting', () => private_key),
            active_private: isRole('active', () => private_key),
            memo_private: private_key,
        })
    } catch (e) {
        // Password (non wif)
        login_owner_pubkey = PrivateKey.fromSeed(username + 'owner' + password).toPublicKey().toString()
        private_keys = fromJS({
            posting_private: isRole('posting', () => PrivateKey.fromSeed(username + 'posting' + password)),
            active_private: isRole('active', () => PrivateKey.fromSeed(username + 'active' + password)),
            memo_private: PrivateKey.fromSeed(username + 'memo' + password),
        })
    }
    if (memoWif)
        private_keys = private_keys.set('memo_private', PrivateKey.fromWif(memoWif))

    yield call(accountAuthLookup, {payload: {account, private_keys, highSecurityLogin, login_owner_pubkey}})
    const authority = yield select(state => state.user.getIn(['authority', username]))
    const fullAuths = authority.reduce((r, auth, type) => (auth === 'full' ? r.add(type) : r), Set())
    if (!fullAuths.size) {
        localStorage.removeItem('autopost2')
        const owner_pub_key = account.getIn(['owner', 'key_auths', 0, 0]);
        // const pub_keys = yield select(state => state.user.get('pub_keys_used'))
        // serverApiRecordEvent('login_attempt', JSON.stringify({name: username, ...pub_keys, cur_owner: owner_pub_key}))
        if (owner_pub_key === 'STM7sw22HqsXbz7D2CmJfmMwt9rimtk518dRzsR1f8Cgw52dQR1pR') {
            yield put(user.actions.loginError({ error: 'Hello. Your account may have been compromised. We are working on restoring an access to your account. Please send an email to support@steemit.com.' }))
            return
        }
        if(login_owner_pubkey === owner_pub_key || login_wif_owner_pubkey === owner_pub_key) {
            yield put(user.actions.loginError({ error: 'owner_login_blocked' }))
        } else {
            const generated_type = password[0] === 'P' && password.length > 40;
            serverApiRecordEvent('login_attempt', JSON.stringify({name: username, login_owner_pubkey, owner_pub_key, generated_type}))
            yield put(user.actions.loginError({ error: 'Incorrect Password' }))
        }
        return
    }
    if (authority.get('posting') !== 'full')
        private_keys = private_keys.remove('posting_private')

    if(!highSecurityLogin || authority.get('active') !== 'full')
        private_keys = private_keys.remove('active_private')

    const owner_pubkey = account.getIn(['owner', 'key_auths', 0, 0])
    const active_pubkey = account.getIn(['active', 'key_auths', 0, 0])
    const posting_pubkey = account.getIn(['posting', 'key_auths', 0, 0])

    if (private_keys.get('memo_private') &&
        account.get('memo_key') !== private_keys.get('memo_private').toPublicKey().toString()
    )
        // provided password did not yield memo key
        private_keys = private_keys.remove('memo_private')

    if(!highSecurityLogin) {
        if(
            posting_pubkey === owner_pubkey ||
            posting_pubkey === active_pubkey
        ) {
            yield put(user.actions.loginError({ error: 'This login gives owner or active permissions and should not be used here.  Please provide a posting only login.' }))
            localStorage.removeItem('autopost2')
            return
        }
    }
    const memo_pubkey = private_keys.has('memo_private') ?
        private_keys.get('memo_private').toPublicKey().toString() : null

    if(
        memo_pubkey === owner_pubkey ||
        memo_pubkey === active_pubkey
    )
        // Memo key could be saved in local storage.. In RAM it is not purged upon LOCATION_CHANGE
        private_keys = private_keys.remove('memo_private')

    // If user is signing operation by operaion and has no saved login, don't save to RAM
    if(!operationType || saveLogin)
        // Keep the posting key in RAM but only when not signing an operation.
        // No operation or the user has checked: Keep me logged in...
        yield put(user.actions.setUser({username, private_keys, login_owner_pubkey}))

    if (!autopost && saveLogin)
        yield put(user.actions.saveLogin());

    serverApiLogin(username);
    if (afterLoginRedirectToAccount) browserHistory.push('/@' + username);
}
Example #23
0
 iS: function(v) {
   return Immutable.Set(v);
 },
Example #24
0
 votes => (approve ? Set(votes).add(witness) : Set(votes).remove(witness)))
Example #25
0
 reducer: (state, {payload: {account, witness, approve}}) =>
     state.updateIn(['accounts', account, 'witness_votes'], Set(),
         votes => (approve ? Set(votes).add(witness) : Set(votes).remove(witness)))
Example #26
0
const mapStateToProps = (state: TypedState, {routeProps}) => ({
  _teams: state.entities.getIn(['teams', 'teamnames'], I.Set()),
  error: Constants.getError(state),
  isTeam: routeProps.get('isTeam'),
  loading: Constants.getLoading(state),
})
Example #27
0
File: main.js Project: srdb/nuclide
export function deactivate(): void {
  gadgetsApi = null;
  allHomeFragmentsStream.next(Immutable.Set());
  subscriptions.dispose();
  subscriptions = (null: any);
}
Example #28
0
File: main.js Project: srdb/nuclide
import type {GadgetsService} from '../../nuclide-gadgets';
import type {HomeFragments} from './types';

export type {HomeFragments} from './types';

import {CompositeDisposable, Disposable} from 'atom';
import featureConfig from '../../nuclide-feature-config';
import Immutable from 'immutable';
import Rx from 'rxjs';

let subscriptions: CompositeDisposable = (null: any);
let gadgetsApi: ?GadgetsService = null;

// A stream of all of the fragments. This is essentially the state of our panel.
const allHomeFragmentsStream: Rx.BehaviorSubject<Immutable.Set<HomeFragments>> =
  new Rx.BehaviorSubject(Immutable.Set());

export function activate(state: ?Object): void {
  considerDisplayingHome();
  subscriptions = new CompositeDisposable();
  subscriptions.add(
    atom.commands.add('atom-workspace', 'nuclide-home:show-settings', () => {
      atom.workspace.open('atom://config/packages/nuclide');
    })
  );
}

export function setHomeFragments(homeFragments: HomeFragments): Disposable {
  allHomeFragmentsStream.next(allHomeFragmentsStream.getValue().add(homeFragments));
  return new Disposable(() => {
    allHomeFragmentsStream.next(allHomeFragmentsStream.getValue().remove(homeFragments));
function* postMessage(action: ChatGen.PostMessagePayload): SagaGenerator<any, any> {
  let {conversationIDKey} = action.payload
  let newConvoTlfName

  if (Constants.isPendingConversationIDKey(conversationIDKey)) {
    // Get a real conversationIDKey
    ;[conversationIDKey, newConvoTlfName] = yield Saga.call(Shared.startNewConversation, conversationIDKey)
    if (!conversationIDKey) {
      return
    }
  }

  // Note: This should happen *after* startNewConversation, because
  // startNewConversation() uses the presence of a pendingConversation
  // that is deleted by exitSearch().
  const inSearch = yield Saga.select((state: TypedState) => state.chat.get('inSearch'))
  if (inSearch) {
    yield Saga.put(ChatGen.createExitSearch({skipSelectPreviousConversation: false}))
  }

  const [inboxConvo, lastMessageID]: [Constants.InboxState, ?Constants.MessageID] = yield Saga.all([
    Saga.select(Constants.getInbox, conversationIDKey),
    Saga.select(Constants.lastMessageID, conversationIDKey),
  ])

  const outboxID = yield Saga.call(RPCChatTypes.localGenerateOutboxIDRpcPromise)
  const author = yield Saga.select(usernameSelector)
  const outboxIDKey = Constants.outboxIDToKey(outboxID)

  const message: Constants.TextMessage = {
    author,
    channelMention: 'None',
    conversationIDKey: conversationIDKey,
    deviceName: '',
    deviceType: isMobile ? 'mobile' : 'desktop',
    editedCount: 0,
    failureDescription: '',
    key: Constants.messageKey(conversationIDKey, 'outboxIDText', outboxIDKey),
    mentions: I.Set(),
    message: new HiddenString(action.payload.text.stringValue()),
    messageState: 'pending',
    outboxID: outboxIDKey,
    rawMessageID: -1,
    senderDeviceRevokedAt: null,
    timestamp: Date.now(),
    type: 'Text',
    you: author,
  }

  const selectedConversation = yield Saga.select(Constants.getSelectedConversation)
  const appFocused = yield Saga.select(Shared.focusedSelector)

  yield Saga.put(
    ChatGen.createAppendMessages({
      conversationIDKey,
      isSelected: conversationIDKey === selectedConversation,
      isAppFocused: appFocused,
      messages: [message],
      svcShouldDisplayNotification: false,
    })
  )

  yield Saga.call(RPCChatTypes.localPostTextNonblockRpcPromise, {
    param: {
      conversationID: Constants.keyToConversationID(conversationIDKey),
      tlfName: (inboxConvo ? inboxConvo.name : newConvoTlfName) || '',
      tlfPublic: false,
      outboxID,
      body: action.payload.text.stringValue(),
      identifyBehavior: yield Saga.call(Shared.getPostingIdentifyBehavior, conversationIDKey),
      clientPrev: lastMessageID ? Constants.parseMessageID(lastMessageID).msgID : 0,
    },
  })
}
Example #30
0
 it('supports React elements {min: false}', () => {
   const reactElement = React.createElement('Mouse', null, 'Hello World');
   expect(Immutable.Set([reactElement, reactElement])).toPrettyPrintTo(
     'Immutable.Set [\n  <Mouse>\n    Hello World\n  </Mouse>,\n]',
   );
 });