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/MemberEventListSummary.js
src/components/views/elements/Spinner.js src/components/views/elements/Spinner.js
src/components/views/elements/TintableSvg.js src/components/views/elements/TintableSvg.js
src/components/views/elements/UserInfo.js
src/components/views/elements/UserSelector.js src/components/views/elements/UserSelector.js
src/components/views/globals/MatrixToolbar.js src/components/views/globals/MatrixToolbar.js
src/components/views/globals/NewVersionBar.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/messages/TextualBody.js
src/components/views/room_settings/AliasSettings.js src/components/views/room_settings/AliasSettings.js
src/components/views/room_settings/ColorSettings.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/Autocomplete.js
src/components/views/rooms/AuxPanel.js src/components/views/rooms/AuxPanel.js
src/components/views/rooms/EntityTile.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/MessageComposer.js
src/components/views/rooms/MessageComposerInput.js src/components/views/rooms/MessageComposerInput.js
src/components/views/rooms/PinnedEventTile.js src/components/views/rooms/PinnedEventTile.js
src/components/views/rooms/RoomDropTarget.js
src/components/views/rooms/RoomList.js src/components/views/rooms/RoomList.js
src/components/views/rooms/RoomPreviewBar.js src/components/views/rooms/RoomPreviewBar.js
src/components/views/rooms/RoomSettings.js src/components/views/rooms/RoomSettings.js
@ -92,7 +89,6 @@ src/Markdown.js
src/MatrixClientPeg.js src/MatrixClientPeg.js
src/Modal.js src/Modal.js
src/notifications/ContentRules.js src/notifications/ContentRules.js
src/notifications/NotificationUtils.js
src/notifications/PushRuleVectorState.js src/notifications/PushRuleVectorState.js
src/notifications/StandardActions.js src/notifications/StandardActions.js
src/notifications/VectorPushRulesDefinitions.js src/notifications/VectorPushRulesDefinitions.js
@ -102,7 +98,6 @@ src/Presence.js
src/rageshake/rageshake.js src/rageshake/rageshake.js
src/rageshake/submit-rageshake.js src/rageshake/submit-rageshake.js
src/ratelimitedfunc.js src/ratelimitedfunc.js
src/RichText.js
src/Roles.js src/Roles.js
src/Rooms.js src/Rooms.js
src/ScalarAuthClient.js src/ScalarAuthClient.js

View file

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

View file

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

View file

@ -20,7 +20,8 @@ import { _t } from '../../../languageHandler';
export default (props) => { export default (props) => {
const description = 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 return (<QuestionDialog
hasCancelButton={false} hasCancelButton={false}

View file

@ -96,7 +96,7 @@ export default React.createClass({
render() { render() {
const EmojiText = sdk.getComponent('elements.EmojiText'); const EmojiText = sdk.getComponent('elements.EmojiText');
const {mxEvent} = this.props; 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(); const {msgtype} = mxEvent.getContent();
if (msgtype === 'm.emote') { if (msgtype === 'm.emote') {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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