Merge pull request #2213 from aaronraimist/lint

Fix various lint errors
This commit is contained in:
David Baker 2018-10-12 09:31:12 +01:00 committed by GitHub
commit 52eb263c2c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 249 additions and 291 deletions

View file

@ -39,7 +39,6 @@ src/components/views/elements/InlineSpinner.js
src/components/views/elements/MemberEventListSummary.js
src/components/views/elements/Spinner.js
src/components/views/elements/TintableSvg.js
src/components/views/elements/UserInfo.js
src/components/views/elements/UserSelector.js
src/components/views/globals/MatrixToolbar.js
src/components/views/globals/NewVersionBar.js
@ -54,7 +53,6 @@ src/components/views/messages/RoomAvatarEvent.js
src/components/views/messages/TextualBody.js
src/components/views/room_settings/AliasSettings.js
src/components/views/room_settings/ColorSettings.js
src/components/views/room_settings/UrlPreviewSettings.js
src/components/views/rooms/Autocomplete.js
src/components/views/rooms/AuxPanel.js
src/components/views/rooms/EntityTile.js
@ -66,7 +64,6 @@ src/components/views/rooms/MemberTile.js
src/components/views/rooms/MessageComposer.js
src/components/views/rooms/MessageComposerInput.js
src/components/views/rooms/PinnedEventTile.js
src/components/views/rooms/RoomDropTarget.js
src/components/views/rooms/RoomList.js
src/components/views/rooms/RoomPreviewBar.js
src/components/views/rooms/RoomSettings.js
@ -92,7 +89,6 @@ src/Markdown.js
src/MatrixClientPeg.js
src/Modal.js
src/notifications/ContentRules.js
src/notifications/NotificationUtils.js
src/notifications/PushRuleVectorState.js
src/notifications/StandardActions.js
src/notifications/VectorPushRulesDefinitions.js
@ -102,7 +98,6 @@ src/Presence.js
src/rageshake/rageshake.js
src/rageshake/submit-rageshake.js
src/ratelimitedfunc.js
src/RichText.js
src/Roles.js
src/Rooms.js
src/ScalarAuthClient.js

View file

@ -56,12 +56,12 @@ class ScalarAuthClient {
// Something went wrong - try to get a new token.
console.warn("Registering for new scalar token");
return this.registerForToken();
})
});
}
}
validateToken(token) {
let url = SdkConfig.get().integrations_rest_url + "/account";
const url = SdkConfig.get().integrations_rest_url + "/account";
return new Promise(function(resolve, reject) {
request({
@ -80,7 +80,7 @@ class ScalarAuthClient {
resolve(body.user_id);
}
});
})
});
}
registerForToken() {
@ -114,7 +114,7 @@ class ScalarAuthClient {
resolve(body.scalar_token);
}
});
})
});
}
getScalarPageTitle(url) {
@ -142,7 +142,7 @@ class ScalarAuthClient {
resolve(title);
}
});
})
});
}
/**

View file

@ -17,9 +17,9 @@ limitations under the License.
"use strict";
import Promise from 'bluebird';
var Matrix = require("matrix-js-sdk");
var Room = Matrix.Room;
var CallHandler = require('./CallHandler');
const Matrix = require("matrix-js-sdk");
const Room = Matrix.Room;
const CallHandler = require('./CallHandler');
// FIXME: this is Riot (Vector) specific code, but will be removed shortly when
// we switch over to jitsi entirely for video conferencing.
@ -28,8 +28,8 @@ var CallHandler = require('./CallHandler');
// This is bad because it prevents people running their own ASes from being used.
// This isn't permanent and will be customisable in the future: see the proposal
// at docs/conferencing.md for more info.
var USER_PREFIX = "fs_";
var DOMAIN = "matrix.org";
const USER_PREFIX = "fs_";
const DOMAIN = "matrix.org";
function ConferenceCall(matrixClient, groupChatRoomId) {
this.client = matrixClient;
@ -38,14 +38,14 @@ function ConferenceCall(matrixClient, groupChatRoomId) {
}
ConferenceCall.prototype.setup = function() {
var self = this;
const self = this;
return this._joinConferenceUser().then(function() {
return self._getConferenceUserRoom();
}).then(function(room) {
// return a call for *this* room to be placed. We also tack on
// confUserId to speed up lookups (else we'd need to loop every room
// looking for a 1:1 room with this conf user ID!)
var call = Matrix.createNewMatrixCall(self.client, room.roomId);
const call = Matrix.createNewMatrixCall(self.client, room.roomId);
call.confUserId = self.confUserId;
call.groupRoomId = self.groupRoomId;
return call;
@ -54,11 +54,11 @@ ConferenceCall.prototype.setup = function() {
ConferenceCall.prototype._joinConferenceUser = function() {
// Make sure the conference user is in the group chat room
var groupRoom = this.client.getRoom(this.groupRoomId);
const groupRoom = this.client.getRoom(this.groupRoomId);
if (!groupRoom) {
return Promise.reject("Bad group room ID");
}
var member = groupRoom.getMember(this.confUserId);
const member = groupRoom.getMember(this.confUserId);
if (member && member.membership === "join") {
return Promise.resolve();
}
@ -67,10 +67,10 @@ ConferenceCall.prototype._joinConferenceUser = function() {
ConferenceCall.prototype._getConferenceUserRoom = function() {
// Use an existing 1:1 with the conference user; else make one
var rooms = this.client.getRooms();
var confRoom = null;
for (var i = 0; i < rooms.length; i++) {
var confUser = rooms[i].getMember(this.confUserId);
const rooms = this.client.getRooms();
let confRoom = null;
for (let i = 0; i < rooms.length; i++) {
const confUser = rooms[i].getMember(this.confUserId);
if (confUser && confUser.membership === "join" &&
rooms[i].getJoinedMemberCount() === 2) {
confRoom = rooms[i];
@ -82,7 +82,7 @@ ConferenceCall.prototype._getConferenceUserRoom = function() {
}
return this.client.createRoom({
preset: "private_chat",
invite: [this.confUserId]
invite: [this.confUserId],
}).then(function(res) {
return new Room(res.room_id, null, client.getUserId());
});
@ -97,9 +97,9 @@ module.exports.isConferenceUser = function(userId) {
if (userId.indexOf("@" + USER_PREFIX) !== 0) {
return false;
}
var base64part = userId.split(":")[0].substring(1 + USER_PREFIX.length);
const base64part = userId.split(":")[0].substring(1 + USER_PREFIX.length);
if (base64part) {
var decoded = new Buffer(base64part, "base64").toString();
const decoded = new Buffer(base64part, "base64").toString();
// ! $STUFF : $STUFF
return /^!.+:.+/.test(decoded);
}
@ -108,23 +108,23 @@ module.exports.isConferenceUser = function(userId) {
module.exports.getConferenceUserIdForRoom = function(roomId) {
// abuse browserify's core node Buffer support (strip padding ='s)
var base64RoomId = new Buffer(roomId).toString("base64").replace(/=/g, "");
const base64RoomId = new Buffer(roomId).toString("base64").replace(/=/g, "");
return "@" + USER_PREFIX + base64RoomId + ":" + DOMAIN;
};
module.exports.createNewMatrixCall = function(client, roomId) {
var confCall = new ConferenceCall(
client, roomId
const confCall = new ConferenceCall(
client, roomId,
);
return confCall.setup();
};
module.exports.getConferenceCallForRoom = function(roomId) {
// search for a conference 1:1 call for this group chat room ID
var activeCall = CallHandler.getAnyActiveCall();
const activeCall = CallHandler.getAnyActiveCall();
if (activeCall && activeCall.confUserId) {
var thisRoomConfUserId = module.exports.getConferenceUserIdForRoom(
roomId
const thisRoomConfUserId = module.exports.getConferenceUserIdForRoom(
roomId,
);
if (thisRoomConfUserId === activeCall.confUserId) {
return activeCall;

View file

@ -20,7 +20,8 @@ import { _t } from '../../../languageHandler';
export default (props) => {
const description =
_t("Riot now uses 3-5x less memory, by only loading information about other users when needed. Please wait whilst we resynchronise with the server!");
_t("Riot now uses 3-5x less memory, by only loading information about other users"
+ " when needed. Please wait whilst we resynchronise with the server!");
return (<QuestionDialog
hasCancelButton={false}

View file

@ -96,7 +96,7 @@ export default React.createClass({
render() {
const EmojiText = sdk.getComponent('elements.EmojiText');
const {mxEvent} = this.props;
let name = mxEvent.sender ? mxEvent.sender.name : mxEvent.getSender();
const name = mxEvent.sender ? mxEvent.sender.name : mxEvent.getSender();
const {msgtype} = mxEvent.getContent();
if (msgtype === 'm.emote') {

View file

@ -114,7 +114,7 @@ export default class Autocomplete extends React.Component {
processQuery(query, selection) {
return this.autocompleter.getCompletions(
query, selection, this.state.forceComplete
query, selection, this.state.forceComplete,
).then((completions) => {
// Only ever process the completions for the most recent query being processed
if (query !== this.queryRequested) {

View file

@ -777,7 +777,7 @@ module.exports = withMatrixClient(React.createClass({
const myMembership = room.getMyMembership();
// not a DM room if we have are not joined
if (myMembership !== 'join') continue;
const them = this.props.member;
// not a DM room if they are not joined
if (!them.membership || them.membership !== 'join') continue;

View file

@ -224,7 +224,7 @@ export default class MessageComposerInput extends React.Component {
object: 'block',
type: type,
nodes: next(el.childNodes),
}
};
}
type = MARK_TAGS[tag];
if (type) {
@ -232,7 +232,7 @@ export default class MessageComposerInput extends React.Component {
object: 'mark',
type: type,
nodes: next(el.childNodes),
}
};
}
// special case links
if (tag === 'a') {
@ -250,15 +250,14 @@ export default class MessageComposerInput extends React.Component {
completion: el.innerText,
completionId: m[1],
},
}
}
else {
};
} else {
return {
object: 'inline',
type: 'link',
data: { href },
nodes: next(el.childNodes),
}
};
}
}
},
@ -268,14 +267,12 @@ export default class MessageComposerInput extends React.Component {
node: obj,
children: children,
});
}
else if (obj.object === 'mark') {
} else if (obj.object === 'mark') {
return this.renderMark({
mark: obj,
children: children,
});
}
else if (obj.object === 'inline') {
} else if (obj.object === 'inline') {
// special case links, pills and emoji otherwise we
// end up with React components getting rendered out(!)
switch (obj.type) {
@ -295,9 +292,9 @@ export default class MessageComposerInput extends React.Component {
children: children,
});
}
}
}
]
},
},
],
});
const savedState = MessageComposerStore.getEditorState(this.props.room.roomId);
@ -361,7 +358,7 @@ export default class MessageComposerInput extends React.Component {
onAction = (payload) => {
const editor = this._editor;
let editorState = this.state.editorState;
const editorState = this.state.editorState;
switch (payload.action) {
case 'reply_to_event':
@ -427,13 +424,13 @@ export default class MessageComposerInput extends React.Component {
this.onChange(change);
} else {
let fragmentChange = fragment.change();
const fragmentChange = fragment.change();
fragmentChange.moveToRangeOfNode(fragment.document)
.wrapBlock(quote);
// FIXME: handle pills and use commonmark rather than md-serialize
const md = this.md.serialize(fragmentChange.value);
let change = editorState.change()
const change = editorState.change()
.insertText(md + '\n\n')
.focus();
this.onChange(change);
@ -535,8 +532,7 @@ export default class MessageComposerInput extends React.Component {
if (this.autocomplete.state.completionList.length > 0 && !this.autocomplete.state.hide &&
!rangeEquals(this.state.editorState.selection, editorState.selection) &&
// XXX: the heuristic failed when inlines like pills weren't taken into account. This is inideal
this.state.editorState.document.toJSON() === editorState.document.toJSON())
{
this.state.editorState.document.toJSON() === editorState.document.toJSON()) {
this.autocomplete.hide();
}
@ -606,8 +602,7 @@ export default class MessageComposerInput extends React.Component {
// child text. This seems to happen due to selection getting
// moved in the normalisation phase after calculating these changes
if (editorState.selection.anchor.key &&
editorState.document.getParent(editorState.selection.anchor.key).type === 'emoji')
{
editorState.document.getParent(editorState.selection.anchor.key).type === 'emoji') {
change = change.moveToStartOfNextText();
editorState = change.value;
}
@ -620,15 +615,14 @@ export default class MessageComposerInput extends React.Component {
const parent = editorState.document.getParent(editorState.blocks.first().key);
if (parent.type === 'numbered-list') {
blockType = 'numbered-list';
}
else if (parent.type === 'bulleted-list') {
} else if (parent.type === 'bulleted-list') {
blockType = 'bulleted-list';
}
}
const inputState = {
marks: editorState.activeMarks,
isRichTextEnabled: this.state.isRichTextEnabled,
blockType
blockType,
};
this.props.onInputStateChanged(inputState);
}
@ -638,7 +632,7 @@ export default class MessageComposerInput extends React.Component {
this.setState({
editorState,
originalEditorState: originalEditorState || null
originalEditorState: originalEditorState || null,
});
};
@ -678,7 +672,7 @@ export default class MessageComposerInput extends React.Component {
// which doesn't roundtrip symmetrically with commonmark, which we use for
// compiling MD out of the MD editor state above.
this.md.serialize(editorState),
{ defaultBlock: DEFAULT_NODE }
{ defaultBlock: DEFAULT_NODE },
);
}
@ -702,7 +696,7 @@ export default class MessageComposerInput extends React.Component {
});
SettingsStore.setValue("MessageComposerInput.isRichTextEnabled", null, SettingLevel.ACCOUNT, enabled);
};
}
/**
* Check if the current selection has a mark with `type` in it.
@ -712,8 +706,8 @@ export default class MessageComposerInput extends React.Component {
*/
hasMark = type => {
const { editorState } = this.state
return editorState.activeMarks.some(mark => mark.type === type)
const { editorState } = this.state;
return editorState.activeMarks.some(mark => mark.type === type);
};
/**
@ -724,20 +718,18 @@ export default class MessageComposerInput extends React.Component {
*/
hasBlock = type => {
const { editorState } = this.state
return editorState.blocks.some(node => node.type === type)
const { editorState } = this.state;
return editorState.blocks.some(node => node.type === type);
};
onKeyDown = (ev: KeyboardEvent, change: Change, editor: Editor) => {
this.suppressAutoComplete = false;
// skip void nodes - see
// https://github.com/ianstormtaylor/slate/issues/762#issuecomment-304855095
if (ev.keyCode === KeyCode.LEFT) {
this.direction = 'Previous';
}
else if (ev.keyCode === KeyCode.RIGHT) {
} else if (ev.keyCode === KeyCode.RIGHT) {
this.direction = 'Next';
} else {
this.direction = '';
@ -815,8 +807,7 @@ export default class MessageComposerInput extends React.Component {
.unwrapBlock('bulleted-list')
.unwrapBlock('numbered-list');
return change;
}
else if (editorState.selection.anchor.offset == 0 && editorState.isCollapsed) {
} else if (editorState.selection.anchor.offset == 0 && editorState.isCollapsed) {
// turn blocks back into paragraphs
if ((this.hasBlock('block-quote') ||
this.hasBlock('heading1') ||
@ -825,8 +816,7 @@ export default class MessageComposerInput extends React.Component {
this.hasBlock('heading4') ||
this.hasBlock('heading5') ||
this.hasBlock('heading6') ||
this.hasBlock('code')))
{
this.hasBlock('code'))) {
return change.setBlocks(DEFAULT_NODE);
}
@ -835,8 +825,7 @@ export default class MessageComposerInput extends React.Component {
if (editorState.selection.anchor.offset == 0 &&
this.hasBlock('paragraph') &&
parent.nodes.size == 1 &&
parent.object !== 'document')
{
parent.object !== 'document') {
return change.replaceNodeByKey(editorState.anchorBlock.key, editorState.anchorText)
.moveToEndOfNode(parent)
.focus();
@ -852,7 +841,7 @@ export default class MessageComposerInput extends React.Component {
return true;
}
let newState: ?Value = null;
const newState: ?Value = null;
// Draft handles rich text mode commands by default but we need to do it ourselves for Markdown.
if (this.state.isRichTextEnabled) {
@ -878,7 +867,7 @@ export default class MessageComposerInput extends React.Component {
} else if (isList) {
change
.unwrapBlock(
type === 'bulleted-list' ? 'numbered-list' : 'bulleted-list'
type === 'bulleted-list' ? 'numbered-list' : 'bulleted-list',
)
.wrapBlock(type);
} else {
@ -1081,8 +1070,7 @@ export default class MessageComposerInput extends React.Component {
const firstGrandChild = firstChild && firstChild.nodes.get(0);
if (firstChild && firstGrandChild &&
firstChild.object === 'block' && firstGrandChild.object === 'text' &&
firstGrandChild.text[0] === '/')
{
firstGrandChild.text[0] === '/') {
commandText = this.plainWithIdPills.serialize(editorState);
cmd = processCommandInput(this.props.room.roomId, commandText);
}
@ -1223,7 +1211,7 @@ export default class MessageComposerInput extends React.Component {
this.setState({
editorState: this.createEditorState(),
}, ()=>{ this._editor.focus() });
}, ()=>{ this._editor.focus(); });
return true;
};
@ -1353,7 +1341,7 @@ export default class MessageComposerInput extends React.Component {
if (displayedCompletion == null) {
if (this.state.originalEditorState) {
let editorState = this.state.originalEditorState;
const editorState = this.state.originalEditorState;
this.setState({editorState});
}
return false;
@ -1364,7 +1352,7 @@ export default class MessageComposerInput extends React.Component {
completion = '',
completionId = '',
href = null,
suffix = ''
suffix = '',
} = displayedCompletion;
let inline;
@ -1397,8 +1385,7 @@ export default class MessageComposerInput extends React.Component {
.insertInlineAtRange(editorState.selection, inline)
.insertText(suffix)
.focus();
}
else {
} else {
change = editorState.change()
.insertTextAtRange(editorState.selection, completion)
.insertText(suffix)
@ -1459,8 +1446,7 @@ export default class MessageComposerInput extends React.Component {
isSelected={isSelected}
{...attributes}
/>;
}
else if (Pill.isPillUrl(url)) {
} else if (Pill.isPillUrl(url)) {
return <Pill
url={url}
room={this.props.room}
@ -1468,8 +1454,7 @@ export default class MessageComposerInput extends React.Component {
isSelected={isSelected}
{...attributes}
/>;
}
else {
} else {
const { text } = node;
return <a href={url} {...props.attributes}>
{ text }
@ -1482,11 +1467,11 @@ export default class MessageComposerInput extends React.Component {
const uri = RichText.unicodeToEmojiUri(emojiUnicode);
const shortname = toShort(emojiUnicode);
const className = classNames('mx_emojione', {
mx_emojione_selected: isSelected
mx_emojione_selected: isSelected,
});
const style = {};
if (props.selected) style.border = '1px solid blue';
return <img className={ className } src={ uri } title={ shortname } alt={ emojiUnicode } style={style}/>;
return <img className={ className } src={ uri } title={ shortname } alt={ emojiUnicode } style={style} />;
}
}
};
@ -1533,8 +1518,7 @@ export default class MessageComposerInput extends React.Component {
if (editorState.selection.anchor.key) {
return editorState.document.getDescendant(editorState.selection.anchor.key).text;
}
else {
} else {
return '';
}
}
@ -1556,7 +1540,7 @@ export default class MessageComposerInput extends React.Component {
start: editorState.selection.anchor.offset,
end: (editorState.selection.anchor.key == editorState.selection.focus.key) ?
editorState.selection.focus.offset : editorState.selection.anchor.offset,
}
};
if (range.start > range.end) {
const tmp = range.start;
range.start = range.end;

View file

@ -16,7 +16,7 @@ limitations under the License.
'use strict';
var React = require('react');
const React = require('react');
module.exports = React.createClass({
displayName: 'RoomDropTarget',
@ -31,5 +31,5 @@ module.exports = React.createClass({
</div>
</div>
);
}
},
});

View file

@ -16,11 +16,11 @@ limitations under the License.
'use strict';
var React = require('react');
var MatrixClientPeg = require('../../../MatrixClientPeg');
var sdk = require('../../../index');
var classNames = require('classnames');
var AccessibleButton = require('../../../components/views/elements/AccessibleButton');
const React = require('react');
const MatrixClientPeg = require('../../../MatrixClientPeg');
const sdk = require('../../../index');
const classNames = require('classnames');
const AccessibleButton = require('../../../components/views/elements/AccessibleButton');
import { _t } from '../../../languageHandler';
module.exports = React.createClass({
@ -28,7 +28,7 @@ module.exports = React.createClass({
getInitialState: function() {
return ({
scope: 'Room'
scope: 'Room',
});
},
@ -54,18 +54,18 @@ module.exports = React.createClass({
},
render: function() {
var searchButtonClasses = classNames({ mx_SearchBar_searchButton : true, mx_SearchBar_searching: this.props.searchInProgress });
var thisRoomClasses = classNames({ mx_SearchBar_button : true, mx_SearchBar_unselected : this.state.scope !== 'Room' });
var allRoomsClasses = classNames({ mx_SearchBar_button : true, mx_SearchBar_unselected : this.state.scope !== 'All' });
const searchButtonClasses = classNames({ mx_SearchBar_searchButton: true, mx_SearchBar_searching: this.props.searchInProgress });
const thisRoomClasses = classNames({ mx_SearchBar_button: true, mx_SearchBar_unselected: this.state.scope !== 'Room' });
const allRoomsClasses = classNames({ mx_SearchBar_button: true, mx_SearchBar_unselected: this.state.scope !== 'All' });
return (
<div className="mx_SearchBar">
<input ref="search_term" className="mx_SearchBar_input" type="text" autoFocus={true} placeholder={_t("Search…")} onKeyDown={this.onSearchChange}/>
<AccessibleButton className={ searchButtonClasses } onClick={this.onSearch}><img src="img/search-button.svg" width="37" height="37" alt={_t("Search")}/></AccessibleButton>
<div className="mx_SearchBar">
<input ref="search_term" className="mx_SearchBar_input" type="text" autoFocus={true} placeholder={_t("Search…")} onKeyDown={this.onSearchChange} />
<AccessibleButton className={ searchButtonClasses } onClick={this.onSearch}><img src="img/search-button.svg" width="37" height="37" alt={_t("Search")} /></AccessibleButton>
<AccessibleButton className={ thisRoomClasses } onClick={this.onThisRoomClick}>{_t("This Room")}</AccessibleButton>
<AccessibleButton className={ allRoomsClasses } onClick={this.onAllRoomsClick}>{_t("All Rooms")}</AccessibleButton>
<AccessibleButton className="mx_SearchBar_cancel" onClick={this.props.onCancelClick}><img src="img/cancel.svg" width="18" height="18" /></AccessibleButton>
</div>
);
}
},
});

View file

@ -16,10 +16,10 @@ limitations under the License.
'use strict';
var React = require('react');
var sdk = require('../../../index');
var MatrixClientPeg = require('../../../MatrixClientPeg');
var dis = require('../../../dispatcher');
const React = require('react');
const sdk = require('../../../index');
const MatrixClientPeg = require('../../../MatrixClientPeg');
const dis = require('../../../dispatcher');
module.exports = React.createClass({
displayName: 'IntegrationsManager',
@ -59,5 +59,5 @@ module.exports = React.createClass({
return (
<iframe src={ this.props.src }></iframe>
);
}
},
});

View file

@ -26,7 +26,7 @@ import {
NotificationUtils,
VectorPushRulesDefinitions,
PushRuleVectorState,
ContentRules
ContentRules,
} from '../../../notifications';
// TODO: this "view" component still has far too much application logic in it,
@ -47,7 +47,7 @@ const LEGACY_RULES = {
"im.vector.rule.room_message": ".m.rule.message",
"im.vector.rule.invite_for_me": ".m.rule.invite_for_me",
"im.vector.rule.call": ".m.rule.call",
"im.vector.rule.notices": ".m.rule.suppress_notices"
"im.vector.rule.notices": ".m.rule.suppress_notices",
};
function portLegacyActions(actions) {
@ -67,7 +67,7 @@ module.exports = React.createClass({
phases: {
LOADING: "LOADING", // The component is loading or sending data to the hs
DISPLAY: "DISPLAY", // The component is ready and display data
ERROR: "ERROR" // There was an error
ERROR: "ERROR", // There was an error
},
propTypes: {
@ -79,7 +79,7 @@ module.exports = React.createClass({
getDefaultProps: function() {
return {
threepids: []
threepids: [],
};
},
@ -90,10 +90,10 @@ module.exports = React.createClass({
vectorPushRules: [], // HS default push rules displayed in Vector UI
vectorContentRules: { // Keyword push rules displayed in Vector UI
vectorState: PushRuleVectorState.ON,
rules: []
rules: [],
},
externalPushRules: [], // Push rules (except content rule) that have been defined outside Vector UI
externalContentRules: [] // Keyword push rules that have been defined outside Vector UI
externalContentRules: [], // Keyword push rules that have been defined outside Vector UI
};
},
@ -104,7 +104,7 @@ module.exports = React.createClass({
onEnableNotificationsChange: function(event) {
const self = this;
this.setState({
phase: this.phases.LOADING
phase: this.phases.LOADING,
});
MatrixClientPeg.get().setPushRuleEnabled('global', self.state.masterPushRule.kind, self.state.masterPushRule.rule_id, !event.target.checked).done(function() {
@ -145,7 +145,7 @@ module.exports = React.createClass({
onEnableEmailNotificationsChange: function(address, event) {
let emailPusherPromise;
if (event.target.checked) {
const data = {}
const data = {};
data['brand'] = this.props.brand || 'Riot';
emailPusherPromise = UserSettingsStore.addEmailPusher(address, data);
} else {
@ -170,9 +170,8 @@ module.exports = React.createClass({
const newPushRuleVectorState = event.target.className.split("-")[1];
if ("_keywords" === vectorRuleId) {
this._setKeywordsPushRuleVectorState(newPushRuleVectorState)
}
else {
this._setKeywordsPushRuleVectorState(newPushRuleVectorState);
} else {
const rule = this.getRule(vectorRuleId);
if (rule) {
this._setPushRuleVectorState(rule, newPushRuleVectorState);
@ -185,7 +184,7 @@ module.exports = React.createClass({
// Compute the keywords list to display
let keywords = [];
for (let i in this.state.vectorContentRules.rules) {
for (const i in this.state.vectorContentRules.rules) {
const rule = this.state.vectorContentRules.rules[i];
keywords.push(rule.pattern);
}
@ -195,8 +194,7 @@ module.exports = React.createClass({
keywords.sort();
keywords = keywords.join(", ");
}
else {
} else {
keywords = "";
}
@ -207,29 +205,28 @@ module.exports = React.createClass({
button: _t('OK'),
value: keywords,
onFinished: function onFinished(should_leave, newValue) {
if (should_leave && newValue !== keywords) {
let newKeywords = newValue.split(',');
for (let i in newKeywords) {
for (const i in newKeywords) {
newKeywords[i] = newKeywords[i].trim();
}
// Remove duplicates and empty
newKeywords = newKeywords.reduce(function(array, keyword){
newKeywords = newKeywords.reduce(function(array, keyword) {
if (keyword !== "" && array.indexOf(keyword) < 0) {
array.push(keyword);
}
return array;
},[]);
}, []);
self._setKeywords(newKeywords);
}
}
},
});
},
getRule: function(vectorRuleId) {
for (let i in this.state.vectorPushRules) {
for (const i in this.state.vectorPushRules) {
const rule = this.state.vectorPushRules[i];
if (rule.vectorRuleId === vectorRuleId) {
return rule;
@ -239,9 +236,8 @@ module.exports = React.createClass({
_setPushRuleVectorState: function(rule, newPushRuleVectorState) {
if (rule && rule.vectorState !== newPushRuleVectorState) {
this.setState({
phase: this.phases.LOADING
phase: this.phases.LOADING,
});
const self = this;
@ -255,8 +251,7 @@ module.exports = React.createClass({
if (!actions) {
// The new state corresponds to disabling the rule.
deferreds.push(cli.setPushRuleEnabled('global', rule.rule.kind, rule.rule.rule_id, false));
}
else {
} else {
// The new state corresponds to enabling the rule and setting specific actions
deferreds.push(this._updatePushRuleActions(rule.rule, actions, true));
}
@ -270,7 +265,7 @@ module.exports = React.createClass({
Modal.createTrackedDialog('Failed to change settings', '', ErrorDialog, {
title: _t('Failed to change settings'),
description: ((error && error.message) ? error.message : _t('Operation failed')),
onFinished: self._refreshFromServer
onFinished: self._refreshFromServer,
});
});
}
@ -287,12 +282,12 @@ module.exports = React.createClass({
const cli = MatrixClientPeg.get();
this.setState({
phase: this.phases.LOADING
phase: this.phases.LOADING,
});
// Update all rules in self.state.vectorContentRules
const deferreds = [];
for (let i in this.state.vectorContentRules.rules) {
for (const i in this.state.vectorContentRules.rules) {
const rule = this.state.vectorContentRules.rules[i];
let enabled, actions;
@ -326,8 +321,7 @@ module.exports = React.createClass({
// Note that the workaround in _updatePushRuleActions will automatically
// enable the rule
deferreds.push(this._updatePushRuleActions(rule, actions, enabled));
}
else if (enabled != undefined) {
} else if (enabled != undefined) {
deferreds.push(cli.setPushRuleEnabled('global', rule.kind, rule.rule_id, enabled));
}
}
@ -340,14 +334,14 @@ module.exports = React.createClass({
Modal.createTrackedDialog('Can\'t update user notifcation settings', '', ErrorDialog, {
title: _t('Can\'t update user notification settings'),
description: ((error && error.message) ? error.message : _t('Operation failed')),
onFinished: self._refreshFromServer
onFinished: self._refreshFromServer,
});
});
},
_setKeywords: function(newKeywords) {
this.setState({
phase: this.phases.LOADING
phase: this.phases.LOADING,
});
const self = this;
@ -356,7 +350,7 @@ module.exports = React.createClass({
// Remove per-word push rules of keywords that are no more in the list
const vectorContentRulesPatterns = [];
for (let i in self.state.vectorContentRules.rules) {
for (const i in self.state.vectorContentRules.rules) {
const rule = self.state.vectorContentRules.rules[i];
vectorContentRulesPatterns.push(rule.pattern);
@ -368,7 +362,7 @@ module.exports = React.createClass({
// If the keyword is part of `externalContentRules`, remove the rule
// before recreating it in the right Vector path
for (let i in self.state.externalContentRules) {
for (const i in self.state.externalContentRules) {
const rule = self.state.externalContentRules[i];
if (newKeywords.indexOf(rule.pattern) >= 0) {
@ -382,9 +376,9 @@ module.exports = React.createClass({
Modal.createTrackedDialog('Failed to update keywords', '', ErrorDialog, {
title: _t('Failed to update keywords'),
description: ((error && error.message) ? error.message : _t('Operation failed')),
onFinished: self._refreshFromServer
onFinished: self._refreshFromServer,
});
}
};
// Then, add the new ones
Promise.all(removeDeferreds).done(function(resps) {
@ -398,14 +392,13 @@ module.exports = React.createClass({
// Thus, this new rule will join the 'vectorContentRules' set.
if (self.state.vectorContentRules.rules.length) {
pushRuleVectorStateKind = PushRuleVectorState.contentRuleVectorStateKind(self.state.vectorContentRules.rules[0]);
}
else {
} else {
// ON is default
pushRuleVectorStateKind = PushRuleVectorState.ON;
pushRuleVectorStateKind = PushRuleVectorState.ON;
}
}
for (let i in newKeywords) {
for (const i in newKeywords) {
const keyword = newKeywords[i];
if (vectorContentRulesPatterns.indexOf(keyword) < 0) {
@ -413,13 +406,12 @@ module.exports = React.createClass({
deferreds.push(cli.addPushRule
('global', 'content', keyword, {
actions: PushRuleVectorState.actionsFor(pushRuleVectorStateKind),
pattern: keyword
pattern: keyword,
}));
}
else {
} else {
deferreds.push(self._addDisabledPushRule('global', 'content', keyword, {
actions: PushRuleVectorState.actionsFor(pushRuleVectorStateKind),
pattern: keyword
pattern: keyword,
}));
}
}
@ -435,7 +427,7 @@ module.exports = React.createClass({
_addDisabledPushRule: function(scope, kind, ruleId, body) {
const cli = MatrixClientPeg.get();
return cli.addPushRule(scope, kind, ruleId, body).then(() =>
cli.setPushRuleEnabled(scope, kind, ruleId, false)
cli.setPushRuleEnabled(scope, kind, ruleId, false),
);
},
@ -446,7 +438,7 @@ module.exports = React.createClass({
const needsUpdate = [];
const cli = MatrixClientPeg.get();
for (let kind in rulesets.global) {
for (const kind in rulesets.global) {
const ruleset = rulesets.global[kind];
for (let i = 0; i < ruleset.length; ++i) {
const rule = ruleset[i];
@ -454,9 +446,9 @@ module.exports = React.createClass({
console.log("Porting legacy rule", rule);
needsUpdate.push( function(kind, rule) {
return cli.setPushRuleActions(
'global', kind, LEGACY_RULES[rule.rule_id], portLegacyActions(rule.actions)
'global', kind, LEGACY_RULES[rule.rule_id], portLegacyActions(rule.actions),
).then(() =>
cli.deletePushRule('global', kind, rule.rule_id)
cli.deletePushRule('global', kind, rule.rule_id),
).catch( (e) => {
console.warn(`Error when porting legacy rule: ${e}`);
});
@ -469,7 +461,7 @@ module.exports = React.createClass({
// If some of the rules need to be ported then wait for the porting
// to happen and then fetch the rules again.
return Promise.all(needsUpdate).then(() =>
cli.getPushRules()
cli.getPushRules(),
);
} else {
// Otherwise return the rules that we already have.
@ -480,7 +472,6 @@ module.exports = React.createClass({
_refreshFromServer: function() {
const self = this;
const pushRulesPromise = MatrixClientPeg.get().getPushRules().then(self._portRulesToNewAPI).then(function(rulesets) {
/// XXX seriously? wtf is this?
MatrixClientPeg.get().pushRules = rulesets;
@ -497,7 +488,7 @@ module.exports = React.createClass({
'.m.rule.invite_for_me': 'vector',
//'.m.rule.member_event': 'vector',
'.m.rule.call': 'vector',
'.m.rule.suppress_notices': 'vector'
'.m.rule.suppress_notices': 'vector',
// Others go to others
};
@ -505,7 +496,7 @@ module.exports = React.createClass({
// HS default rules
const defaultRules = {master: [], vector: {}, others: []};
for (let kind in rulesets.global) {
for (const kind in rulesets.global) {
for (let i = 0; i < Object.keys(rulesets.global[kind]).length; ++i) {
const r = rulesets.global[kind][i];
const cat = rule_categories[r.rule_id];
@ -514,11 +505,9 @@ module.exports = React.createClass({
if (r.rule_id[0] === '.') {
if (cat === 'vector') {
defaultRules.vector[r.rule_id] = r;
}
else if (cat === 'master') {
} else if (cat === 'master') {
defaultRules.master.push(r);
}
else {
} else {
defaultRules['others'].push(r);
}
}
@ -551,9 +540,9 @@ module.exports = React.createClass({
'.m.rule.invite_for_me',
//'im.vector.rule.member_event',
'.m.rule.call',
'.m.rule.suppress_notices'
'.m.rule.suppress_notices',
];
for (let i in vectorRuleIds) {
for (const i in vectorRuleIds) {
const vectorRuleId = vectorRuleIds[i];
if (vectorRuleId === '_keywords') {
@ -562,20 +551,19 @@ module.exports = React.createClass({
// it corresponds to all content push rules (stored in self.state.vectorContentRule)
self.state.vectorPushRules.push({
"vectorRuleId": "_keywords",
"description" : (
"description": (
<span>
{ _t('Messages containing <span>keywords</span>',
{},
{ 'span': (sub) =>
<span className="mx_UserNotifSettings_keywords" onClick={ self.onKeywordsClicked }>{sub}</span>
<span className="mx_UserNotifSettings_keywords" onClick={ self.onKeywordsClicked }>{sub}</span>,
},
)}
</span>
),
"vectorState": self.state.vectorContentRules.vectorState
"vectorState": self.state.vectorContentRules.vectorState,
});
}
else {
} else {
const ruleDefinition = VectorPushRulesDefinitions[vectorRuleId];
const rule = defaultRules.vector[vectorRuleId];
@ -585,7 +573,7 @@ module.exports = React.createClass({
self.state.vectorPushRules.push({
"vectorRuleId": vectorRuleId,
"description" : _t(ruleDefinition.description), // Text from VectorPushRulesDefinitions.js
"description": _t(ruleDefinition.description), // Text from VectorPushRulesDefinitions.js
"rule": rule,
"vectorState": vectorState,
});
@ -604,7 +592,7 @@ module.exports = React.createClass({
'.m.rule.fallback': _t('Notify me for anything else'),
};
for (let i in defaultRules.others) {
for (const i in defaultRules.others) {
const rule = defaultRules.others[i];
const ruleDescription = otherRulesDescriptions[rule.rule_id];
@ -622,12 +610,12 @@ module.exports = React.createClass({
Promise.all([pushRulesPromise, pushersPromise]).then(function() {
self.setState({
phase: self.phases.DISPLAY
phase: self.phases.DISPLAY,
});
}, function(error) {
console.error(error);
self.setState({
phase: self.phases.ERROR
phase: self.phases.ERROR,
});
}).finally(() => {
// actually explicitly update our state having been deep-manipulating it
@ -645,12 +633,12 @@ module.exports = React.createClass({
const cli = MatrixClientPeg.get();
return cli.setPushRuleActions(
'global', rule.kind, rule.rule_id, actions
'global', rule.kind, rule.rule_id, actions,
).then( function() {
// Then, if requested, enabled or disabled the rule
if (undefined != enabled) {
return cli.setPushRuleEnabled(
'global', rule.kind, rule.rule_id, enabled
'global', rule.kind, rule.rule_id, enabled,
);
}
});
@ -689,7 +677,7 @@ module.exports = React.createClass({
renderNotifRulesTableRows: function() {
const rows = [];
for (let i in this.state.vectorPushRules) {
for (const i in this.state.vectorPushRules) {
const rule = this.state.vectorPushRules[i];
//console.log("rendering: " + rule.description + ", " + rule.vectorRuleId + ", " + rule.vectorState);
rows.push(this.renderNotifRulesTableRow(rule.description, rule.vectorRuleId, rule.vectorState));
@ -769,20 +757,20 @@ module.exports = React.createClass({
// This only supports the first email address in your profile for now
emailNotificationsRow = this.emailNotificationsRow(
emailThreepids[0].address,
`${_t('Enable email notifications')} (${emailThreepids[0].address})`
`${_t('Enable email notifications')} (${emailThreepids[0].address})`,
);
}
// Build external push rules
const externalRules = [];
for (let i in this.state.externalPushRules) {
for (const i in this.state.externalPushRules) {
const rule = this.state.externalPushRules[i];
externalRules.push(<li>{ _t(rule.description) }</li>);
}
// Show keywords not displayed by the vector UI as a single external push rule
let externalKeywords = [];
for (let i in this.state.externalContentRules) {
for (const i in this.state.externalContentRules) {
const rule = this.state.externalContentRules[i];
externalKeywords.push(rule.pattern);
}
@ -793,7 +781,7 @@ module.exports = React.createClass({
let devicesSection;
if (this.state.pushers === undefined) {
devicesSection = <div className="error">{ _t('Unable to fetch notification target list') }</div>
devicesSection = <div className="error">{ _t('Unable to fetch notification target list') }</div>;
} else if (this.state.pushers.length == 0) {
devicesSection = null;
} else {
@ -824,7 +812,7 @@ module.exports = React.createClass({
advancedSettings = (
<div>
<h3>{ _t('Advanced notification settings') }</h3>
{ _t('There are advanced notifications which are not shown here') }.<br/>
{ _t('There are advanced notifications which are not shown here') }.<br />
{ _t('You might have configured them in a client other than Riot. You cannot tune them in Riot but they still apply') }.
<ul>
{ externalRules }
@ -915,5 +903,5 @@ module.exports = React.createClass({
</div>
);
}
},
});

View file

@ -97,19 +97,17 @@ export function _t(text, variables, tags) {
// The translation returns text so there's no XSS vector here (no unsafe HTML, no code execution)
const translated = safeCounterpartTranslate(text, args);
let substituted = substitute(translated, variables, tags);
const substituted = substitute(translated, variables, tags);
// For development/testing purposes it is useful to also output the original string
// Don't do that for release versions
if (ANNOTATE_STRINGS) {
if (typeof substituted === 'string') {
return `@@${text}##${substituted}@@`
}
else {
return `@@${text}##${substituted}@@`;
} else {
return <span className='translated-string' data-orig-string={text}>{substituted}</span>;
}
}
else {
} else {
return substituted;
}
}

View file

@ -16,7 +16,7 @@ limitations under the License.
'use strict';
var PushRuleVectorState = require('./PushRuleVectorState');
const PushRuleVectorState = require('./PushRuleVectorState');
module.exports = {
/**
@ -32,7 +32,7 @@ module.exports = {
*/
parseContentRules: function(rulesets) {
// first categorise the keyword rules in terms of their actions
var contentRules = this._categoriseContentRules(rulesets);
const contentRules = this._categoriseContentRules(rulesets);
// Decide which content rules to display in Vector UI.
// Vector displays a single global rule for a list of keywords
@ -54,41 +54,38 @@ module.exports = {
rules: contentRules.loud,
externalRules: [].concat(contentRules.loud_but_disabled, contentRules.on, contentRules.on_but_disabled, contentRules.other),
};
}
else if (contentRules.loud_but_disabled.length) {
} else if (contentRules.loud_but_disabled.length) {
return {
vectorState: PushRuleVectorState.OFF,
rules: contentRules.loud_but_disabled,
externalRules: [].concat(contentRules.on, contentRules.on_but_disabled, contentRules.other),
};
}
else if (contentRules.on.length) {
} else if (contentRules.on.length) {
return {
vectorState: PushRuleVectorState.ON,
rules: contentRules.on,
externalRules: [].concat(contentRules.on_but_disabled, contentRules.other),
};
}
else if (contentRules.on_but_disabled.length) {
} else if (contentRules.on_but_disabled.length) {
return {
vectorState: PushRuleVectorState.OFF,
rules: contentRules.on_but_disabled,
externalRules: contentRules.other,
}
} else {
};
} else {
return {
vectorState: PushRuleVectorState.ON,
rules: [],
externalRules: contentRules.other,
}
};
}
},
_categoriseContentRules: function(rulesets) {
var contentRules = {on: [], on_but_disabled:[], loud: [], loud_but_disabled: [], other: []};
for (var kind in rulesets.global) {
for (var i = 0; i < Object.keys(rulesets.global[kind]).length; ++i) {
var r = rulesets.global[kind][i];
const contentRules = {on: [], on_but_disabled: [], loud: [], loud_but_disabled: [], other: []};
for (const kind in rulesets.global) {
for (let i = 0; i < Object.keys(rulesets.global[kind]).length; ++i) {
const r = rulesets.global[kind][i];
// check it's not a default rule
if (r.rule_id[0] === '.' || kind !== 'content') {
@ -101,16 +98,14 @@ module.exports = {
case PushRuleVectorState.ON:
if (r.enabled) {
contentRules.on.push(r);
}
else {
} else {
contentRules.on_but_disabled.push(r);
}
break;
case PushRuleVectorState.LOUD:
if (r.enabled) {
contentRules.loud.push(r);
}
else {
} else {
contentRules.loud_but_disabled.push(r);
}
break;

View file

@ -24,11 +24,11 @@ module.exports = {
// }
// to a list of push actions.
encodeActions: function(action) {
var notify = action.notify;
var sound = action.sound;
var highlight = action.highlight;
const notify = action.notify;
const sound = action.sound;
const highlight = action.highlight;
if (notify) {
var actions = ["notify"];
const actions = ["notify"];
if (sound) {
actions.push({"set_tweak": "sound", "value": sound});
}
@ -50,19 +50,19 @@ module.exports = {
// }
// If the actions couldn't be decoded then returns null.
decodeActions: function(actions) {
var notify = false;
var sound = null;
var highlight = false;
let notify = false;
let sound = null;
let highlight = false;
for (var i = 0; i < actions.length; ++i) {
var action = actions[i];
for (let i = 0; i < actions.length; ++i) {
const action = actions[i];
if (action === "notify") {
notify = true;
} else if (action === "dont_notify") {
notify = false;
} else if (typeof action === 'object') {
if (action.set_tweak === "sound") {
sound = action.value
sound = action.value;
} else if (action.set_tweak === "highlight") {
highlight = action.value;
} else {
@ -80,7 +80,7 @@ module.exports = {
highlight = true;
}
var result = {notify: notify, highlight: highlight};
const result = {notify: notify, highlight: highlight};
if (sound !== null) {
result.sound = sound;
}

View file

@ -16,10 +16,10 @@ limitations under the License.
'use strict';
var StandardActions = require('./StandardActions');
var NotificationUtils = require('./NotificationUtils');
const StandardActions = require('./StandardActions');
const NotificationUtils = require('./NotificationUtils');
var states = {
const states = {
/** The push rule is disabled */
OFF: "off",
@ -48,8 +48,7 @@ module.exports = {
actionsFor: function(pushRuleVectorState) {
if (pushRuleVectorState === this.ON) {
return StandardActions.ACTION_NOTIFY;
}
else if (pushRuleVectorState === this.LOUD) {
} else if (pushRuleVectorState === this.LOUD) {
return StandardActions.ACTION_HIGHLIGHT_DEFAULT_SOUND;
}
},
@ -62,21 +61,21 @@ module.exports = {
* state. Returns null if it does not match these categories.
*/
contentRuleVectorStateKind: function(rule) {
var decoded = NotificationUtils.decodeActions(rule.actions);
const decoded = NotificationUtils.decodeActions(rule.actions);
if (!decoded) {
return null;
}
// Count tweaks to determine if it is a ON or LOUD rule
var tweaks = 0;
let tweaks = 0;
if (decoded.sound) {
tweaks++;
}
if (decoded.highlight) {
tweaks++;
}
var stateKind = null;
let stateKind = null;
switch (tweaks) {
case 0:
stateKind = this.ON;
@ -89,6 +88,6 @@ module.exports = {
},
};
for (var k in states) {
for (const k in states) {
module.exports[k] = states[k];
};
}

View file

@ -18,8 +18,8 @@ limitations under the License.
import { _td } from '../languageHandler';
var StandardActions = require('./StandardActions');
var PushRuleVectorState = require('./PushRuleVectorState');
const StandardActions = require('./StandardActions');
const PushRuleVectorState = require('./PushRuleVectorState');
class VectorPushRuleDefinition {
constructor(opts) {
@ -30,16 +30,16 @@ class VectorPushRuleDefinition {
// Translate the rule actions and its enabled value into vector state
ruleToVectorState(rule) {
var enabled = false;
var actions = null;
let enabled = false;
let actions = null;
if (rule) {
enabled = rule.enabled;
actions = rule.actions;
}
for (var stateKey in PushRuleVectorState.states) {
var state = PushRuleVectorState.states[stateKey];
var vectorStateToActions = this.vectorStateToActions[state];
for (const stateKey in PushRuleVectorState.states) {
const state = PushRuleVectorState.states[stateKey];
const vectorStateToActions = this.vectorStateToActions[state];
if (!vectorStateToActions) {
// No defined actions means that this vector state expects a disabled (or absent) rule
@ -58,7 +58,7 @@ class VectorPushRuleDefinition {
JSON.stringify(rule));
return undefined;
}
};
}
/**
* The descriptions of rules managed by the Vector UI.
@ -71,8 +71,8 @@ module.exports = {
vectorStateToActions: { // The actions for each vector state, or null to disable the rule.
on: StandardActions.ACTION_NOTIFY,
loud: StandardActions.ACTION_HIGHLIGHT_DEFAULT_SOUND,
off: StandardActions.ACTION_DISABLED
}
off: StandardActions.ACTION_DISABLED,
},
}),
// Messages containing user's username (localpart/MXID)
@ -82,8 +82,8 @@ module.exports = {
vectorStateToActions: { // The actions for each vector state, or null to disable the rule.
on: StandardActions.ACTION_NOTIFY,
loud: StandardActions.ACTION_HIGHLIGHT_DEFAULT_SOUND,
off: StandardActions.ACTION_DISABLED
}
off: StandardActions.ACTION_DISABLED,
},
}),
// Messages just sent to the user in a 1:1 room
@ -93,8 +93,8 @@ module.exports = {
vectorStateToActions: {
on: StandardActions.ACTION_NOTIFY,
loud: StandardActions.ACTION_NOTIFY_DEFAULT_SOUND,
off: StandardActions.ACTION_DONT_NOTIFY
}
off: StandardActions.ACTION_DONT_NOTIFY,
},
}),
// Messages just sent to a group chat room
@ -106,8 +106,8 @@ module.exports = {
vectorStateToActions: {
on: StandardActions.ACTION_NOTIFY,
loud: StandardActions.ACTION_NOTIFY_DEFAULT_SOUND,
off: StandardActions.ACTION_DONT_NOTIFY
}
off: StandardActions.ACTION_DONT_NOTIFY,
},
}),
// Invitation for the user
@ -117,8 +117,8 @@ module.exports = {
vectorStateToActions: {
on: StandardActions.ACTION_NOTIFY,
loud: StandardActions.ACTION_NOTIFY_DEFAULT_SOUND,
off: StandardActions.ACTION_DISABLED
}
off: StandardActions.ACTION_DISABLED,
},
}),
// Incoming call
@ -128,8 +128,8 @@ module.exports = {
vectorStateToActions: {
on: StandardActions.ACTION_NOTIFY,
loud: StandardActions.ACTION_NOTIFY_RING_SOUND,
off: StandardActions.ACTION_DISABLED
}
off: StandardActions.ACTION_DISABLED,
},
}),
// Notifications from bots
@ -141,6 +141,6 @@ module.exports = {
on: StandardActions.ACTION_DISABLED,
loud: StandardActions.ACTION_NOTIFY_DEFAULT_SOUND,
off: StandardActions.ACTION_DONT_NOTIFY,
}
},
}),
};

View file

@ -60,11 +60,11 @@ class ConsoleLogger {
};
Object.keys(consoleFunctionsToLevels).forEach((fnName) => {
const level = consoleFunctionsToLevels[fnName];
let originalFn = consoleObj[fnName].bind(consoleObj);
const originalFn = consoleObj[fnName].bind(consoleObj);
consoleObj[fnName] = (...args) => {
this.log(level, ...args);
originalFn(...args);
}
};
});
}
@ -116,7 +116,7 @@ class IndexedDBLogStore {
* @return {Promise} Resolves when the store is ready.
*/
connect() {
let req = this.indexedDB.open("logs");
const req = this.indexedDB.open("logs");
return new Promise((resolve, reject) => {
req.onsuccess = (event) => {
this.db = event.target.result;
@ -137,7 +137,7 @@ class IndexedDBLogStore {
req.onupgradeneeded = (event) => {
const db = event.target.result;
const logObjStore = db.createObjectStore("logs", {
keyPath: ["id", "index"]
keyPath: ["id", "index"],
});
// Keys in the database look like: [ "instance-148938490", 0 ]
// Later on we need to query everything based on an instance id.
@ -146,15 +146,15 @@ class IndexedDBLogStore {
logObjStore.add(
this._generateLogEntry(
new Date() + " ::: Log database was created."
)
new Date() + " ::: Log database was created.",
),
);
const lastModifiedStore = db.createObjectStore("logslastmod", {
keyPath: "id",
});
lastModifiedStore.add(this._generateLastModifiedTime());
}
};
});
}
@ -206,21 +206,21 @@ class IndexedDBLogStore {
resolve();
return;
}
let txn = this.db.transaction(["logs", "logslastmod"], "readwrite");
let objStore = txn.objectStore("logs");
const txn = this.db.transaction(["logs", "logslastmod"], "readwrite");
const objStore = txn.objectStore("logs");
txn.oncomplete = (event) => {
resolve();
};
txn.onerror = (event) => {
console.error(
"Failed to flush logs : ", event
"Failed to flush logs : ", event,
);
reject(
new Error("Failed to write logs: " + event.target.errorCode)
new Error("Failed to write logs: " + event.target.errorCode),
);
}
};
objStore.add(this._generateLogEntry(lines));
let lastModStore = txn.objectStore("logslastmod");
const lastModStore = txn.objectStore("logslastmod");
lastModStore.put(this._generateLastModifiedTime());
});
return this.flushPromise;
@ -247,13 +247,13 @@ class IndexedDBLogStore {
return {
lines: cursor.value.lines,
index: cursor.value.index,
}
};
}).then((linesArray) => {
// We have been storing logs periodically, so string them all
// together *in order of index* now
linesArray.sort((a, b) => {
return a.index - b.index;
})
});
return linesArray.map((l) => l.lines).join("");
});
}
@ -262,7 +262,7 @@ class IndexedDBLogStore {
function fetchLogIds() {
// To gather all the log IDs, query for all records in logslastmod.
const o = db.transaction("logslastmod", "readonly").objectStore(
"logslastmod"
"logslastmod",
);
return selectQuery(o, undefined, (cursor) => {
return {
@ -280,7 +280,7 @@ class IndexedDBLogStore {
function deleteLogs(id) {
return new Promise((resolve, reject) => {
const txn = db.transaction(
["logs", "logslastmod"], "readwrite"
["logs", "logslastmod"], "readwrite",
);
const o = txn.objectStore("logs");
// only load the key path, not the data which may be huge
@ -292,7 +292,7 @@ class IndexedDBLogStore {
}
o.delete(cursor.primaryKey);
cursor.continue();
}
};
txn.oncomplete = () => {
resolve();
};
@ -300,8 +300,8 @@ class IndexedDBLogStore {
reject(
new Error(
"Failed to delete logs for " +
`'${id}' : ${event.target.errorCode}`
)
`'${id}' : ${event.target.errorCode}`,
),
);
};
// delete last modified entries
@ -310,12 +310,12 @@ class IndexedDBLogStore {
});
}
let allLogIds = await fetchLogIds();
const allLogIds = await fetchLogIds();
let removeLogIds = [];
let logs = [];
const logs = [];
let size = 0;
for (let i = 0; i < allLogIds.length; i++) {
let lines = await fetchLogs(allLogIds[i]);
const lines = await fetchLogs(allLogIds[i]);
// always include at least one log file, but only include
// subsequent ones if they won't take us over the MAX_LOG_SIZE
@ -343,7 +343,7 @@ class IndexedDBLogStore {
console.log(`Removed ${removeLogIds.length} old logs.`);
}, (err) => {
console.error(err);
})
});
}
return logs;
}
@ -352,7 +352,7 @@ class IndexedDBLogStore {
return {
id: this.id,
lines: lines,
index: this.index++
index: this.index++,
};
}
@ -377,7 +377,7 @@ class IndexedDBLogStore {
function selectQuery(store, keyRange, resultMapper) {
const query = store.openCursor(keyRange);
return new Promise((resolve, reject) => {
let results = [];
const results = [];
query.onerror = (event) => {
reject(new Error("Query failed: " + event.target.errorCode));
};
@ -390,7 +390,7 @@ function selectQuery(store, keyRange, resultMapper) {
}
results.push(resultMapper(cursor));
cursor.continue();
}
};
});
}
@ -414,7 +414,7 @@ module.exports = {
let indexedDB;
try {
indexedDB = window.indexedDB;
} catch(e) {}
} catch (e) {}
if (indexedDB) {
global.mx_rage_store = new IndexedDBLogStore(indexedDB, global.mx_rage_logger);
@ -451,7 +451,7 @@ module.exports = {
getLogsForReport: async function() {
if (!global.mx_rage_logger) {
throw new Error(
"No console logger, did you forget to call init()?"
"No console logger, did you forget to call init()?",
);
}
// If in incognito mode, store is null, but we still want bug report
@ -460,8 +460,7 @@ module.exports = {
// flush most recent logs
await global.mx_rage_store.flush();
return await global.mx_rage_store.consume();
}
else {
} else {
return [{
lines: global.mx_rage_logger.flush(true),
id: "-",

View file

@ -22,7 +22,7 @@ import MatrixClientPeg from '../MatrixClientPeg';
import PlatformPeg from '../PlatformPeg';
import { _t } from '../languageHandler';
import rageshake from './rageshake'
import rageshake from './rageshake';
// polyfill textencoder if necessary
@ -59,8 +59,7 @@ export default async function sendBugReport(bugReportEndpoint, opts) {
let version = "UNKNOWN";
try {
version = await PlatformPeg.get().getAppVersion();
}
catch (err) {} // PlatformPeg already logs this.
} catch (err) {} // PlatformPeg already logs this.
let userAgent = "UNKNOWN";
if (window.navigator && window.navigator.userAgent) {
@ -85,7 +84,7 @@ export default async function sendBugReport(bugReportEndpoint, opts) {
if (opts.sendLogs) {
progressCallback(_t("Collecting logs"));
const logs = await rageshake.getLogsForReport();
for (let entry of logs) {
for (const entry of logs) {
// encode as UTF-8
const buf = new TextEncoder().encode(entry.lines);

View file

@ -104,7 +104,7 @@ export default class DMRoomMap {
.some((ids) => ids.roomId === roomId);
});
guessedUserIdsThatChanged.forEach(({userId, roomId}) => {
let roomIds = userToRooms[userId];
const roomIds = userToRooms[userId];
if (!roomIds) {
userToRooms[userId] = [roomId];
} else {