diff --git a/README.md b/README.md index 1265c2bd77..c2e3737b81 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ matrix-react-sdk This is a react-based SDK for inserting a Matrix chat/voip client into a web page. This package provides the React components needed to build a Matrix web client -using React. It is not useable in isolation, and instead must must be used from +using React. It is not useable in isolation, and instead must be used from a 'skin'. A skin provides: * Customised implementations of presentation components. * Custom CSS @@ -82,7 +82,7 @@ practices that anyone working with the SDK needs to be be aware of and uphold: 'Stealing' styling information from other components (including parents) is not cool, as it breaks the independence of the components. - * CSS classes are named with an app-specific namespacing prefix to try to avoid + * CSS classes are named with an app-specific name-spacing prefix to try to avoid CSS collisions. The base skin shipped by Matrix.org with the matrix-react-sdk uses the naming prefix "mx_". A company called Yoyodyne Inc might use a prefix like "yy_" for its app-specific classes. @@ -107,7 +107,7 @@ practices that anyone working with the SDK needs to be be aware of and uphold: .mx_RoomTile {} in RoomList.css - only RoomTile.css is allowed to define its own CSS. Instead, say .mx_RoomList .mx_RoomTile {} to scope the override only to the context of RoomList views. N.B. overrides should be relatively - rare as in general CSS inheritence should be enough. + rare as in general CSS inheritance should be enough. * Components should render only within the bounding box of their outermost DOM element. Page-absolute positioning and negative CSS margins and similar are diff --git a/package.json b/package.json index 8688fe42e6..a1ebc6602d 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,6 @@ "diff-i18n": "cp src/i18n/strings/en_EN.json src/i18n/strings/en_EN_orig.json && ./scripts/gen-i18n.js && node scripts/compare-file.js src/i18n/strings/en_EN_orig.json src/i18n/strings/en_EN.json", "build": "yarn reskindex && yarn start:init", "build:watch": "babel src -w --skip-initial-build -d lib --source-maps --copy-files", - "emoji-data-strip": "node scripts/emoji-data-strip.js", "start": "yarn start:init && yarn start:all", "start:all": "concurrently --kill-others-on-fail --prefix \"{time} [{name}]\" -n build,reskindex \"yarn build:watch\" \"yarn reskindex:watch\"", "start:init": "babel src -d lib --source-maps --copy-files", @@ -75,7 +74,6 @@ "file-saver": "^1.3.3", "filesize": "3.5.6", "flux": "2.1.1", - "react-focus-lock": "^2.2.1", "focus-visible": "^5.0.2", "fuse.js": "^2.2.0", "gemini-scrollbar": "github:matrix-org/gemini-scrollbar#91e1e566", @@ -83,6 +81,7 @@ "glob": "^5.0.14", "glob-to-regexp": "^0.4.1", "highlight.js": "^9.15.8", + "humanize": "^0.0.9", "is-ip": "^2.0.0", "isomorphic-fetch": "^2.2.1", "linkifyjs": "^2.1.6", @@ -100,6 +99,7 @@ "react-addons-css-transition-group": "15.6.2", "react-beautiful-dnd": "^4.0.1", "react-dom": "^16.9.0", + "react-focus-lock": "^2.2.1", "react-gemini-scrollbar": "github:matrix-org/react-gemini-scrollbar#9cf17f63b7c0b0ec5f31df27da0f82f7238dc594", "resize-observer-polyfill": "^1.5.0", "sanitize-html": "^1.18.4", diff --git a/res/css/_components.scss b/res/css/_components.scss index 233c781d7f..7a9ebfdf26 100644 --- a/res/css/_components.scss +++ b/res/css/_components.scss @@ -24,7 +24,6 @@ @import "./structures/_SearchBox.scss"; @import "./structures/_TabbedView.scss"; @import "./structures/_TagPanel.scss"; -@import "./structures/_TagPanelButtons.scss"; @import "./structures/_ToastContainer.scss"; @import "./structures/_TopLeftMenuButton.scss"; @import "./structures/_UploadBar.scss"; @@ -57,6 +56,7 @@ @import "./views/dialogs/_ConfirmUserActionDialog.scss"; @import "./views/dialogs/_CreateGroupDialog.scss"; @import "./views/dialogs/_CreateRoomDialog.scss"; +@import "./views/dialogs/_DMInviteDialog.scss"; @import "./views/dialogs/_DeactivateAccountDialog.scss"; @import "./views/dialogs/_DeviceVerifyDialog.scss"; @import "./views/dialogs/_DevtoolsDialog.scss"; @@ -174,6 +174,7 @@ @import "./views/rooms/_SendMessageComposer.scss"; @import "./views/rooms/_Stickers.scss"; @import "./views/rooms/_TopUnreadMessagesBar.scss"; +@import "./views/rooms/_UserOnlineDot.scss"; @import "./views/rooms/_WhoIsTypingTile.scss"; @import "./views/settings/_AvatarSetting.scss"; @import "./views/settings/_CrossSigningPanel.scss"; diff --git a/res/css/structures/_CustomRoomTagPanel.scss b/res/css/structures/_CustomRoomTagPanel.scss index 45961d7be1..1fb18ec41e 100644 --- a/res/css/structures/_CustomRoomTagPanel.scss +++ b/res/css/structures/_CustomRoomTagPanel.scss @@ -26,11 +26,16 @@ limitations under the License. .mx_CustomRoomTagPanel_scroller { max-height: inherit; + display: flex; + flex-direction: column; + align-items: center; } .mx_CustomRoomTagPanel .mx_AccessibleButton { - margin: 9px auto; + margin: 0 auto; width: 40px; + padding: 10px 0 9px 0; + position: relative; } .mx_CustomRoomTagPanel .mx_BaseAvatar_image { @@ -39,7 +44,13 @@ limitations under the License. height: 40px; } -.mx_CustomRoomTagPanel .mx_AccessibleButton.CustomRoomTagPanel_tileSelected .mx_BaseAvatar_image { - border: 3px solid $warning-color; - border-radius: 40px; +.mx_CustomRoomTagPanel .mx_AccessibleButton.CustomRoomTagPanel_tileSelected::before { + content: ''; + height: 56px; + background-color: $accent-color-alt; + width: 5px; + position: absolute; + left: -15px; + border-radius: 0 3px 3px 0; + top: 2px; // 10 [padding-top] - (56 - 40)/2 } diff --git a/res/css/structures/_TagPanel.scss b/res/css/structures/_TagPanel.scss index b03d36a592..dddd2e324c 100644 --- a/res/css/structures/_TagPanel.scss +++ b/res/css/structures/_TagPanel.scss @@ -68,7 +68,7 @@ limitations under the License. } .mx_TagPanel .mx_TagPanel_tagTileContainer > div { height: 40px; - padding: 5px 0 4px 0; + padding: 10px 0 9px 0; } .mx_TagPanel .mx_TagTile { @@ -82,21 +82,39 @@ limitations under the License. // opacity: 1; } -.mx_TagPanel .mx_TagTile.mx_TagTile_selected .mx_TagTile_avatar .mx_BaseAvatar { - background-color: $accent-color; - border-radius: 40px; - - /* In case this is a "initial" avatar */ - display: block; +.mx_TagPanel .mx_TagTile_plus { + margin-bottom: 12px; height: 40px; width: 40px; + border-radius: 20px; + background-color: $roomheader-addroom-bg-color; + position: relative; + /* overwrite mx_RoleButton inline-block */ + display: block !important; + + &::before { + background-color: $roomheader-addroom-fg-color; + mask-image: url('$(res)/img/feather-customised/plus.svg'); + mask-position: center; + mask-repeat: no-repeat; + content: ''; + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + } } -.mx_TagPanel .mx_TagTile_selected .mx_BaseAvatar_image { - border: 3px solid $accent-color; - height: 40px; - width: 40px; - box-sizing: border-box; +.mx_TagPanel .mx_TagTile.mx_TagTile_selected::before { + content: ''; + height: 56px; + background-color: $accent-color; + width: 5px; + position: absolute; + left: -15px; + border-radius: 0 3px 3px 0; + top: -8px; // (56 - 40)/2 } .mx_TagPanel .mx_TagTile.mx_AccessibleButton:focus { diff --git a/res/css/structures/_TagPanelButtons.scss b/res/css/structures/_TagPanelButtons.scss deleted file mode 100644 index 70fea92959..0000000000 --- a/res/css/structures/_TagPanelButtons.scss +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2019 New Vector Ltd. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -.mx_TagPanelButtons { - background-color: $tagpanel-bg-color; - display: flex; - flex-direction: column; - align-items: center; - justify-content: space-between; - padding: 17px 0 3px 0; -} - -.mx_TagPanelButtons > .mx_GroupsButton::before { - mask: url('$(res)/img/feather-customised/users.svg'); - mask-position: center 11px; -} - -.mx_TagPanelButtons > .mx_TagPanelButtons_report::before { - mask: url('$(res)/img/feather-customised/life-buoy.svg'); - mask-position: center 9px; -} - -.mx_TagPanelButtons > .mx_AccessibleButton { - margin-bottom: 12px; - height: 40px; - width: 40px; - border-radius: 20px; - background-color: $tagpanel-button-color; - position: relative; - /* overwrite mx_RoleButton inline-block */ - display: block !important; - - &::before { - background-color: $tagpanel-bg-color; - mask-repeat: no-repeat; - content: ''; - position: absolute; - top: 0; - bottom: 0; - left: 0; - right: 0; - } -} diff --git a/res/css/views/context_menus/_TopLeftMenu.scss b/res/css/views/context_menus/_TopLeftMenu.scss index d17d683e7e..ed0d0106bc 100644 --- a/res/css/views/context_menus/_TopLeftMenu.scss +++ b/res/css/views/context_menus/_TopLeftMenu.scss @@ -53,6 +53,10 @@ limitations under the License. mask-image: url('$(res)/img/feather-customised/home.svg'); } + .mx_TopLeftMenu_icon_help::after { + mask-image: url('$(res)/img/feather-customised/life-buoy.svg'); + } + .mx_TopLeftMenu_icon_settings::after { mask-image: url('$(res)/img/feather-customised/settings.svg'); } diff --git a/res/css/views/dialogs/_DMInviteDialog.scss b/res/css/views/dialogs/_DMInviteDialog.scss new file mode 100644 index 0000000000..1153ecb0d4 --- /dev/null +++ b/res/css/views/dialogs/_DMInviteDialog.scss @@ -0,0 +1,81 @@ +/* +Copyright 2019, 2020 The Matrix.org Foundation C.I.C. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +.mx_DMInviteDialog_addressBar { + display: flex; + flex-direction: row; + + .mx_DMInviteDialog_editor { + flex: 1; + width: 100%; // Needed to make the Field inside grow + } + + .mx_Field { + margin: 0; + } + + .mx_DMInviteDialog_goButton { + width: 48px; + margin-left: 10px; + } +} + +.mx_DMInviteDialog_section { + padding-bottom: 10px; + + h3 { + font-size: 12px; + color: $muted-fg-color; + font-weight: bold; + text-transform: uppercase; + } +} + +.mx_DMInviteDialog_roomTile { + cursor: pointer; + padding: 5px 10px; + + &:hover { + background-color: $user-tile-hover-bg-color; + border-radius: 4px; + } + + * { + vertical-align: middle; + } + + .mx_DMInviteDialog_roomTile_name { + font-weight: 600; + font-size: 14px; + color: $primary-fg-color; + margin-left: 7px; + } + + .mx_DMInviteDialog_roomTile_userId { + font-size: 12px; + color: $muted-fg-color; + margin-left: 7px; + } + + .mx_DMInviteDialog_roomTile_time { + text-align: right; + font-size: 12px; + color: $muted-fg-color; + float: right; + line-height: 36px; // Height of the avatar to keep the time vertically aligned + } +} + diff --git a/res/css/views/dialogs/_RoomSettingsDialog.scss b/res/css/views/dialogs/_RoomSettingsDialog.scss index 08839d8493..aa66e97f9e 100644 --- a/res/css/views/dialogs/_RoomSettingsDialog.scss +++ b/res/css/views/dialogs/_RoomSettingsDialog.scss @@ -29,6 +29,11 @@ limitations under the License. mask-image: url('$(res)/img/feather-customised/users-sm.svg'); } +.mx_RoomSettingsDialog_bridgesIcon::before { + // This icon is pants, please improve :) + mask-image: url('$(res)/img/feather-customised/bridge.svg'); +} + .mx_RoomSettingsDialog_warningIcon::before { mask-image: url('$(res)/img/feather-customised/warning-triangle.svg'); } @@ -50,3 +55,17 @@ limitations under the License. mask-size: 36px; mask-position: center; } + +.mx_RoomSettingsDialog_BridgeList { + padding: 0; +} + +.mx_RoomSettingsDialog_BridgeList li { + list-style-type: none; + padding: 5px; + margin-bottom: 5px; + border-width: 1px 0px; + border-color: #dee1f3; + border-style: solid; +} + diff --git a/res/css/views/rooms/_EventTile.scss b/res/css/views/rooms/_EventTile.scss index 5359992f84..fbac1e932a 100644 --- a/res/css/views/rooms/_EventTile.scss +++ b/res/css/views/rooms/_EventTile.scss @@ -1,5 +1,6 @@ /* Copyright 2015, 2016 OpenMarket Ltd +Copyright 2020 The Matrix.org Foundation C.I.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -353,7 +354,6 @@ div.mx_EventTile_notSent.mx_EventTile_redacted .mx_UnknownBody { left: 46px; width: 15px; height: 15px; - cursor: pointer; display: block; bottom: 0; right: 0; diff --git a/res/css/views/rooms/_RoomRecoveryReminder.scss b/res/css/views/rooms/_RoomRecoveryReminder.scss index 68e2bf861e..85d42ca4b4 100644 --- a/res/css/views/rooms/_RoomRecoveryReminder.scss +++ b/res/css/views/rooms/_RoomRecoveryReminder.scss @@ -40,4 +40,5 @@ limitations under the License. .mx_RoomRecoveryReminder_secondary { font-size: 90%; + margin-top: 1em; } diff --git a/res/css/views/rooms/_RoomTile.scss b/res/css/views/rooms/_RoomTile.scss index 1814919b61..e5c7948216 100644 --- a/res/css/views/rooms/_RoomTile.scss +++ b/res/css/views/rooms/_RoomTile.scss @@ -1,5 +1,6 @@ /* Copyright 2015, 2016 OpenMarket Ltd +Copyright 2019 The Matrix.org Foundation C.I.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/res/css/views/rooms/_UserOnlineDot.scss b/res/css/views/rooms/_UserOnlineDot.scss new file mode 100644 index 0000000000..339e5cc48a --- /dev/null +++ b/res/css/views/rooms/_UserOnlineDot.scss @@ -0,0 +1,23 @@ +/* +Copyright 2019 The Matrix.org Foundation C.I.C. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +.mx_UserOnlineDot { + border-radius: 50%; + background-color: $accent-color; + height: 5px; + width: 5px; + display: inline-block; +} diff --git a/res/img/feather-customised/bridge.svg b/res/img/feather-customised/bridge.svg new file mode 100644 index 0000000000..f8f3468155 --- /dev/null +++ b/res/img/feather-customised/bridge.svg @@ -0,0 +1,50 @@ + + diff --git a/res/img/feather-customised/plus.svg b/res/img/feather-customised/plus.svg new file mode 100644 index 0000000000..c747253139 --- /dev/null +++ b/res/img/feather-customised/plus.svg @@ -0,0 +1,4 @@ + diff --git a/res/themes/dark/css/_dark.scss b/res/themes/dark/css/_dark.scss index eadde4c672..a3515a9d99 100644 --- a/res/themes/dark/css/_dark.scss +++ b/res/themes/dark/css/_dark.scss @@ -16,6 +16,7 @@ $room-highlight-color: #343a46; // typical text (dark-on-white in light skin) $primary-fg-color: $text-primary-color; $primary-bg-color: $bg-color; +$muted-fg-color: $header-panel-text-primary-color; // used for dialog box text $light-fg-color: $header-panel-text-secondary-color; @@ -172,6 +173,8 @@ $interactive-tooltip-fg-color: #ffffff; $breadcrumb-placeholder-bg-color: #272c35; +$user-tile-hover-bg-color: $header-panel-bg-color; + // ***** Mixins! ***** @define-mixin mx_DialogButton { @@ -243,3 +246,13 @@ $breadcrumb-placeholder-bg-color: #272c35; } } } + +// diff highlight colors +// intentionally swapped to avoid inversion +.hljs-addition { + background: #fdd; +} + +.hljs-deletion { + background: #dfd; +} diff --git a/res/themes/light/css/_light.scss b/res/themes/light/css/_light.scss index 0a3ef812b8..288fb3cadc 100644 --- a/res/themes/light/css/_light.scss +++ b/res/themes/light/css/_light.scss @@ -21,6 +21,7 @@ $header-panel-bg-color: #f3f8fd; // typical text (dark-on-white in light skin) $primary-fg-color: #2e2f32; $primary-bg-color: #ffffff; +$muted-fg-color: #61708b; // Commonly used in headings and relevant alt text // used for dialog box text $light-fg-color: #747474; @@ -293,6 +294,8 @@ $interactive-tooltip-fg-color: #ffffff; $breadcrumb-placeholder-bg-color: #e8eef5; +$user-tile-hover-bg-color: $header-panel-bg-color; + // ***** Mixins! ***** @define-mixin mx_DialogButton { @@ -338,3 +341,12 @@ $breadcrumb-placeholder-bg-color: #e8eef5; color: $accent-color; text-decoration: none; } + +// diff highlight colors +.hljs-addition { + background: #dfd; +} + +.hljs-deletion { + background: #fdd; +} diff --git a/scripts/ci/end-to-end-tests.sh b/scripts/ci/end-to-end-tests.sh index ae88ef70c7..a592888292 100755 --- a/scripts/ci/end-to-end-tests.sh +++ b/scripts/ci/end-to-end-tests.sh @@ -36,7 +36,8 @@ echo "--- Install synapse & other dependencies" ./install.sh # install static webserver to server symlinked local copy of riot ./riot/install-webserver.sh -mkdir logs || rm -r logs/* +rm -r logs || true +mkdir logs echo "+++ Running end-to-end tests" TESTS_STARTED=1 ./run.sh --no-sandbox --log-directory logs/ diff --git a/scripts/emoji-data-strip.js b/scripts/emoji-data-strip.js deleted file mode 100644 index 1c3738cab1..0000000000 --- a/scripts/emoji-data-strip.js +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env node - -// This generates src/stripped-emoji.json as used by the EmojiProvider autocomplete -// provider. - -const EMOJIBASE = require('emojibase-data/en/compact.json'); - -const fs = require('fs'); - -const output = EMOJIBASE.map( - (datum) => { - const newDatum = { - name: datum.annotation, - shortname: `:${datum.shortcodes[0]}:`, - category: datum.group, - emoji_order: datum.order, - }; - if (datum.shortcodes.length > 1) { - newDatum.aliases = datum.shortcodes.slice(1).map(s => `:${s}:`); - } - if (datum.emoticon) { - newDatum.aliases_ascii = [ datum.emoticon ]; - } - return newDatum; - } -); - -// Write to a file in src. Changes should be checked into git. This file is copied by -// babel using --copy-files -fs.writeFileSync('./src/stripped-emoji.json', JSON.stringify(output)); diff --git a/src/ContentMessages.js b/src/ContentMessages.js index 6908a6a18e..0ce349f348 100644 --- a/src/ContentMessages.js +++ b/src/ContentMessages.js @@ -422,6 +422,9 @@ export default class ContentMessages { const UploadConfirmDialog = sdk.getComponent("dialogs.UploadConfirmDialog"); let uploadAll = false; + // Promise to complete before sending next file into room, used for synchronisation of file-sending + // to match the order the files were specified in + let promBefore = Promise.resolve(); for (let i = 0; i < okFiles.length; ++i) { const file = okFiles[i]; if (!uploadAll) { @@ -440,11 +443,11 @@ export default class ContentMessages { }); if (!shouldContinue) break; } - this._sendContentToRoom(file, roomId, matrixClient); + promBefore = this._sendContentToRoom(file, roomId, matrixClient, promBefore); } } - _sendContentToRoom(file, roomId, matrixClient) { + _sendContentToRoom(file, roomId, matrixClient, promBefore) { const content = { body: file.name || 'Attachment', info: { @@ -517,7 +520,10 @@ export default class ContentMessages { content.file = result.file; content.url = result.url; }); - }).then(function(url) { + }).then((url) => { + // Await previous message being sent into the room + return promBefore; + }).then(function() { return matrixClient.sendMessage(roomId, content); }, function(err) { error = err; diff --git a/src/CrossSigningManager.js b/src/CrossSigningManager.js index ab0a22e4d5..f3953b1897 100644 --- a/src/CrossSigningManager.js +++ b/src/CrossSigningManager.js @@ -97,7 +97,7 @@ export const crossSigningCallbacks = { * * Additionally, the secret storage keys are cached during the scope of this function * to ensure the user is prompted only once for their secret storage - * passphrase. The cache is then + * passphrase. The cache is then cleared once the provided function completes. * * @param {Function} [func] An operation to perform once secret storage has been * bootstrapped. Optional. diff --git a/src/HtmlUtils.js b/src/HtmlUtils.js index 2b7384a5aa..7cdff26a21 100644 --- a/src/HtmlUtils.js +++ b/src/HtmlUtils.js @@ -32,9 +32,9 @@ import classNames from 'classnames'; import MatrixClientPeg from './MatrixClientPeg'; import url from 'url'; -import EMOJIBASE from 'emojibase-data/en/compact.json'; import EMOJIBASE_REGEX from 'emojibase-regex'; import {tryTransformPermalinkToLocalHref} from "./utils/permalinks/Permalinks"; +import {SHORTCODE_TO_EMOJI, getEmojiFromUnicode} from "./emoji"; linkifyMatrix(linkify); @@ -58,8 +58,6 @@ const COLOR_REGEX = /^#[0-9a-fA-F]{6}$/; const PERMITTED_URL_SCHEMES = ['http', 'https', 'ftp', 'mailto', 'magnet']; -const VARIATION_SELECTOR = String.fromCharCode(0xFE0F); - /* * Return true if the given string contains emoji * Uses a much, much simpler regex than emojibase's so will give false @@ -71,21 +69,6 @@ function mightContainEmoji(str) { return SURROGATE_PAIR_PATTERN.test(str) || SYMBOL_PATTERN.test(str); } -/** - * Find emoji data in emojibase by character. - * - * @param {String} char The emoji character - * @return {Object} The emoji data - */ -export function findEmojiData(char) { - // Check against both the char and the char with an empty variation selector - // appended because that's how emojibase stores its base emojis which have - // variations. - // See also https://github.com/vector-im/riot-web/issues/9785. - const emptyVariation = char + VARIATION_SELECTOR; - return EMOJIBASE.find(e => e.unicode === char || e.unicode === emptyVariation); -} - /** * Returns the shortcode for an emoji character. * @@ -93,7 +76,7 @@ export function findEmojiData(char) { * @return {String} The shortcode (such as :thumbup:) */ export function unicodeToShortcode(char) { - const data = findEmojiData(char); + const data = getEmojiFromUnicode(char); return (data && data.shortcodes ? `:${data.shortcodes[0]}:` : ''); } @@ -105,7 +88,7 @@ export function unicodeToShortcode(char) { */ export function shortcodeToUnicode(shortcode) { shortcode = shortcode.slice(1, shortcode.length - 1); - const data = EMOJIBASE.find(e => e.shortcodes && e.shortcodes.includes(shortcode)); + const data = SHORTCODE_TO_EMOJI.get(shortcode); return data ? data.unicode : null; } diff --git a/src/KeyRequestHandler.js b/src/KeyRequestHandler.js index c3de7988b2..4ee258da53 100644 --- a/src/KeyRequestHandler.js +++ b/src/KeyRequestHandler.js @@ -111,6 +111,12 @@ export default class KeyRequestHandler { this._currentUser = null; this._currentDevice = null; + if (!this._pendingKeyRequests[userId] || !this._pendingKeyRequests[userId][deviceId]) { + // request was removed in the time the dialog was displayed + this._processNextRequest(); + return; + } + if (r) { for (const req of this._pendingKeyRequests[userId][deviceId]) { req.share(); diff --git a/src/RoomInvite.js b/src/RoomInvite.js index 48baad5d9f..ba9fe1f541 100644 --- a/src/RoomInvite.js +++ b/src/RoomInvite.js @@ -25,6 +25,7 @@ import sdk from './'; import dis from './dispatcher'; import DMRoomMap from './utils/DMRoomMap'; import { _t } from './languageHandler'; +import SettingsStore from "./settings/SettingsStore"; /** * Invites multiple addresses to a room @@ -41,6 +42,18 @@ function inviteMultipleToRoom(roomId, addrs) { } export function showStartChatInviteDialog() { + if (SettingsStore.isFeatureEnabled("feature_ftue_dms")) { + const DMInviteDialog = sdk.getComponent("dialogs.DMInviteDialog"); + Modal.createTrackedDialog('Start DM', '', DMInviteDialog, { + onFinished: (inviteIds) => { + // TODO: Replace _onStartDmFinished with less hacks + if (inviteIds.length > 0) _onStartDmFinished(true, inviteIds.map(i => ({address: i}))); + // else ignore and just do nothing + }, + }, /*className=*/null, /*isPriority=*/false, /*isStatic=*/true); + return; + } + const AddressPickerDialog = sdk.getComponent("dialogs.AddressPickerDialog"); Modal.createTrackedDialog('Start a chat', '', AddressPickerDialog, { @@ -99,7 +112,7 @@ export function isValid3pidInvite(event) { return true; } -// TODO: Immutable DMs replaces this +// TODO: Canonical DMs replaces this function _onStartDmFinished(shouldInvite, addrs) { if (!shouldInvite) return; diff --git a/src/SlashCommands.js b/src/SlashCommands.js index a9c015fdaf..21fa4a134e 100644 --- a/src/SlashCommands.js +++ b/src/SlashCommands.js @@ -780,54 +780,52 @@ export const CommandMap = { const deviceId = matches[2]; const fingerprint = matches[3]; - return success( - // Promise.resolve to handle transition from static result to promise; can be removed - // in future - Promise.resolve(cli.getStoredDevice(userId, deviceId)).then((device) => { - if (!device) { - throw new Error(_t('Unknown (user, device) pair:') + ` (${userId}, ${deviceId})`); - } + return success((async () => { + const device = await cli.getStoredDevice(userId, deviceId); + if (!device) { + throw new Error(_t('Unknown (user, device) pair:') + ` (${userId}, ${deviceId})`); + } + const deviceTrust = await cli.checkDeviceTrust(userId, deviceId); - if (device.isVerified()) { - if (device.getFingerprint() === fingerprint) { - throw new Error(_t('Device already verified!')); - } else { - throw new Error(_t('WARNING: Device already verified, but keys do NOT MATCH!')); - } + if (deviceTrust.isVerified()) { + if (device.getFingerprint() === fingerprint) { + throw new Error(_t('Device already verified!')); + } else { + throw new Error(_t('WARNING: Device already verified, but keys do NOT MATCH!')); } + } - if (device.getFingerprint() !== fingerprint) { - const fprint = device.getFingerprint(); - throw new Error( - _t('WARNING: KEY VERIFICATION FAILED! The signing key for %(userId)s and device' + - ' %(deviceId)s is "%(fprint)s" which does not match the provided key ' + - '"%(fingerprint)s". This could mean your communications are being intercepted!', - { - fprint, - userId, - deviceId, - fingerprint, - })); - } + if (device.getFingerprint() !== fingerprint) { + const fprint = device.getFingerprint(); + throw new Error( + _t('WARNING: KEY VERIFICATION FAILED! The signing key for %(userId)s and device' + + ' %(deviceId)s is "%(fprint)s" which does not match the provided key ' + + '"%(fingerprint)s". This could mean your communications are being intercepted!', + { + fprint, + userId, + deviceId, + fingerprint, + })); + } - return cli.setDeviceVerified(userId, deviceId, true); - }).then(() => { - // Tell the user we verified everything - const InfoDialog = sdk.getComponent('dialogs.InfoDialog'); - Modal.createTrackedDialog('Slash Commands', 'Verified key', InfoDialog, { - title: _t('Verified key'), - description:
- { - _t('The signing key you provided matches the signing key you received ' + - 'from %(userId)s\'s device %(deviceId)s. Device marked as verified.', - {userId, deviceId}) - } -
-+ { + _t('The signing key you provided matches the signing key you received ' + + 'from %(userId)s\'s device %(deviceId)s. Device marked as verified.', + {userId, deviceId}) + } +
+{_t( + "Secret Storage will be set up using your existing key backup details." + + "Your secret storage passphrase and recovery key will be the same as " + + " they were for your key backup", + )}
++ {_t( + "If you can't find someone, ask them for their username, or share your " + + "username (%(userId)s) or profile link.", + {userId}, + {a: (sub) => {sub}}, + )} +
+ {targets} +{ _t('In reply to', {}, { diff --git a/src/components/views/elements/RoomAliasField.js b/src/components/views/elements/RoomAliasField.js index 03f4000e59..7054dfcce2 100644 --- a/src/components/views/elements/RoomAliasField.js +++ b/src/components/views/elements/RoomAliasField.js @@ -20,11 +20,13 @@ import sdk from '../../../index'; import withValidation from './Validation'; import MatrixClientPeg from '../../../MatrixClientPeg'; +// Controlled form component wrapping Field for inputting a room alias scoped to a given domain export default class RoomAliasField extends React.PureComponent { static propTypes = { id: PropTypes.string.isRequired, domain: PropTypes.string.isRequired, onChange: PropTypes.func, + value: PropTypes.string.isRequired, }; constructor(props) { @@ -53,6 +55,7 @@ export default class RoomAliasField extends React.PureComponent { onValidate={this._onValidate} placeholder={_t("e.g. my-room")} onChange={this._onChange} + value={this.props.value.substring(1, this.props.value.length - this.props.domain.length - 1)} maxLength={maxlength} /> ); } @@ -61,7 +64,7 @@ export default class RoomAliasField extends React.PureComponent { if (this.props.onChange) { this.props.onChange(this._asFullAlias(ev.target.value)); } - } + }; _onValidate = async (fieldState) => { const result = await this._validationRules(fieldState); diff --git a/src/components/views/elements/SyntaxHighlight.js b/src/components/views/elements/SyntaxHighlight.js index 82b5ae572c..bce65cf1a9 100644 --- a/src/components/views/elements/SyntaxHighlight.js +++ b/src/components/views/elements/SyntaxHighlight.js @@ -24,8 +24,8 @@ export default class SyntaxHighlight extends React.Component { children: PropTypes.node, }; - constructor(props, context) { - super(props, context); + constructor(props) { + super(props); this._ref = this._ref.bind(this); } diff --git a/src/components/views/elements/TagTile.js b/src/components/views/elements/TagTile.js index e31c1c524e..0b81098124 100644 --- a/src/components/views/elements/TagTile.js +++ b/src/components/views/elements/TagTile.js @@ -20,17 +20,16 @@ import React, {createRef} from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; import classNames from 'classnames'; -import { MatrixClient } from 'matrix-js-sdk'; import sdk from '../../../index'; import dis from '../../../dispatcher'; -import {_t} from '../../../languageHandler'; import { isOnlyCtrlOrCmdIgnoreShiftKeyEvent } from '../../../Keyboard'; import * as FormattingUtils from '../../../utils/FormattingUtils'; import FlairStore from '../../../stores/FlairStore'; import GroupStore from '../../../stores/GroupStore'; import TagOrderStore from '../../../stores/TagOrderStore'; -import {ContextMenu, ContextMenuButton, toRightOf} from "../../structures/ContextMenu"; +import {ContextMenu, toRightOf} from "../../structures/ContextMenu"; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; // A class for a child of TagPanel (possibly wrapped in a DNDTagTile) that represents // a thing to click on for the user to filter the visible rooms in the RoomList to: @@ -46,8 +45,8 @@ export default createReactClass({ tag: PropTypes.string, }, - contextTypes: { - matrixClient: PropTypes.instanceOf(MatrixClient).isRequired, + statics: { + contextType: MatrixClientContext, }, getInitialState() { @@ -83,7 +82,7 @@ export default createReactClass({ _onFlairStoreUpdated() { if (this.unmounted) return; FlairStore.getGroupProfileCached( - this.context.matrixClient, + this.context, this.props.tag, ).then((profile) => { if (this.unmounted) return; @@ -114,12 +113,10 @@ export default createReactClass({ }, onMouseOver: function() { - console.log("DEBUG onMouseOver"); this.setState({hover: true}); }, onMouseOut: function() { - console.log("DEBUG onMouseOut"); this.setState({hover: false}); }, @@ -142,12 +139,11 @@ export default createReactClass({ render: function() { const BaseAvatar = sdk.getComponent('avatars.BaseAvatar'); - const Tooltip = sdk.getComponent('elements.Tooltip'); const profile = this.state.profile || {}; const name = profile.name || this.props.tag; const avatarHeight = 40; - const httpUrl = profile.avatarUrl ? this.context.matrixClient.mxcUrlToHttp( + const httpUrl = profile.avatarUrl ? this.context.mxcUrlToHttp( profile.avatarUrl, avatarHeight, avatarHeight, "crop", ) : null; @@ -166,9 +162,6 @@ export default createReactClass({ badgeElement = ( {FormattingUtils.formatCount(badge.count)}); } - const tip = this.state.hover ? -: - ; // FIXME: this ought to use AccessibleButton for a11y but that causes onMouseOut/onMouseOver to fire too much const contextButton = this.state.hover || this.state.menuDisplayed ? @@ -186,14 +179,9 @@ export default createReactClass({ ); } + const AccessibleTooltipButton = sdk.getComponent("elements.AccessibleTooltipButton"); return); -}); +}; UserInfo.propTypes = { user: PropTypes.oneOfType([ diff --git a/src/components/views/room_settings/AliasSettings.js b/src/components/views/room_settings/AliasSettings.js index daf5c6edc2..aa9d46c9d5 100644 --- a/src/components/views/room_settings/AliasSettings.js +++ b/src/components/views/room_settings/AliasSettings.js @@ -15,6 +15,8 @@ See the License for the specific language governing permissions and limitations under the License. */ +import EditableItemList from "../elements/EditableItemList"; + const React = require('react'); import PropTypes from 'prop-types'; const MatrixClientPeg = require('../../../MatrixClientPeg'); @@ -22,8 +24,33 @@ const sdk = require("../../../index"); import { _t } from '../../../languageHandler'; import Field from "../elements/Field"; import ErrorDialog from "../dialogs/ErrorDialog"; +import AccessibleButton from "../elements/AccessibleButton"; const Modal = require("../../../Modal"); +class EditableAliasesList extends EditableItemList { + _renderNewItemField() { + const RoomAliasField = sdk.getComponent('views.elements.RoomAliasField'); + const onChange = (alias) => this._onNewItemChanged({target: {value: alias}}); + return ( + + ); + } +} + export default class AliasSettings extends React.Component { static propTypes = { roomId: PropTypes.string.isRequired, @@ -47,7 +74,6 @@ export default class AliasSettings extends React.Component { remoteDomains: [], // [ domain.com, foobar.com ] canonicalAlias: null, // #canonical:domain.com updatingCanonicalAlias: false, - newItem: "", }; const localDomain = MatrixClientPeg.get().getDomain(); @@ -181,7 +207,6 @@ export default class AliasSettings extends React.Component { }; render() { - const EditableItemList = sdk.getComponent("elements.EditableItemList"); const localDomain = MatrixClientPeg.get().getDomain(); let found = false; @@ -233,7 +258,7 @@ export default class AliasSettings extends React.Component { return (- ; diff --git a/src/components/views/emojipicker/EmojiPicker.js b/src/components/views/emojipicker/EmojiPicker.js index 0ec11c2b38..4d49b25100 100644 --- a/src/components/views/emojipicker/EmojiPicker.js +++ b/src/components/views/emojipicker/EmojiPicker.js @@ -16,54 +16,12 @@ limitations under the License. import React from 'react'; import PropTypes from 'prop-types'; -import EMOJIBASE from 'emojibase-data/en/compact.json'; import sdk from '../../../index'; import { _t } from '../../../languageHandler'; import * as recent from './recent'; - -const EMOJIBASE_CATEGORY_IDS = [ - "people", // smileys - "people", // actually people - "control", // modifiers and such, not displayed in picker - "nature", - "foods", - "places", - "activity", - "objects", - "symbols", - "flags", -]; - -const DATA_BY_CATEGORY = { - "people": [], - "nature": [], - "foods": [], - "places": [], - "activity": [], - "objects": [], - "symbols": [], - "flags": [], -}; -const DATA_BY_EMOJI = {}; - -const VARIATION_SELECTOR = String.fromCharCode(0xFE0F); -EMOJIBASE.forEach(emoji => { - if (emoji.unicode.includes(VARIATION_SELECTOR)) { - // Clone data into variation-less version - emoji = Object.assign({}, emoji, { - unicode: emoji.unicode.replace(VARIATION_SELECTOR, ""), - }); - } - DATA_BY_EMOJI[emoji.unicode] = emoji; - const categoryId = EMOJIBASE_CATEGORY_IDS[emoji.group]; - if (DATA_BY_CATEGORY.hasOwnProperty(categoryId)) { - DATA_BY_CATEGORY[categoryId].push(emoji); - } - // This is used as the string to match the query against when filtering emojis. - emoji.filterString = `${emoji.annotation}\n${emoji.shortcodes.join('\n')}}\n${emoji.emoticon || ''}`.toLowerCase(); -}); +import {DATA_BY_CATEGORY, getEmojiFromUnicode} from "../../../emoji"; export const CATEGORY_HEADER_HEIGHT = 22; export const EMOJI_HEIGHT = 37; @@ -91,7 +49,7 @@ class EmojiPicker extends React.Component { // Convert recent emoji characters to emoji data, removing unknowns. this.recentlyUsed = recent.get() - .map(unicode => DATA_BY_EMOJI[unicode]) + .map(unicode => getEmojiFromUnicode(unicode)) .filter(data => !!data); this.memoizedDataByCategory = { recent: this.recentlyUsed, diff --git a/src/components/views/emojipicker/QuickReactions.js b/src/components/views/emojipicker/QuickReactions.js index 8444fb2d9c..e4419e9f3a 100644 --- a/src/components/views/emojipicker/QuickReactions.js +++ b/src/components/views/emojipicker/QuickReactions.js @@ -19,15 +19,15 @@ import PropTypes from 'prop-types'; import sdk from '../../../index'; import { _t } from '../../../languageHandler'; -import { findEmojiData } from '../../../HtmlUtils'; +import {getEmojiFromUnicode} from "../../../emoji"; +// We use the variation-selector Heart in Quick Reactions for some reason const QUICK_REACTIONS = ["👍", "👎", "😄", "🎉", "😕", "❤️", "🚀", "👀"].map(emoji => { - const data = findEmojiData(emoji); + const data = getEmojiFromUnicode(emoji); if (!data) { throw new Error(`Emoji ${emoji} doesn't exist in emojibase`); } - // Prefer our unicode value for quick reactions (which does not have - // variation selectors). + // Prefer our unicode value for quick reactions as we sometimes use variation selectors. return Object.assign({}, data, { unicode: emoji }); }); diff --git a/src/components/views/globals/MatrixToolbar.js b/src/components/views/globals/MatrixToolbar.js index aabf0810f8..1e496741ad 100644 --- a/src/components/views/globals/MatrixToolbar.js +++ b/src/components/views/globals/MatrixToolbar.js @@ -34,7 +34,7 @@ module.exports = createReactClass({ render: function() { return (+ + { contextMenu } -- { tip } { contextButton } { badgeElement } -); -}); +}; + +const UserInfo = ({user, groupId, roomId, onClose}) => { + const cli = useContext(MatrixClientContext); -// cli is injected by withLegacyMatrixClient -const UserInfo = withLegacyMatrixClient(({matrixClient: cli, user, groupId, roomId, onClose}) => { // Load room if we are given a room id and memoize it const room = useMemo(() => roomId ? cli.getRoom(roomId) : null, [cli, roomId]); @@ -1260,11 +1272,20 @@ const UserInfo = withLegacyMatrixClient(({matrixClient: cli, user, groupId, room const devicesSection = isRoomEncrypted ? (+
{ _t('You are not receiving desktop notifications') } { _t('Enable them now') }diff --git a/src/components/views/globals/NewVersionBar.js b/src/components/views/globals/NewVersionBar.js index abb9334242..f6bd029969 100644 --- a/src/components/views/globals/NewVersionBar.js +++ b/src/components/views/globals/NewVersionBar.js @@ -97,7 +97,7 @@ export default createReactClass({ } return (-); -}); +}; const _warnSelfDemote = async () => { const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog"); @@ -404,7 +402,12 @@ const useRoomPowerLevels = (cli, room) => { return powerLevels; }; -const RoomKickButton = withLegacyMatrixClient(({matrixClient: cli, member, startUpdating, stopUpdating}) => { +const RoomKickButton = ({member, startUpdating, stopUpdating}) => { + const cli = useContext(MatrixClientContext); + + // check if user can be kicked/disinvited + if (member.membership !== "invite" && member.membership !== "join") return null; + const onKick = async () => { const ConfirmUserActionDialog = sdk.getComponent("dialogs.ConfirmUserActionDialog"); const {finished} = Modal.createTrackedDialog( @@ -444,9 +447,11 @@ const RoomKickButton = withLegacyMatrixClient(({matrixClient: cli, member, start return+
{_t("A new version of Riot is available.")}diff --git a/src/components/views/groups/GroupInviteTile.js b/src/components/views/groups/GroupInviteTile.js index a21b091145..c0d0d9eafe 100644 --- a/src/components/views/groups/GroupInviteTile.js +++ b/src/components/views/groups/GroupInviteTile.js @@ -19,13 +19,13 @@ limitations under the License. import React from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; -import { MatrixClient } from 'matrix-js-sdk'; import sdk from '../../../index'; import dis from '../../../dispatcher'; import {_t} from '../../../languageHandler'; import classNames from 'classnames'; import MatrixClientPeg from "../../../MatrixClientPeg"; import {ContextMenu, ContextMenuButton, toRightOf} from "../../structures/ContextMenu"; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; // XXX this class copies a lot from RoomTile.js export default createReactClass({ @@ -35,8 +35,8 @@ export default createReactClass({ group: PropTypes.object.isRequired, }, - contextTypes: { - matrixClient: PropTypes.instanceOf(MatrixClient), + statics: { + contextType: MatrixClientContext, }, getInitialState: function() { @@ -58,7 +58,7 @@ export default createReactClass({ onMouseEnter: function() { const state = {hover: true}; // Only allow non-guests to access the context menu - if (!this.context.matrixClient.isGuest()) { + if (!this.context.isGuest()) { state.badgeHover = true; } this.setState(state); @@ -118,7 +118,7 @@ export default createReactClass({ const groupName = this.props.group.name || this.props.group.groupId; const httpAvatarUrl = this.props.group.avatarUrl ? - this.context.matrixClient.mxcUrlToHttp(this.props.group.avatarUrl, 24, 24) : null; + this.context.mxcUrlToHttp(this.props.group.avatarUrl, 24, 24) : null; const av =; diff --git a/src/components/views/groups/GroupMemberInfo.js b/src/components/views/groups/GroupMemberInfo.js index 3dac90fc35..eb90cdc0f8 100644 --- a/src/components/views/groups/GroupMemberInfo.js +++ b/src/components/views/groups/GroupMemberInfo.js @@ -18,7 +18,6 @@ limitations under the License. import React from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; -import { MatrixClient } from 'matrix-js-sdk'; import dis from '../../../dispatcher'; import Modal from '../../../Modal'; import sdk from '../../../index'; @@ -26,12 +25,13 @@ import { _t } from '../../../languageHandler'; import { GroupMemberType } from '../../../groups'; import GroupStore from '../../../stores/GroupStore'; import AccessibleButton from '../elements/AccessibleButton'; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; module.exports = createReactClass({ displayName: 'GroupMemberInfo', - contextTypes: { - matrixClient: PropTypes.instanceOf(MatrixClient), + statics: { + contextType: MatrixClientContext, }, propTypes: { @@ -85,7 +85,7 @@ module.exports = createReactClass({ _onKick: function() { const ConfirmUserActionDialog = sdk.getComponent("dialogs.ConfirmUserActionDialog"); Modal.createDialog(ConfirmUserActionDialog, { - matrixClient: this.context.matrixClient, + matrixClient: this.context, groupMember: this.props.groupMember, action: this.state.isUserInvited ? _t('Disinvite') : _t('Remove from community'), title: this.state.isUserInvited ? _t('Disinvite this user from community?') @@ -95,7 +95,7 @@ module.exports = createReactClass({ if (!proceed) return; this.setState({removingUser: true}); - this.context.matrixClient.removeUserFromGroup( + this.context.removeUserFromGroup( this.props.groupId, this.props.groupMember.userId, ).then(() => { // return to the user list @@ -171,7 +171,7 @@ module.exports = createReactClass({ const avatarUrl = this.props.groupMember.avatarUrl; let avatarElement; if (avatarUrl) { - const httpUrl = this.context.matrixClient.mxcUrlToHttp(avatarUrl, 800, 800); + const httpUrl = this.context.mxcUrlToHttp(avatarUrl, 800, 800); avatarElement = ( ); diff --git a/src/components/views/groups/GroupMemberTile.js b/src/components/views/groups/GroupMemberTile.js index c4b41d23ce..7a9ba9289b 100644 --- a/src/components/views/groups/GroupMemberTile.js +++ b/src/components/views/groups/GroupMemberTile.js @@ -19,10 +19,10 @@ limitations under the License. import React from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; -import { MatrixClient } from 'matrix-js-sdk'; import sdk from '../../../index'; import dis from '../../../dispatcher'; import { GroupMemberType } from '../../../groups'; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; export default createReactClass({ displayName: 'GroupMemberTile', @@ -36,8 +36,8 @@ export default createReactClass({ return {}; }, - contextTypes: { - matrixClient: PropTypes.instanceOf(MatrixClient).isRequired, + statics: { + contextType: MatrixClientContext, }, onClick: function(e) { @@ -53,7 +53,7 @@ export default createReactClass({ const EntityTile = sdk.getComponent('rooms.EntityTile'); const name = this.props.member.displayname || this.props.member.userId; - const avatarUrl = this.context.matrixClient.mxcUrlToHttp( + const avatarUrl = this.context.mxcUrlToHttp( this.props.member.avatarUrl, 36, 36, 'crop', ); diff --git a/src/components/views/groups/GroupRoomInfo.js b/src/components/views/groups/GroupRoomInfo.js index f9f7324e23..d5b8759a67 100644 --- a/src/components/views/groups/GroupRoomInfo.js +++ b/src/components/views/groups/GroupRoomInfo.js @@ -17,18 +17,18 @@ limitations under the License. import React from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; -import { MatrixClient } from 'matrix-js-sdk'; import dis from '../../../dispatcher'; import Modal from '../../../Modal'; import sdk from '../../../index'; import { _t } from '../../../languageHandler'; import GroupStore from '../../../stores/GroupStore'; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; module.exports = createReactClass({ displayName: 'GroupRoomInfo', - contextTypes: { - matrixClient: PropTypes.instanceOf(MatrixClient), + statics: { + contextType: MatrixClientContext, }, propTypes: { @@ -206,7 +206,7 @@ module.exports = createReactClass({ const avatarUrl = this.state.groupRoom.avatarUrl; let avatarElement; if (avatarUrl) { - const httpUrl = this.context.matrixClient.mxcUrlToHttp(avatarUrl, 800, 800); + const httpUrl = this.context.mxcUrlToHttp(avatarUrl, 800, 800); avatarElement = (
); diff --git a/src/components/views/groups/GroupRoomTile.js b/src/components/views/groups/GroupRoomTile.js index ae325d4796..527e65d30c 100644 --- a/src/components/views/groups/GroupRoomTile.js +++ b/src/components/views/groups/GroupRoomTile.js @@ -17,10 +17,10 @@ limitations under the License. import React from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; -import {MatrixClient} from 'matrix-js-sdk'; import sdk from '../../../index'; import dis from '../../../dispatcher'; import { GroupRoomType } from '../../../groups'; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; const GroupRoomTile = createReactClass({ displayName: 'GroupRoomTile', @@ -41,7 +41,7 @@ const GroupRoomTile = createReactClass({ render: function() { const BaseAvatar = sdk.getComponent('avatars.BaseAvatar'); const AccessibleButton = sdk.getComponent('elements.AccessibleButton'); - const avatarUrl = this.context.matrixClient.mxcUrlToHttp( + const avatarUrl = this.context.mxcUrlToHttp( this.props.groupRoom.avatarUrl, 36, 36, 'crop', ); @@ -66,9 +66,7 @@ const GroupRoomTile = createReactClass({ }, }); -GroupRoomTile.contextTypes = { - matrixClient: PropTypes.instanceOf(MatrixClient).isRequired, -}; +GroupRoomTile.contextType = MatrixClientContext; export default GroupRoomTile; diff --git a/src/components/views/groups/GroupTile.js b/src/components/views/groups/GroupTile.js index 3b64c10a1e..f3d7418a44 100644 --- a/src/components/views/groups/GroupTile.js +++ b/src/components/views/groups/GroupTile.js @@ -17,11 +17,11 @@ limitations under the License. import React from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; -import {MatrixClient} from 'matrix-js-sdk'; import { Draggable, Droppable } from 'react-beautiful-dnd'; import sdk from '../../../index'; import dis from '../../../dispatcher'; import FlairStore from '../../../stores/FlairStore'; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; function nop() {} @@ -37,8 +37,8 @@ const GroupTile = createReactClass({ draggable: PropTypes.bool, }, - contextTypes: { - matrixClient: PropTypes.instanceOf(MatrixClient).isRequired, + statics: { + contextType: MatrixClientContext, }, getInitialState() { @@ -56,7 +56,7 @@ const GroupTile = createReactClass({ }, componentWillMount: function() { - FlairStore.getGroupProfileCached(this.context.matrixClient, this.props.groupId).then((profile) => { + FlairStore.getGroupProfileCached(this.context, this.props.groupId).then((profile) => { this.setState({profile}); }).catch((err) => { console.error('Error whilst getting cached profile for GroupTile', err); @@ -80,7 +80,7 @@ const GroupTile = createReactClass({ const descElement = this.props.showDescription ?
{ profile.shortDescription }: ; - const httpUrl = profile.avatarUrl ? this.context.matrixClient.mxcUrlToHttp( + const httpUrl = profile.avatarUrl ? this.context.mxcUrlToHttp( profile.avatarUrl, avatarHeight, avatarHeight, "crop") : null; let avatarElement = ( diff --git a/src/components/views/groups/GroupUserSettings.js b/src/components/views/groups/GroupUserSettings.js index 3cd5731b99..297c0fbd30 100644 --- a/src/components/views/groups/GroupUserSettings.js +++ b/src/components/views/groups/GroupUserSettings.js @@ -15,17 +15,16 @@ limitations under the License. */ import React from 'react'; -import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; import sdk from '../../../index'; -import { MatrixClient } from 'matrix-js-sdk'; import { _t } from '../../../languageHandler'; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; export default createReactClass({ displayName: 'GroupUserSettings', - contextTypes: { - matrixClient: PropTypes.instanceOf(MatrixClient), + statics: { + contextType: MatrixClientContext, }, getInitialState() { @@ -36,7 +35,7 @@ export default createReactClass({ }, componentWillMount: function() { - this.context.matrixClient.getJoinedGroups().then((result) => { + this.context.getJoinedGroups().then((result) => { this.setState({groups: result.groups || [], error: null}); }, (err) => { console.error(err); diff --git a/src/components/views/messages/MFileBody.js b/src/components/views/messages/MFileBody.js index 552b1108d2..6045ec0571 100644 --- a/src/components/views/messages/MFileBody.js +++ b/src/components/views/messages/MFileBody.js @@ -26,6 +26,7 @@ import {decryptFile} from '../../../utils/DecryptFile'; import Tinter from '../../../Tinter'; import request from 'browser-request'; import Modal from '../../../Modal'; +import SdkConfig from "../../../SdkConfig"; // A cached tinted copy of require("../../../../res/img/download.svg") @@ -214,10 +215,6 @@ module.exports = createReactClass({ tileShape: PropTypes.string, }, - contextTypes: { - appConfig: PropTypes.object, - }, - /** * Extracts a human readable label for the file attachment to use as * link text. @@ -360,8 +357,9 @@ module.exports = createReactClass({ // If the attachment is encryped then put the link inside an iframe. let renderer_url = DEFAULT_CROSS_ORIGIN_RENDERER; - if (this.context.appConfig && this.context.appConfig.cross_origin_renderer_url) { - renderer_url = this.context.appConfig.cross_origin_renderer_url; + const appConfig = SdkConfig.get(); + if (appConfig && appConfig.cross_origin_renderer_url) { + renderer_url = appConfig.cross_origin_renderer_url; } renderer_url += "?origin=" + encodeURIComponent(window.location.origin); return ( diff --git a/src/components/views/messages/MImageBody.js b/src/components/views/messages/MImageBody.js index 427056203d..dbe6636c6b 100644 --- a/src/components/views/messages/MImageBody.js +++ b/src/components/views/messages/MImageBody.js @@ -18,7 +18,6 @@ limitations under the License. import React, {createRef} from 'react'; import PropTypes from 'prop-types'; -import { MatrixClient } from 'matrix-js-sdk'; import MFileBody from './MFileBody'; import Modal from '../../../Modal'; @@ -26,6 +25,7 @@ import sdk from '../../../index'; import { decryptFile } from '../../../utils/DecryptFile'; import { _t } from '../../../languageHandler'; import SettingsStore from "../../../settings/SettingsStore"; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; export default class MImageBody extends React.Component { static propTypes = { @@ -39,9 +39,7 @@ export default class MImageBody extends React.Component { maxImageHeight: PropTypes.number, }; - static contextTypes = { - matrixClient: PropTypes.instanceOf(MatrixClient), - }; + static contextType = MatrixClientContext; constructor(props) { super(props); @@ -71,7 +69,7 @@ export default class MImageBody extends React.Component { componentWillMount() { this.unmounted = false; - this.context.matrixClient.on('sync', this.onClientSync); + this.context.on('sync', this.onClientSync); } // FIXME: factor this out and aplpy it to MVideoBody and MAudioBody too! @@ -174,7 +172,7 @@ export default class MImageBody extends React.Component { if (content.file !== undefined) { return this.state.decryptedUrl; } else { - return this.context.matrixClient.mxcUrlToHttp(content.url); + return this.context.mxcUrlToHttp(content.url); } } @@ -198,7 +196,7 @@ export default class MImageBody extends React.Component { // special case to return clientside sender-generated thumbnails for SVGs, if any, // given we deliberately don't thumbnail them serverside to prevent // billion lol attacks and similar - return this.context.matrixClient.mxcUrlToHttp( + return this.context.mxcUrlToHttp( content.info.thumbnail_url, thumbWidth, thumbHeight, @@ -221,7 +219,7 @@ export default class MImageBody extends React.Component { pixelRatio === 1.0 || (!info || !info.w || !info.h || !info.size) ) { - return this.context.matrixClient.mxcUrlToHttp(content.url, thumbWidth, thumbHeight); + return this.context.mxcUrlToHttp(content.url, thumbWidth, thumbHeight); } else { // we should only request thumbnails if the image is bigger than 800x600 // (or 1600x1200 on retina) otherwise the image in the timeline will just @@ -242,7 +240,7 @@ export default class MImageBody extends React.Component { // image is too large physically and bytewise to clutter our timeline so // we ask for a thumbnail, despite knowing that it will be max 800x600 // despite us being retina (as synapse doesn't do 1600x1200 thumbs yet). - return this.context.matrixClient.mxcUrlToHttp( + return this.context.mxcUrlToHttp( content.url, thumbWidth, thumbHeight, @@ -251,7 +249,7 @@ export default class MImageBody extends React.Component { // download the original image otherwise, so we can scale it client side // to take pixelRatio into account. // ( no width/height means we want the original image) - return this.context.matrixClient.mxcUrlToHttp( + return this.context.mxcUrlToHttp( content.url, ); } @@ -308,7 +306,7 @@ export default class MImageBody extends React.Component { componentWillUnmount() { this.unmounted = true; - this.context.matrixClient.removeListener('sync', this.onClientSync); + this.context.removeListener('sync', this.onClientSync); this._afterComponentWillUnmount(); if (this.state.decryptedUrl) { diff --git a/src/components/views/messages/MessageActionBar.js b/src/components/views/messages/MessageActionBar.js index 81e806cf62..5c40c19b49 100644 --- a/src/components/views/messages/MessageActionBar.js +++ b/src/components/views/messages/MessageActionBar.js @@ -25,7 +25,7 @@ import dis from '../../../dispatcher'; import Modal from '../../../Modal'; import {aboveLeftOf, ContextMenu, ContextMenuButton, useContextMenu} from '../../structures/ContextMenu'; import { isContentActionable, canEditContent } from '../../../utils/EventUtils'; -import {RoomContext} from "../../structures/RoomView"; +import RoomContext from "../../../contexts/RoomContext"; const OptionsButton = ({mxEvent, getTile, getReplyThread, permalinkCreator, onFocusChange}) => { const [menuDisplayed, button, openMenu, closeMenu] = useContextMenu(); @@ -88,7 +88,7 @@ const ReactButton = ({mxEvent, reactions, onFocusChange}) => { if (menuDisplayed) { const buttonRect = button.current.getBoundingClientRect(); const ReactionPicker = sdk.getComponent('emojipicker.ReactionPicker'); - contextMenu =+ contextMenu = ; } @@ -117,9 +117,7 @@ export default class MessageActionBar extends React.PureComponent { onFocusChange: PropTypes.func, }; - static contextTypes = { - room: RoomContext, - }; + static contextType = RoomContext; componentDidMount() { this.props.mxEvent.on("Event.decrypted", this.onDecrypted); @@ -164,12 +162,12 @@ export default class MessageActionBar extends React.PureComponent { let editButton; if (isContentActionable(this.props.mxEvent)) { - if (this.context.room.canReact) { + if (this.context.canReact) { reactButton = ( ); } - if (this.context.room.canReply) { + if (this.context.canReply) { replyButton = { if (this.unmounted) return; this.setState({userGroups}); }); - this.context.matrixClient.on('RoomState.events', this.onRoomStateEvents); + this.context.on('RoomState.events', this.onRoomStateEvents); }, componentWillUnmount() { this.unmounted = true; - this.context.matrixClient.removeListener('RoomState.events', this.onRoomStateEvents); + this.context.removeListener('RoomState.events', this.onRoomStateEvents); }, onRoomStateEvents(event) { @@ -71,7 +71,7 @@ export default createReactClass({ _updateRelatedGroups() { if (this.unmounted) return; - const room = this.context.matrixClient.getRoom(this.props.mxEvent.getRoomId()); + const room = this.context.getRoom(this.props.mxEvent.getRoomId()); if (!room) return; const relatedGroupsEvent = room.currentState.getStateEvents('m.room.related_groups', ''); diff --git a/src/components/views/right_panel/UserInfo.js b/src/components/views/right_panel/UserInfo.js index 65fc0bf66b..809fdcb6d7 100644 --- a/src/components/views/right_panel/UserInfo.js +++ b/src/components/views/right_panel/UserInfo.js @@ -17,7 +17,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -import React, {useCallback, useMemo, useState, useEffect} from 'react'; +import React, {useCallback, useMemo, useState, useEffect, useContext} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import {Group, RoomMember, User} from 'matrix-js-sdk'; @@ -37,9 +37,9 @@ import MultiInviter from "../../../utils/MultiInviter"; import GroupStore from "../../../stores/GroupStore"; import MatrixClientPeg from "../../../MatrixClientPeg"; import E2EIcon from "../rooms/E2EIcon"; -import withLegacyMatrixClient from "../../../utils/withLegacyMatrixClient"; import {useEventEmitter} from "../../../hooks/useEventEmitter"; import {textualPowerLevel} from '../../../Roles'; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; const _disambiguateDevices = (devices) => { const names = Object.create(null); @@ -74,17 +74,6 @@ const _getE2EStatus = (cli, userId, devices) => { return "warning"; }; -async function unverifyUser(matrixClient, userId) { - const devices = await matrixClient.getStoredDevicesForUser(userId); - for (const device of devices) { - if (device.isVerified()) { - matrixClient.setDeviceVerified( - userId, device.deviceId, false, - ); - } - } -} - function openDMForUser(matrixClient, userId) { const dmRooms = DMRoomMap.shared().getDMRoomsForUserId(userId); const lastActiveRoom = dmRooms.reduce((lastActiveRoom, roomId) => { @@ -129,17 +118,20 @@ function verifyDevice(userId, device) { } function DeviceItem({userId, device}) { + const cli = useContext(MatrixClientContext); + const deviceTrust = cli.checkDeviceTrust(userId, device.deviceId); + const classes = classNames("mx_UserInfo_device", { - mx_UserInfo_device_verified: device.isVerified(), - mx_UserInfo_device_unverified: !device.isVerified(), + mx_UserInfo_device_verified: deviceTrust.isVerified(), + mx_UserInfo_device_unverified: !deviceTrust.isVerified(), }); const iconClasses = classNames("mx_E2EIcon", { - mx_E2EIcon_verified: device.isVerified(), - mx_E2EIcon_warning: !device.isVerified(), + mx_E2EIcon_verified: deviceTrust.isVerified(), + mx_E2EIcon_warning: !deviceTrust.isVerified(), }); const onDeviceClick = () => { - if (!device.isVerified()) { + if (!deviceTrust.isVerified()) { verifyDevice(userId, device); } }; @@ -147,7 +139,7 @@ function DeviceItem({userId, device}) { const deviceName = device.ambiguous ? (device.getDisplayName() ? device.getDisplayName() : "") + " (" + device.deviceId + ")" : device.getDisplayName(); - const trustedLabel = device.isVerified() ? _t("Trusted") : _t("Not trusted"); + const trustedLabel = deviceTrust.isVerified() ? _t("Trusted") : _t("Not trusted"); return ( ); } - let unverifyButton; - if (devices && devices.some(device => device.isVerified())) { - unverifyButton = ( - {deviceName}@@ -157,6 +149,7 @@ function DeviceItem({userId, device}) { function DevicesSection({devices, userId, loading}) { const Spinner = sdk.getComponent("elements.Spinner"); + const cli = useContext(MatrixClientContext); const [isExpanded, setExpanded] = useState(false); @@ -167,9 +160,21 @@ function DevicesSection({devices, userId, loading}) { if (devices === null) { return _t("Unable to load device list"); } + const deviceTrusts = devices.map(d => cli.checkDeviceTrust(userId, d.deviceId)); - const unverifiedDevices = devices.filter(d => !d.isVerified()); - const verifiedDevices = devices.filter(d => d.isVerified()); + const unverifiedDevices = []; + const verifiedDevices = []; + + for (let i = 0; i < devices.length; ++i) { + const device = devices[i]; + const deviceTrust = deviceTrusts[i]; + + if (deviceTrust.isVerified()) { + verifiedDevices.push(device); + } else { + unverifiedDevices.push(device); + } + } let expandButton; if (verifiedDevices.length) { @@ -203,7 +208,9 @@ function DevicesSection({devices, userId, loading}) { ); } -const UserOptionsSection = withLegacyMatrixClient(({matrixClient: cli, member, isIgnored, canInvite, devices}) => { +const UserOptionsSection = ({member, isIgnored, canInvite, devices}) => { + const cli = useContext(MatrixClientContext); + let ignoreButton = null; let insertPillButton = null; let inviteUserButton = null; @@ -313,14 +320,6 @@ const UserOptionsSection = withLegacyMatrixClient(({matrixClient: cli, member, iunverifyUser(cli, member.userId)} className="mx_UserInfo_field mx_UserInfo_destructive"> - { _t('Unverify user') } - - ); - } return (@@ -332,11 +331,10 @@ const UserOptionsSection = withLegacyMatrixClient(({matrixClient: cli, member, i { insertPillButton } { inviteUserButton } { ignoreButton } - { unverifyButton }{ kickLabel } ; -}); +}; + +const RedactMessagesButton = ({member}) => { + const cli = useContext(MatrixClientContext); -const RedactMessagesButton = withLegacyMatrixClient(({matrixClient: cli, member}) => { const onRedactAllMessages = async () => { const {roomId, userId} = member; const room = cli.getRoom(roomId); @@ -517,9 +522,11 @@ const RedactMessagesButton = withLegacyMatrixClient(({matrixClient: cli, member} return{ _t("Remove recent messages") } ; -}); +}; + +const BanToggleButton = ({member, startUpdating, stopUpdating}) => { + const cli = useContext(MatrixClientContext); -const BanToggleButton = withLegacyMatrixClient(({matrixClient: cli, member, startUpdating, stopUpdating}) => { const onBanOrUnban = async () => { const ConfirmUserActionDialog = sdk.getComponent("dialogs.ConfirmUserActionDialog"); const {finished} = Modal.createTrackedDialog( @@ -573,207 +580,209 @@ const BanToggleButton = withLegacyMatrixClient(({matrixClient: cli, member, star return{ label } ; -}); +}; -const MuteToggleButton = withLegacyMatrixClient( - ({matrixClient: cli, member, room, powerLevels, startUpdating, stopUpdating}) => { - const isMuted = _isMuted(member, powerLevels); - const onMuteToggle = async () => { - const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); - const roomId = member.roomId; - const target = member.userId; +const MuteToggleButton = ({member, room, powerLevels, startUpdating, stopUpdating}) => { + const cli = useContext(MatrixClientContext); - // if muting self, warn as it may be irreversible - if (target === cli.getUserId()) { - try { - if (!(await _warnSelfDemote())) return; - } catch (e) { - console.error("Failed to warn about self demotion: ", e); - return; - } + // Don't show the mute/unmute option if the user is not in the room + if (member.membership !== "join") return null; + + const isMuted = _isMuted(member, powerLevels); + const onMuteToggle = async () => { + const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); + const roomId = member.roomId; + const target = member.userId; + + // if muting self, warn as it may be irreversible + if (target === cli.getUserId()) { + try { + if (!(await _warnSelfDemote())) return; + } catch (e) { + console.error("Failed to warn about self demotion: ", e); + return; } + } - const powerLevelEvent = room.currentState.getStateEvents("m.room.power_levels", ""); - if (!powerLevelEvent) return; + const powerLevelEvent = room.currentState.getStateEvents("m.room.power_levels", ""); + if (!powerLevelEvent) return; - const powerLevels = powerLevelEvent.getContent(); - const levelToSend = ( - (powerLevels.events ? powerLevels.events["m.room.message"] : null) || - powerLevels.events_default - ); - let level; - if (isMuted) { // unmute - level = levelToSend; - } else { // mute - level = levelToSend - 1; - } - level = parseInt(level); + const powerLevels = powerLevelEvent.getContent(); + const levelToSend = ( + (powerLevels.events ? powerLevels.events["m.room.message"] : null) || + powerLevels.events_default + ); + let level; + if (isMuted) { // unmute + level = levelToSend; + } else { // mute + level = levelToSend - 1; + } + level = parseInt(level); - if (!isNaN(level)) { - startUpdating(); - cli.setPowerLevel(roomId, target, level, powerLevelEvent).then(() => { - // NO-OP; rely on the m.room.member event coming down else we could - // get out of sync if we force setState here! - console.log("Mute toggle success"); - }, function(err) { - console.error("Mute error: " + err); - Modal.createTrackedDialog('Failed to mute user', '', ErrorDialog, { - title: _t("Error"), - description: _t("Failed to mute user"), - }); - }).finally(() => { - stopUpdating(); + if (!isNaN(level)) { + startUpdating(); + cli.setPowerLevel(roomId, target, level, powerLevelEvent).then(() => { + // NO-OP; rely on the m.room.member event coming down else we could + // get out of sync if we force setState here! + console.log("Mute toggle success"); + }, function(err) { + console.error("Mute error: " + err); + Modal.createTrackedDialog('Failed to mute user', '', ErrorDialog, { + title: _t("Error"), + description: _t("Failed to mute user"), }); - } + }).finally(() => { + stopUpdating(); + }); + } + }; + + const classes = classNames("mx_UserInfo_field", { + mx_UserInfo_destructive: !isMuted, + }); + + const muteLabel = isMuted ? _t("Unmute") : _t("Mute"); + return+ { muteLabel } + ; +}; + +const RoomAdminToolsContainer = ({room, children, member, startUpdating, stopUpdating, powerLevels}) => { + const cli = useContext(MatrixClientContext); + let kickButton; + let banButton; + let muteButton; + let redactButton; + + const editPowerLevel = ( + (powerLevels.events ? powerLevels.events["m.room.power_levels"] : null) || + powerLevels.state_default + ); + + const me = room.getMember(cli.getUserId()); + const isMe = me.userId === member.userId; + const canAffectUser = member.powerLevel < me.powerLevel || isMe; + + if (canAffectUser && me.powerLevel >= powerLevels.kick) { + kickButton =; + } + if (me.powerLevel >= powerLevels.redact) { + redactButton = ( + + ); + } + if (canAffectUser && me.powerLevel >= powerLevels.ban) { + banButton = ; + } + if (canAffectUser && me.powerLevel >= editPowerLevel) { + muteButton = ( + + ); + } + + if (kickButton || banButton || muteButton || redactButton || children) { + return + { muteButton } + { kickButton } + { banButton } + { redactButton } + { children } + ; + } + + return ; +}; + +const GroupAdminToolsSection = ({children, groupId, groupMember, startUpdating, stopUpdating}) => { + const cli = useContext(MatrixClientContext); + + const [isPrivileged, setIsPrivileged] = useState(false); + const [isInvited, setIsInvited] = useState(false); + + // Listen to group store changes + useEffect(() => { + let unmounted = false; + + const onGroupStoreUpdated = () => { + if (unmounted) return; + setIsPrivileged(GroupStore.isUserPrivileged(groupId)); + setIsInvited(GroupStore.getGroupInvitedMembers(groupId).some( + (m) => m.userId === groupMember.userId, + )); }; - const classes = classNames("mx_UserInfo_field", { - mx_UserInfo_destructive: !isMuted, - }); + GroupStore.registerListener(groupId, onGroupStoreUpdated); + onGroupStoreUpdated(); + // Handle unmount + return () => { + unmounted = true; + GroupStore.unregisterListener(onGroupStoreUpdated); + }; + }, [groupId, groupMember.userId]); - const muteLabel = isMuted ? _t("Unmute") : _t("Mute"); - return- { muteLabel } - ; - }, -); + if (isPrivileged) { + const _onKick = async () => { + const ConfirmUserActionDialog = sdk.getComponent("dialogs.ConfirmUserActionDialog"); + const {finished} = Modal.createDialog(ConfirmUserActionDialog, { + matrixClient: cli, + groupMember, + action: isInvited ? _t('Disinvite') : _t('Remove from community'), + title: isInvited ? _t('Disinvite this user from community?') + : _t('Remove this user from community?'), + danger: true, + }); -const RoomAdminToolsContainer = withLegacyMatrixClient( - ({matrixClient: cli, room, children, member, startUpdating, stopUpdating, powerLevels}) => { - let kickButton; - let banButton; - let muteButton; - let redactButton; + const [proceed] = await finished; + if (!proceed) return; - const editPowerLevel = ( - (powerLevels.events ? powerLevels.events["m.room.power_levels"] : null) || - powerLevels.state_default + startUpdating(); + cli.removeUserFromGroup(groupId, groupMember.userId).then(() => { + // return to the user list + dis.dispatch({ + action: "view_user", + member: null, + }); + }).catch((e) => { + const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); + Modal.createTrackedDialog('Failed to remove user from group', '', ErrorDialog, { + title: _t('Error'), + description: isInvited ? + _t('Failed to withdraw invitation') : + _t('Failed to remove user from community'), + }); + console.log(e); + }).finally(() => { + stopUpdating(); + }); + }; + + const kickButton = ( ++ { isInvited ? _t('Disinvite') : _t('Remove from community') } + ); - const me = room.getMember(cli.getUserId()); - const isMe = me.userId === member.userId; - const canAffectUser = member.powerLevel < me.powerLevel || isMe; + // No make/revoke admin API yet + /*const opLabel = this.state.isTargetMod ? _t("Revoke Moderator") : _t("Make Moderator"); + giveModButton =+ {giveOpLabel} + ;*/ - if (canAffectUser && me.powerLevel >= powerLevels.kick) { - kickButton =; - } - if (me.powerLevel >= powerLevels.redact) { - redactButton = ( - - ); - } - if (canAffectUser && me.powerLevel >= powerLevels.ban) { - banButton = ; - } - if (canAffectUser && me.powerLevel >= editPowerLevel) { - muteButton = ( - - ); - } + return + { kickButton } + { children } + ; + } - if (kickButton || banButton || muteButton || redactButton || children) { - return- { muteButton } - { kickButton } - { banButton } - { redactButton } - { children } - ; - } - - return ; - }, -); - -const GroupAdminToolsSection = withLegacyMatrixClient( - ({matrixClient: cli, children, groupId, groupMember, startUpdating, stopUpdating}) => { - const [isPrivileged, setIsPrivileged] = useState(false); - const [isInvited, setIsInvited] = useState(false); - - // Listen to group store changes - useEffect(() => { - let unmounted = false; - - const onGroupStoreUpdated = () => { - if (unmounted) return; - setIsPrivileged(GroupStore.isUserPrivileged(groupId)); - setIsInvited(GroupStore.getGroupInvitedMembers(groupId).some( - (m) => m.userId === groupMember.userId, - )); - }; - - GroupStore.registerListener(groupId, onGroupStoreUpdated); - onGroupStoreUpdated(); - // Handle unmount - return () => { - unmounted = true; - GroupStore.unregisterListener(onGroupStoreUpdated); - }; - }, [groupId, groupMember.userId]); - - if (isPrivileged) { - const _onKick = async () => { - const ConfirmUserActionDialog = sdk.getComponent("dialogs.ConfirmUserActionDialog"); - const {finished} = Modal.createDialog(ConfirmUserActionDialog, { - matrixClient: cli, - groupMember, - action: isInvited ? _t('Disinvite') : _t('Remove from community'), - title: isInvited ? _t('Disinvite this user from community?') - : _t('Remove this user from community?'), - danger: true, - }); - - const [proceed] = await finished; - if (!proceed) return; - - startUpdating(); - cli.removeUserFromGroup(groupId, groupMember.userId).then(() => { - // return to the user list - dis.dispatch({ - action: "view_user", - member: null, - }); - }).catch((e) => { - const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); - Modal.createTrackedDialog('Failed to remove user from group', '', ErrorDialog, { - title: _t('Error'), - description: isInvited ? - _t('Failed to withdraw invitation') : - _t('Failed to remove user from community'), - }); - console.log(e); - }).finally(() => { - stopUpdating(); - }); - }; - - const kickButton = ( -- { isInvited ? _t('Disinvite') : _t('Remove from community') } - - ); - - // No make/revoke admin API yet - /*const opLabel = this.state.isTargetMod ? _t("Revoke Moderator") : _t("Make Moderator"); - giveModButton =- {giveOpLabel} - ;*/ - - return- { kickButton } - { children } - ; - } - - return ; - }, -); + return ; +}; const GroupMember = PropTypes.shape({ userId: PropTypes.string.isRequired, @@ -849,7 +858,7 @@ function useRoomPermissions(cli, room, user) { return roomPermissions; } -const PowerLevelSection = withLegacyMatrixClient(({matrixClient: cli, user, room, roomPermissions, powerLevels}) => { +const PowerLevelSection = ({user, room, roomPermissions, powerLevels}) => { const [isEditing, setEditing] = useState(false); if (room && user.roomId) { // is in room if (isEditing) { @@ -876,9 +885,11 @@ const PowerLevelSection = withLegacyMatrixClient(({matrixClient: cli, user, room } else { return null; } -}); +}; + +const PowerLevelEditor = ({user, room, roomPermissions, onFinished}) => { + const cli = useContext(MatrixClientContext); -const PowerLevelEditor = withLegacyMatrixClient(({matrixClient: cli, user, room, roomPermissions, onFinished}) => { const [isUpdating, setIsUpdating] = useState(false); const [selectedPowerLevel, setSelectedPowerLevel] = useState(parseInt(user.powerLevel, 10)); const [isDirty, setIsDirty] = useState(false); @@ -953,7 +964,7 @@ const PowerLevelEditor = withLegacyMatrixClient(({matrixClient: cli, user, room, }); const [confirmed] = await finished; - if (confirmed) return; + if (!confirmed) return; } await _applyPowerChange(roomId, target, powerLevel, powerLevelEvent); } finally { @@ -982,10 +993,11 @@ const PowerLevelEditor = withLegacyMatrixClient(({matrixClient: cli, user, room, {buttonOrSpinner}) : null; + + const userVerified = cli.checkUserTrust(user.userId).isVerified(); + let verifyButton; + if (!userVerified) { + verifyButton = verifyDevice(user.userId, null)}> + {_t("Verify")} + ; + } + const securitySection = (); @@ -1316,7 +1337,7 @@ const UserInfo = withLegacyMatrixClient(({matrixClient: cli, user, groupId, room{ _t("Security") }
{ text }
-verifyDevice(user.userId, null)}>{_t("Verify")} + {verifyButton} { devicesSection }{canonicalAliasSection} -diff --git a/src/components/views/room_settings/RelatedGroupSettings.js b/src/components/views/room_settings/RelatedGroupSettings.js index c30f446f41..20118f4f44 100644 --- a/src/components/views/room_settings/RelatedGroupSettings.js +++ b/src/components/views/room_settings/RelatedGroupSettings.js @@ -16,11 +16,12 @@ limitations under the License. import React from 'react'; import PropTypes from 'prop-types'; -import {MatrixEvent, MatrixClient} from 'matrix-js-sdk'; +import {MatrixEvent} from 'matrix-js-sdk'; import sdk from '../../../index'; import { _t } from '../../../languageHandler'; import Modal from '../../../Modal'; import ErrorDialog from "../dialogs/ErrorDialog"; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; const GROUP_ID_REGEX = /\+\S+:\S+/; @@ -31,9 +32,7 @@ export default class RelatedGroupSettings extends React.Component { relatedGroupsEvent: PropTypes.instanceOf(MatrixEvent), }; - static contextTypes = { - matrixClient: PropTypes.instanceOf(MatrixClient), - }; + static contextType = MatrixClientContext; static defaultProps = { canSetRelatedGroups: false, @@ -49,7 +48,7 @@ export default class RelatedGroupSettings extends React.Component { } updateGroups(newGroupsList) { - this.context.matrixClient.sendStateEvent(this.props.roomId, 'm.room.related_groups', { + this.context.sendStateEvent(this.props.roomId, 'm.room.related_groups', { groups: newGroupsList, }, '').catch((err) => { console.error(err); @@ -99,7 +98,7 @@ export default class RelatedGroupSettings extends React.Component { }; render() { - const localDomain = this.context.matrixClient.getDomain(); + const localDomain = this.context.getDomain(); const EditableItemList = sdk.getComponent('elements.EditableItemList'); return{remoteAliasesSection} e.emoticon ? e.emoticon.toLowerCase() === query : false); + const data = EMOTICON_TO_EMOJI.get(query); + if (data) { const {partCreator} = model; const hasPrecedingSpace = emoticonMatch[0][0] === " "; diff --git a/src/components/views/rooms/EditMessageComposer.js b/src/components/views/rooms/EditMessageComposer.js index 34b2d92590..43f378a1e0 100644 --- a/src/components/views/rooms/EditMessageComposer.js +++ b/src/components/views/rooms/EditMessageComposer.js @@ -26,11 +26,11 @@ import {findEditableEvent} from '../../../utils/EventUtils'; import {parseEvent} from '../../../editor/deserialize'; import {PartCreator} from '../../../editor/parts'; import EditorStateTransfer from '../../../utils/EditorStateTransfer'; -import {MatrixClient} from 'matrix-js-sdk'; import classNames from 'classnames'; import {EventStatus} from 'matrix-js-sdk'; import BasicMessageComposer from "./BasicMessageComposer"; import {Key} from "../../../Keyboard"; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; function _isReply(mxEvent) { const relatesTo = mxEvent.getContent()["m.relates_to"]; @@ -105,12 +105,10 @@ export default class EditMessageComposer extends React.Component { editState: PropTypes.instanceOf(EditorStateTransfer).isRequired, }; - static contextTypes = { - matrixClient: PropTypes.instanceOf(MatrixClient).isRequired, - }; + static contextType = MatrixClientContext; - constructor(props, context) { - super(props, context); + constructor(props) { + super(props); this.model = null; this._editorRef = null; @@ -124,7 +122,7 @@ export default class EditMessageComposer extends React.Component { }; _getRoom() { - return this.context.matrixClient.getRoom(this.props.editState.getEvent().getRoomId()); + return this.context.getRoom(this.props.editState.getEvent().getRoomId()); } _onKeyDown = (event) => { @@ -190,7 +188,7 @@ export default class EditMessageComposer extends React.Component { if (this._isContentModified(newContent)) { const roomId = editedEvent.getRoomId(); this._cancelPreviousPendingEdit(); - this.context.matrixClient.sendMessage(roomId, editContent); + this.context.sendMessage(roomId, editContent); } // close the event editing and focus composer @@ -205,7 +203,7 @@ export default class EditMessageComposer extends React.Component { previousEdit.status === EventStatus.QUEUED || previousEdit.status === EventStatus.NOT_SENT )) { - this.context.matrixClient.cancelPendingEvent(previousEdit); + this.context.cancelPendingEvent(previousEdit); } } @@ -232,7 +230,7 @@ export default class EditMessageComposer extends React.Component { _createEditorModel() { const {editState} = this.props; const room = this._getRoom(); - const partCreator = new PartCreator(room, this.context.matrixClient); + const partCreator = new PartCreator(room, this.context); let parts; if (editState.hasEditorState()) { // if restoring state from a previous editor, diff --git a/src/components/views/rooms/EventTile.js b/src/components/views/rooms/EventTile.js index 988482df7f..b71771a916 100644 --- a/src/components/views/rooms/EventTile.js +++ b/src/components/views/rooms/EventTile.js @@ -1,8 +1,8 @@ /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2017 New Vector Ltd -Copyright 2019 The Matrix.org Foundation C.I.C. Copyright 2019 Michael Telatynski <7t3chguy@gmail.com> +Copyright 2019, 2020 The Matrix.org Foundation C.I.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -24,17 +24,17 @@ import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; const classNames = require("classnames"); import { _t, _td } from '../../../languageHandler'; -const Modal = require('../../../Modal'); const sdk = require('../../../index'); const TextForEvent = require('../../../TextForEvent'); import dis from '../../../dispatcher'; import SettingsStore from "../../../settings/SettingsStore"; -import {EventStatus, MatrixClient} from 'matrix-js-sdk'; +import {EventStatus} from 'matrix-js-sdk'; import {formatTime} from "../../../DateUtils"; import MatrixClientPeg from '../../../MatrixClientPeg'; import {ALL_RULE_TYPES} from "../../../mjolnir/BanList"; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; const ObjectUtils = require('../../../ObjectUtils'); @@ -222,8 +222,8 @@ module.exports = createReactClass({ }; }, - contextTypes: { - matrixClient: PropTypes.instanceOf(MatrixClient).isRequired, + statics: { + contextType: MatrixClientContext, }, componentWillMount: function() { @@ -237,7 +237,7 @@ module.exports = createReactClass({ componentDidMount: function() { this._suppressReadReceiptAnimation = false; - const client = this.context.matrixClient; + const client = this.context; client.on("deviceVerificationChanged", this.onDeviceVerificationChanged); this.props.mxEvent.on("Event.decrypted", this._onDecrypted); if (this.props.showReactions) { @@ -262,7 +262,7 @@ module.exports = createReactClass({ }, componentWillUnmount: function() { - const client = this.context.matrixClient; + const client = this.context; client.removeListener("deviceVerificationChanged", this.onDeviceVerificationChanged); this.props.mxEvent.removeListener("Event.decrypted", this._onDecrypted); if (this.props.showReactions) { @@ -291,7 +291,7 @@ module.exports = createReactClass({ return; } - const verified = await this.context.matrixClient.isEventSenderVerified(mxEvent); + const verified = await this.context.isEventSenderVerified(mxEvent); this.setState({ verified: verified, }, () => { @@ -349,11 +349,11 @@ module.exports = createReactClass({ }, shouldHighlight: function() { - const actions = this.context.matrixClient.getPushActionsForEvent(this.props.mxEvent); + const actions = this.context.getPushActionsForEvent(this.props.mxEvent); if (!actions || !actions.tweaks) { return false; } // don't show self-highlights from another of our clients - if (this.props.mxEvent.getSender() === this.context.matrixClient.credentials.userId) { + if (this.props.mxEvent.getSender() === this.context.credentials.userId) { return false; } @@ -442,15 +442,6 @@ module.exports = createReactClass({ }); }, - onCryptoClick: function(e) { - const event = this.props.mxEvent; - - Modal.createTrackedDialogAsync('Encrypted Event Dialog', '', - import('../../../async-components/views/dialogs/EncryptedEventDialog'), - {event}, - ); - }, - onRequestKeysClick: function() { this.setState({ // Indicate in the UI that the keys have been requested (this is expected to @@ -461,7 +452,7 @@ module.exports = createReactClass({ // Cancel any outgoing key request for this event and resend it. If a response // is received for the request with the required keys, the event could be // decrypted successfully. - this.context.matrixClient.cancelAndResendEventRoomKeyRequest(this.props.mxEvent); + this.context.cancelAndResendEventRoomKeyRequest(this.props.mxEvent); }, onPermalinkClicked: function(e) { @@ -478,11 +469,10 @@ module.exports = createReactClass({ _renderE2EPadlock: function() { const ev = this.props.mxEvent; - const props = {onClick: this.onCryptoClick}; // event could not be decrypted if (ev.getContent().msgtype === 'm.bad.encrypted') { - return ; + return ; } // event is encrypted, display padlock corresponding to whether or not it is verified @@ -490,11 +480,11 @@ module.exports = createReactClass({ if (this.state.verified) { return; // no icon for verified } else { - return ( ); + return ( ); } } - if (this.context.matrixClient.isRoomEncrypted(ev.getRoomId())) { + if (this.context.isRoomEncrypted(ev.getRoomId())) { // else if room is encrypted // and event is being encrypted or is not_sent (Unknown Devices/Network Error) if (ev.status === EventStatus.ENCRYPTING) { @@ -507,7 +497,7 @@ module.exports = createReactClass({ return; // we expect this to be unencrypted } // if the event is not encrypted, but it's an e2e room, show the open padlock - return ; + return ; } // no padlock needed @@ -741,7 +731,7 @@ module.exports = createReactClass({ switch (this.props.tileShape) { case 'notif': { - const room = this.context.matrixClient.getRoom(this.props.mxEvent.getRoomId()); + const room = this.context.getRoom(this.props.mxEvent.getRoomId()); return ( ; - const isEncrypted = this.context.matrixClient.isRoomEncrypted(this.props.member.roomId); + const isEncrypted = this.context.isRoomEncrypted(this.props.member.roomId); if (this.state.e2eStatus && isEncrypted) { e2eIconElement = (@@ -919,7 +909,6 @@ class E2ePadlock extends React.Component { static propTypes = { icon: PropTypes.string.isRequired, title: PropTypes.string.isRequired, - onClick: PropTypes.func, }; constructor() { @@ -930,10 +919,6 @@ class E2ePadlock extends React.Component { }; } - onClick = (e) => { - if (this.props.onClick) this.props.onClick(e); - }; - onHoverStart = () => { this.setState({hover: true}); }; diff --git a/src/components/views/rooms/MemberDeviceInfo.js b/src/components/views/rooms/MemberDeviceInfo.js index ff88c6f6e6..ba90850b35 100644 --- a/src/components/views/rooms/MemberDeviceInfo.js +++ b/src/components/views/rooms/MemberDeviceInfo.js @@ -23,6 +23,8 @@ import classNames from 'classnames'; export default class MemberDeviceInfo extends React.Component { render() { const DeviceVerifyButtons = sdk.getComponent('elements.DeviceVerifyButtons'); + // XXX: These checks are not cross-signing aware but this component is only used + // from the old, pre-cross-signing memberinfopanel const iconClasses = classNames({ mx_MemberDeviceInfo_icon: true, mx_MemberDeviceInfo_icon_blacklisted: this.props.device.isBlocked(), diff --git a/src/components/views/rooms/MemberInfo.js b/src/components/views/rooms/MemberInfo.js index 1a2c8e2212..cb8c5b8d49 100644 --- a/src/components/views/rooms/MemberInfo.js +++ b/src/components/views/rooms/MemberInfo.js @@ -31,7 +31,6 @@ import React from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; import classNames from 'classnames'; -import { MatrixClient } from 'matrix-js-sdk'; import dis from '../../../dispatcher'; import Modal from '../../../Modal'; import sdk from '../../../index'; @@ -48,7 +47,7 @@ import SettingsStore from "../../../settings/SettingsStore"; import E2EIcon from "./E2EIcon"; import AutoHideScrollbar from "../../structures/AutoHideScrollbar"; import MatrixClientPeg from "../../../MatrixClientPeg"; -import {EventTimeline} from "matrix-js-sdk"; +import MatrixClientContext from "../../../contexts/MatrixClientContext"; module.exports = createReactClass({ displayName: 'MemberInfo', @@ -76,13 +75,13 @@ module.exports = createReactClass({ }; }, - contextTypes: { - matrixClient: PropTypes.instanceOf(MatrixClient).isRequired, + statics: { + contextType: MatrixClientContext, }, componentWillMount: function() { this._cancelDeviceList = null; - const cli = this.context.matrixClient; + const cli = this.context; // only display the devices list if our client supports E2E this._enableDevices = cli.isCryptoEnabled(); @@ -112,7 +111,7 @@ module.exports = createReactClass({ }, componentWillUnmount: function() { - const client = this.context.matrixClient; + const client = this.context; if (client) { client.removeListener("deviceVerificationChanged", this.onDeviceVerificationChanged); client.removeListener("Room", this.onRoom); @@ -131,7 +130,7 @@ module.exports = createReactClass({ }, _checkIgnoreState: function() { - const isIgnoring = this.context.matrixClient.isUserIgnored(this.props.member.userId); + const isIgnoring = this.context.isUserIgnored(this.props.member.userId); this.setState({isIgnoring: isIgnoring}); }, @@ -163,7 +162,7 @@ module.exports = createReactClass({ // Promise.resolve to handle transition from static result to promise; can be removed // in future - Promise.resolve(this.context.matrixClient.getStoredDevicesForUser(userId)).then((devices) => { + Promise.resolve(this.context.getStoredDevicesForUser(userId)).then((devices) => { this.setState({ devices: devices, e2eStatus: this._getE2EStatus(devices), @@ -197,7 +196,7 @@ module.exports = createReactClass({ onRoomReceipt: function(receiptEvent, room) { // because if we read a notification, it will affect notification count // only bother updating if there's a receipt from us - if (findReadReceiptFromUserId(receiptEvent, this.context.matrixClient.credentials.userId)) { + if (findReadReceiptFromUserId(receiptEvent, this.context.credentials.userId)) { this.forceUpdate(); } }, @@ -242,7 +241,7 @@ module.exports = createReactClass({ let cancelled = false; this._cancelDeviceList = function() { cancelled = true; }; - const client = this.context.matrixClient; + const client = this.context; const self = this; client.downloadKeys([member.userId], true).then(() => { return client.getStoredDevicesForUser(member.userId); @@ -267,7 +266,7 @@ module.exports = createReactClass({ }, onIgnoreToggle: function() { - const ignoredUsers = this.context.matrixClient.getIgnoredUsers(); + const ignoredUsers = this.context.getIgnoredUsers(); if (this.state.isIgnoring) { const index = ignoredUsers.indexOf(this.props.member.userId); if (index !== -1) ignoredUsers.splice(index, 1); @@ -275,7 +274,7 @@ module.exports = createReactClass({ ignoredUsers.push(this.props.member.userId); } - this.context.matrixClient.setIgnoredUsers(ignoredUsers).then(() => { + this.context.setIgnoredUsers(ignoredUsers).then(() => { return this.setState({isIgnoring: !this.state.isIgnoring}); }); }, @@ -293,7 +292,7 @@ module.exports = createReactClass({ if (!proceed) return; this.setState({ updating: this.state.updating + 1 }); - this.context.matrixClient.kick( + this.context.kick( this.props.member.roomId, this.props.member.userId, reason || undefined, ).then(function() { @@ -329,11 +328,11 @@ module.exports = createReactClass({ this.setState({ updating: this.state.updating + 1 }); let promise; if (this.props.member.membership === 'ban') { - promise = this.context.matrixClient.unban( + promise = this.context.unban( this.props.member.roomId, this.props.member.userId, ); } else { - promise = this.context.matrixClient.ban( + promise = this.context.ban( this.props.member.roomId, this.props.member.userId, reason || undefined, ); @@ -360,7 +359,7 @@ module.exports = createReactClass({ onRedactAllMessages: async function() { const {roomId, userId} = this.props.member; - const room = this.context.matrixClient.getRoom(roomId); + const room = this.context.getRoom(roomId); if (!room) { return; } @@ -414,7 +413,7 @@ module.exports = createReactClass({ console.info(`Started redacting recent ${count} messages for ${user} in ${roomId}`); await Promise.all(eventsToRedact.map(async event => { try { - await this.context.matrixClient.redactEvent(roomId, event.getId()); + await this.context.redactEvent(roomId, event.getId()); } catch (err) { // log and swallow errors console.error("Could not redact", event.getId()); @@ -446,11 +445,11 @@ module.exports = createReactClass({ const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); const roomId = this.props.member.roomId; const target = this.props.member.userId; - const room = this.context.matrixClient.getRoom(roomId); + const room = this.context.getRoom(roomId); if (!room) return; // if muting self, warn as it may be irreversible - if (target === this.context.matrixClient.getUserId()) { + if (target === this.context.getUserId()) { try { if (!(await this._warnSelfDemote())) return; } catch (e) { @@ -478,7 +477,7 @@ module.exports = createReactClass({ if (!isNaN(level)) { this.setState({ updating: this.state.updating + 1 }); - this.context.matrixClient.setPowerLevel(roomId, target, level, powerLevelEvent).then( + this.context.setPowerLevel(roomId, target, level, powerLevelEvent).then( function() { // NO-OP; rely on the m.room.member event coming down else we could // get out of sync if we force setState here! @@ -500,13 +499,13 @@ module.exports = createReactClass({ const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); const roomId = this.props.member.roomId; const target = this.props.member.userId; - const room = this.context.matrixClient.getRoom(roomId); + const room = this.context.getRoom(roomId); if (!room) return; const powerLevelEvent = room.currentState.getStateEvents("m.room.power_levels", ""); if (!powerLevelEvent) return; - const me = room.getMember(this.context.matrixClient.credentials.userId); + const me = room.getMember(this.context.credentials.userId); if (!me) return; const defaultLevel = powerLevelEvent.getContent().users_default; @@ -515,7 +514,7 @@ module.exports = createReactClass({ // toggle the level const newLevel = this.state.isTargetMod ? defaultLevel : modLevel; this.setState({ updating: this.state.updating + 1 }); - this.context.matrixClient.setPowerLevel(roomId, target, parseInt(newLevel), powerLevelEvent).then( + this.context.setPowerLevel(roomId, target, parseInt(newLevel), powerLevelEvent).then( function() { // NO-OP; rely on the m.room.member event coming down else we could // get out of sync if we force setState here! @@ -550,7 +549,7 @@ module.exports = createReactClass({ danger: true, onFinished: (accepted) => { if (!accepted) return; - this.context.matrixClient.deactivateSynapseUser(this.props.member.userId).catch(e => { + this.context.deactivateSynapseUser(this.props.member.userId).catch(e => { console.error("Failed to deactivate user"); console.error(e); @@ -566,7 +565,7 @@ module.exports = createReactClass({ _applyPowerChange: function(roomId, target, powerLevel, powerLevelEvent) { this.setState({ updating: this.state.updating + 1 }); - this.context.matrixClient.setPowerLevel(roomId, target, parseInt(powerLevel), powerLevelEvent).then( + this.context.setPowerLevel(roomId, target, parseInt(powerLevel), powerLevelEvent).then( function() { // NO-OP; rely on the m.room.member event coming down else we could // get out of sync if we force setState here! @@ -587,7 +586,7 @@ module.exports = createReactClass({ onPowerChange: async function(powerLevel) { const roomId = this.props.member.roomId; const target = this.props.member.userId; - const room = this.context.matrixClient.getRoom(roomId); + const room = this.context.getRoom(roomId); if (!room) return; const powerLevelEvent = room.currentState.getStateEvents("m.room.power_levels", ""); @@ -598,7 +597,7 @@ module.exports = createReactClass({ return; } - const myUserId = this.context.matrixClient.getUserId(); + const myUserId = this.context.getUserId(); const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog"); // If we are changing our own PL it can only ever be decreasing, which we cannot reverse. @@ -650,9 +649,9 @@ module.exports = createReactClass({ _calculateOpsPermissions: async function(member) { let canDeactivate = false; - if (this.context.matrixClient) { + if (this.context) { try { - canDeactivate = await this.context.matrixClient.isSynapseAdministrator(); + canDeactivate = await this.context.isSynapseAdministrator(); } catch (e) { console.error(e); } @@ -665,13 +664,13 @@ module.exports = createReactClass({ }, muted: false, }; - const room = this.context.matrixClient.getRoom(member.roomId); + const room = this.context.getRoom(member.roomId); if (!room) return defaultPerms; const powerLevels = room.currentState.getStateEvents("m.room.power_levels", ""); if (!powerLevels) return defaultPerms; - const me = room.getMember(this.context.matrixClient.credentials.userId); + const me = room.getMember(this.context.credentials.userId); if (!me) return defaultPerms; const them = member; @@ -738,7 +737,7 @@ module.exports = createReactClass({ const avatarUrl = member.getMxcAvatarUrl(); if (!avatarUrl) return; - const httpUrl = this.context.matrixClient.mxcUrlToHttp(avatarUrl); + const httpUrl = this.context.mxcUrlToHttp(avatarUrl); const ImageView = sdk.getComponent("elements.ImageView"); const params = { src: httpUrl, @@ -797,7 +796,7 @@ module.exports = createReactClass({ }, _renderUserOptions: function() { - const cli = this.context.matrixClient; + const cli = this.context; const member = this.props.member; let ignoreButton = null; @@ -905,9 +904,9 @@ module.exports = createReactClass({ let synapseDeactivateButton; let spinner; - if (this.props.member.userId !== this.context.matrixClient.credentials.userId) { + if (this.props.member.userId !== this.context.credentials.userId) { // TODO: Immutable DMs replaces a lot of this - const dmRoomMap = new DMRoomMap(this.context.matrixClient); + const dmRoomMap = new DMRoomMap(this.context); // dmRooms will not include dmRooms that we have been invited into but did not join. // Because DMRoomMap runs off account_data[m.direct] which is only set on join of dm room. // XXX: we potentially want DMs we have been invited to, to also show up here :L @@ -918,7 +917,7 @@ module.exports = createReactClass({ const tiles = []; for (const roomId of dmRooms) { - const room = this.context.matrixClient.getRoom(roomId); + const room = this.context.getRoom(roomId); if (room) { const myMembership = room.getMyMembership(); // not a DM room if we have are not joined @@ -1064,12 +1063,12 @@ module.exports = createReactClass({ } } - const room = this.context.matrixClient.getRoom(this.props.member.roomId); + const room = this.context.getRoom(this.props.member.roomId); const powerLevelEvent = room ? room.currentState.getStateEvents("m.room.power_levels", "") : null; const powerLevelUsersDefault = powerLevelEvent ? powerLevelEvent.getContent().users_default : 0; const enablePresenceByHsUrl = SdkConfig.get()["enable_presence_by_hs_url"]; - const hsUrl = this.context.matrixClient.baseUrl; + const hsUrl = this.context.baseUrl; let showPresence = true; if (enablePresenceByHsUrl && enablePresenceByHsUrl[hsUrl] !== undefined) { showPresence = enablePresenceByHsUrl[hsUrl]; @@ -1108,7 +1107,7 @@ module.exports = createReactClass({); } @@ -1117,7 +1116,7 @@ module.exports = createReactClass({ const avatarUrl = this.props.member.getMxcAvatarUrl(); let avatarElement; if (avatarUrl) { - const httpUrl = this.context.matrixClient.mxcUrlToHttp(avatarUrl, 800, 800); + const httpUrl = this.context.mxcUrlToHttp(avatarUrl, 800, 800); avatarElement = ; diff --git a/src/components/views/rooms/MemberList.js b/src/components/views/rooms/MemberList.js index 0805c0342c..de0a6fe478 100644 --- a/src/components/views/rooms/MemberList.js +++ b/src/components/views/rooms/MemberList.js @@ -32,6 +32,10 @@ const INITIAL_LOAD_NUM_MEMBERS = 30; const INITIAL_LOAD_NUM_INVITED = 5; const SHOW_MORE_INCREMENT = 100; +// Regex applied to filter our punctuation in member names before applying sort, to fuzzy it a little +// matches all ASCII punctuation: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ +const SORT_REGEX = /[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]+/g; + module.exports = createReactClass({ displayName: 'MemberList', @@ -336,10 +340,13 @@ module.exports = createReactClass({ } // Fourth by name (alphabetical) - const nameA = memberA.name[0] === '@' ? memberA.name.substr(1) : memberA.name; - const nameB = memberB.name[0] === '@' ? memberB.name.substr(1) : memberB.name; + const nameA = (memberA.name[0] === '@' ? memberA.name.substr(1) : memberA.name).replace(SORT_REGEX, ""); + const nameB = (memberB.name[0] === '@' ? memberB.name.substr(1) : memberB.name).replace(SORT_REGEX, ""); // console.log(`Comparing userA_name=${nameA} against userB_name=${nameB} - returning`); - return nameA.localeCompare(nameB); + return nameA.localeCompare(nameB, { + ignorePunctuation: true, + sensitivity: "base", + }); }, onSearchQueryChanged: function(searchQuery) { diff --git a/src/components/views/rooms/MessageComposer.js b/src/components/views/rooms/MessageComposer.js index 580e3b0d81..06e6834bec 100644 --- a/src/components/views/rooms/MessageComposer.js +++ b/src/components/views/rooms/MessageComposer.js @@ -107,8 +107,8 @@ class UploadButton extends React.Component { roomId: PropTypes.string.isRequired, } - constructor(props, context) { - super(props, context); + constructor(props) { + super(props); this.onUploadClick = this.onUploadClick.bind(this); this.onUploadFileInputChange = this.onUploadFileInputChange.bind(this); @@ -165,8 +165,8 @@ class UploadButton extends React.Component { } export default class MessageComposer extends React.Component { - constructor(props, context) { - super(props, context); + constructor(props) { + super(props); this.onInputStateChanged = this.onInputStateChanged.bind(this); this.onEvent = this.onEvent.bind(this); this._onRoomStateEvents = this._onRoomStateEvents.bind(this); diff --git a/src/components/views/rooms/MessageComposerInput.js b/src/components/views/rooms/MessageComposerInput.js index a5d8492d99..595ec0681f 100644 --- a/src/components/views/rooms/MessageComposerInput.js +++ b/src/components/views/rooms/MessageComposerInput.js @@ -48,7 +48,6 @@ import Markdown from '../../../Markdown'; import MessageComposerStore from '../../../stores/MessageComposerStore'; import ContentMessages from '../../../ContentMessages'; -import EMOJIBASE from 'emojibase-data/en/compact.json'; import EMOTICON_REGEX from 'emojibase-regex/emoticon'; import SettingsStore, {SettingLevel} from "../../../settings/SettingsStore"; @@ -61,6 +60,7 @@ import AccessibleButton from '../elements/AccessibleButton'; import {findEditableEvent} from '../../../utils/EventUtils'; import SlateComposerHistoryManager from "../../../SlateComposerHistoryManager"; import TypingStore from "../../../stores/TypingStore"; +import {EMOTICON_TO_EMOJI} from "../../../emoji"; const REGEX_EMOTICON_WHITESPACE = new RegExp('(?:^|\\s)(' + EMOTICON_REGEX.source + ')\\s$'); @@ -141,8 +141,8 @@ export default class MessageComposerInput extends React.Component { autocomplete: Autocomplete; historyManager: SlateComposerHistoryManager; - constructor(props, context) { - super(props, context); + constructor(props) { + super(props); const isRichTextEnabled = SettingsStore.getValue('MessageComposerInput.isRichTextEnabled'); @@ -464,7 +464,7 @@ export default class MessageComposerInput extends React.Component { const emoticonMatch = REGEX_EMOTICON_WHITESPACE.exec(text.slice(0, currentStartOffset)); if (emoticonMatch) { const query = emoticonMatch[1].toLowerCase().replace("-", ""); - const data = EMOJIBASE.find(e => e.emoticon ? e.emoticon.toLowerCase() === query : false); + const data = EMOTICON_TO_EMOJI.get(query); // only perform replacement if we found a match, otherwise we would be not letting user type if (data) { diff --git a/src/components/views/rooms/ReadReceiptMarker.js b/src/components/views/rooms/ReadReceiptMarker.js index 27c5e8c20e..35d745ae5a 100644 --- a/src/components/views/rooms/ReadReceiptMarker.js +++ b/src/components/views/rooms/ReadReceiptMarker.js @@ -14,8 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -import React from 'react'; -import ReactDOM from 'react-dom'; +import React, {createRef} from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; @@ -90,6 +89,10 @@ module.exports = createReactClass({ }; }, + UNSAFE_componentWillMount: function() { + this._avatar = createRef(); + }, + componentWillUnmount: function() { // before we remove the rr, store its location in the map, so that if // it reappears, it can be animated from the right place. @@ -105,7 +108,7 @@ module.exports = createReactClass({ return; } - const avatarNode = ReactDOM.findDOMNode(this); + const avatarNode = this._avatar.current; rrInfo.top = avatarNode.offsetTop; rrInfo.left = avatarNode.offsetLeft; rrInfo.parent = avatarNode.offsetParent; @@ -125,7 +128,7 @@ module.exports = createReactClass({ oldTop = oldInfo.top + oldInfo.parent.getBoundingClientRect().top; } - const newElement = ReactDOM.findDOMNode(this); + const newElement = this._avatar.current; let startTopOffset; if (!newElement.offsetParent) { // this seems to happen sometimes for reasons I don't understand @@ -175,7 +178,7 @@ module.exports = createReactClass({ render: function() { const MemberAvatar = sdk.getComponent('avatars.MemberAvatar'); if (this.state.suppressDisplay) { - return ; + return ; } const style = { @@ -215,6 +218,7 @@ module.exports = createReactClass({ style={style} title={title} onClick={this.props.onClick} + inputRef={this._avatar} /> ); diff --git a/src/components/views/rooms/ReplyPreview.js b/src/components/views/rooms/ReplyPreview.js index caf8feeea2..af2ea640f5 100644 --- a/src/components/views/rooms/ReplyPreview.js +++ b/src/components/views/rooms/ReplyPreview.js @@ -35,8 +35,8 @@ export default class ReplyPreview extends React.Component { permalinkCreator: PropTypes.instanceOf(RoomPermalinkCreator).isRequired, }; - constructor(props, context) { - super(props, context); + constructor(props) { + super(props); this.unmounted = false; this.state = { diff --git a/src/components/views/rooms/RoomList.js b/src/components/views/rooms/RoomList.js index 80a03e7a73..35a5ca9e66 100644 --- a/src/components/views/rooms/RoomList.js +++ b/src/components/views/rooms/RoomList.js @@ -22,6 +22,7 @@ import React from "react"; import ReactDOM from "react-dom"; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; +import utils from "matrix-js-sdk/lib/utils"; import { _t } from '../../../languageHandler'; const MatrixClientPeg = require("../../../MatrixClientPeg"); const CallHandler = require('../../../CallHandler'); @@ -589,10 +590,17 @@ module.exports = createReactClass({ _applySearchFilter: function(list, filter) { if (filter === "") return list; const lcFilter = filter.toLowerCase(); + // apply toLowerCase before and after removeHiddenChars because different rules get applied + // e.g M -> M but m -> n, yet some unicode homoglyphs come out as uppercase, e.g 𝚮 -> H + const fuzzyFilter = utils.removeHiddenChars(lcFilter).toLowerCase(); // case insensitive if room name includes filter, // or if starts with `#` and one of room's aliases starts with filter - return list.filter((room) => (room.name && room.name.toLowerCase().includes(lcFilter)) || - (filter[0] === '#' && room.getAliases().some((alias) => alias.toLowerCase().startsWith(lcFilter)))); + return list.filter((room) => { + if (filter[0] === "#" && room.getAliases().some((alias) => alias.toLowerCase().startsWith(lcFilter))) { + return true; + } + return room.name && utils.removeHiddenChars(room.name.toLowerCase()).toLowerCase().includes(fuzzyFilter); + }); }, _handleCollapsedState: function(key, collapsed) { @@ -628,7 +636,6 @@ module.exports = createReactClass({ const defaultProps = { collapsed: this.props.collapsed, isFiltered: !!this.props.searchFilter, - incomingCall: this.state.incomingCall, }; subListsProps.forEach((p) => { @@ -641,7 +648,7 @@ module.exports = createReactClass({ })); return subListsProps.reduce((components, props, i) => { - props = Object.assign({}, defaultProps, props); + props = {...defaultProps, ...props}; const isLast = i === subListsProps.length - 1; const len = props.list.length + (props.extraTiles ? props.extraTiles.length : 0); const {key, label, onHeaderClick, ...otherProps} = props; @@ -652,12 +659,12 @@ module.exports = createReactClass({ onHeaderClick(collapsed); } }; - let startAsHidden = props.startAsHidden || this.collapsedState[chosenKey]; + const startAsHidden = props.startAsHidden || this.collapsedState[chosenKey]; this._layoutSections.push({ id: chosenKey, count: len, }); - let subList = (![]()
{setupCaption} - -
{ _t("Not now") } - +
+ { _t("Don't ask me again") } -
{ _t("This bridge was provisioned by
{_t("This bridge is managed by
{_t("Connected via %(protocolName)s", { protocolName })}
+{chanAndNetworkInfo}
+{ _t("Below is a list of bridges connected to this room.") }
+