From 0ffb8e6203215d746727b763ad998e7161994f0e Mon Sep 17 00:00:00 2001 From: Christopher Speller Date: Wed, 2 Sep 2015 10:42:26 -0400 Subject: Cosmetic refactoring for ESLint --- web/react/stores/channel_store.jsx | 256 ++++++++++---------- web/react/utils/async_client.jsx | 293 ++++++++++++---------- web/react/utils/client.jsx | 297 +++++++++++------------ web/react/utils/constants.jsx | 182 +++++++------- web/react/utils/utils.jsx | 484 +++++++++++++++++++++---------------- 5 files changed, 812 insertions(+), 700 deletions(-) (limited to 'web/react') diff --git a/web/react/stores/channel_store.jsx b/web/react/stores/channel_store.jsx index 678d50bbd..bd655b767 100644 --- a/web/react/stores/channel_store.jsx +++ b/web/react/stores/channel_store.jsx @@ -3,7 +3,6 @@ var AppDispatcher = require('../dispatcher/app_dispatcher.jsx'); var EventEmitter = require('events').EventEmitter; -var assign = require('object-assign'); var Constants = require('../utils/constants.jsx'); var ActionTypes = Constants.ActionTypes; @@ -14,36 +13,42 @@ var CHANGE_EVENT = 'change'; var MORE_CHANGE_EVENT = 'change'; var EXTRA_INFO_EVENT = 'extra_info'; -var ChannelStore = assign({}, EventEmitter.prototype, { - currentId: null, - emitChange: function() { +class ChannelStoreClass extends EventEmitter { + constructor(props) { + super(props); + + this.setMaxListeners(11); + + this.currentId = null; + } + emitChange() { this.emit(CHANGE_EVENT); - }, - addChangeListener: function(callback) { + } + addChangeListener(callback) { this.on(CHANGE_EVENT, callback); - }, - removeChangeListener: function(callback) { + } + removeChangeListener(callback) { this.removeListener(CHANGE_EVENT, callback); - }, - emitMoreChange: function() { + } + emitMoreChange() { this.emit(MORE_CHANGE_EVENT); - }, - addMoreChangeListener: function(callback) { + } + addMoreChangeListener(callback) { this.on(MORE_CHANGE_EVENT, callback); - }, - removeMoreChangeListener: function(callback) { + } + removeMoreChangeListener(callback) { this.removeListener(MORE_CHANGE_EVENT, callback); - }, - emitExtraInfoChange: function() { + } + emitExtraInfoChange() { this.emit(EXTRA_INFO_EVENT); - }, - addExtraInfoChangeListener: function(callback) { + } + addExtraInfoChangeListener(callback) { this.on(EXTRA_INFO_EVENT, callback); - }, - removeExtraInfoChangeListener: function(callback) { + } + removeExtraInfoChangeListener(callback) { this.removeListener(EXTRA_INFO_EVENT, callback); - }, - findFirstBy: function(field, value) { + } + findFirstBy(field, value) { var channels = this.pGetChannels(); for (var i = 0; i < channels.length; i++) { if (channels[i][field] === value) { @@ -52,39 +57,39 @@ var ChannelStore = assign({}, EventEmitter.prototype, { } return null; - }, - get: function(id) { + } + get(id) { return this.findFirstBy('id', id); - }, - getMember: function(id) { + } + getMember(id) { return this.getAllMembers()[id]; - }, - getByName: function(name) { + } + getByName(name) { return this.findFirstBy('name', name); - }, - getAll: function() { + } + getAll() { return this.pGetChannels(); - }, - getAllMembers: function() { + } + getAllMembers() { return this.pGetChannelMembers(); - }, - getMoreAll: function() { + } + getMoreAll() { return this.pGetMoreChannels(); - }, - setCurrentId: function(id) { + } + setCurrentId(id) { this.currentId = id; - }, - setLastVisitedName: function(name) { + } + setLastVisitedName(name) { if (name == null) { BrowserStore.removeItem('last_visited_name'); } else { BrowserStore.setItem('last_visited_name', name); } - }, - getLastVisitedName: function() { + } + getLastVisitedName() { return BrowserStore.getItem('last_visited_name'); - }, - resetCounts: function(id) { + } + resetCounts(id) { var cm = this.pGetChannelMembers(); for (var cmid in cm) { if (cm[cmid].channel_id === id) { @@ -97,36 +102,36 @@ var ChannelStore = assign({}, EventEmitter.prototype, { } } this.pStoreChannelMembers(cm); - }, - getCurrentId: function() { + } + getCurrentId() { return this.currentId; - }, - getCurrent: function() { + } + getCurrent() { var currentId = this.getCurrentId(); if (currentId) { return this.get(currentId); - } else { - return null; } - }, - getCurrentMember: function() { - var currentId = ChannelStore.getCurrentId(); + + return null; + } + getCurrentMember() { + var currentId = this.getCurrentId(); if (currentId) { return this.getAllMembers()[currentId]; - } else { - return null; } - }, - setChannelMember: function(member) { + + return null; + } + setChannelMember(member) { var members = this.pGetChannelMembers(); members[member.channel_id] = member; this.pStoreChannelMembers(members); this.emitChange(); - }, - getCurrentExtraInfo: function() { - var currentId = ChannelStore.getCurrentId(); + } + getCurrentExtraInfo() { + var currentId = this.getCurrentId(); var extra = null; if (currentId) { @@ -138,8 +143,8 @@ var ChannelStore = assign({}, EventEmitter.prototype, { } return extra; - }, - getExtraInfo: function(channelId) { + } + getExtraInfo(channelId) { var extra = null; if (channelId) { @@ -151,8 +156,8 @@ var ChannelStore = assign({}, EventEmitter.prototype, { } return extra; - }, - pStoreChannel: function(channel) { + } + pStoreChannel(channel) { var channels = this.pGetChannels(); var found; @@ -179,28 +184,28 @@ var ChannelStore = assign({}, EventEmitter.prototype, { }); this.pStoreChannels(channels); - }, - pStoreChannels: function(channels) { + } + pStoreChannels(channels) { BrowserStore.setItem('channels', channels); - }, - pGetChannels: function() { + } + pGetChannels() { return BrowserStore.getItem('channels', []); - }, - pStoreChannelMember: function(channelMember) { + } + pStoreChannelMember(channelMember) { var members = this.pGetChannelMembers(); members[channelMember.channel_id] = channelMember; this.pStoreChannelMembers(members); - }, - pStoreChannelMembers: function(channelMembers) { + } + pStoreChannelMembers(channelMembers) { BrowserStore.setItem('channel_members', channelMembers); - }, - pGetChannelMembers: function() { + } + pGetChannelMembers() { return BrowserStore.getItem('channel_members', {}); - }, - pStoreMoreChannels: function(channels) { + } + pStoreMoreChannels(channels) { BrowserStore.setItem('more_channels', channels); - }, - pGetMoreChannels: function() { + } + pGetMoreChannels() { var channels = BrowserStore.getItem('more_channels'); if (channels == null) { @@ -209,66 +214,67 @@ var ChannelStore = assign({}, EventEmitter.prototype, { } return channels; - }, - pStoreExtraInfos: function(extraInfos) { + } + pStoreExtraInfos(extraInfos) { BrowserStore.setItem('extra_infos', extraInfos); - }, - pGetExtraInfos: function() { + } + pGetExtraInfos() { return BrowserStore.getItem('extra_infos', {}); - }, - isDefault: function(channel) { + } + isDefault(channel) { return channel.name === Constants.DEFAULT_CHANNEL; } -}); +} + +var ChannelStore = new ChannelStoreClass(); -ChannelStore.dispatchToken = AppDispatcher.register(function(payload) { +ChannelStore.dispatchToken = AppDispatcher.register(function handleAction(payload) { var action = payload.action; var currentId; - switch(action.type) { - - case ActionTypes.CLICK_CHANNEL: - ChannelStore.setCurrentId(action.id); - ChannelStore.setLastVisitedName(action.name); - ChannelStore.resetCounts(action.id); - ChannelStore.emitChange(); - break; - - case ActionTypes.RECIEVED_CHANNELS: - ChannelStore.pStoreChannels(action.channels); - ChannelStore.pStoreChannelMembers(action.members); - currentId = ChannelStore.getCurrentId(); - if (currentId) { - ChannelStore.resetCounts(currentId); - } - ChannelStore.emitChange(); - break; - - case ActionTypes.RECIEVED_CHANNEL: - ChannelStore.pStoreChannel(action.channel); - ChannelStore.pStoreChannelMember(action.member); - currentId = ChannelStore.getCurrentId(); - if (currentId) { - ChannelStore.resetCounts(currentId); - } - ChannelStore.emitChange(); - break; + switch (action.type) { + case ActionTypes.CLICK_CHANNEL: + ChannelStore.setCurrentId(action.id); + ChannelStore.setLastVisitedName(action.name); + ChannelStore.resetCounts(action.id); + ChannelStore.emitChange(); + break; + + case ActionTypes.RECIEVED_CHANNELS: + ChannelStore.pStoreChannels(action.channels); + ChannelStore.pStoreChannelMembers(action.members); + currentId = ChannelStore.getCurrentId(); + if (currentId) { + ChannelStore.resetCounts(currentId); + } + ChannelStore.emitChange(); + break; + + case ActionTypes.RECIEVED_CHANNEL: + ChannelStore.pStoreChannel(action.channel); + ChannelStore.pStoreChannelMember(action.member); + currentId = ChannelStore.getCurrentId(); + if (currentId) { + ChannelStore.resetCounts(currentId); + } + ChannelStore.emitChange(); + break; - case ActionTypes.RECIEVED_MORE_CHANNELS: - ChannelStore.pStoreMoreChannels(action.channels); - ChannelStore.emitMoreChange(); - break; + case ActionTypes.RECIEVED_MORE_CHANNELS: + ChannelStore.pStoreMoreChannels(action.channels); + ChannelStore.emitMoreChange(); + break; - case ActionTypes.RECIEVED_CHANNEL_EXTRA_INFO: - var extraInfos = ChannelStore.pGetExtraInfos(); - extraInfos[action.extra_info.id] = action.extra_info; - ChannelStore.pStoreExtraInfos(extraInfos); - ChannelStore.emitExtraInfoChange(); - break; + case ActionTypes.RECIEVED_CHANNEL_EXTRA_INFO: + var extraInfos = ChannelStore.pGetExtraInfos(); + extraInfos[action.extra_info.id] = action.extra_info; + ChannelStore.pStoreExtraInfos(extraInfos); + ChannelStore.emitExtraInfoChange(); + break; - default: + default: + break; } }); -ChannelStore.setMaxListeners(11); -module.exports = ChannelStore; +export default ChannelStore; diff --git a/web/react/utils/async_client.jsx b/web/react/utils/async_client.jsx index c03a0230b..6ccef0506 100644 --- a/web/react/utils/async_client.jsx +++ b/web/react/utils/async_client.jsx @@ -4,7 +4,6 @@ var client = require('./client.jsx'); var AppDispatcher = require('../dispatcher/app_dispatcher.jsx'); var ChannelStore = require('../stores/channel_store.jsx'); -var ConfigStore = require('../stores/config_store.jsx'); var PostStore = require('../stores/post_store.jsx'); var UserStore = require('../stores/user_store.jsx'); var utils = require('./utils.jsx'); @@ -15,14 +14,13 @@ var ActionTypes = Constants.ActionTypes; // Used to track in progress async calls var callTracker = {}; -function dispatchError(err, method) { +export function dispatchError(err, method) { AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVED_ERROR, err: err, method: method }); } -module.exports.dispatchError = dispatchError; function isCallInProgress(callName) { if (!(callName in callTracker)) { @@ -34,14 +32,14 @@ function isCallInProgress(callName) { } if (utils.getTimestamp() - callTracker[callName] > 5000) { - console.log('AsyncClient call ' + callName + ' expired after more than 5 seconds'); + //console.log('AsyncClient call ' + callName + ' expired after more than 5 seconds'); return false; } return true; } -function getChannels(force, updateLastViewed, checkVersion) { +export function getChannels(force, updateLastViewed, checkVersion) { var channels = ChannelStore.getAll(); if (channels.length === 0 || force) { @@ -52,7 +50,7 @@ function getChannels(force, updateLastViewed, checkVersion) { callTracker.getChannels = utils.getTimestamp(); client.getChannels( - function(data, textStatus, xhr) { + function getChannelsSuccess(data, textStatus, xhr) { callTracker.getChannels = 0; if (checkVersion) { @@ -65,7 +63,7 @@ function getChannels(force, updateLastViewed, checkVersion) { if (serverVersion !== UserStore.getLastVersion()) { UserStore.setLastVersion(serverVersion); window.location.href = window.location.href; - console.log('Detected version update refreshing the page'); + console.log('Detected version update refreshing the page'); //eslint-disable-line no-console } } @@ -79,7 +77,7 @@ function getChannels(force, updateLastViewed, checkVersion) { members: data.members }); }, - function(err) { + function getChannelsFailure(err) { callTracker.getChannels = 0; dispatchError(err, 'getChannels'); } @@ -92,7 +90,7 @@ function getChannels(force, updateLastViewed, checkVersion) { callTracker.getChannelCounts = utils.getTimestamp(); client.getChannelCounts( - function(data, textStatus, xhr) { + function getChannelCountsSuccess(data, textStatus, xhr) { callTracker.getChannelCounts = 0; if (xhr.status === 304 || !data) { @@ -103,15 +101,17 @@ function getChannels(force, updateLastViewed, checkVersion) { var updateAtMap = data.update_times; for (var id in countMap) { - var c = ChannelStore.get(id); - var count = countMap[id]; - var updateAt = updateAtMap[id]; - if (!c || c.total_msg_count !== count || updateAt > c.update_at) { - getChannel(id); + if ({}.hasOwnProperty.call(countMap, id)) { + var c = ChannelStore.get(id); + var count = countMap[id]; + var updateAt = updateAtMap[id]; + if (!c || c.total_msg_count !== count || updateAt > c.update_at) { + getChannel(id); + } } } }, - function(err) { + function getChannelCountsFailure(err) { callTracker.getChannelCounts = 0; dispatchError(err, 'getChannelCounts'); } @@ -119,12 +119,11 @@ function getChannels(force, updateLastViewed, checkVersion) { } if (updateLastViewed && ChannelStore.getCurrentId() != null) { - module.exports.updateLastViewedAt(); + updateLastViewedAt(); } } -module.exports.getChannels = getChannels; -function getChannel(id) { +export function getChannel(id) { if (isCallInProgress('getChannel' + id)) { return; } @@ -132,7 +131,7 @@ function getChannel(id) { callTracker['getChannel' + id] = utils.getTimestamp(); client.getChannel(id, - function(data, textStatus, xhr) { + function getChannelSuccess(data, textStatus, xhr) { callTracker['getChannel' + id] = 0; if (xhr.status === 304 || !data) { @@ -145,43 +144,49 @@ function getChannel(id) { member: data.member }); }, - function(err) { + function getChannelFailure(err) { callTracker['getChannel' + id] = 0; dispatchError(err, 'getChannel'); } ); } -module.exports.getChannel = getChannel; -module.exports.updateLastViewedAt = function() { - if (isCallInProgress('updateLastViewed')) return; +export function updateLastViewedAt() { + if (isCallInProgress('updateLastViewed')) { + return; + } - if (ChannelStore.getCurrentId() == null) return; + if (ChannelStore.getCurrentId() == null) { + return; + } - callTracker['updateLastViewed'] = utils.getTimestamp(); + callTracker.updateLastViewed = utils.getTimestamp(); client.updateLastViewedAt( ChannelStore.getCurrentId(), - function(data) { - callTracker['updateLastViewed'] = 0; + function updateLastViewedAtSuccess() { + callTracker.updateLastViewed = 0; }, - function(err) { - callTracker['updateLastViewed'] = 0; + function updateLastViewdAtFailure(err) { + callTracker.updateLastViewed = 0; dispatchError(err, 'updateLastViewedAt'); } ); } -module.exports.getMoreChannels = function(force) { - if (isCallInProgress('getMoreChannels')) return; +export function getMoreChannels(force) { + if (isCallInProgress('getMoreChannels')) { + return; + } if (ChannelStore.getMoreAll().loading || force) { - - callTracker['getMoreChannels'] = utils.getTimestamp(); + callTracker.getMoreChannels = utils.getTimestamp(); client.getMoreChannels( - function(data, textStatus, xhr) { - callTracker['getMoreChannels'] = 0; + function getMoreChannelsSuccess(data, textStatus, xhr) { + callTracker.getMoreChannels = 0; - if (xhr.status === 304 || !data) return; + if (xhr.status === 304 || !data) { + return; + } AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVED_MORE_CHANNELS, @@ -189,37 +194,44 @@ module.exports.getMoreChannels = function(force) { members: data.members }); }, - function(err) { - callTracker['getMoreChannels'] = 0; + function getMoreChannelsFailure(err) { + callTracker.getMoreChannels = 0; dispatchError(err, 'getMoreChannels'); } ); } } -module.exports.getChannelExtraInfo = function(force) { +export function getChannelExtraInfo(force) { var channelId = ChannelStore.getCurrentId(); if (channelId != null) { - if (isCallInProgress('getChannelExtraInfo_'+channelId)) return; - var minMembers = ChannelStore.getCurrent() && ChannelStore.getCurrent().type === 'D' ? 1 : 0; + if (isCallInProgress('getChannelExtraInfo_' + channelId)) { + return; + } + var minMembers = 0; + if (ChannelStore.getCurrent() && ChannelStore.getCurrent().type === 'D') { + minMembers = 1; + } if (ChannelStore.getCurrentExtraInfo().members.length <= minMembers || force) { - callTracker['getChannelExtraInfo_'+channelId] = utils.getTimestamp(); + callTracker['getChannelExtraInfo_' + channelId] = utils.getTimestamp(); client.getChannelExtraInfo( channelId, - function(data, textStatus, xhr) { - callTracker['getChannelExtraInfo_'+channelId] = 0; + function getChannelExtraInfoSuccess(data, textStatus, xhr) { + callTracker['getChannelExtraInfo_' + channelId] = 0; - if (xhr.status === 304 || !data) return; + if (xhr.status === 304 || !data) { + return; + } AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVED_CHANNEL_EXTRA_INFO, extra_info: data }); }, - function(err) { - callTracker['getChannelExtraInfo_'+channelId] = 0; + function getChannelExtraInfoFailure(err) { + callTracker['getChannelExtraInfo_' + channelId] = 0; dispatchError(err, 'getChannelExtraInfo'); } ); @@ -227,124 +239,144 @@ module.exports.getChannelExtraInfo = function(force) { } } -module.exports.getProfiles = function() { - if (isCallInProgress('getProfiles')) return; +export function getProfiles() { + if (isCallInProgress('getProfiles')) { + return; + } - callTracker['getProfiles'] = utils.getTimestamp(); + callTracker.getProfiles = utils.getTimestamp(); client.getProfiles( - function(data, textStatus, xhr) { - callTracker['getProfiles'] = 0; + function getProfilesSuccess(data, textStatus, xhr) { + callTracker.getProfiles = 0; - if (xhr.status === 304 || !data) return; + if (xhr.status === 304 || !data) { + return; + } AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVED_PROFILES, profiles: data }); }, - function(err) { - callTracker['getProfiles'] = 0; + function getProfilesFailure(err) { + callTracker.getProfiles = 0; dispatchError(err, 'getProfiles'); } ); } -module.exports.getSessions = function() { - if (isCallInProgress('getSessions')) return; +export function getSessions() { + if (isCallInProgress('getSessions')) { + return; + } - callTracker['getSessions'] = utils.getTimestamp(); + callTracker.getSessions = utils.getTimestamp(); client.getSessions( UserStore.getCurrentId(), - function(data, textStatus, xhr) { - callTracker['getSessions'] = 0; + function getSessionsSuccess(data, textStatus, xhr) { + callTracker.getSessions = 0; - if (xhr.status === 304 || !data) return; + if (xhr.status === 304 || !data) { + return; + } AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVED_SESSIONS, sessions: data }); }, - function(err) { - callTracker['getSessions'] = 0; + function getSessionsFailure(err) { + callTracker.getSessions = 0; dispatchError(err, 'getSessions'); } ); } -module.exports.getAudits = function() { - if (isCallInProgress('getAudits')) return; +export function getAudits() { + if (isCallInProgress('getAudits')) { + return; + } - callTracker['getAudits'] = utils.getTimestamp(); + callTracker.getAudits = utils.getTimestamp(); client.getAudits( UserStore.getCurrentId(), - function(data, textStatus, xhr) { - callTracker['getAudits'] = 0; + function getAuditsSuccess(data, textStatus, xhr) { + callTracker.getAudits = 0; - if (xhr.status === 304 || !data) return; + if (xhr.status === 304 || !data) { + return; + } AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVED_AUDITS, audits: data }); }, - function(err) { - callTracker['getAudits'] = 0; + function getAuditsFailure(err) { + callTracker.getAudits = 0; dispatchError(err, 'getAudits'); } ); } -module.exports.findTeams = function(email) { - if (isCallInProgress('findTeams_'+email)) return; +export function findTeams(email) { + if (isCallInProgress('findTeams_' + email)) { + return; + } var user = UserStore.getCurrentUser(); if (user) { - callTracker['findTeams_'+email] = utils.getTimestamp(); + callTracker['findTeams_' + email] = utils.getTimestamp(); client.findTeams( user.email, - function(data, textStatus, xhr) { - callTracker['findTeams_'+email] = 0; + function findTeamsSuccess(data, textStatus, xhr) { + callTracker['findTeams_' + email] = 0; - if (xhr.status === 304 || !data) return; + if (xhr.status === 304 || !data) { + return; + } AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVED_TEAMS, teams: data }); }, - function(err) { - callTracker['findTeams_'+email] = 0; + function findTeamsFailure(err) { + callTracker['findTeams_' + email] = 0; dispatchError(err, 'findTeams'); } ); } } -module.exports.search = function(terms) { - if (isCallInProgress('search_'+String(terms))) return; +export function search(terms) { + if (isCallInProgress('search_' + String(terms))) { + return; + } - callTracker['search_'+String(terms)] = utils.getTimestamp(); + callTracker['search_' + String(terms)] = utils.getTimestamp(); client.search( terms, - function(data, textStatus, xhr) { - callTracker['search_'+String(terms)] = 0; + function searchSuccess(data, textStatus, xhr) { + callTracker['search_' + String(terms)] = 0; - if (xhr.status === 304 || !data) return; + if (xhr.status === 304 || !data) { + return; + } AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVED_SEARCH, results: data }); }, - function(err) { - callTracker['search_'+String(terms)] = 0; + function searchFailure(err) { + callTracker['search_' + String(terms)] = 0; dispatchError(err, 'search'); } ); } -module.exports.getPostsPage = function(force, id, maxPosts) { +export function getPostsPage(force, id, maxPosts) { if (PostStore.getCurrentPosts() == null || force) { var channelId = id; if (channelId == null) { @@ -377,8 +409,10 @@ module.exports.getPostsPage = function(force, id, maxPosts) { channelId, 0, numPosts, - function(data, textStatus, xhr) { - if (xhr.status === 304 || !data) return; + function getPostsPageSuccess(data, textStatus, xhr) { + if (xhr.status === 304 || !data) { + return; + } AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVED_POSTS, @@ -386,20 +420,20 @@ module.exports.getPostsPage = function(force, id, maxPosts) { post_list: data }); - module.exports.getProfiles(); + getProfiles(); }, - function(err) { + function getPostsPageFailure(err) { dispatchError(err, 'getPostsPage'); }, - function() { + function getPostsPageComplete() { callTracker['getPostsPage_' + channelId] = 0; } ); } } -}; +} -function getPosts(id) { +export function getPosts(id) { var channelId = id; if (channelId == null) { if (ChannelStore.getCurrentId() == null) { @@ -413,7 +447,7 @@ function getPosts(id) { } if (PostStore.getCurrentPosts() == null) { - module.exports.getPostsPage(true, id, Constants.POST_CHUNK_SIZE); + getPostsPage(true, id, Constants.POST_CHUNK_SIZE); return; } @@ -435,7 +469,7 @@ function getPosts(id) { post_list: data }); - module.exports.getProfiles(); + getProfiles(); }, function fail(err) { dispatchError(err, 'getPosts'); @@ -445,86 +479,94 @@ function getPosts(id) { } ); } -module.exports.getPosts = getPosts; -function getMe() { +export function getMe() { if (isCallInProgress('getMe')) { return; } callTracker.getMe = utils.getTimestamp(); client.getMeSynchronous( - function(data, textStatus, xhr) { + function getMeSyncSuccess(data, textStatus, xhr) { callTracker.getMe = 0; - if (xhr.status === 304 || !data) return; + if (xhr.status === 304 || !data) { + return; + } AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVED_ME, me: data }); }, - function(err) { + function getMeSyncFailure(err) { callTracker.getMe = 0; dispatchError(err, 'getMe'); } ); } -module.exports.getMe = getMe; -module.exports.getStatuses = function() { - if (isCallInProgress('getStatuses')) return; +export function getStatuses() { + if (isCallInProgress('getStatuses')) { + return; + } - callTracker['getStatuses'] = utils.getTimestamp(); + callTracker.getStatuses = utils.getTimestamp(); client.getStatuses( - function(data, textStatus, xhr) { - callTracker['getStatuses'] = 0; + function getStatusesSuccess(data, textStatus, xhr) { + callTracker.getStatuses = 0; - if (xhr.status === 304 || !data) return; + if (xhr.status === 304 || !data) { + return; + } AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVED_STATUSES, statuses: data }); }, - function(err) { - callTracker['getStatuses'] = 0; + function getStatusesFailure(err) { + callTracker.getStatuses = 0; dispatchError(err, 'getStatuses'); } ); } -module.exports.getMyTeam = function() { - if (isCallInProgress('getMyTeam')) return; +export function getMyTeam() { + if (isCallInProgress('getMyTeam')) { + return; + } - callTracker['getMyTeam'] = utils.getTimestamp(); + callTracker.getMyTeam = utils.getTimestamp(); client.getMyTeam( - function(data, textStatus, xhr) { - callTracker['getMyTeam'] = 0; + function getMyTeamSuccess(data, textStatus, xhr) { + callTracker.getMyTeam = 0; - if (xhr.status === 304 || !data) return; + if (xhr.status === 304 || !data) { + return; + } AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVED_TEAM, team: data }); }, - function(err) { - callTracker['getMyTeam'] = 0; + function getMyTeamFailure(err) { + callTracker.getMyTeam = 0; dispatchError(err, 'getMyTeam'); } ); } -function getConfig() { +export function getConfig() { if (isCallInProgress('getConfig')) { return; } - callTracker['getConfig'] = utils.getTimestamp(); + callTracker.getConfig = utils.getTimestamp(); client.getConfig( - function(data, textStatus, xhr) { - callTracker['getConfig'] = 0; + function getConfigSuccess(data, textStatus, xhr) { + callTracker.getConfig = 0; if (data && xhr.status !== 304) { AppDispatcher.handleServerAction({ @@ -533,10 +575,9 @@ function getConfig() { }); } }, - function(err) { - callTracker['getConfig'] = 0; + function getConfigFailure(err) { + callTracker.getConfig = 0; dispatchError(err, 'getConfig'); } ); } -module.exports.getConfig = getConfig; diff --git a/web/react/utils/client.jsx b/web/react/utils/client.jsx index 082f82a08..10f9c0b37 100644 --- a/web/react/utils/client.jsx +++ b/web/react/utils/client.jsx @@ -3,15 +3,15 @@ var BrowserStore = require('../stores/browser_store.jsx'); var TeamStore = require('../stores/team_store.jsx'); -module.exports.track = function(category, action, label, prop, val) { +export function track(category, action, label, prop, val) { global.window.snowplow('trackStructEvent', category, action, label, prop, val); global.window.analytics.track(action, {category: category, label: label, property: prop, value: val}); -}; +} -module.exports.trackPage = function() { +export function trackPage() { global.window.snowplow('trackPageView'); global.window.analytics.page(); -}; +} function handleError(methodName, xhr, status, err) { var LTracker = global.window.LTracker || []; @@ -41,7 +41,7 @@ function handleError(methodName, xhr, status, err) { console.error(e); //eslint-disable-line no-console LTracker.push(msg); - module.exports.track('api', 'api_weberror', methodName, 'message', msg); + track('api', 'api_weberror', methodName, 'message', msg); if (xhr.status === 401) { if (window.location.href.indexOf('/channels') === 0) { @@ -55,7 +55,7 @@ function handleError(methodName, xhr, status, err) { return e; } -module.exports.createTeamFromSignup = function(teamSignup, success, error) { +export function createTeamFromSignup(teamSignup, success, error) { $.ajax({ url: '/api/v1/teams/create_from_signup', dataType: 'json', @@ -68,9 +68,9 @@ module.exports.createTeamFromSignup = function(teamSignup, success, error) { error(e); } }); -}; +} -module.exports.createTeamWithSSO = function(team, service, success, error) { +export function createTeamWithSSO(team, service, success, error) { $.ajax({ url: '/api/v1/teams/create_with_sso/' + service, dataType: 'json', @@ -83,9 +83,9 @@ module.exports.createTeamWithSSO = function(team, service, success, error) { error(e); } }); -}; +} -module.exports.createUser = function(user, data, emailHash, success, error) { +export function createUser(user, data, emailHash, success, error) { $.ajax({ url: '/api/v1/users/create?d=' + encodeURIComponent(data) + '&h=' + encodeURIComponent(emailHash), dataType: 'json', @@ -99,10 +99,10 @@ module.exports.createUser = function(user, data, emailHash, success, error) { } }); - module.exports.track('api', 'api_users_create', user.team_id, 'email', user.email); -}; + track('api', 'api_users_create', user.team_id, 'email', user.email); +} -module.exports.updateUser = function(user, success, error) { +export function updateUser(user, success, error) { $.ajax({ url: '/api/v1/users/update', dataType: 'json', @@ -116,10 +116,10 @@ module.exports.updateUser = function(user, success, error) { } }); - module.exports.track('api', 'api_users_update'); -}; + track('api', 'api_users_update'); +} -module.exports.updatePassword = function(data, success, error) { +export function updatePassword(data, success, error) { $.ajax({ url: '/api/v1/users/newpassword', dataType: 'json', @@ -133,10 +133,10 @@ module.exports.updatePassword = function(data, success, error) { } }); - module.exports.track('api', 'api_users_newpassword'); -}; + track('api', 'api_users_newpassword'); +} -module.exports.updateUserNotifyProps = function(data, success, error) { +export function updateUserNotifyProps(data, success, error) { $.ajax({ url: '/api/v1/users/update_notify', dataType: 'json', @@ -149,9 +149,9 @@ module.exports.updateUserNotifyProps = function(data, success, error) { error(e); } }); -}; +} -module.exports.updateRoles = function(data, success, error) { +export function updateRoles(data, success, error) { $.ajax({ url: '/api/v1/users/update_roles', dataType: 'json', @@ -165,10 +165,10 @@ module.exports.updateRoles = function(data, success, error) { } }); - module.exports.track('api', 'api_users_update_roles'); -}; + track('api', 'api_users_update_roles'); +} -module.exports.updateActive = function(userId, active, success, error) { +export function updateActive(userId, active, success, error) { var data = {}; data.user_id = userId; data.active = '' + active; @@ -186,10 +186,10 @@ module.exports.updateActive = function(userId, active, success, error) { } }); - module.exports.track('api', 'api_users_update_roles'); -}; + track('api', 'api_users_update_roles'); +} -module.exports.sendPasswordReset = function(data, success, error) { +export function sendPasswordReset(data, success, error) { $.ajax({ url: '/api/v1/users/send_password_reset', dataType: 'json', @@ -203,10 +203,10 @@ module.exports.sendPasswordReset = function(data, success, error) { } }); - module.exports.track('api', 'api_users_send_password_reset'); -}; + track('api', 'api_users_send_password_reset'); +} -module.exports.resetPassword = function(data, success, error) { +export function resetPassword(data, success, error) { $.ajax({ url: '/api/v1/users/reset_password', dataType: 'json', @@ -220,17 +220,17 @@ module.exports.resetPassword = function(data, success, error) { } }); - module.exports.track('api', 'api_users_reset_password'); -}; + track('api', 'api_users_reset_password'); +} -module.exports.logout = function() { - module.exports.track('api', 'api_users_logout'); +export function logout() { + track('api', 'api_users_logout'); var currentTeamUrl = TeamStore.getCurrentTeamUrl(); BrowserStore.clear(); window.location.href = currentTeamUrl + '/logout'; -}; +} -module.exports.loginByEmail = function(name, email, password, success, error) { +export function loginByEmail(name, email, password, success, error) { $.ajax({ url: '/api/v1/users/login', dataType: 'json', @@ -238,19 +238,19 @@ module.exports.loginByEmail = function(name, email, password, success, error) { type: 'POST', data: JSON.stringify({name: name, email: email, password: password}), success: function onSuccess(data, textStatus, xhr) { - module.exports.track('api', 'api_users_login_success', data.team_id, 'email', data.email); + track('api', 'api_users_login_success', data.team_id, 'email', data.email); success(data, textStatus, xhr); }, error: function onError(xhr, status, err) { - module.exports.track('api', 'api_users_login_fail', window.getSubDomain(), 'email', email); + track('api', 'api_users_login_fail', name, 'email', email); var e = handleError('loginByEmail', xhr, status, err); error(e); } }); -}; +} -module.exports.revokeSession = function(altId, success, error) { +export function revokeSession(altId, success, error) { $.ajax({ url: '/api/v1/users/revoke_session', dataType: 'json', @@ -263,9 +263,9 @@ module.exports.revokeSession = function(altId, success, error) { error(e); } }); -}; +} -module.exports.getSessions = function(userId, success, error) { +export function getSessions(userId, success, error) { $.ajax({ cache: false, url: '/api/v1/users/' + userId + '/sessions', @@ -278,9 +278,9 @@ module.exports.getSessions = function(userId, success, error) { error(e); } }); -}; +} -module.exports.getAudits = function(userId, success, error) { +export function getAudits(userId, success, error) { $.ajax({ url: '/api/v1/users/' + userId + '/audits', dataType: 'json', @@ -292,9 +292,9 @@ module.exports.getAudits = function(userId, success, error) { error(e); } }); -}; +} -module.exports.getMeSynchronous = function(success, error) { +export function getMeSynchronous(success, error) { var currentUser = null; $.ajax({ async: false, @@ -318,9 +318,9 @@ module.exports.getMeSynchronous = function(success, error) { }); return currentUser; -}; +} -module.exports.inviteMembers = function(data, success, error) { +export function inviteMembers(data, success, error) { $.ajax({ url: '/api/v1/teams/invite_members', dataType: 'json', @@ -334,10 +334,10 @@ module.exports.inviteMembers = function(data, success, error) { } }); - module.exports.track('api', 'api_teams_invite_members'); -}; + track('api', 'api_teams_invite_members'); +} -module.exports.updateTeamDisplayName = function(data, success, error) { +export function updateTeamDisplayName(data, success, error) { $.ajax({ url: '/api/v1/teams/update_name', dataType: 'json', @@ -351,10 +351,10 @@ module.exports.updateTeamDisplayName = function(data, success, error) { } }); - module.exports.track('api', 'api_teams_update_name'); -}; + track('api', 'api_teams_update_name'); +} -module.exports.signupTeam = function(email, success, error) { +export function signupTeam(email, success, error) { $.ajax({ url: '/api/v1/teams/signup', dataType: 'json', @@ -368,10 +368,10 @@ module.exports.signupTeam = function(email, success, error) { } }); - module.exports.track('api', 'api_teams_signup'); -}; + track('api', 'api_teams_signup'); +} -module.exports.createTeam = function(team, success, error) { +export function createTeam(team, success, error) { $.ajax({ url: '/api/v1/teams/create', dataType: 'json', @@ -384,9 +384,9 @@ module.exports.createTeam = function(team, success, error) { error(e); } }); -}; +} -module.exports.findTeamByName = function(teamName, success, error) { +export function findTeamByName(teamName, success, error) { $.ajax({ url: '/api/v1/teams/find_team_by_name', dataType: 'json', @@ -399,9 +399,9 @@ module.exports.findTeamByName = function(teamName, success, error) { error(e); } }); -}; +} -module.exports.findTeamsSendEmail = function(email, success, error) { +export function findTeamsSendEmail(email, success, error) { $.ajax({ url: '/api/v1/teams/email_teams', dataType: 'json', @@ -415,10 +415,10 @@ module.exports.findTeamsSendEmail = function(email, success, error) { } }); - module.exports.track('api', 'api_teams_email_teams'); -}; + track('api', 'api_teams_email_teams'); +} -module.exports.findTeams = function(email, success, error) { +export function findTeams(email, success, error) { $.ajax({ url: '/api/v1/teams/find_teams', dataType: 'json', @@ -431,9 +431,9 @@ module.exports.findTeams = function(email, success, error) { error(e); } }); -}; +} -module.exports.createChannel = function(channel, success, error) { +export function createChannel(channel, success, error) { $.ajax({ url: '/api/v1/channels/create', dataType: 'json', @@ -447,10 +447,10 @@ module.exports.createChannel = function(channel, success, error) { } }); - module.exports.track('api', 'api_channels_create', channel.type, 'name', channel.name); -}; + track('api', 'api_channels_create', channel.type, 'name', channel.name); +} -module.exports.createDirectChannel = function(channel, userId, success, error) { +export function createDirectChannel(channel, userId, success, error) { $.ajax({ url: '/api/v1/channels/create_direct', dataType: 'json', @@ -458,16 +458,16 @@ module.exports.createDirectChannel = function(channel, userId, success, error) { type: 'POST', data: JSON.stringify({user_id: userId}), success: success, - error: function(xhr, status, err) { + error: function onError(xhr, status, err) { var e = handleError('createDirectChannel', xhr, status, err); error(e); } }); - module.exports.track('api', 'api_channels_create_direct', channel.type, 'name', channel.name); -}; + track('api', 'api_channels_create_direct', channel.type, 'name', channel.name); +} -module.exports.updateChannel = function(channel, success, error) { +export function updateChannel(channel, success, error) { $.ajax({ url: '/api/v1/channels/update', dataType: 'json', @@ -481,10 +481,10 @@ module.exports.updateChannel = function(channel, success, error) { } }); - module.exports.track('api', 'api_channels_update'); -}; + track('api', 'api_channels_update'); +} -module.exports.updateChannelDesc = function(data, success, error) { +export function updateChannelDesc(data, success, error) { $.ajax({ url: '/api/v1/channels/update_desc', dataType: 'json', @@ -498,10 +498,10 @@ module.exports.updateChannelDesc = function(data, success, error) { } }); - module.exports.track('api', 'api_channels_desc'); -}; + track('api', 'api_channels_desc'); +} -module.exports.updateNotifyLevel = function(data, success, error) { +export function updateNotifyLevel(data, success, error) { $.ajax({ url: '/api/v1/channels/update_notify_level', dataType: 'json', @@ -514,9 +514,9 @@ module.exports.updateNotifyLevel = function(data, success, error) { error(e); } }); -}; +} -module.exports.joinChannel = function(id, success, error) { +export function joinChannel(id, success, error) { $.ajax({ url: '/api/v1/channels/' + id + '/join', dataType: 'json', @@ -529,10 +529,10 @@ module.exports.joinChannel = function(id, success, error) { } }); - module.exports.track('api', 'api_channels_join'); -}; + track('api', 'api_channels_join'); +} -module.exports.leaveChannel = function(id, success, error) { +export function leaveChannel(id, success, error) { $.ajax({ url: '/api/v1/channels/' + id + '/leave', dataType: 'json', @@ -545,10 +545,10 @@ module.exports.leaveChannel = function(id, success, error) { } }); - module.exports.track('api', 'api_channels_leave'); -}; + track('api', 'api_channels_leave'); +} -module.exports.deleteChannel = function(id, success, error) { +export function deleteChannel(id, success, error) { $.ajax({ url: '/api/v1/channels/' + id + '/delete', dataType: 'json', @@ -561,10 +561,10 @@ module.exports.deleteChannel = function(id, success, error) { } }); - module.exports.track('api', 'api_channels_delete'); -}; + track('api', 'api_channels_delete'); +} -module.exports.updateLastViewedAt = function(channelId, success, error) { +export function updateLastViewedAt(channelId, success, error) { $.ajax({ url: '/api/v1/channels/' + channelId + '/update_last_viewed_at', dataType: 'json', @@ -576,9 +576,9 @@ module.exports.updateLastViewedAt = function(channelId, success, error) { error(e); } }); -}; +} -function getChannels(success, error) { +export function getChannels(success, error) { $.ajax({ cache: false, url: '/api/v1/channels/', @@ -592,9 +592,8 @@ function getChannels(success, error) { } }); } -module.exports.getChannels = getChannels; -module.exports.getChannel = function(id, success, error) { +export function getChannel(id, success, error) { $.ajax({ cache: false, url: '/api/v1/channels/' + id + '/', @@ -607,10 +606,10 @@ module.exports.getChannel = function(id, success, error) { } }); - module.exports.track('api', 'api_channel_get'); -}; + track('api', 'api_channel_get'); +} -module.exports.getMoreChannels = function(success, error) { +export function getMoreChannels(success, error) { $.ajax({ url: '/api/v1/channels/more', dataType: 'json', @@ -622,9 +621,9 @@ module.exports.getMoreChannels = function(success, error) { error(e); } }); -}; +} -function getChannelCounts(success, error) { +export function getChannelCounts(success, error) { $.ajax({ cache: false, url: '/api/v1/channels/counts', @@ -638,9 +637,8 @@ function getChannelCounts(success, error) { } }); } -module.exports.getChannelCounts = getChannelCounts; -module.exports.getChannelExtraInfo = function(id, success, error) { +export function getChannelExtraInfo(id, success, error) { $.ajax({ url: '/api/v1/channels/' + id + '/extra_info', dataType: 'json', @@ -651,9 +649,9 @@ module.exports.getChannelExtraInfo = function(id, success, error) { error(e); } }); -}; +} -module.exports.executeCommand = function(channelId, command, suggest, success, error) { +export function executeCommand(channelId, command, suggest, success, error) { $.ajax({ url: '/api/v1/command', dataType: 'json', @@ -666,9 +664,9 @@ module.exports.executeCommand = function(channelId, command, suggest, success, e error(e); } }); -}; +} -module.exports.getPostsPage = function(channelId, offset, limit, success, error, complete) { +export function getPostsPage(channelId, offset, limit, success, error, complete) { $.ajax({ cache: false, url: '/api/v1/channels/' + channelId + '/posts/' + offset + '/' + limit, @@ -682,9 +680,9 @@ module.exports.getPostsPage = function(channelId, offset, limit, success, error, }, complete: complete }); -}; +} -module.exports.getPosts = function(channelId, since, success, error, complete) { +export function getPosts(channelId, since, success, error, complete) { $.ajax({ url: '/api/v1/channels/' + channelId + '/posts/' + since, dataType: 'json', @@ -697,9 +695,9 @@ module.exports.getPosts = function(channelId, since, success, error, complete) { }, complete: complete }); -}; +} -module.exports.getPost = function(channelId, postId, success, error) { +export function getPost(channelId, postId, success, error) { $.ajax({ cache: false, url: '/api/v1/channels/' + channelId + '/post/' + postId, @@ -712,9 +710,9 @@ module.exports.getPost = function(channelId, postId, success, error) { error(e); } }); -}; +} -module.exports.search = function(terms, success, error) { +export function search(terms, success, error) { $.ajax({ url: '/api/v1/posts/search', dataType: 'json', @@ -727,10 +725,10 @@ module.exports.search = function(terms, success, error) { } }); - module.exports.track('api', 'api_posts_search'); -}; + track('api', 'api_posts_search'); +} -module.exports.deletePost = function(channelId, id, success, error) { +export function deletePost(channelId, id, success, error) { $.ajax({ url: '/api/v1/channels/' + channelId + '/post/' + id + '/delete', dataType: 'json', @@ -743,10 +741,10 @@ module.exports.deletePost = function(channelId, id, success, error) { } }); - module.exports.track('api', 'api_posts_delete'); -}; + track('api', 'api_posts_delete'); +} -module.exports.createPost = function(post, channel, success, error) { +export function createPost(post, channel, success, error) { $.ajax({ url: '/api/v1/channels/' + post.channel_id + '/create', dataType: 'json', @@ -760,7 +758,7 @@ module.exports.createPost = function(post, channel, success, error) { } }); - module.exports.track('api', 'api_posts_create', channel.name, 'length', post.message.length); + track('api', 'api_posts_create', channel.name, 'length', post.message.length); // global.window.analytics.track('api_posts_create', { // category: 'api', @@ -770,9 +768,9 @@ module.exports.createPost = function(post, channel, success, error) { // files: (post.filenames || []).length, // mentions: (post.message.match('//g') || []).length // }); -}; +} -module.exports.updatePost = function(post, success, error) { +export function updatePost(post, success, error) { $.ajax({ url: '/api/v1/channels/' + post.channel_id + '/update', dataType: 'json', @@ -786,10 +784,10 @@ module.exports.updatePost = function(post, success, error) { } }); - module.exports.track('api', 'api_posts_update'); -}; + track('api', 'api_posts_update'); +} -module.exports.addChannelMember = function(id, data, success, error) { +export function addChannelMember(id, data, success, error) { $.ajax({ url: '/api/v1/channels/' + id + '/add', dataType: 'json', @@ -803,10 +801,10 @@ module.exports.addChannelMember = function(id, data, success, error) { } }); - module.exports.track('api', 'api_channels_add_member'); -}; + track('api', 'api_channels_add_member'); +} -module.exports.removeChannelMember = function(id, data, success, error) { +export function removeChannelMember(id, data, success, error) { $.ajax({ url: '/api/v1/channels/' + id + '/remove', dataType: 'json', @@ -820,10 +818,10 @@ module.exports.removeChannelMember = function(id, data, success, error) { } }); - module.exports.track('api', 'api_channels_remove_member'); -}; + track('api', 'api_channels_remove_member'); +} -module.exports.getProfiles = function(success, error) { +export function getProfiles(success, error) { $.ajax({ cache: false, url: '/api/v1/users/profiles', @@ -837,9 +835,9 @@ module.exports.getProfiles = function(success, error) { error(e); } }); -}; +} -module.exports.uploadFile = function(formData, success, error) { +export function uploadFile(formData, success, error) { var request = $.ajax({ url: '/api/v1/files/upload', type: 'POST', @@ -856,12 +854,12 @@ module.exports.uploadFile = function(formData, success, error) { } }); - module.exports.track('api', 'api_files_upload'); + track('api', 'api_files_upload'); return request; -}; +} -module.exports.getFileInfo = function(filename, success, error) { +export function getFileInfo(filename, success, error) { $.ajax({ url: '/api/v1/files/get_info' + filename, dataType: 'json', @@ -873,9 +871,9 @@ module.exports.getFileInfo = function(filename, success, error) { error(e); } }); -}; +} -module.exports.getPublicLink = function(data, success, error) { +export function getPublicLink(data, success, error) { $.ajax({ url: '/api/v1/files/get_public_link', dataType: 'json', @@ -887,9 +885,9 @@ module.exports.getPublicLink = function(data, success, error) { error(e); } }); -}; +} -module.exports.uploadProfileImage = function(imageData, success, error) { +export function uploadProfileImage(imageData, success, error) { $.ajax({ url: '/api/v1/users/newimage', type: 'POST', @@ -903,9 +901,9 @@ module.exports.uploadProfileImage = function(imageData, success, error) { error(e); } }); -}; +} -module.exports.importSlack = function(fileData, success, error) { +export function importSlack(fileData, success, error) { $.ajax({ url: '/api/v1/teams/import_team', type: 'POST', @@ -919,9 +917,9 @@ module.exports.importSlack = function(fileData, success, error) { error(e); } }); -}; +} -module.exports.getStatuses = function(success, error) { +export function getStatuses(success, error) { $.ajax({ url: '/api/v1/users/status', dataType: 'json', @@ -933,9 +931,9 @@ module.exports.getStatuses = function(success, error) { error(e); } }); -}; +} -module.exports.getMyTeam = function(success, error) { +export function getMyTeam(success, error) { $.ajax({ url: '/api/v1/teams/me', dataType: 'json', @@ -947,9 +945,9 @@ module.exports.getMyTeam = function(success, error) { error(e); } }); -}; +} -module.exports.updateValetFeature = function(data, success, error) { +export function updateValetFeature(data, success, error) { $.ajax({ url: '/api/v1/teams/update_valet_feature', dataType: 'json', @@ -963,10 +961,10 @@ module.exports.updateValetFeature = function(data, success, error) { } }); - module.exports.track('api', 'api_teams_update_valet_feature'); -}; + track('api', 'api_teams_update_valet_feature'); +} -function getConfig(success, error) { +export function getConfig(success, error) { $.ajax({ url: '/api/v1/config/get_all', dataType: 'json', @@ -979,4 +977,3 @@ function getConfig(success, error) { } }); } -module.exports.getConfig = getConfig; diff --git a/web/react/utils/constants.jsx b/web/react/utils/constants.jsx index 8721ced7c..3a6ca1b89 100644 --- a/web/react/utils/constants.jsx +++ b/web/react/utils/constants.jsx @@ -4,97 +4,107 @@ var keyMirror = require('keymirror'); module.exports = { - ActionTypes: keyMirror({ - RECIEVED_ERROR: null, + ActionTypes: keyMirror({ + RECIEVED_ERROR: null, - CLICK_CHANNEL: null, - CREATE_CHANNEL: null, - RECIEVED_CHANNELS: null, - RECIEVED_CHANNEL: null, - RECIEVED_MORE_CHANNELS: null, - RECIEVED_CHANNEL_EXTRA_INFO: null, + CLICK_CHANNEL: null, + CREATE_CHANNEL: null, + RECIEVED_CHANNELS: null, + RECIEVED_CHANNEL: null, + RECIEVED_MORE_CHANNELS: null, + RECIEVED_CHANNEL_EXTRA_INFO: null, - RECIEVED_POSTS: null, - RECIEVED_POST: null, - RECIEVED_SEARCH: null, - RECIEVED_POST_SELECTED: null, - RECIEVED_MENTION_DATA: null, - RECIEVED_ADD_MENTION: null, + RECIEVED_POSTS: null, + RECIEVED_POST: null, + RECIEVED_SEARCH: null, + RECIEVED_POST_SELECTED: null, + RECIEVED_MENTION_DATA: null, + RECIEVED_ADD_MENTION: null, - RECIEVED_PROFILES: null, - RECIEVED_ME: null, - RECIEVED_SESSIONS: null, - RECIEVED_AUDITS: null, - RECIEVED_TEAMS: null, - RECIEVED_STATUSES: null, + RECIEVED_PROFILES: null, + RECIEVED_ME: null, + RECIEVED_SESSIONS: null, + RECIEVED_AUDITS: null, + RECIEVED_TEAMS: null, + RECIEVED_STATUSES: null, - RECIEVED_MSG: null, + RECIEVED_MSG: null, - CLICK_TEAM: null, - RECIEVED_TEAM: null, + CLICK_TEAM: null, + RECIEVED_TEAM: null, - RECIEVED_CONFIG: null - }), + RECIEVED_CONFIG: null + }), - PayloadSources: keyMirror({ - SERVER_ACTION: null, - VIEW_ACTION: null - }), - SPECIAL_MENTIONS: ['all', 'channel'], - CHARACTER_LIMIT: 4000, - IMAGE_TYPES: ['jpg', 'gif', 'bmp', 'png', 'jpeg'], - AUDIO_TYPES: ['mp3', 'wav', 'wma', 'm4a', 'flac', 'aac'], - VIDEO_TYPES: ['mp4', 'avi', 'webm', 'mkv', 'wmv', 'mpg', 'mov', 'flv'], - SPREADSHEET_TYPES: ['ppt', 'pptx', 'csv'], - EXCEL_TYPES: ['xlsx'], - WORD_TYPES: ['doc', 'docx'], - CODE_TYPES: ['css', 'html', 'js', 'php', 'rb'], - PDF_TYPES: ['pdf'], - PATCH_TYPES: ['patch'], - ICON_FROM_TYPE: {'audio': 'audio', 'video': 'video', 'spreadsheet': 'ppt', 'pdf': 'pdf', 'code': 'code' , 'word': 'word' , 'excel': 'excel' , 'patch': 'patch', 'other': 'generic'}, - MAX_DISPLAY_FILES: 5, - MAX_UPLOAD_FILES: 5, - MAX_FILE_SIZE: 50000000, // 50 MB - THUMBNAIL_WIDTH: 128, - THUMBNAIL_HEIGHT: 100, - DEFAULT_CHANNEL: 'town-square', - OFFTOPIC_CHANNEL: 'off-topic', - GITLAB_SERVICE: 'gitlab', - EMAIL_SERVICE: 'email', - POST_CHUNK_SIZE: 60, - MAX_POST_CHUNKS: 3, - POST_LOADING: 'loading', - POST_FAILED: 'failed', - POST_DELETED: 'deleted', - RESERVED_TEAM_NAMES: [ - "www", - "web", - "admin", - "support", - "notify", - "test", - "demo", - "mail", - "team", - "channel", - "internal", - "localhost", - "dockerhost", - "stag", - "post", - "cluster", - "api", - ], - RESERVED_USERNAMES: [ - "valet", - "all", - "channel", - ], - MONTHS: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], - MAX_DMS: 20, - MAX_POST_LEN: 4000, - ONLINE_ICON_SVG: "", - OFFLINE_ICON_SVG: "", - MENU_ICON: " ", - COMMENT_ICON: " " + PayloadSources: keyMirror({ + SERVER_ACTION: null, + VIEW_ACTION: null + }), + SPECIAL_MENTIONS: ['all', 'channel'], + CHARACTER_LIMIT: 4000, + IMAGE_TYPES: ['jpg', 'gif', 'bmp', 'png', 'jpeg'], + AUDIO_TYPES: ['mp3', 'wav', 'wma', 'm4a', 'flac', 'aac'], + VIDEO_TYPES: ['mp4', 'avi', 'webm', 'mkv', 'wmv', 'mpg', 'mov', 'flv'], + PRESENTATION_TYPES: ['ppt', 'pptx'], + SPREADSHEET_TYPES: ['xlsx', 'csv'], + WORD_TYPES: ['doc', 'docx'], + CODE_TYPES: ['css', 'html', 'js', 'php', 'rb'], + PDF_TYPES: ['pdf'], + PATCH_TYPES: ['patch'], + ICON_FROM_TYPE: { + audio: 'audio', + video: 'video', + spreadsheet: 'excel', + presentation: 'ppt', + pdf: 'pdf', + code: 'code', + word: 'word', + patch: 'patch', + other: 'generic' + }, + MAX_DISPLAY_FILES: 5, + MAX_UPLOAD_FILES: 5, + MAX_FILE_SIZE: 50000000, // 50 MB + THUMBNAIL_WIDTH: 128, + THUMBNAIL_HEIGHT: 100, + DEFAULT_CHANNEL: 'town-square', + OFFTOPIC_CHANNEL: 'off-topic', + GITLAB_SERVICE: 'gitlab', + EMAIL_SERVICE: 'email', + POST_CHUNK_SIZE: 60, + MAX_POST_CHUNKS: 3, + POST_LOADING: 'loading', + POST_FAILED: 'failed', + POST_DELETED: 'deleted', + RESERVED_TEAM_NAMES: [ + 'www', + 'web', + 'admin', + 'support', + 'notify', + 'test', + 'demo', + 'mail', + 'team', + 'channel', + 'internal', + 'localhost', + 'dockerhost', + 'stag', + 'post', + 'cluster', + 'api' + ], + RESERVED_USERNAMES: [ + 'valet', + 'all', + 'channel' + ], + MONTHS: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + MAX_DMS: 20, + MAX_POST_LEN: 4000, + ONLINE_ICON_SVG: "", + OFFLINE_ICON_SVG: "", + MENU_ICON: " ", + COMMENT_ICON: " " }; diff --git a/web/react/utils/utils.jsx b/web/react/utils/utils.jsx index a1dc72ae2..6267ebd8f 100644 --- a/web/react/utils/utils.jsx +++ b/web/react/utils/utils.jsx @@ -10,19 +10,19 @@ var AsyncClient = require('./async_client.jsx'); var client = require('./client.jsx'); var Autolinker = require('autolinker'); -module.exports.isEmail = function(email) { +export function isEmail(email) { var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; return regex.test(email); -}; +} -module.exports.cleanUpUrlable = function(input) { +export function cleanUpUrlable(input) { var cleaned = input.trim().replace(/-/g, ' ').replace(/[^\w\s]/gi, '').toLowerCase().replace(/\s/g, '-'); cleaned = cleaned.replace(/^\-+/, ''); cleaned = cleaned.replace(/\-+$/, ''); return cleaned; -}; +} -module.exports.isTestDomain = function() { +export function isTestDomain() { if ((/^localhost/).test(window.location.hostname)) { return true; } @@ -52,38 +52,9 @@ module.exports.isTestDomain = function() { } return false; -}; - -function getSubDomain() { - if (module.exports.isTestDomain()) { - return ''; - } - - if ((/^www/).test(window.location.hostname)) { - return ''; - } - - if ((/^beta/).test(window.location.hostname)) { - return ''; - } - - if ((/^ci/).test(window.location.hostname)) { - return ''; - } - - var parts = window.location.hostname.split('.'); - - if (parts.length !== 3) { - return ''; - } - - return parts[0]; } -global.window.getSubDomain = getSubDomain; -module.exports.getSubDomain = getSubDomain; - -module.exports.getDomainWithOutSub = function() { +export function getDomainWithOutSub() { var parts = window.location.host.split('.'); if (parts.length === 1) { @@ -95,17 +66,17 @@ module.exports.getDomainWithOutSub = function() { } return parts[1] + '.' + parts[2]; -}; +} -module.exports.getCookie = function(name) { +export function getCookie(name) { var value = '; ' + document.cookie; var parts = value.split('; ' + name + '='); if (parts.length === 2) { return parts.pop().split(';').shift(); } -}; +} -module.exports.notifyMe = function(title, body, channel) { +export function notifyMe(title, body, channel) { if ('Notification' in window && Notification.permission !== 'denied') { Notification.requestPermission(function onRequestPermission(permission) { if (Notification.permission !== permission) { @@ -117,7 +88,7 @@ module.exports.notifyMe = function(title, body, channel) { notification.onclick = function onClick() { window.focus(); if (channel) { - module.exports.switchChannel(channel); + switchChannel(channel); } else { window.location.href = '/'; } @@ -128,16 +99,16 @@ module.exports.notifyMe = function(title, body, channel) { } }); } -}; +} -module.exports.ding = function() { - if (!module.exports.isBrowserFirefox()) { +export function ding() { + if (!isBrowserFirefox()) { var audio = new Audio('/static/images/ding.mp3'); audio.play(); } -}; +} -module.exports.getUrlParameter = function(sParam) { +export function getUrlParameter(sParam) { var sPageURL = window.location.search.substring(1); var sURLVariables = sPageURL.split('&'); for (var i = 0; i < sURLVariables.length; i++) { @@ -147,20 +118,20 @@ module.exports.getUrlParameter = function(sParam) { } } return null; -}; +} -module.exports.getDateForUnixTicks = function(ticks) { +export function getDateForUnixTicks(ticks) { return new Date(ticks); -}; +} -module.exports.displayDate = function(ticks) { +export function displayDate(ticks) { var d = new Date(ticks); var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; return monthNames[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear(); -}; +} -module.exports.displayTime = function(ticks) { +export function displayTime(ticks) { var d = new Date(ticks); var hours = d.getHours(); var minutes = d.getMinutes(); @@ -178,9 +149,9 @@ module.exports.displayTime = function(ticks) { minutes = '0' + minutes; } return hours + ':' + minutes + ' ' + ampm; -}; +} -module.exports.displayDateTime = function(ticks) { +export function displayDateTime(ticks) { var seconds = Math.floor((Date.now() - ticks) / 1000); var interval = Math.floor(seconds / 3600); @@ -203,16 +174,16 @@ module.exports.displayDateTime = function(ticks) { } return '1 minute ago'; -}; +} -module.exports.displayCommentDateTime = function(ticks) { - return module.exports.displayDate(ticks) + ' ' + module.exports.displayTime(ticks); +export function displayCommentDateTime(ticks) { + return displayDate(ticks) + ' ' + displayTime(ticks); } // returns Unix timestamp in milliseconds -module.exports.getTimestamp = function() { +export function getTimestamp() { return Date.now(); -}; +} function testUrlMatch(text) { var urlMatcher = new Autolinker.matchParser.MatchParser({ @@ -240,7 +211,7 @@ function testUrlMatch(text) { return result; } -module.exports.extractLinks = function(text) { +export function extractLinks(text) { var repRegex = new RegExp('
', 'g'); var matches = testUrlMatch(text.replace(repRegex, '\n')); @@ -254,11 +225,11 @@ module.exports.extractLinks = function(text) { } return {links: links, text: text}; -}; +} -module.exports.escapeRegExp = function(string) { +export function escapeRegExp(string) { return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'); -}; +} function handleYoutubeTime(link) { var timeRegex = /[\\?&]t=([0-9hms]+)/; @@ -317,7 +288,7 @@ function getYoutubeEmbed(link) { return; } var metadata = data.items[0].snippet; - $('.video-type.' + youtubeId).html("Youtube - ") + $('.video-type.' + youtubeId).html('Youtube - '); $('.video-uploader.' + youtubeId).html(metadata.channelTitle); $('.video-title.' + youtubeId).find('a').html(metadata.title); $('.post-list-holder-by-time').scrollTop($('.post-list-holder-by-time')[0].scrollHeight); @@ -328,7 +299,7 @@ function getYoutubeEmbed(link) { async: true, url: 'https://www.googleapis.com/youtube/v3/videos', type: 'GET', - data: {part: 'snippet', id: youtubeId, key:config.GoogleDeveloperKey}, + data: {part: 'snippet', id: youtubeId, key: config.GoogleDeveloperKey}, success: success }); } @@ -340,12 +311,22 @@ function getYoutubeEmbed(link) {

-
+
-
- +
+
- +
@@ -354,7 +335,7 @@ function getYoutubeEmbed(link) { ); } -module.exports.getEmbed = function(link) { +export function getEmbed(link) { var ytRegex = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|watch\?(?:[a-zA-Z-_]+=[a-zA-Z0-9-_]+&)+v=)([^#\&\?]*).*/; var match = link.trim().match(ytRegex); @@ -406,13 +387,13 @@ module.exports.getEmbed = function(link) {
); */ -}; +} -module.exports.areStatesEqual = function(state1, state2) { +export function areStatesEqual(state1, state2) { return JSON.stringify(state1) === JSON.stringify(state2); -}; +} -module.exports.replaceHtmlEntities = function(text) { +export function replaceHtmlEntities(text) { var tagsToReplace = { '&': '&', '<': '<', @@ -426,9 +407,9 @@ module.exports.replaceHtmlEntities = function(text) { } } return newtext; -}; +} -module.exports.insertHtmlEntities = function(text) { +export function insertHtmlEntities(text) { var tagsToReplace = { '&': '&', '<': '<', @@ -442,33 +423,33 @@ module.exports.insertHtmlEntities = function(text) { } } return newtext; -}; +} -module.exports.searchForTerm = function(term) { +export function searchForTerm(term) { AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVED_SEARCH_TERM, term: term, do_search: true }); -}; +} var puncStartRegex = /^((?![@#])\W)+/g; var puncEndRegex = /(\W)+$/g; -module.exports.textToJsx = function(text, options) { - - if (options && options['singleline']) { - var repRegex = new RegExp('\n', 'g'); +export function textToJsx(textin, options) { + var text = textin; + if (options && options.singleline) { + var repRegex = new RegExp('\n', 'g'); //eslint-disable-line no-control-regex text = text.replace(repRegex, ' '); } - var searchTerm = '' - if (options && options['searchTerm']) { - searchTerm = options['searchTerm'].toLowerCase() + var searchTerm = ''; + if (options && options.searchTerm) { + searchTerm = options.searchTerm.toLowerCase(); } var mentionClass = 'mention-highlight'; - if (options && options['noMentionHighlight']) { + if (options && options.noMentionHighlight) { mentionClass = ''; } @@ -480,11 +461,11 @@ module.exports.textToJsx = function(text, options) { var implicitKeywords = UserStore.getCurrentMentionKeys(); var lines = text.split('\n'); - for (var i = 0; i < lines.length; i++) { + for (let i = 0; i < lines.length; i++) { var line = lines[i]; var words = line.split(' '); var highlightSearchClass = ''; - for (var z = 0; z < words.length; z++) { + for (let z = 0; z < words.length; z++) { var word = words[z]; var trimWord = word.replace(puncStartRegex, '').replace(puncEndRegex, '').trim(); var mentionRegex = /^(?:@)([a-z0-9_]+)$/gi; // looks loop invariant but a weird JS bug needs it to be redefined here @@ -493,15 +474,17 @@ module.exports.textToJsx = function(text, options) { if (searchTerm !== '') { let searchWords = searchTerm.split(' '); for (let idx in searchWords) { - let searchWord = searchWords[idx]; - if (searchWord === word.toLowerCase() || searchWord === trimWord.toLowerCase()) { - highlightSearchClass = ' search-highlight'; - break; - } else if (searchWord.charAt(searchWord.length - 1) === '*') { - let searchWordPrefix = searchWord.slice(0,-1); - if (trimWord.toLowerCase().indexOf(searchWordPrefix) > -1 || word.toLowerCase().indexOf(searchWordPrefix) > -1) { + if ({}.hasOwnProperty.call(searchWords, idx)) { + let searchWord = searchWords[idx]; + if (searchWord === word.toLowerCase() || searchWord === trimWord.toLowerCase()) { highlightSearchClass = ' search-highlight'; break; + } else if (searchWord.charAt(searchWord.length - 1) === '*') { + let searchWordPrefix = searchWord.slice(0, -1); + if (trimWord.toLowerCase().indexOf(searchWordPrefix) > -1 || word.toLowerCase().indexOf(searchWordPrefix) > -1) { + highlightSearchClass = ' search-highlight'; + break; + } } } } @@ -509,68 +492,147 @@ module.exports.textToJsx = function(text, options) { if (explicitMention && (UserStore.getProfileByUsername(explicitMention[1]) || - Constants.SPECIAL_MENTIONS.indexOf(explicitMention[1]) !== -1)) - { - var name = explicitMention[1]; - // do both a non-case sensitive and case senstive check - var mClass = implicitKeywords.indexOf('@'+name.toLowerCase()) !== -1 || implicitKeywords.indexOf('@'+name) !== -1 ? mentionClass : ''; + Constants.SPECIAL_MENTIONS.indexOf(explicitMention[1]) !== -1)) { + let name = explicitMention[1]; - var suffix = word.match(puncEndRegex); - var prefix = word.match(puncStartRegex); - - if (searchTerm === name) { - highlightSearchClass = ' search-highlight'; - } + // do both a non-case sensitive and case senstive check + let mClass = ''; + if (('@' + name.toLowerCase()) !== -1 || implicitKeywords.indexOf('@' + name) !== -1) { + mClass = mentionClass; + } - inner.push({prefix}@{name}{suffix} ); - } else if (testUrlMatch(word).length) { - var match = testUrlMatch(word)[0]; - var link = match.link; + let suffix = word.match(puncEndRegex); + let prefix = word.match(puncStartRegex); - var prefix = word.substring(0,word.indexOf(match.text)); - var suffix = word.substring(word.indexOf(match.text)+match.text.length); + if (searchTerm === name) { + highlightSearchClass = ' search-highlight'; + } - inner.push({prefix}{match.text}{suffix} ); + inner.push( + + {prefix} + searchForTerm(name)} //eslint-disable-line no-loop-func + > + @{name} + + {suffix} + {' '} + + ); + } else if (testUrlMatch(word).length) { + let match = testUrlMatch(word)[0]; + let link = match.link; + + let prefix = word.substring(0, word.indexOf(match.text)); + let suffix = word.substring(word.indexOf(match.text) + match.text.length); + + inner.push( + + {prefix} + + {match.text} + + {suffix} + {' '} + + ); + } else if (trimWord.match(hashRegex)) { + let suffix = word.match(puncEndRegex); + let prefix = word.match(puncStartRegex); + let mClass = ''; + if (implicitKeywords.indexOf(trimWord) !== -1 || implicitKeywords.indexOf(trimWord.toLowerCase()) !== -1) { + mClass = mentionClass; + } - } else if (trimWord.match(hashRegex)) { - var suffix = word.match(puncEndRegex); - var prefix = word.match(puncStartRegex); - var mClass = implicitKeywords.indexOf(trimWord) !== -1 || implicitKeywords.indexOf(trimWord.toLowerCase()) !== -1 ? mentionClass : ''; + if (searchTerm === trimWord.substring(1).toLowerCase() || searchTerm === trimWord.toLowerCase()) { + highlightSearchClass = ' search-highlight'; + } - if (searchTerm === trimWord.substring(1).toLowerCase() || searchTerm === trimWord.toLowerCase()) { + inner.push( + + {prefix} + searchForTerm(trimWord)} //eslint-disable-line no-loop-func + > + {trimWord} + + {suffix} + {' '} + + ); + } else if (implicitKeywords.indexOf(trimWord) !== -1 || implicitKeywords.indexOf(trimWord.toLowerCase()) !== -1) { + let suffix = word.match(puncEndRegex); + let prefix = word.match(puncStartRegex); + + if (trimWord.charAt(0) === '@') { + if (searchTerm === trimWord.substring(1).toLowerCase()) { highlightSearchClass = ' search-highlight'; } - - inner.push({prefix}{trimWord}{suffix} ); - - } else if (implicitKeywords.indexOf(trimWord) !== -1 || implicitKeywords.indexOf(trimWord.toLowerCase()) !== -1) { - var suffix = word.match(puncEndRegex); - var prefix = word.match(puncStartRegex); - - if (trimWord.charAt(0) === '@') { - if (searchTerm === trimWord.substring(1).toLowerCase()) { - highlightSearchClass = ' search-highlight'; - } - inner.push({prefix}{trimWord}{suffix} ); - } else { - inner.push({prefix}{module.exports.replaceHtmlEntities(trimWord)}{suffix} ); - } - - } else if (word === '') { - // if word is empty dont include a span + inner.push( + + {prefix} + + {trimWord} + + {suffix} + {' '} + + ); } else { - inner.push({module.exports.replaceHtmlEntities(word)} ); + inner.push( + + {prefix} + + {replaceHtmlEntities(trimWord)} + + {suffix} + {' '} + + ); } - highlightSearchClass = ''; + } else if (word === '') { + + // if word is empty dont include a span + + } else { + inner.push( + + + {replaceHtmlEntities(word)} + + {' '} + + ); + } + highlightSearchClass = ''; + } + if (i !== lines.length - 1) { + inner.push( +
+ ); } - if (i != lines.length-1) - inner.push(
); } return inner; } -module.exports.getFileType = function(extin) { +export function getFileType(extin) { var ext = extin.toLowerCase(); if (Constants.IMAGE_TYPES.indexOf(ext) > -1) { return 'image'; @@ -596,8 +658,8 @@ module.exports.getFileType = function(extin) { return 'word'; } - if (Constants.EXCEL_TYPES.indexOf(ext) > -1) { - return 'excel'; + if (Constants.PRESENTATION_TYPES.indexOf(ext) > -1) { + return 'presentation'; } if (Constants.PDF_TYPES.indexOf(ext) > -1) { @@ -609,9 +671,9 @@ module.exports.getFileType = function(extin) { } return 'other'; -}; +} -module.exports.getPreviewImagePathForFileType = function(fileTypeIn) { +export function getPreviewImagePathForFileType(fileTypeIn) { var fileType = fileTypeIn.toLowerCase(); var icon; @@ -622,9 +684,9 @@ module.exports.getPreviewImagePathForFileType = function(fileTypeIn) { } return '/static/images/icons/' + icon + '.png'; -}; +} -module.exports.getIconClassName = function(fileTypeIn) { +export function getIconClassName(fileTypeIn) { var fileType = fileTypeIn.toLowerCase(); if (fileType in Constants.ICON_FROM_TYPE) { @@ -632,9 +694,9 @@ module.exports.getIconClassName = function(fileTypeIn) { } return 'glyphicon-file'; -}; +} -module.exports.splitFileLocation = function(fileLocation) { +export function splitFileLocation(fileLocation) { var fileSplit = fileLocation.split('.'); var ext = ''; @@ -647,16 +709,16 @@ module.exports.splitFileLocation = function(fileLocation) { var filename = filePath.split('/')[filePath.split('/').length - 1]; return {ext: ext, name: filename, path: filePath}; -}; +} -module.exports.toTitleCase = function(str) { +export function toTitleCase(str) { function doTitleCase(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); } return str.replace(/\w\S*/g, doTitleCase); -}; +} -module.exports.changeCss = function(className, classValue) { +export function changeCss(className, classValue) { // we need invisible container to store additional css definitions var cssMainContainer = $('#css-modifier-container'); if (cssMainContainer.length === 0) { @@ -674,9 +736,9 @@ module.exports.changeCss = function(className, classValue) { // append additional style classContainer.html(''); -}; +} -module.exports.rgb2hex = function(rgbIn) { +export function rgb2hex(rgbIn) { if (/^#[0-9A-F]{6}$/i.test(rgbIn)) { return rgbIn; } @@ -686,9 +748,9 @@ module.exports.rgb2hex = function(rgbIn) { return ('0' + parseInt(x, 10).toString(16)).slice(-2); } return '#' + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); -}; +} -module.exports.placeCaretAtEnd = function(el) { +export function placeCaretAtEnd(el) { el.focus(); if (typeof window.getSelection != 'undefined' && typeof document.createRange != 'undefined') { var range = document.createRange(); @@ -703,9 +765,9 @@ module.exports.placeCaretAtEnd = function(el) { textRange.collapse(false); textRange.select(); } -}; +} -module.exports.getCaretPosition = function(el) { +export function getCaretPosition(el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { @@ -724,9 +786,9 @@ module.exports.getCaretPosition = function(el) { return rc.text.length; } return 0; -}; +} -module.exports.setSelectionRange = function(input, selectionStart, selectionEnd) { +export function setSelectionRange(input, selectionStart, selectionEnd) { if (input.setSelectionRange) { input.focus(); input.setSelectionRange(selectionStart, selectionEnd); @@ -737,13 +799,13 @@ module.exports.setSelectionRange = function(input, selectionStart, selectionEnd) range.moveStart('character', selectionStart); range.select(); } -}; +} -module.exports.setCaretPosition = function(input, pos) { - module.exports.setSelectionRange(input, pos, pos); -}; +export function setCaretPosition(input, pos) { + setSelectionRange(input, pos, pos); +} -module.exports.getSelectedText = function(input) { +export function getSelectedText(input) { var selectedText; if (typeof document.selection !== 'undefined') { input.focus(); @@ -756,9 +818,9 @@ module.exports.getSelectedText = function(input) { } return selectedText; -}; +} -module.exports.isValidUsername = function(name) { +export function isValidUsername(name) { var error = ''; if (!name) { error = 'This field is required'; @@ -780,20 +842,18 @@ module.exports.isValidUsername = function(name) { } return error; -}; +} -function updateTabTitle(name) { +export function updateTabTitle(name) { document.title = name + ' ' + document.title.substring(document.title.lastIndexOf('-')); } -module.exports.updateTabTitle = updateTabTitle; -function updateAddressBar(channelName) { +export function updateAddressBar(channelName) { var teamURL = window.location.href.split('/channels')[0]; history.replaceState('data', '', teamURL + '/channels/' + channelName); } -module.exports.updateAddressBar = updateAddressBar; -function switchChannel(channel, teammateName) { +export function switchChannel(channel, teammateName) { AppDispatcher.handleViewAction({ type: ActionTypes.CLICK_CHANNEL, name: channel.name, @@ -819,20 +879,19 @@ function switchChannel(channel, teammateName) { return false; } -module.exports.switchChannel = switchChannel; -module.exports.isMobile = function() { +export function isMobile() { return screen.width <= 768; -}; +} -module.exports.isComment = function(post) { +export function isComment(post) { if ('root_id' in post) { return post.root_id !== ''; } return false; -}; +} -module.exports.getDirectTeammate = function(channelId) { +export function getDirectTeammate(channelId) { var userIds = ChannelStore.get(channelId).name.split('__'); var curUserId = UserStore.getCurrentId(); var teammate = {}; @@ -849,9 +908,9 @@ module.exports.getDirectTeammate = function(channelId) { } return teammate; -}; +} -Image.prototype.load = function(url, progressCallback) { +Image.prototype.load = function imageLoad(url, progressCallback) { var self = this; var xmlHTTP = new XMLHttpRequest(); xmlHTTP.open('GET', url, true); @@ -878,7 +937,7 @@ Image.prototype.load = function(url, progressCallback) { Image.prototype.completedPercentage = 0; -module.exports.changeColor = function(colourIn, amt) { +export function changeColor(colourIn, amt) { var usePound = false; var col = colourIn; @@ -919,10 +978,9 @@ module.exports.changeColor = function(colourIn, amt) { } return pound + String('000000' + (g | (b << 8) | (r << 16)).toString(16)).slice(-6); -}; - -module.exports.changeOpacity = function(oldColor, opacity) { +} +export function changeOpacity(oldColor, opacity) { var col = oldColor; if (col[0] === '#') { col = col.slice(1); @@ -933,9 +991,9 @@ module.exports.changeOpacity = function(oldColor, opacity) { var b = parseInt(col.substring(4, 6), 16); return 'rgba(' + r + ',' + g + ',' + b + ',' + opacity + ')'; -}; +} -module.exports.getFullName = function(user) { +export function getFullName(user) { if (user.first_name && user.last_name) { return user.first_name + ' ' + user.last_name; } else if (user.first_name) { @@ -945,23 +1003,23 @@ module.exports.getFullName = function(user) { } return ''; -}; +} -module.exports.getDisplayName = function(user) { +export function getDisplayName(user) { if (user.nickname && user.nickname.trim().length > 0) { return user.nickname; } - var fullName = module.exports.getFullName(user); + var fullName = getFullName(user); if (fullName) { return fullName; } return user.username; -}; +} //IE10 does not set window.location.origin automatically so this must be called instead when using it -module.exports.getWindowLocationOrigin = function() { +export function getWindowLocationOrigin() { var windowLocationOrigin = window.location.origin; if (!windowLocationOrigin) { windowLocationOrigin = window.location.protocol + '//' + window.location.hostname; @@ -970,10 +1028,10 @@ module.exports.getWindowLocationOrigin = function() { } } return windowLocationOrigin; -}; +} // Converts a file size in bytes into a human-readable string of the form '123MB'. -module.exports.fileSizeToString = function(bytes) { +export function fileSizeToString(bytes) { // it's unlikely that we'll have files bigger than this if (bytes > 1024 * 1024 * 1024 * 1024) { return Math.floor(bytes / (1024 * 1024 * 1024 * 1024)) + 'TB'; @@ -986,29 +1044,29 @@ module.exports.fileSizeToString = function(bytes) { } return bytes + 'B'; -}; +} // Converts a filename (like those attached to Post objects) to a url that can be used to retrieve attachments from the server. -module.exports.getFileUrl = function(filename) { +export function getFileUrl(filename) { var url = filename; // This is a temporary patch to fix issue with old files using absolute paths if (url.indexOf('/api/v1/files/get') !== -1) { url = filename.split('/api/v1/files/get')[1]; } - url = module.exports.getWindowLocationOrigin() + '/api/v1/files/get' + url; + url = getWindowLocationOrigin() + '/api/v1/files/get' + url; return url; -}; +} // Gets the name of a file (including extension) from a given url or file path. -module.exports.getFileName = function(path) { +export function getFileName(path) { var split = path.split('/'); return split[split.length - 1]; -}; +} // Generates a RFC-4122 version 4 compliant globally unique identifier. -module.exports.generateId = function() { +export function generateId() { // implementation taken from http://stackoverflow.com/a/2117523 var id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'; @@ -1026,14 +1084,14 @@ module.exports.generateId = function() { }); return id; -}; +} -module.exports.isBrowserFirefox = function() { +export function isBrowserFirefox() { return navigator && navigator.userAgent && navigator.userAgent.toLowerCase().indexOf('firefox') > -1; -}; +} // Checks if browser is IE10 or IE11 -module.exports.isBrowserIE = function() { +export function isBrowserIE() { if (window.navigator && window.navigator.userAgent) { var ua = window.navigator.userAgent; @@ -1041,14 +1099,14 @@ module.exports.isBrowserIE = function() { } return false; -}; +} -module.exports.isBrowserEdge = function() { +export function isBrowserEdge() { return window.naviagtor && navigator.userAgent && navigator.userAgent.toLowerCase().indexOf('edge') > -1; -}; +} // Used to get the id of the other user from a DM channel -module.exports.getUserIdFromChannelName = function(channel) { +export function getUserIdFromChannelName(channel) { var ids = channel.name.split('__'); var otherUserId = ''; if (ids[0] === UserStore.getCurrentId()) { @@ -1058,13 +1116,13 @@ module.exports.getUserIdFromChannelName = function(channel) { } return otherUserId; -}; +} -module.exports.importSlack = function(file, success, error) { +export function importSlack(file, success, error) { var formData = new FormData(); formData.append('file', file, file.name); formData.append('filesize', file.size); formData.append('importFrom', 'slack'); client.importSlack(formData, success, error); -}; +} -- cgit v1.2.3-1-g7c22